An Introduction To Programming Using Microsoft Visual C # 2005 Express Edition

xiaoxiao2021-03-06  63

August 2004

Download The Code.msi Sample File.

Note this article associus you're a hobbyist, student, or programming-minded Individual INTERESTED in Exploring the c # programing language and the

.NET Platform Using Visual C # 2005 Express Edition. No prior Exposure To C # is Assumed or Expected, HoWever, Some Previous Programming Experience Will Be Helpful.

Applies TO: Microsoft Visual C # 2005 Express Edition

Contents

What Is Visual C # 2005 Express Edition High Level Features of Visual C # 2005 ExpressVisual C # 2005 Express ProjectsAssemblies, Namespaces, and TypesTheory into Practice:? Using External TypesHanding Exceptions with C # ExpressHanding the Exception ProgrammaticallyCreating a C # Class Library ProjectBuilding a Windows Forms ApplicationGo Forth and Code : Visual C # 2005 Express Starter Kitsummary

What is Visual C # 2005 Express Edition?

A .net application can be created using a variety of approaches. Die-hard developers are free to take the commando approach and build .net programs using a no-frills text editor (such as notepad.exe) and the C # command line compiler ( csc.exe). While the .net Software Development Kit (SDK) is freely downloadable from Microsoft (www.microsoft.com/net), this approach will surely result in hand cramps, due to the lack of code generation utilities (wizards) , Graphical Debuggers, And IntelliSense Functionality In the SDK.

To help lessen the burden of building software at the command line, many .net developers make use of visual tools such as Microsoft's full-featured IDE, Visual Studio .net 2003 (http://msdn.microsoft.com/vstudio). While this product is very powerful, the Enterprise Edition may be cost prohibitive for the .net hobbyist and / or college student. To be honest, unless you are a professional software engineer, the magnitude of options provided by Visual Studio .net 2003 typically complicates, rather than facilitates, the learning process.Somewhere between notepad.exe and Visual Studio .net 2003 sits Microsoft's newest IDE, Visual C # 2005 Express Edition. At the time of this writing, the beta version of 2005 Express Edition is offered free Visual C # of Charge Through A Web Download (http://msdn.microsoft.com/express). Given The Relative SMALL Size, Visual C # 2005 Express Can Be Easily Acquired Even Using A 56k Modem Connection.

Visual C # 2005 Express IS Actually ONE SEVERAL MEMBERS IN The Express Family. Specify, Microsoft Provides The Following Express Edition Products:

Visual Web Developer 2005 Express: A lightweight tool for building dynamic Web sites and XML Web services using ASP.NET Visual Basic 2005 Express:.. A streamlined programming tool ideal for beginning programmers to learn how to build Windows applications Visual C # 2005 Express, Visual C 2005 Express, and Visual J # 2005 Express: Targeted programming tools for students and enthusiasts who wish to learn the fundamentals of computer science SQL Server 2005 Express:. An entry-level database management system geared towards hobbyists, enthusiasts, and students developers.

In a nutshell, the Express Edition product lineup is an ideal entry point for hobbyist, students, and newcomers to the .net platform. If this sounds like you, download and install Visual C # 2005 Express and read on.High Level Features of Visual C # 2005 Express

Visual C # 2005 Express Offers Many of The Key Features You Would EXPECT To FIND IN A .NET Developments Environment, for Example:

An ANSI compliant C # 2.0 compiler A full-featured integrated debugger Advanced IntelliSense capabilities Design time support for Windows Forms development Support for local database access Extremely simple access to XML Web services

It is also important to understand what Visual C # 2005 Express Does Not Bring to the Table. Specification, Visual C # 2005 ExpRESS DOESN'T Directly Support:

ASP.NET Web Applications Construction of XML Web Services Mobile Application Development (Cell Phones, PDAs, Windows CE Devices) Remote Database Connection Tools

Within the pages that follow, you will be provided with an introduction of C # and the .net platform using Visual C # 2005 Express. Please be aware however that this article is not intended to be a comprehensive tutorial on the C # programming language, the .net Platform, or the Visual C # 2005 Express IDE. The Conclusion of this Article Provides Additional Links To .NET Web Sites To Further Your Learning Process.

Visual C # 2005 Express Projects

A Visual C # 2005 Express project is composed of any number of C # source code files (which take a * .cs file extension), supporting content files (XML documents, application icons, images, and so forth) and referenced assemblies (defined later in this article). Rather than forcing us to create the same boilerplate code for a specific type of project (Windows Forms application, Console application, and so forth), Visual C # 2005 Express provides a number of core project types, described in the following table .Visual C # 2005 Express Project TypeDefinitionWindows ApplicationCreates a new Windows Forms project. This type of project is used to create desktop application such as Microsoft Word.Class LibraryThis project is used to create a reusable code library (packaged as * .dll files), which CAN Be Used Across Your .NET Applications. Console Applicationthis Project Creates A Console Based Application. Thase Applications Are Very Useful When Learning A New Programming Language Such As C #, As Yo . U do not need to concern yourself with the construction of graphical user interfaces (GUIs) .Empty ProjectThis option generates a project with no initial C # code files This can be helpful when you wish to import existing files into a new project using the Project | Add existing Item Menu Item.

To begin Investigating C #, WE WILL CREATE A BRAND New Console Application Named MycsharPEXPRESSAPP. The File | New | Project Menu Selection Activates The New Project Dialog As Shown in Figure 1.

Figure 1. CREANG A New Console Application Project

At this Point, You May Wish To Save Using The File | Save All Menu Selection. From The Resulting Dialog Box, Specify A Location of Your Choosing, AS Shown in Figure 2.

Figure 2. Saving the current projectNote This first Console application will not provide much functionality, but will serve as a vehicle to examine some fundamental concepts. We will build a complete (and more interesting) application later in this article.

Assemblies, Namespaces, and Types

Before we get too far along in this first example, it is important to come to grips with some key terms of the .net programming trade. In my years of teaching software professionals, I can say with complete certainty that the distinction between an assembly, Namespace, And Type Consistently Confuses New .Net Developers. Let's Try to you.

When you build a project you are actually creating a .net assembly. Formally speaking, an assembly is a physical file (which typically take a * .exe or * .dll file extension) that you can directly view on your hard drive using the Windows Explorer.

The Visual C # 2005 Express Solution Explorer window displays a subfolder named References, which lists the set of assemblies used by the current project. While different projects tend to reference a unique set of assemblies, Figure 3 shows the assemblies for the current Console Application.

Figure 3. REFERENCED Assembly Project

As you are building more elaborate .net applications, you will often need to use assemblies beyond the set included by a particular project To do so, C # Express provides the Add Reference dialog box, which can be activated using the Project |. Add Reference dialog .......................

Figure 4. The C # Express Add Reference Dialog Box

An assembly contains a set of namespaces. Simply put, a namespace is nothing more than a collection of types that are semantically related. Understand that it is very common for a single assembly to contain multiple namespaces. For example, the mscorlib.dll assembly contains Namespaces for File Input and Output (System.io), Collection Types (System.collections), General Purpose Utility Types (System), And So On.note EVERY

.NET Application Automatically References Mscorlib.dll, Therefore you will never need to manually reference this core library.

.

.net TypeMeaning in LifeClassA class is a blueprint for an object. Like the blueprints to a house, a class can be used to create objects. Just like houses, the properties of each individual object can be totally different (blue vs red houses), but the blueprint will never change.InterfaceInterfaces define a set of common methods a class or interface may support. Interfaces allow you to define a set of members a class or structure must support. StructureSimply put, structures are lightweight class types. This type of type is ideal when modeling mathematical, geometric, or other fairly atomic data. Structures lack the object-oriented features of classes, such as inheritance.EnumerationEnumerations (or simply enums) are a named collection of name / value pairs. Enums allow you to define known VALUES for Use IN Your Program Down To Type Safe Function Pointers. There Types Are The Foundation Of The .NET Event Architecture. Regardless of if you are Handling A Button's Cl ick event or handing a post back to an ASP.NET Web page, delegates are the underlying plumbing.When a C # project needs to make use of types within a given assembly, the first step is to reference the * .dll using the Add Reference dialog as shown in Figure 4. The second step is to add a using directive at the top of the file to specify the namespace you wish to access. in reality, the C # using directive is nothing more a shorthand for specifying lengthy namespaces in your code ALLOWING US to Use Just File IN Our Code in Place of The Full Name System.IO.File. To Illustrate, Assume The Following Code:

Using system;

Namespace SomeProgram

{

Class Program

{

Static void main (string [] args)

{

// Create An ArrayList and Hashtable

// (The Hard Way) .system.collections.ArrayList A =

New system.collections.arraylist ();

System.collections.hashtable h =

NEW system.collections.hashtable ();

}

}

}

Here, we are creating an ArrayList and Hashtable type, both of which are within the System.Collections namespace Rather than prefixing the namespace to the type directly, you can save yourself some typing with the following using directive.:

Using system;

Using system.collections; // add this!

Namespace SomeProgram

{

Class Program

{

Static void main (string [] args)

{

// Create An ArrayList and Hashtable

// (The Easy Way).

ArrayList a = new arraylist ();

Hashtable h = new hashtable ();

}

}

}

As you may suspect, your major goal as a .net programmer is to become acquainted with the assemblies, namespaces, and types that you have at your disposal Thankfully, C # Express provides an integrated object browser utility that can be activated from the View. | Other Windows | Object Browser Menu Item. Using this Tool, You Can View The namespaces and types forin Each Reference Assembly, AS Shown in Figure 5.

Figure 5. The C # Express Object Browser

THEORY INTO PRACTICE: Using External Types

Now let's add some code to the MyCSharpExpressApp project. When you are building an application that needs to interact with the local file system, you need to use the System.IO namespace. By way of an example, update your file's using directives and enter the FOLLOWING CODE for Xin Your () Method:

#Region Using Directives

Using system;

Using system.collections.Generic;

Using system.text;

Using system.io; // NEED this for io type!

#ndregion

Namespace MycsharpexpressApp

{

Class Program

{

Static void main (string [] args)

{

// Open a file named myinfo.txt // located on the root c: / drive.

String myfilecontents;

MyFileContents = file.readall (@ "c: /myinfo.txt");

// Now print it to the console.

Console.writeline (MyFileContents);

Console.readline ();

}

}

}

This application makes use of the File.ReadAll () method to open the specified file and return the contents as a string. In this case, the contents of a file named myInfo.txt is displayed directly to the console. Assume this file has been Created with notepad.exe and this it Contains a Single Line of Text, AS Shown In Figure 6.

Figure 6. The MyInfo.txt File

Save this file Directly in your c Drive and Run the Application useing the debug | Start without debugging menu Option. IF All IWELL, You Should See The Output As Shown in Figure 7.

Figure 7. Your First C # Express Application

Note if this Example Does NOT WORK AS EXPECTED, Keep Reading. The next section Excenes How To Debug Runtime Exceptions Using Visual C # 2005 Express.

Now Assume you wish to display this information within a windows forms message box, rather Than the console. To do so you will need to:

Reference the System.Windows.Forms.dll assembly. Specify that you are 'using' the System.Windows.Forms namespace. Pass the string returned from File.ReadAll () to the MessageBox.Show () method.

First, Reference System.Windows.Forms.dll Using The Add References Dialog Box Shwon in Figure 8.

Figure 8. referencing the system.windows.forms.dll assembly

Next, Update your code as SO:

#Region Using Directives

Using system;

Using system.collections.Generic;

Using system.text;

Using system.io; // NEED this for io type!

Using System.windows.Forms; // NEED this for messagebox!

#ndregion

Namespace mycsharpexpressapp {

Class Program

{

Static void main (string [] args)

{

// Open a file named myinfo.txt

// located on the root c: / drive.

String myfilecontents;

MyFileContents = file.readall (@ "c: /myinfo.txt");

// this Time, Place In a Message Box.

Messagebox.show (MyFileContents);

Console.readline ();

}

}

}

Once You Run Your Application Again, You Will Find The Contents of Your File Displayed Withnin A Windows Forms Message Box Like Figure 9.

Figure 9. Interacting with the messagebox class type

Handing Exceptions with C # Express

The current example has made the rather large assumption that a file named myInfo.txt does indeed exist on the root C drive. If this is not the case, you will receive a runtime error (more formally termed, a runtime exception). Visual C # 2005 Express can help you diagnose such errors To illustrate, delete (or rename) the myInfo.txt file and debug your program using the Debug |. Start menu selection As you can see from Figure 10, you are provided with numerous details regarding the. Current Exception, As Well As Suggestions for Correcting The Issue.

Figure 10. Debugging Exceptions Using Visual C # 2005 Express

To FIX The Current Problem, Rename Your Text File To MyInfo.txt.

Handing the Exception Programmatically

Given that the presence of an external file is not discovered until your application is running, C # programmers make use of a technique termed structured exception handling. As you will see, structured exception handing involves the use of a small number of C # keywords (most importantly Try and catch).

When you are calling methods (such as the File.ReadAll () method) that may return a runtime exception, wrap the statements within a try scope. If an exception is triggered, the error is passed to a related catch scope, where you can . handle the problem gracefully If each statement in the try scope executes without error, the catch block is skipped completely To test this out firsthand, update your current code as so:. namespace MyCSharpExpressApp

{

Class Program

{

Static void main (string [] args)

{

// Attempt to open a file named myinfo.txt

// located on the root c: / drive.

String myfilecontents;

Try

{

MyFileContents = file.readall (@ "c: /myinfo.txt");

Messagebox.show (MyFileContents);

}

FilenotFoundException EX)

{

Console.writeline ("Error: {0}",

EXMESSAGE);

}

Console.readline ();

}

}

}

Here, WE Are Making Use of the Message Property of the FileNotFoundException Class To Format Our Error Message In The Case That The File 11.

Figure 11. Programmatically Handling The FileNotFoundException

So Much for this Initial Example Application. Now That You Have A Better Und'S CREATE A More Complex (AND Interesting) C # Application.

Creating a c # Class Library Project

Our next goal is to build a .net class library named ManagerSpeakLib.dll Begin by closing the current MyCSharpExpressApp project (using File | Close Project). And create a new Class Library project named ManagerSpeakLib, as shown in Figure 12. Notice that you are given the option of 'discarding' the MyCSharpExpressApp project if you have not saved it previously, allowing you to create quick test projects without cluttering your system with unnecessary code.Figure 12. Creating a new Class Library project

The role of this class (which we'll rename to ManagerSpeak) is to return a randomly generated phrase that mocks the chatter often found in the corporate world Update the ManagerSpeak class with a method named StateTheProblem ().:

#Region Using Directives

Using system;

Using system.collections.Generic;

Using system.text;

#ndregion

Namespace ManagerSpeaklib

{

Public Class ManagerSpeak

{

Public ManagerSpeak () {}

// this Method Returns a Randomly Selected Problem.

Public String StateTheproblem ()

{

String [] POSSIBLEPROBLEM = {

"I Think We Really need to Leverage ...",

"We can Emerge as a dominant force if we optimize ...",

"To Achieve An Effective Use of Synergy We Need to Consider ..."};

Random r = new random ();

Return PossibleProblem [R.Next (3)];

}

}

}

Here we are making use of the System.Random class to return one of the three statements in the local string array. The Next () method is used to obtain a random number, which in this case is between 0 and 2 (for a total Of Three Possiblilties: 0, 1, 2).

Of Course, Every Problem Needs A Solution. Theefore, Add Another Method To The ManagerSpeak Class Named getSolution ():

Public Class ManagerSpeak

{

...

// this method returns a randomly successd solution.public string getsolution ()

{

// String arrays with 10 segments each.

String [] list1 = {"integrated",

"Individualized", "Cooperative", "Flexible", "Authentic",

"Functional", "Responsive", "Alternative", "Performance",

"cognitive"};

String [] list2 = {"behavioral",

"Relevant", "Criteria", "Prescriptive", "Perceptual",

"Facilitated", "Modular", "Diagnostic", "Structure",

"situational"};

String [] List3 = {"Strategies",

"Methodologies", "Assessments", "Analysis", "Learning",

"Interaction", "Objectives", "Concepts", "Recoveries",

"management"}

// Make Use of a system.random type to TO

// Obtain a random string from each array.

Random r = new random ();

INT A = R.Next (10);

INT B = R.Next (10);

INT C = R.Next (10);

// Now create and return the statement.

String newmsg = list1 [a] "" list2 [b] "" List3 [C];

Return newmsg;

}

}

At this point, save your entire project (in a folder of your choice) using the File |.. Save All menu command Compile your new code library by activating the Build menu At this point, you should find your new code library located under the Bin / Release Subdirectory Shown in Figure 13.

Figure 13. The ManagerSpeaklib.dll Class Library

As you may know, * .dll assemblies can not be directly executed by double-clicking on them from the Windows Explorer. Rather, they are loaded by the runtime when another application requests them. Given this, our next step is to build an application that Uses managerspeaklib.dll.building a Windows forMs Application

The Application To Make Use of ManagerSpeaklib.dll Will Be a New Windows Forms Project Named ManagerSpeakClient (Figure 14).

Figure 14. Building a Windows Forms Application

Once The Project Has Loaded, You Will Notice That A Visual Form Designer Is Opened Automatic or SHOWN in Figure 15.

Figure 15. The Visual C # 2005 Express Form Designer

Visual C # 2005 Express supplies numerous tools that make the process of building graphical user interfaces (GUIs) a snap (all of which are accessible from the View menu). For example the Toolbox dialogue shown in Figure 16 displays numerous Windows Forms components that can be Used to build your form's user interface.

Figure 16. The Windows Forms Toolbox

ON A Related Note, The Properties Window Shown in Figure 17 Allows You To Configure The Currently Selected Widget (Form, Button, And So On) At Design Time.

Figure 17. The Properties WINDOW

Using these tools, create a simple user interface that consists of a Button and Label as shown in Figure 18. Note that I set the Text property (using the Properties window) of the Label, Form, and Button to fitting descriptions.

Figure 18. The Manager Client Form

Next we need to reference ManagerSpeakLib.dll using the Add References dialog (again, activated using the Project | Add Reference menu item). Be aware that when you wish to reference your own custom * .dlls, you will need to select the Browse tab And manually navigate to the location of the code library you wish to use, as shown Figure 19.figure 19. Referencing Your ManagerSpeaklib.dll Assembly

To Complete Our Windows Forms Application, Double Click On The Button Using The Formatical Handle The Click Event for the Button Type and Generate The Following Code:

Private void button1_click (Object Sender, Eventargs E)

{

}

At this Point You are free to add the code to manipulate the managerspeak class. Here is The Complete Code Update (NOTICE THE C. Using Directive for ManagerSpeaklib).

#Region Using Directives

Using system;

Using system.collections.Generic;

Using system.componentmodel;

Using system.data;

Using system.drawing;

Using system.windows.forms;

Using managerspeaklib; // NEED THIS!

#ndregion

Namespace ManagerSpeakClient

{

Partial Class Form1: Form

{

Public Form1 ()

{

InitializationComponent ();

}

Private void button1_click (Object Sender, Eventargs E)

{

// Make a manager.

Managerspeak m = new managerspeak ();

// Get the problem.

String currentproblem = m.statetheproblem ();

// Get the Solution.

String solution = m.getsolution ();

// Show the details!

Messagebox.show (String.Format ("{0} / n {1}",

CurrentPROBLEM, SOLUTION));

}

}

}

Now run your Windows Forms application and click the Button. You will find a randomly generated problem / solution, shown in Figure 20, in the very distinct (and generally annoying) dialect of 'manger-speak'.

Figure 20. Behold, Manager-Speak! This Wraps Up Our Windows Forms Application. Fell Free to Save this Project On Your Machine Using The File | Save All Menu Option.

Go Forth and Code: Visual C # 2005 Express Starter Kits

At this point you have created three different C # Express projects (a Console program, a Class Library, and a Windows Forms Application). While this introductory article did not cover all aspects of the C # language (or the full functionality of Visual C # 2005 Express ), I do hope you are in a good position for further expemblation.

To wrap up this article, I leave you with the topic of starter kits. Simply put, a starter kit is a complete C # application that intends to illustrate numerous programming concepts. Moreover, starter kits provide full documentation, code walkthroughs, and suggestions for extending the out-of-the-box functionality One default starter kit is the Screen Saver Starter Kit, which can be selected from the New Project dialog box shown in Figure 21. You can launch the kit using the File |. New | Project .. Menu selection.

Figure 21. Selecting The Screen Saver Starter Kit

Once you have selected the Screen Saver project and clicked the OK button, the starter kit's documentation file (ScreenSaverStarterKit.htm), shown in Figure 22, is loaded by the IDE. Here you can learn about the basic composition of the project at hand.

Figure 22. Reading Up on the screen saver starter kit

As you can see, this starter kit provides details of each code file, as well as a step-by-step walkthrough of the project's design. You can run the application by pressing the F5 key. If you are connected to the Internet, you Will Be Able To View RSS (Really Simple Syndication) Feeds Presented on Top of A Rotating Set of Background images.summary

Visual C # 2005 Express is an ideal entry point for newcomers to the .net platform. As you have seen in this article, the IDE provides a set of project types, a graphical debugger, and numerous Windows Forms designers. While this article did not offer A Complete Tour of the IDE, You Are Hopefully More Comfortable Navigating Around your Active Projects.

The bulk of this article was spent introducing some core terms in the .net universe. Recall that assemblies are binary files that contain any number of namespaces. A namespace in turn defines any number of types (classes, interfaces, structures, enumerations, and delegates ). NESE TYPES, .NET Programmers Are Able To Build ANY Sort of Application.

Hopefully, this Article Has Stirred Up Some Interest in Checking Out C # and the .NET Platform in Further Detail. If You Require Additional Information Regarding C #, You May wish To Consult the Following Links:

Sharp New Language: C # Offers The Power of C and Simplicity of Visual Basic C # programming Language Future Features The GotdotNet Web Site

转载请注明原文地址:https://www.9cbs.com/read-119044.html

New Post(0)