Introduction to programming using Microsoft Visual C # 2005 Express Edition

xiaoxiao2021-03-06  52

Release Date: 9/9/2004

| Update Date: 9/9/2004

Andrew W. TroelsenIntertech training

Summary: This article describes how to program the C # language using Microsoft Visual C # 2005 Express Edition integration development environment (IDE). In this paper, the main concepts of several aspects and .NET platforms are introduced to the readers through various example projects.

Download the code.msi sample file.

Note This article assumes that the reader is interested in exploring the C # language and .NET platform of the C # language and .NET platform, a student or a personal person with a programming idea. Do not require you to have always contacted C #, but some of the previous programming experience will help.

Applicable to: Microsoft Visual C # 2005 Express Edition

This page

What is Visual C # 2005 Express Edition? Visual C # 2005 Express's Advanced Functions Visual C # 2005 Express project assembly, namespace, and type From theory to practice: Use external type by c # express processing exception By programming an exception creation C # class library project to build a Windows Form application start Postal Code: Visual C # 2005 Express Starter Pack

What is Visual C # 2005 Express Edition?

.NET applications can be created in a variety of ways. Stubborn Developers can build a .NET program with a strike method using a streamlined text editor (eg, NotePad.exe), and CSC.exe) to build .NET programs. Although .NET Software Development Kit (SDK) can download from the Microsoft site (www.microsoft.com/net), this method brings a lot of trouble because it does not provide code generation utility (wizard) in the SDK. , Graphic debugger and intelliSense feature.

To help reduce the burden of the command line build software, many .NET developers use visual tools, such as Microsoft Funny IDE and Visual Studio .NET 2003 (http://msdn.microsoft.com/vstudio). Although the function of this product is very powerful, the company's price is too high for .NET amateur enthusiasts and / or college students. Honestly, unless you are a professional software engineer, the large number of options provided by Visual Studio .NET 2003 usually makes your learning process complicates without any help.

Between NOTEPAD.EXE and Visual Studio .Net 2003 software features are the latest IDE of Microsoft, which is Visual C # 2005 Express Edition. When writing this article, the test version of Visual C # 2005 Express Edition has been provided free of charge via Web Download (http://msdn.microsoft.com/express). Since Visual C # 2005 Express is relatively small, it can be easily obtained even if you use a 56K modem connection.

Visual C # 2005 Express is actually one of several members of the Express family. Specifically, Microsoft provides the following Express Edition products:

• Visual Web Developer 2005 Express: a lightweight tool for building a dynamic web site and an XML web service using ASP.NET. • Visual Basic 2005 Express: An ideal simplified programming tool for primary programmers learning how to build a Windows application. • Visual C # 2005 Express, Visual C 2005 Express and Visual J # 2005 Express: Target programming tools for students who wish to learn basic knowledge of computer science. • SQL Server 2005 Express: An entry-level database management system for amateurs, enthusiasts and student developers. Simply put, the Express Edition product line is an intention of hobbies, students and novices to understand the ideal entry tools for the .NET platform. If you belong to one of them, download and install Visual C # 2005 Express, then continue reading this article.

Back to top

Visual C # 2005 EXPRESS Advanced Features

Visual C # 2005 Express provides a number of key features you need in the .NET development environment, for example:

• Compatible with ANSI compatible C # 2.0 compiler • Fully complete integrated debugger • Advanced IntelliSense features • Support for Design for Windows Forms • Support local database access • Visit XML Web services very easy

You also need to understand the features that Visual C # 2005 Express does not support. Specifically, Visual C # 2005 Express does not directly support the following features:

• ASP.NET Web Applications • Structure of XML Web Services • Mobile App Development (Mobile Phone, PDA, Windows CE Device) • Remote Database Connection Tool

In the following, we will introduce you to the C # and .NET platform using Visual C # 2005 Express. However, please note that this article is not a comprehensive tutorial for C # programming languages, .NET platforms, or Visual C # 2005 Express IDE. This article provides additional links to the .NET Web site to further enhance your learning process.

Back to top

Visual C # 2005 Express Project

Visual C # 2005 Express item consists of any number of C # source code files (using * .cs file extensions), it supports content files (XML documents, application icons, images, etc.) and referenced assemblies (detailed later in this article ). Visual C # 2005 Express provides a number of core project types (described in the following table), rather than forced us to create the same formula for specific types of items (Windows Form Applications, Console Applications, etc.).

Visual C # 2005 Express Project Type Defines Windows Applications Create a new Windows Forms. Such items are used to create desktop applications such as Microsoft Word. Class Library This item is used to create reused code bases (packaged * .dll files), which can be used across your .NET application. Console Application This project can create a console-based application. These applications are useful when learning new programming languages ​​(for example, C #), because you do not need to consider the structure of the graphical user interface (GUI). Empty Project This option can generate items that do not have an initial C # code file. This option is useful when you want to use the Project | Add EXISTING ITEM menu item to import an existing file into a new project. In order to start studying C #, we will create a new console application called MycsharPexPressApp. File | New | Project Menu Select You can activate a new project dialog as shown in Figure 1.

Figure 1. Creating a new console application project

At this point, you may want to save it using the FILE | SAVE menu selection. In the obtained dialog, specify the location you selected, as shown in Figure 2.

Figure 2. Save the current project

Note The first console application will not provide a lot of features, it is just a tool for checking some basic concepts. Before this article, we will build a complete (and more interesting) application.

Back to top

Jacks, namespaces and types

Before we study the first example, you need to understand some of the key terms in .NET programming. In a few years, I can affirm that the difference between the assembly, namespace and types is always confused. NET developers. We try not to let this happen to you.

When you build an item, you are actually created .NET assembly. From the form, the assembly is a physical file (its file extension is usually * .exe or * .dll), you can use Windows Explorer to view this file directly on your hard drive.

Visual C # 2005 Express Solution The browser window will display a subfolder called References, which lists the collection of assemblies used by the current project. However, different projects need to reference a set of unique assemblies, Figure 3 shows the assembly of the current console application.

Figure 3. Console application project referenced

With the build increasingly fine .NET application, you usually need to use assemblies other than the collection included in a particular project. To do this, C # Express provides the Add Reference dialog that can be activated using the Project | Add Reference dialog. At this point, you don't have to add additional assemblies. Figure 4 shows the above dialog.

Figure 4. C # Express "Add Reference" dialog

The assembly contains a set of namespaces. Simply put, namespace is a collection of types related to semantics. You have to know that a single assembly usually contains multiple namespaces. For example, the mscorlib.dll assembly contains namespaces that contain file inputs and output (System.IO), Group Type (System.Collections), General Utility Tool Type (System), and the like.

Note Each .NET application automatically references Mscorlib.dll, so you don't need to manually reference the core library.

Namespaces can define any number of types. For .NET 2.0, the next table briefly (keyword is briefly) describes 5 types.

.NET type Basic meaning Class class is a design diagram of an object. Like the design of the house, the class can be used to create an object. Like the house, the properties of each independent object can be completely different (for example, blue houses and red houses), but the design drawings will not change. The Interface interface can define a set of public methods supported by the class or interface. The interface allows you to define a group of members that must be supported by the class or structure. Structure briefly, the structure is a light type type. This type is ideal when modeling mathematics, geometric or other atomic data. The structure lacks the object-oriented function of the class, for example, inherits. Enumeration Enumeration (English Micro ENUMS) is the named collection of names / values. Enumerates you can define the known values ​​used in the program. Delegate commissioned to the type of security function pointer. These types are the foundation of the .NET event architecture. Whether you are a CLICK event of a handle button or a return of the ASP.NET web page, delegate is an infrastructure. When a C # project needs to use the type in a given assembly, the first step is to reference * .dll, as shown in Figure 4. The second step is to add a USING instruction at the beginning of the file to specify the namespace you want to access. In fact, the C # Using instruction is just an abbreviation for specifying a longer namespace in the code, which allows us to use only file in the code instead of the full name System.IO.File. For the proof, you can 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 have to create ArrayList and HashTable types, which are all in the System.Collections namespace. Use the following using instructions, you can type some content without having to place the namespace directly in front:

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 guess, as a .NET programmer, your main purpose is to familiarize yourself with the assembly, namespace, and type used. Fortunately, C # Express provides an integrated object browser utility that can be activated from View | Other Windows | Object Browser menu items. With this tool, you can see the namespaces and types in each reference set, as shown in Figure 5.

Figure 5. C # Express object browser

Back to top

From theory to practice: use external types

Now let's add some code to the MycsharPexpressApp project. When building an application that needs to interact with the local file system, you need to use System.io namespace. With an example, update your file's USING instruction and enter the following code in the Main () 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 ();

}

}

}

The application uses the file.readall () method to open the specified file and return content in the form of a string. In this case, the contents of the files named myinfo.txt will be displayed directly in the console. Assume that the file is created using NOTEPAD.exe and it contains only one line of line, as shown in Figure 6.

Figure 6. Myinfo.txt file

Save the file directly in the C drive and run the app with the debug | Start WITHOUT DEBUGGING menu option. If everything is normal, you should see the output shown in Figure 7.

Figure 7. Your first C # Express application

Note If this example does not run in an expected manner, please read it. The next section illustrates how to use Visual C # 2005 Express debugging runtime exception.

Now, assume that you want to display this information in the Windows Form Message box (not the console). To do this, you need to do the following:

• Quote System.Windows.Forms.dll assembly. • Specify you want to use the System.Windows.Forms namespace. • Pass the string returned from File.Readall () to the MessageBox.show () method.

First, use System.Windows.Forms.dll using the Add References dialog box shown in Figure 8.

Figure 8. Quote System.Windows.Forms.dll assembly

Then, update the code as follows:

#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 the application again, you will find that the file content displayed in the Windows Form Message box is similar to the content in Figure 9.

Figure 9. Interaction with the MessageBox class type

Back to top

Treatment through C # Express

The current example is bold to assume that files named myinfo.txt exist on root drive C. If there is no existence, you will receive a runtime error (more officially speaking, it is an abnormality). Visual C # 2005 Express can help you diagnose such errors. To delete (or rename) myinfo.txt files, then use the debug | Start menu to debug your program. As you can see in Figure 10, the system provides you with a lot of detailed information about current exceptions, as well as recommendations for correcting the issue.

Figure 10. Using Visual C # 2005 Express Commissioning Expellence

To fix the current problem, rename your text file as MyInfo.txt.

Back to top

Handling exception by programming

Assuming that there is an external file until your application is running, then the C # programmer can use technologies called structured abnormal processing. You will see that structural exception handling involves using a small amount of C # keywords (the most important thing is TRY and CATCH).

When you want to call a method of running an exception (for example, a file.readall () method, you should package the statement into the TRY scope. If an exception is triggered, the error will be passed to the related Catch scope, and you can properly handle this problem in this scope. If each statement in the TRY scope does not have an error, the entire Catch block will be skipped. To test directly, update your current code as follows:

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 used the Message property of the FilenotFoundException class to format the error message to prevent file loss, as shown in Figure 11.

Figure 11. Processing FileNotFoundException by programming

Description of this initial sample application is here. Now, you have a better understanding of basic knowledge, let us create a more complex (and more interesting) C # app.

Back to top

Create a C # class library project

Our next goal is to build a .NET class library called ManagerSpeaklib.dll. First, turn off the current MycsharPexpressApp project (using file | close project), then create a new class library item called ManagerSpeaklib, as shown in Figure 12. Please note that if you have not saved the MycsharPexpressApp project, you will display an option to "Abandon" the project to enable you to create a quick test item while avoiding the use of useless code to disturb your system.

Figure 12. Creating a new class library project

The role of this class (we rename it is managerspeak) will return randomly generated phrases that mimensize internal chat. Update the ManagerSpeak class using a method called 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 use the System.random class to return one of the three statements in the local string array. Next () method is used to obtain random number, in this case, the number between 0 and 2 (there are three possibilities: 0, 1, 2).

Of course, each problem requires a solution. Therefore, add another method to the ManagerSpeak class named getSolution ():

Public Class ManagerSpeak

{

...

// this Method Returns a Randomly Selected 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, use the File | Save All menu command to save the entire project (in the folder you selected). By activating the build menu to compile your new code base. At this point, you should find that the new code library is located in the bin / release subdirectory, as shown in Figure 13.

Figure 13. ManagerSpeaklib.dll class library

You may know, *. DLL assembly cannot be performed directly by double-clicking on them from Windows Explorer, but when other applications reques them, they are loaded by the run. This way, our next step is to build applications using ManagerSpeaklib.dll.

Back to top

Build a Windows Form Application

To use ManagerSpeaklib.dll, the application will be a new Windows Formwork, named ManagerSpeakClient (Figure 14).

Figure 14. Building a Windows Form Application

Once the project is loaded, you will notice that the visual form designer will open automatically, as shown in Figure 15.

Figure 15. Visual C # 2005 Express Form Designer

Visual C # 2005 Express provides a large number of tools that allow you to quickly build a graphical user interface (GUI) (all interfaces can be accessed from View menu). For example, the "Toolbox" dialog box shown in Figure 16 displays a large number of Windows form components that can be used to build the form user interface.

Figure 16. Windows Form Toolbox

According to the description, the Properties window shown in Figure 17 enables you to configure the currently selected widget (form, buttons, etc.) when designing.

Figure 17. "Properties" window

Use these tools to create a simple user interface consisting of a button and tag, as shown in Figure 18. Note that in order to comply with the instructions, I set the Text property of the label, form, and buttons (using the Properties window). Figure 18. Manager Client Form

Next, we need to use the Add References dialog (re-use the Project | Add Reference menu item to activate) to reference ManagerSpeaklib.dll. Note that if you want to reference your own custom * .dll, you need to select the Browse tab and manually navigate to the location of the code base to use, as shown in Figure 19.

Figure 19. Quote ManagerSpeaklib.dll assembly

To complete our Windows Form Application, double-click the button using the Form Designer. This will automatically process the click type Click event and generate the following code:

Private void button1_click (Object Sender, Eventargs E)

{

}

At this point, you can add code to the ManagerSpeak class. Here is a complete code update (Note the C # Using Directive of 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 Form Application and click the button. You will see randomly generated issues, as shown in Figure 20, which is expressed in a very unique (usually annoying "tone.

Figure 20. Note that the manager is speaking!

This packs our Windows Form Application. You can use the File | Save All menu option to save the item on your computer at any time.

Back to top

Start Code: Visual C # 2005 Express Starter Pack

At this point, you have created three different C # Express items (a console program, a class library, and a Windows Form Application). Although this introductory article cannot cover all aspects of the C # language (or Visual C # 2005 Express's full feature), I hope this article will help you better explore in the future. In order to summarize this article, I have a starting toolkit topic. Simply put, the starting kit is a complete C # application designed to explain a lot of programming concepts. In addition, the starting kits also provide full documentation, code drills, and recommendations for extended additional features. One of the default starting kits is the Screen Saver Start Kit, which you can select it from the New Project dialog box shown in Figure 21. You can use the File | New | Project ... menu selection to start the toolkit.

Figure 21. Selecting the Screen Saver Start Kit

Once you have selected the Screen Saver project and click the OK button, the IDE will load the document file (ScreensAverStarterkit.htm) of the starting kit, as shown in Figure 22. Here you can learn about the basic content of the current project.

Figure 22. Understanding the Screen Saver Starter Kit

As you can see, the starting kit provides detailed information for each code file, as well as the step-by-step drill of the project design. You can run the application by pressing the F5 key. If you are connected to the Internet, you can see the RSS (truly simple combination) news headline displayed on a set of rotating background images.

Back to top

summary

Visual C # 2005 Express is an ideal entry point for a newbie .NET platform. As you can see in this article, IDE can provide a set of project types, a graphical debugger, and a large number of Windows Form Designer. Although this article does not provide a complete IDE introduction, you may be more accustomed to browsing event projects.

Most of this article is some of the core terms in the .NET field. Recall now, the assembly is a binary file containing any number of namespaces. Namespaces can define any number of types (classes, interfaces, structures, enumerations, and delegate). Use these types, .NET programmers can build a variety of applications.

I hope this article can inspire you to learn more about the interest of the C # and .NET platforms. If you need additional information about C #, you may need to access the following link:

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

Andrew Troelsen is an advisor and trainer of Intertech Training. Andrew is a lot of books, including winning C # and the .NET Platform Second Edition (APRESS Press, 2002). He also wrote an article for all layouts of MacTech monthly columns. In this column, he explored how to develop .NET on UNIX based systems using SSCLI, Portible.Net and Mono CLI distribution software.

Go to the original English page

Back to top

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

New Post(0)