Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Pro CSharp 2008 And The .NET 3.5 Platform [eng]

.pdf
Скачиваний:
71
Добавлен:
16.08.2013
Размер:
22.5 Mб
Скачать

32 CHAPTER 1 THE PHILOSOPHY OF .NET

However, if you deploy an assembly to a computer that does not have .NET installed, it will fail to run. For this reason, Microsoft provides a setup package named dotnetfx3setup.exe that can be freely shipped and installed along with your .NET software. This installation program can be freely downloaded from Microsoft from their .NET download area (http://msdn.microsoft.com/ netframework). Once dotNetFx35setup.exe is installed, the target machine will now contain the

.NET base class libraries, .NET runtime (mscoree.dll), and additional .NET infrastructure (such as the GAC).

Note The Vista operating system is preconfigured with the necessary .NET runtime infrastructure. However, if you are deploying your application to Windows XP or Windows Server 2003, you will want to ensure the target machine has the .NET runtime environment installed and configured.

The Platform-Independent Nature of .NET

To close this chapter, allow me to briefly comment on the platform-independent nature of the .NET platform. To the surprise of most developers, .NET assemblies can be developed and executed on non-Microsoft operating systems (Mac OS X, numerous Linux distributions, and Solaris, to name a few). To understand how this is possible, you need to come to terms with yet another abbreviation in the .NET universe: CLI (Common Language Infrastructure).

When Microsoft released the C# programming language and the .NET platform, they also crafted a set of formal documents that described the syntax and semantics of the C# and CIL languages, the .NET assembly format, core .NET namespaces, and the mechanics of a hypothetical

.NET runtime engine (known as the Virtual Execution System, or VES).

Better yet, these documents have been submitted to (and ratified by) ECMA International as official international standards (http://www.ecma-international.org). The specifications of interest are

ECMA-334: The C# Language Specification

ECMA-335: The Common Language Infrastructure (CLI)

The importance of these documents becomes clear when you understand that they enable third parties to build distributions of the .NET platform for any number of operating systems and/or processors. ECMA-335 is perhaps the more “meaty” of the two specifications, so much so that is has been broken into various partitions, including those shown in Table 1-4.

Table 1-4. Partitions of the CLI

Partitions of ECMA-335

Meaning in Life

Partition I: Architecture

Describes the overall architecture of the CLI, including the rules of the

 

CTS and CLS, and the mechanics of the .NET runtime engine

Partition II: Metadata

Describes the details of .NET metadata

Partition III: CIL

Describes the syntax and semantics of CIL code

Partition IV: Libraries

Gives a high-level overview of the minimal and complete class libraries

 

that must be supported by a .NET distribution.

Partition V: Annexes

Provides a collection of “odds and ends” details such as class library

 

design guidelines and the implementation details of a CIL compiler

 

 

CHAPTER 1 THE PHILOSOPHY OF .NET

33

Be aware that Partition IV (Libraries) defines only a minimal set of namespaces that represent the core services expected by a CLI distribution (collections, console I/O, file I/O, threading, reflection, network access, core security needs, XML manipulation, and so forth). The CLI does not define namespaces that facilitate web development (ASP.NET), database access (ADO.NET), or desktop graphical user interface (GUI) application development (Windows Forms/Windows Presentation Foundation).

The good news, however, is that the mainstream .NET distributions extend the CLI libraries with Microsoft-compatible equivalents of ASP.NET, ADO.NET, and Windows Forms in order to provide full-featured, production-level development platforms. To date, there are two major implementations of the CLI (beyond Microsoft’s Windows-specific offering). Although this text focuses on the creation of .NET applications using Microsoft’s .NET distribution, Table 1-5 provides information regarding the Mono and Portable .NET projects.

Table 1-5. Open Source .NET Distributions

Distribution

Meaning in Life

http://www.mono-project.com

The Mono project is an open source distribution of the CLI that

 

targets various Linux distributions (e.g., SuSE, Fedora, and so on)

 

as well as Win32 and Mac OS X.

http://www.dotgnu.org

Portable.NET is another open source distribution of the CLI that

 

runs on numerous operating systems. Portable.NET aims to

 

target as many operating systems as possible (Win32, AIX, BeOS,

 

Mac OS X, Solaris, all major Linux distributions, and so on).

 

 

Both Mono and Portable.NET provide an ECMA-compliant C# compiler, .NET runtime engine, code samples, documentation, as well as numerous development tools that are functionally equivalent to the tools that ship with Microsoft’s .NET Framework 3.5 SDK. Furthermore, Mono and Portable.NET collectively ship with a VB .NET, Java, and C complier.

Note Coverage of creating cross-platform .NET applications using Mono can be found in Appendix B.

Summary

The point of this chapter was to lay out the conceptual framework necessary for the remainder of this book. I began by examining a number of limitations and complexities found within the technologies prior to .NET, and followed up with an overview of how .NET and C# attempt to simplify the current state of affairs.

.NET basically boils down to a runtime execution engine (mscoree.dll) and base class library (mscorlib.dll and associates). The common language runtime (CLR) is able to host any .NET binary (a.k.a. assembly) that abides by the rules of managed code. As you have seen, assemblies contain CIL instructions (in addition to type metadata and the assembly manifest) that are compiled to platform-specific instructions using a just-in-time (JIT) compiler. In addition, you explored the role of the Common Language Specification (CLS) and Common Type System (CTS).

This was followed by an examination of the ildasm.exe and reflector.exe object browsing utilities, as well as coverage of how to configure a machine to host .NET applications using dotnetfx3setup.exe. I wrapped up by briefly addressing the platform-independent nature of C# and the .NET platform, a topic further examined in Appendix B.

C H A P T E R 2

Building C# Applications

As a C# programmer, you may choose among numerous tools to build .NET applications. The point of this chapter is to provide a tour of various .NET development options, including, of course, Visual Studio 2008. The chapter opens, however, with an examination of working with the C# command-line compiler, csc.exe, and the simplest of all text editors, the Notepad application

that ships with the Microsoft Windows OS.

Once you become comfortable compiling assemblies “IDE-free,” you will then examine various lightweight editors (such as TextPad and Notepad++) that allow you to author C# source code files and interact with the compiler in a slightly more sophisticated manner.

While you could work through this entire text using nothing other than csc.exe and a basic text editor, I’d bet you are also interested in working with feature-rich integrated development environments (IDEs). To this end, you will be introduced to a free, open source .NET IDE named SharpDevelop. This IDE rivals the functionality of many commercial .NET development environments. After briefly examining the Visual C# 2008 Express IDE (which is also free), you will be given a guided tour of the key features of Visual Studio 2008. This chapter wraps up with a quick tour of a number of complementary .NET development tools (again, many of which are open source) and describes where to obtain them.

Note Over the course of this chapter, you will see a number of C# programming constructs we have not formally examined. If you are unfamiliar with the syntax, don’t fret. Chapter 3 will formally begin your examination of the C# language.

The Role of the .NET Framework 3.5 SDK

One common misconception regarding .NET development is the belief that programmers must purchase a copy of Visual Studio in order to build their C# applications. The truth of the matter is that you are able to build any sort of .NET program using the freely downloadable .NET Framework 3.5 Software Development Kit (SDK). This SDK provides you with numerous managed compilers, command-line utilities, white papers, sample code, the .NET class libraries, and a complete documentation system.

Note The .NET Framework 3.5 SDK (dotNetFx35setup.exe) can be obtained from the .NET download website (http://msdn.microsoft.com/netframework).

35

36 CHAPTER 2 BUILDING C# APPLICATIONS

If you are indeed going to be using Visual Studio 2008 or Visual C# 2008 Express, you have no need to manually install the .NET Framework 3.5 SDK. When you install either of these products, the SDK is installed automatically, thereby giving you everything you need out of the box. However, if you are not going to be using a Microsoft IDE as you work through this text, be sure to install the SDK before proceeding.

The Visual Studio 2008 Command Prompt

When you install the .NET Framework 3.5 SDK, Visual Studio 2008, or Visual C# 2008 Express, you will end up with a number of new directories on your local hard drive, each of which contains various .NET development tools. Many of these tools are driven from the command prompt, so if you wish to use these utilities from any Windows command window, you will need to register these paths with the operating system.

While you could update your PATH variable manually to do so, you can save yourself some time by simply making use of the Visual Studio 2008 Command Prompt that is accessible from the StartPrograms Visual Studio 2008 Visual Studio Tools folder (see Figure 2-1).

Figure 2-1. The Visual Studio 2008 command prompt

The benefit of using this particular command prompt is that it has been preconfigured to provide access to each of the .NET development tools. Assuming you have a .NET development environment installed, type the following command and press the Enter key:

csc -?

If all is well, you should see a list of command-line arguments of the C# command-line compiler (where csc stands for the C-sharp compiler).

Building C# Applications Using csc.exe

While it is true that you may never decide to build a large-scale application using the C# commandline compiler, it is important to understand the basics of how to compile your code files by hand. I can think of a few reasons you should get a grip on the process:

The most obvious reason is the simple fact that you might not have a copy of Visual Studio 2008.

You may be in a university setting where you are prohibited from using code generation tools/IDEs in the classroom.

You plan to make use of automated build tools such as MSBuild or NAnt, which require you to know the command-line options of the tools you are utilizing.

CHAPTER 2 BUILDING C# APPLICATIONS

37

You want to deepen your understanding of C#. When you use graphical IDEs to build applications, you are ultimately instructing csc.exe how to manipulate your C# input files. In this light, it’s edifying to see what takes place behind the scenes.

Another nice by-product of working with csc.exe in the raw is that you become that much more comfortable manipulating other command-line tools included with the .NET Framework 3.5 SDK. As you will see throughout this book, a number of important utilities are accessible only from the command line.

To illustrate how to build a .NET application IDE-free, we will build a simple executable assembly named TestApp.exe using the C# command-line compiler and Notepad. First, you need some source code. Open Notepad (using the Start Programs Accessories menu option) and enter the following trivial C# code:

// A simple C# application. using System;

class TestApp

{

static void Main()

{

Console.WriteLine("Testing! 1, 2, 3");

}

}

Once you have finished, save the file in a convenient location (e.g., C:\CscExample) as TestApp.cs. Now, let’s get to know the core options of the C# compiler.

Note As a convention, all C# code files take a *.cs file extension. The name of the file does not need to have any mapping to the name of the type (or types) it is defining.

Specifying Input and Output Targets

The first point of interest is to understand how to specify the name and type of assembly to create (e.g., a console application named MyShell.exe, a code library named MathLib.dll, a Windows Forms application named Halo8.exe, and so forth). Each possibility is represented by a specific flag passed into csc.exe as a command-line parameter (see Table 2-1).

Table 2-1. Output Options of the C# Compiler

Option

Meaning in Life

/out

This option is used to specify the name of the assembly to be created. By

 

default, the assembly name is the same as the name of the initial input *.cs

 

file.

/target:exe

This option builds an executable console application. This is the default

 

assembly output type, and thus may be omitted when building this type of

 

application.

/target:library

This option builds a single-file *.dll assembly.

/target:module

This option builds a module. Modules are elements of multifile assemblies

 

(fully described in Chapter 15).

/target:winexe

Although you are free to build graphical user interface–based applications

 

using the /target:exe option, /target:winexe prevents a console window

 

from appearing in the background.

 

 

38 CHAPTER 2 BUILDING C# APPLICATIONS

Note The options sent to the command-line compiler (as well as most other command-line tools) can be prefixed with either a dash (-?) or a slash (/?).

To compile TestApp.cs into a console application named TestApp.exe, change to the directory containing your source code file:

cd C:\CscExample

and enter the following command set (note that command-line flags must come before the name of the input files, not after):

csc /target:exe TestApp.cs

Here I did not explicitly specify an /out flag, therefore the executable will be named TestApp.exe, given that TestApp is the name of the input file. Also be aware that most of the C# compiler flags support an abbreviated version, such as /t rather than /target (you can view all abbreviations by entering csc -? at the command prompt).

csc /t:exe TestApp.cs

Furthermore, given that the /t:exe flag is the default output used by the C# compiler, you could also compile TestApp.cs simply by typing

csc TestApp.cs

TestApp.exe can now be run from the command line as shown in Figure 2-2.

Figure 2-2. TestApp.exe in action

Referencing External Assemblies

Next, let’s examine how to compile an application that makes use of types defined in a separate

.NET assembly. Speaking of which, just in case you are wondering how the C# compiler understood your reference to the System.Console type, recall from Chapter 1 that mscorlib.dll is automatically referenced during the compilation process (if for some strange reason you wish to disable this behavior, you may specify the /nostdlib option of csc.exe).

Let’s update the TestApp application to display a Windows Forms message box. Open your TestApp.cs file and modify it as follows:

using System;

// Add this!

using System.Windows.Forms;

class TestApp

{

CHAPTER 2 BUILDING C# APPLICATIONS

39

static void Main()

{

Console.WriteLine("Testing! 1, 2, 3");

// Add this!

MessageBox.Show("Hello...");

}

}

Notice you are importing the System.Windows.Forms namespace via the C# using keyword (introduced in Chapter 1). Recall that when you explicitly list the namespaces used within a given *.cs file, you avoid the need to make use of fully qualified names of a type (which can lead to hand cramps).

At the command line, you must inform csc.exe which assembly contains the namespaces you are using. Given that you have made use of the System.Windows.Forms.MessageBox class, you must specify the System.Windows.Forms.dll assembly using the /reference flag (which can be abbreviated to /r):

csc /r:System.Windows.Forms.dll TestApp.cs

If you now rerun your application, you should see what appears in Figure 2-3 in addition to the console output.

Figure 2-3. Your first Windows Forms application

Referencing Multiple External Assemblies

On a related note, what if you need to reference numerous external assemblies using csc.exe? Simply list each assembly using a semicolon-delimited list. You don’t need to specify multiple external assemblies for the current example, but some sample usage follows:

csc /r:System.Windows.Forms.dll;System.Drawing.dll *.cs

Compiling Multiple Source Files

The current incarnation of the TestApp.exe application was created using a single *.cs source code file. While it is perfectly permissible to have all of your .NET types defined in a single *.cs file, most projects are composed of multiple *.cs files to keep your code base a bit more flexible. Assume you have authored an additional class contained in a new file named HelloMsg.cs:

// The HelloMessage class using System;

using System.Windows.Forms;

class HelloMessage

{

40 CHAPTER 2 BUILDING C# APPLICATIONS

public void Speak()

{

MessageBox.Show("Hello...");

}

}

Now, update your initial TestApp class to make use of this new class type, and comment out the previous Windows Forms logic:

using System;

//Don't need this anymore.

//using System.Windows.Forms;

class TestApp

{

static void Main()

{

Console.WriteLine("Testing! 1, 2, 3");

//Don't need this anymore either.

//MessageBox.Show("Hello...");

//Use the HelloMessage class!

HelloMessage h = new HelloMessage(); h.Speak();

}

}

You can compile your C# files by listing each input file explicitly:

csc /r:System.Windows.Forms.dll TestApp.cs HelloMsg.cs

As an alternative, the C# compiler allows you to make use of the wildcard character (*) to inform csc.exe to include all *.cs files contained in the project directory as part of the current build:

csc /r:System.Windows.Forms.dll *.cs

When you run the program again, the output is identical. The only difference between the two applications is the fact that the current logic has been split among multiple files.

Working with C# Response Files

As you might guess, if you were to build a complex C# application at the command prompt, you would have to specify a tedious number of input options to inform the compiler how to process your source code. To help lessen your typing burden, the C# compiler honors the use of response files.

C# response files contain all the instructions to be used during the compilation of your current build. By convention, these files end in a *.rsp (response) extension. Assume that you have created a response file named TestApp.rsp that contains the following options (as you can see, comments are denoted with the # character):

#This is the response file

#for the TestApp.exe example

#of Chapter 2.

CHAPTER 2 BUILDING C# APPLICATIONS

41

#External assembly references.

/r:System.Windows.Forms.dll

#output and files to compile (using wildcard syntax).

/target:exe /out:TestApp.exe *.cs

Now, assuming this file is saved in the same directory as the C# source code files to be compiled, you are able to build your entire application as follows (note the use of the @ symbol):

csc @TestApp.rsp

If the need should arise, you are also able to specify multiple *.rsp files as input (e.g., csc @FirstFile.rsp @SecondFile.rsp @ThirdFile.rsp). If you take this approach, do be aware that the compiler processes the command options as they are encountered! Therefore, command-line arguments in a later *.rsp file can override options in a previous response file.

Also note that flags listed explicitly on the command line before a response file will be overridden by the specified *.rsp file. Thus, if you were to enter the following:

csc /out:MyCoolApp.exe @TestApp.rsp

the name of the assembly would still be TestApp.exe (rather than MyCoolApp.exe), given the /out:TestApp.exe flag listed in the TestApp.rsp response file. However, if you list flags after a response file, the flag will override settings in the response file.

Note The effect of the /reference flag is cumulative. Regardless of where you specify external assemblies (before, after, or within a response file), the end result is a summation of each reference assembly.

The Default Response File (csc.rsp)

The final point to be made regarding response files is that the C# compiler has an associated default response file (csc.rsp), which is located in the same directory as csc.exe itself (which is by default installed under C:\Windows\Microsoft.NET\Framework\v3.5). If you were to open this file using Notepad, you will find that numerous .NET assemblies have already been specified using the /r: flag, including various libraries for web development, LINQ, data access, and other core libraries (beyond mscorlib.dll).

When you are building your C# programs using csc.exe, this response file will be automatically referenced, even when you supply a custom *.rsp file. Given the presence of the default response file, the current TestApp.exe application could be successfully compiled using the following command set (as System.Windows.Forms.dll is referenced within csc.rsp):

csc /out:TestApp.exe *.cs

In the event that you wish to disable the automatic reading of csc.rsp, you can specify the

/noconfig option:

csc @TestApp.rsp /noconfig

Note If you reference assemblies (via the /r option) that you do not actually make use of; they are ignored by the compiler. Therefore, you have no need to worry about “code bloat.”