Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# and the NET Platform, Second Edition - Andrew Troelsen.pdf
Скачиваний:
67
Добавлен:
24.05.2014
Размер:
22.43 Mб
Скачать

An Overview of .NET Assemblies

 

C# and the .NET Platform, S cond Edition

 

by Andrew Troelsen

ISBN:1590590554

Now that you understand the problems, let's check out the solution. .NET applications are constructed by

Apress © 2003 (1200 pages)

piecing together any number of assemblies. Simply put, an assembly is nothing more than a versioned,

This comprehensive text starts with a brief overview of the

self-describing binaryC# language(*.dll or and*.exe)thencontainingquickly movessometocollectionkey echnicalof typesand(classes, interfaces, structures, etc.) and optionalaresourceschitectural(images,ssues forstring.NET tables,dev lopersand. whatnot). One thing to be painfully aware of right now is that the internal organization of a .NET assembly is nothing like the internal organization of a classic COM server (regardless of the shared file extensions). For example, an in-process COM server

Table of Contents

exports four functions (DllCanUnloadNow(), DllGetClassObject(), DllRegisterServer() and

C# and the .NET Platform, Second Edition

DllUnregisterServer()),to allow the COM runtime to access its contents. .NET DLLs on the other hand do

Introductionnot.

Part One - Introducing C# and the .NET Platform

Local COM servers define WinMain() as the sole entry point into the *.exe, which is implemented to test for

Chapter 1 - The Philosophy of .NET

various command line parameters to perform the same duties as a COM *.dll. Not so under the .NET

Chapter 2 - Building C# Applications

protocol. Although .NET *.exe binaries do provide an entry point (identified using the .entrypoint CIL

Part Two - The C# Programming Language

directive), the behind-the-scenes logic is entirely different.

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

Given that .NET binaries are a completely new binary format, the next logical question would be how

Chapter 5 - Exceptions and Object Lifetime

managed assemblies are composed under the hood. Specifically speaking, a .NET binary consists of five

Chapter 6 - Interfaces and Collections major elements:

Chapter 7 - Callback Interfaces, Delegates, and Events

A standard Windows file header

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

A CLR header that marks the file as a managed module

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

CIL code

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part FourType- Leveragingmetadata the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

The assembly manifest

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

The first two elements (the Win32 header and CLR header) are entities that you can safely ignore;

Choweverapt r 15 - Programming with Windows Forms Controls

they do deserve some brief consideration. The Win32 header is just about identical to that of an Chapterunmanaged16 - Thebinary,Systemand.IOis simplyNamespaceused to identify that the module is usable by the Windows operating

Chaptersystem17. This- DataheaderAccessalsowidentifiesth ADO.NETthe type of application to be launched (console-based, GUI-based, or a

Part*.dllFivemodule)- Web. IfApplicationsyou were toandopenXMLa Web.NETServicesassembly using dumpbin.exe and specify the /headers flag, you

Chapterwould indeed18 - ASPfile.NETa blockWeb identifyiPages andg WthebWin32Controlsheader information. To illustrate, Figure 9-1 shows the Chapteroutput of19viewing- ASP.NETtheWebCarLibraryApplications.dll assembly you will build a bit later in this chapter:

Chapter 20 - XML Web Services

Index

List of

List of

Figure 9-1: Assembly Win32 header file information

The CLR header is a block of information that all .NET files must support (and do support, courtesy of the C# compiler) to be loaded by the CLR. In a nutshell, this header defines numerous flags that enable the runtime to understand the layout of the managed file. For example, flags exist that identify the location of

the metadata and resources within the file, the version of the runtime the assembly was built against, the

C# and the .NET Platform, Second Edition value of the (optional) public key, and so forth.

by Andrew Troelsen

ISBN:1590590554

For those who areApressinterested,© 2003 (1200notepages)that all of this information is represented by a C-style structure (IMAGE_COR20_ThisHEADER)comprehensivedefinedtextin <corhdrstarts with.h>. aAlthoughbrief overview99.99 ofpercentthe (or greater) of .NET programmers willC#neverlanguageneedandto interactthen quicklywith thismovesUDT,to forkeyyourtechnicaledification,nd here is the layout of the

architectural issues for .NET developers. structure in question:

// CLR 2.0 header structure.

Table of Contents

typedef struct IMAGE_COR20_HEADER

C# and the .NET Platform, Second Edition

{

Introduction

// Header versioning

Part One - Introducing C# and the .NET Platform

ULONG cb;

Chapter 1 - The Philosophy of .NET

USHORT MajorRuntimeVersion;

Chapter 2 - Building C# Applications

USHORT MinorRuntimeVersion;

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

// Symbol table and startup information

Chapter 4 - Object-Oriented Programming with C#

IMAGE_DATA_DIRECTORY MetaData;

Chapter 5 - Exceptions and Object Lifetime

ULONG Flags;

Chapter 6 - Interfaces and Collections

ULONG EntryPointToken;

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter//8 Binding- Adva cedinformationC# Type Construction Techniques

Part ThreeIMAGE- ProgrammingDATA DIRECTORYwith .NET AssembliesResources;

ChapterIMAGE9 - UnderstandingDATA DIRECTORY.NET AssembliesStrongNameSignature;

Chapter 10 - Processes, AppDomains, Contexts, and Threads

// Regular fixup and binding information

Chapter 11 - Type Reflection, Late Bind ng, and Attribute-Based Programming

IMAGE_DATA_DIRECTORY CodeManagerTable;

Part Four - Leveraging the .NET Libraries

IMAGE_DATA_DIRECTORY VTableFixups;

Chapter 12 - Object Serialization and the .NET Remoting Layer

IMAGE_DATA_DIRECTORY ExportAddressTableJumps;

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

// Precompiled image info (internal use only - set to zero)

Chapter 15 - Programming with Windows Forms Controls

IMAGE_DATA_DIRECTORY ManagedNativeHeader;

Chapter 16 - The System.IO Namespace

} IMAGE_COR20_HEADER;

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Header information aside, the key point is that an unmanaged binary contains instructions that target a

Chapter 19 - ASP.NET Web Applications

specific platform and specific CPU and platform. In contrast, .NET binaries contain common intermediate Chapterlanguage20 (CIL),- XMLwhichWeb Servicesis platform-and CPU-agnostic. At runtime, the internal CIL is compiled on the fly

Index(using a just-in-time compiler) to platform and CPU-specific instructions. This is a powerful extension of

Listclassicof FiguresCOM in that .NET assemblies are poised to be platform-neutral entities that are not necessarily tied Listto theof TablesWindows operating system (see Chapter 1).

In addition to CIL code, an assembly also contains metadata that completely describes each type defined within the current assembly as well as the set of external types referenced by this assembly. For example, if you created a class named JoyStick using some .NET-aware language, the corresponding compiler emits metadata describing all the fields, methods, properties, and events defined by this custom type. Also, if the application in question makes calls to Console.WriteLine(), the metadata records information about the external System.Console type. The .NET runtime uses this metadata to resolve the location of types (and their members) within the binary, create object instances, as well as to facilitate remote method invocations. We check out the details of the .NET metadata format in Chapter 11 during our examination of reflection services.

Finally, unlike traditional unmanaged Windows files or classic COM servers, an assembly must contain an associatedmanifest (also referred to as "assembly metadata"). The manifest documents each module within the assembly, establishes the version of the assembly, and also documents any external assemblies referenced by the current assembly (unlike a classic COM type library that does not document required external dependencies). Given all these elements, a .NET assembly is a completely self-

describing entity.

C# and the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Single File and

©Multifile2003 (1200 pages)Assemblies

 

Apress

 

 

This comprehensive text starts with a brief overview of the

Under the hood, a given assembly can be composed of multiple modules. A module is really nothing more

C# language and then quickly moves to key technical and

than a generic name for a valid .NET file. In this light, an assembly can be viewed as a unit of versioning architectural issues for .NET developers.

and deployment (often termed a "logical DLL"). In most situations, an assembly is in fact composed of a single module. In this case, there is a one-to-one correspondence between the (logical) assembly and the

Tableunderlyingof Contents(physical) binary, as shown in Figure 9-2.

C# and the .NET Platform, Second Edition

Part

Chapter

Chapter

Part

Chapter

 

Chapter

C#

Chapter

 

Chapter

 

Chapter

Events

Chapter

Techniques

Part

 

Chapter

 

Chapter

and Threads

Chapter

Attribute-Based Programming

Part

 

Chapter

Remoting Layer

Chapter

Windows Forms)

Chapter

 

Chapter

Controls

Chapter

 

Chapter

Part Five - Web Applications and XML Web Services

Figure 9-2: A single file assembly

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

When you create an assembly that is composed of multiple files, you gain a more efficient way to

Chapter 20 - XML Web Services

download content. For example, assume you have a remote client that is referencing a multifile assembly

Index

composed of three modules, one of which is automatically installed with the client. If the client references Listanotherf Figuresof the remote modules, the .NET runtime will download the file on demand. If each module is 1

ListMBofinTablsize,sI'm sure you can see the benefits.

Understand that multifile assemblies are not literally linked together into a new (larger) file. Rather, multifile assemblies are logically related by information contained in the corresponding manifest. On a related note, multifile assemblies contain a single manifest that may be placed in a stand-alone file, but is more typically bundled directly into the primary module. The big picture is seen in Figure 9-3.

ISBN:1590590554

of the

and

Table

C# and

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Figure 9-3: A multifile assembly

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Two Views of an Assembly: Physical and Logical

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

As you begin to work with .NET binaries, it can be helpful to regard an assembly (both single file and

Chapter 10 - Processes, AppDomains, Contexts, and Threads

multifile) as having two conceptual views. When you build an assembly, you are interested in the physical

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

view. In this case, the assembly can be realized as some number of files that contain your custom types

Part Four - Leveraging the .NET Libraries

and resources (Figure 9-4).

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter

Chapter

Chapter

Chapter

Part

Chapter

Chapter

Figure 9-4: The physical view of a .NET assembly

Chapter 20 - XML Web Servi es

Index

List of Figures

As an assembly consumer, you are typically interested in a logical view of the assembly (Figure 9-5). In

List of Tables

this case, you can understand an assembly as a versioned collection of public types that you can use in your current application (recall that "internal" types can only be referenced by the assembly in which they are defined).

Figure 9-5: The logical view of a .NET assembly

For example, the kind folks in Redmond who developed System.Drawing.dll created a physical assembly for you to consume in your applications. Although System.Drawing.dll can be physically viewed as a binary *.dll, you logically regard this assembly as a collection of related types. Of course, ildasm.exe is the tool of

Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 12 - Object Serialization and the .NET Remoting Layer
Part Three - Programming with .NET Assemblies
Part One - Introducing C# and the .NET Platform

choice when you are interested in discovering the logical layout of a given assembly.

C# and the .NET Platform, Second Edition

The chances arebygoodAndrewthat youTroelsenwill play the role of both an assemblyISBN:1590590554builder and assembly consumer, as is the case throughoutApressthis© 2003book(1200. However,pag s) before digging into the code, let's briefly examine some of the core benefits of thisThisnewcomprehensivefile format. text starts with a brief overview of the

C# language and then quickly moves to key technical and

architectural issues for .NET developers.

Assemblies Promote Code Reuse

Assemblies contain code that is executed by the .NET runtime. As you might imagine, the types and

Table of Contents

resources contained within an assembly can be shared and reused by multiple applications, much like a

C# and the .NET Platform, Second Edition

traditional COM binary. Unlike COM, it is possible to configure "private" assemblies as well (in fact, this is

Introduction

the default behavior). Private assemblies are intended for use only by a single application on a given

machine. As you will see, private assemblies greatly simplify the deployment and versioning of your

Chapter 1 - The Philosophy of .NET applications.

Chapter 2 - Building C# Applications

PartLikeTwoCOM,- ThebinaryC# Programmingreuse under Languagethe .NET platform honors the ideal of language independence. C# is one of Chaptnumerousr 3 -languagesC# L nguagecapableFundamentalsof building managed code, with even more languages to come. When a

Chapter.NET-aware4 - Objectlanguage-OrientedadheresProgrammingto the ruleswithof C#the Common Language Specification (CLS), your choice of

Chapterlanguage5 becomes- ExceptionslittleandmoreObjectthanLifetimea personal preference.

Chapter 6 - Interfaces and Collections

Therefore, it is not only possible to reuse types between languages, but to extend types across languages

Chapter 7 - Callback Interfaces, Delegates, and Events

as well. In classic COM, developers were unable to derive COM object A from COM object B (even if both

Chapter 8 - Advanced C# Type Construction Techniques

types were developed in the same language). In short, classic COM did not support classical inheritance

(the "is-a" relationship). Later in this chapter you'll see an example of cross-language inheritance.

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Assemblies Establish a Type Boundary

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Assemblies are used to define a boundary for the types (and resources) they contain. In .NET, the identity of a given type is defined (in part) by the assembly in which it resides. Therefore, if two assemblies each

define an identically named type (class, structure, or whatnot) they are considered independent entities in

Chapter 14 - A Better Painting Framework (GDI+) the .NET universe.

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Assemblies Are Versionable and Self-Describing Entities

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

As mentioned, in the world of COM, the developer is in charge of correctly versioning a binary. For

Chapter 18 - ASP.NET Web Pages and Web Controls

example, to ensure binary compatibility between MyComServer.dll version 1.0 and MyComServer.dll

Chapter 19 - ASP.NET Web Applications

version 2.4, the programmer must use basic common sense to ensure interface definitions remain

Chapter 20 - XML Web Services

unaltered or run the risk of breaking client code. While a healthy dose of versioning common sense also

Index

comes in handy under the .NET universe, the central problem with the COM versioning scheme is that

List of Figures

these programmer-defined techniques are not enforced by the runtime.

List of Tables

Another major headache with current versioning practices is that COM does not provide a way for a binary server to explicitly list the set of other binaries that must be present for it to function correctly. If an end user mistakenly moves, renames, or deletes a dependency, the solution fails.

Under .NET, an assembly's manifest is the entity in charge of explicitly listing all internal and external contingencies. Each assembly has a version identifier that applies to all types and all resources contained within each module of the assembly. Using a version identifier, the runtime is able to ensure that the correct assembly is loaded on behalf of the calling client, using a well-defined versioning policy (detailed later). An assembly's version identifier is composed of two basic pieces: A friendly text string (termed the informational version) and a numerical identifier (termed the compatibility version).

For example, assume you have created a new assembly with an informational string of "MyInterestingTypes." This same assembly would also define a compatibility number, such as 1.0.70.3. The compatibility version number always takes the same general format (four numbers separated by periods). The first and second numbers identify the major and minor version of the assembly (1.0 in this case). The third value (70) marks the build number, followed by the current revision number (3).

Note You areC#notandrequiredthe .NETto providePlatform,fourSecond-part versionEditionnumber. This is simply a convention suggestedby Andrewby MicrosoftTroelsen. If you wish, you may chooseISBN:1590590554to version a binary using a major and minor numericalApressvalue© 2003(such(1200aspages)1.0).

This comprehensive text starts with a brief overview of the

C# language and then quickly moves to key technical and

Assemblies Define a Security Context

architectural issues for .NET developers.

An assembly may also contain security details. Under the .NET platform, security measures are scoped at

the assembly level. For example, if AssemblyA wishes to use a class contained within AssemblyB,

Table of Contents

AssemblyB is the entity that chooses to provide access (or not). The security constraints defined by an

C# and the .NET Platform, Second Edition

assembly are explicitly listed within its manifest. While a treatment of .NET security measures is outside

Introduction

the mission of this text, simply be aware that access to an assembly's contents is verified using assembly

Part One - Introducing C# and the .NET Platform

metadata.

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

Note If you are interested in investigating .NET security issues, check out .NET Security (Bock et al.,

Part Two - TheApressC# Programming2002). Language

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

Assemblies Enable Side-by-Side Execution

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

Perhaps the biggest advantage of the .NET assembly is the ability to install and load multiple versions of Chapterthe same7 assembly- Callback onI terfaces,singleDelegates,machine. InandthisEventsway, clients are isolated from other incompatible versions

Chaptof thersame8 - AdvancedassemblyC#. Type Construction Techniques

Part Three - Programming with .NET Assemblies

Furthermore, it is possible to control which version of a (shared) assembly should be loaded using

Chapter 9 - Understanding .NET Assemblies

application configuration files. These files are little more than a simple text file describing (via XML syntax)

Chapter 10 - Processes, AppDomains, Contexts, and Threads

the version, and specific location, of the assembly to be loaded on behalf of the calling application. You

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

learn how to author application configuration files later in this chapter.

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Building a SingleC# and theFile.NETTestPlatform,AssemblySecond Edition

by Andrew Troelsen

ISBN:1590590554

Now that you have a better understanding of the benefits provided by .NET assemblies, let's build a

Apress © 2003 (1200 pages)

minimal and complete code library using C#. Physically, this will be a single file assembly named

This comprehensive text starts with a brief overview of the

CarLibrary. Logically,C# languagethis binaryandwillthencontainquicklya moveshandfultoofkeypublictechnicaltypesandfor consumption by other .NET binaries. To buildarchitecturala code libraryissusinges forthe.NETVisualdevelopersStudio.NET IDE, you would select a new Class Library project workspace (Figure 9-6).

Table of Contents

C# and

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part Three - Programming with .NET Assemblies

Figure 9-6: Creating a C# code library (e.g., a managed *.dll)

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

ChapterThe design11 - ofTypeourReflection,automobileLatelibraryBinding,beginsandwiAthtributean abstract-Based Programmingbase class named Car that defines a number

Partof protectedF ur - Leveragingdata membersthe .NETexposedLibrariesthrough custom properties. This class has a single abstract method Chnamedpt r 12TurboBoost()- Object Serializationand makesandusetheof.NETa singleRemotingenumerationLayer (EngineState). Here is the initial definition of

the CarLibrary namespace:

Chapter 13 - Building Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter// The15single- Programmingfile withassemblyWindows. Forms Controls

Chapterusing16System;- The System.IO Namespace

Chnamespacept r 17 - DataCarLibraryAccess with ADO.NET

{

Part Five - Web Applications and XML Web Services

// Holds the state of the engine.

Chapter 18 - ASP.NET Web Pages and Web Controls

public enum EngineState

Chapter 19 - ASP.NET Web Applications

{

Chapter 20 - XML Web Services

engineAlive,

Index

engineDead

List of Figures

}

List of Tables

// The abstract base class in the hierarchy.

public abstract class Car

{

// Protected state data. protected string petName; protected short currSpeed; protected short maxSpeed; protected EngineState egnState;

public Car(){egnState = EngineState.engineAlive;} public Car(string name, short max, short curr)

{

egnState = EngineState.engineAlive;

petName = name; maxSpeed = max; currSpeed = curr;

}

public string PetName

{

public override void TurboBoost()
// TurboBoost impl.
C# and the .NET Platform, Second Edition

 

get {

return petName; }

 

 

C# and the .NET Platform, Second Edition

 

 

set { petName = value; }

ISBN:1590590554

}

by Andrew Troelsen

Apress © 2003 (1200 pages)

 

public short CurrSpeed

 

{

This comprehensive text starts with a brief overview of the

 

C# language and then quickly moves to key technical and

 

get { return currSpeed; }

 

 

architectural issues for .NET developers.

 

 

set {

currSpeed = value; }

 

}

public short MaxSpeed

Table of Contents

{get { return maxSpeed; } }

public EngineState EngineState

Introduction

{get { return egnState; } }

Part One - Introducing C# and the .NET Platform

public abstract void TurboBoost();

Chapter 1 - The Philosophy of .NET

}

Chapter 2 - Building C# Applications

}

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

ChapterNow assume4 - Objectthat -youOrientedhave Prtwogrammingdirect descendentswith C# of the Car type named MiniVan and SportsCar. Each

Chaimplementst r 5 - Exceptionsthe abstractandTurOboBoost()ject Lifetimethod in an appropriate manner:

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

using System;

Chapterusing8System- Advanced.WindowsC# Type.Forms;Construction//TechniquesNeeded for MessageBox definition.

PartnamespaceThree - ProgrammingCarLibrarywith .NET Assemblies

Chapter{ 9 - Understanding .NET Assemblies

Chapter//10The- Processes,SportsCarAppDomains, Contexts, and Threads

public class SportsCar : Car

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

{

Part Four - Leveraging the .NET Libraries

// Ctors.

Chapter 12 - Object Serialization and the .NET Remoting Layer

public SportsCar(){ }

Chapter 13 - Building a Better Window (Introducing Windows Forms)

public SportsCar(string name, short max, short curr)

Chapter 14 - A Better Painting Framework (GDI+)

: base (name, max, curr){ }

Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

{

Part Five - Web Applications and XML Web Services

MessageBox.Show("Ramming speed!", "Faster is better...");

Chapter 18 - ASP.NET Web Pages and Web Controls

}

Chapter}19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

// The MiniVan

Index public class MiniVan : Car

List of Figures

{

List of Tables// Ctors.

public MiniVan(){ }

public MiniVan(string name, short max, short curr)

:base (name, max, curr){ }

//TurboBoost impl.

public override void TurboBoost()

{

// Minivans have poor turbo capabilities! egnState = EngineState.engineDead;

MessageBox.Show("Time to call AAA", "Your car is dead");

}

}

}

Notice how each subclass implements TurboBoost() using the MessageBox class, which is defined in the

Chapter 17 - Data Access with ADO.NET
Chapter 16 - The System.IO Namespace

System.Windows.Forms.dll assembly. For your assembly to make use of the types defined within this

C# and the .NET Platform, Second Edition

assembly, the CarLibrary project must include a reference to this binary using the "Project | Add

by Andrew Troelsen ISBN:1590590554

Reference" menu selection (Figure 9-7).

Apress © 2003 (1200 pages)

This comprehensive text starts with a brief overview of the technical and

Table

C# and

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Figure 9-7: Referencing external .NET assemblies begins here.

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

InChapter 13, the System.Windows.Forms namespace is described in detail. As you can tell by its name,

Chapter 10 - Processes, AppDomains, Contexts, and Threads

this namespace contains numerous types to help you build desktop applications. For now, the ChapterMessageBox11 - TypeclassReflection,is all youLateneedBinding,to concernand Attributeyourself-Basedwith. IfPryougraremmingfollowing along, go ahead and

PartcompileFour -yourLeveragingnew codethelibrary.NET Libraries.

Chapter 12 - Object Serialization and the .NET Remoting Layer

Note The list of assemblies displayed in the Add Reference dialog box of VS .NET does not represent

Chapter 13 - Building a Better Window (Introducing Windows Forms)

each and every assembly on your development machine, does not list your custom assemblies,

Chapter 14 - A Better Painting Framework (GDI+)

and does not map to the Global Assembly Cache (GAC)! The items in the Add Reference list

Chapter 15 - Programming with Windows Forms Controls

box are simply a suggested set that VS .NET has been configured to show automatically. When you are building applications that require the use of an assembly not listed within the Add

Reference dialog, you need to click the Browse button to manually navigate to the *.dll in

Part Five - Web Applications and XML Web Services

question.

Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

A C# ClientC#Applicationand the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Because each of our types has been declared "public," other binaries are able to make use of them. In a

Apress © 2003 (1200 pages)

moment, you learn how to make use of these types from other .NET-aware languages such as VB .NET.

This comprehensive text starts with a brief overview of the

Until then, let's createC# languagea C# clientand.thBeginn quicklyby creatingmovesatonewkeyC#technicalConsoleandApplication project (CSharpCarClient)architectural. Next, set aissuesreferencefor .NETto yourdevelopersCarLibrary. .dll, using the Browse button of the Add Reference dialog to navigate to the location of your custom assembly.

TableOnceofyouContentsadd a reference to your CarLibrary assembly, the Visual Studio .NET IDE responds by making a C#fullandcopytheof.NETthe Platform,referencedSecondassemblyEditionand placing it into your Debug folder (assuming, of course, you have

configured a debug build) (Figure 9-8). Obviously this is a huge change from classic COM, where the

Introduction

resolution of the binary is achieved using the system registry.

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part

ChapterFigure9 - 9Understanding-8: Local copies.NETofAssemblies(non-shared) assemblies are placed in your Debug folder.

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Now that your client application has been configured to reference the CarLibrary assembly, you are free to

Part Four - Leveraging the .NET Libraries

create a class that makes use of these types. Here is a test drive (pun intended):

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms) using System;

Chapter 14 - A Better Painting Framework (GDI+)

// Make use of the CarLib types!

Chapter 15 - Programming with Windows Forms Controls using CarLibrary;

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET namespace CSharpCarClient

Part Five - Web Applications and XML Web Services

{

Chapter 18 - ASP.NET Web Pages and Web Controls

public class CarClient

Chapter 19 - ASP.NET Web Applications

{

Chapter 20 - XML Web Services

public static int Main(string[] args)

Index {

List of Figures

List of Tables

}

}

}

// Make a sports car.

SportsCar viper = new SportsCar("Viper", 240, 40); viper.TurboBoost();

// Make a minivan.

MiniVan mv = new MiniVan();

mv.TurboBoost();

return 0;

This code looks just like the other applications developed thus far. The only point of interest is that the C# client application is now making use of types defined within a unique assembly (and therefore must specify the namespace name via the "using" keyword and set a reference to the CarLibrary.dll assembly). Go ahead and run your program. As you would expect, the execution of this program results in the display of two message boxes.

C# and the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Apress © 2003 (1200 pages)

This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.

Table of Contents

C# and the .NET Platform, Second Edition

Introduction

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

A Visual BasicC# and.NETthe .NETClientPlatform,ApplicationSecond Edition

by Andrew Troelsen

ISBN:1590590554

When you install Visual Studio .NET, you receive four languages that are capable of building managed

Apress © 2003 (1200 pages)

code: JScript.NET, C++ with managed extensions (MC++), C#, and Visual Basic .NET. A nice feature of

This comprehensive text starts with a brief overview of the

Visual Studio .NETC#islanguagethat all languagesd then quicklysharemovesthe sameto keyIDEtechnical. Therefore,and VB .NET, ATL, C#, and MFC programmers allarchitecturalmake use ofissuesa commonfor .NETdevelopmentd velop rs.environment. Given this fact, the process of building a Visual Basic .NET application making use of the CarLibrary is simple. Assume a new VB .NET Windows Application project workspace named VBCarClient has been created (Figure 9-9).

Table of Contents

C# and the .NET Platform, Second Edition

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part

Chapter

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Figure 9-9: Selecting a VB .NET Windows Forms Application

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Similar to Visual Basic 6.0, this project workspace provides a design time template used to build the GUI of

Chapter 12 - Object Serialization and the .NET Remoting Layer

the main window. However, VB .NET is a completely different animal. The template you are looking at is

Chapter 13 - Building a Better Window (Introducing Windows Forms)

actually a subclass of the Form type, which is quite different from a traditional VB 6.0 Form.

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Now, set a reference to the C# CarLibrary, again using the Add Reference dialog. Like C#, VB .NET

Chapter 16 - The System.IO Namespace

requires you to list each namespace used within your project. However, VB .NET makes use of the

Chapter 17 - Data Access with ADO.NET

"Imports" keyword rather than the C# "using" keyword. Thus, open the code window for your Form (simply PartrightFive-click- Webthe designApplications-time templateand XML Weband selectServices"View Code") and add the following:

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

' Like C#, VB .NET needs to 'see' the namespaces used by a given file.

Chapter 20 - XML Web Services

Imports CarLibrary

Index

List of Figures

Switching back to the design-time template, construct a minimal and complete user interface to exercise

List of Tables

your automobile types (Figure 9-10). Two buttons should fit the bill (simply select the Button widget from the Toolbox and draw it on the Form object).

Figure 9-10: A painfully simple GUI

The next step is to add event handlers to capture the Click event of each Button object. To do so, simply double-click each button on the Form. The IDE responds by writing stub code that will be called when a particular button is clicked. Here is some sample code:

C# and the .NET Platform, Second Edition

' A taste of VB .NET.

by Andrew Troelsen ISBN:1590590554

Private Sub btnMiniVan_Click(ByVal sender As Object,

Apress © 2003 (1200 pages)

ByVal e As System.EventArgs) Handles btnMiniVan.Click

Dim sc ThisAs comprehensiveNew MiniVan()text starts with a brief overview of the

C# language and then quickly moves to key technical and sc.TurboBoost()

architectural issues for .NET developers.

End Sub

Private Sub btnCar_Click(ByVal sender As Object,

ByVal e As System.EventArgs) Handles btnCar.Click

Table of Contents

Dim sc As New SportsCar()

C# and the .NET Platform, Second Edition sc.TurboBoost()

Introduction

End Sub

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

ChapterAlthough2 the- Buildinggoal ofC#thisApplicatiobook is nots to turn you into a powerhouse VB .NET developer, here is one point of

PartinterestTwo.-NoticeThe C#howProgrammingeach Car subclassLanguageis created using the "New" keyword. Unlike VB 6.0 however,

Chclassespter 3now- C#haveLangtrueageconstructors!FundamentalsTherefore, the empty parentheses suffixed on the class name do

Chaptindeedr 4invoke- Objecta given-OrientedconstructorProgrammingon the classwith C#. As you would expect, when you run the program, each

Chapterautomobile5 - respondsExceptionsappropriatelyand Object Lifetime.

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Cross-LanguageC# nd theInheritance.NET Pl tform, Second Edition

by Andrew Troelsen

ISBN:1590590554

A very sexy aspect of .NET development is the notion of cross-language inheritance. To illustrate, let's

Apress © 2003 (1200 pages)

create a new VB .NET class that derives from CarLibrary.SportsCar. Impossible you say? Well, if you were

This comprehensive text starts with a brief overview of the

using Visual BasicC#6.language0 this wouldandbethenthequicklycase. mHoweverves to keywithtechnicalthe adventandof VB .NET, programmers are able to use the same objectarchitectural-orientedissufeaturess for .NETfounddevelopersin C#, Java,. and C++, including classical inheritance (i.e., the "is-a" relationship).

TableTo illustrate,of Contentsadd a new class to your current VB .NET client application named PerformanceCar (using C#theand"Projectthe .NET| AddPlatform,Class"Secondmenu selection)Edition . In the code that follows, notice you are deriving from the C# Car

type using the VB .NET "Inherits" keyword. As you recall, the Car class defined an abstract TurboBoost()

Introduction

method, which we implement using the VB .NET "Overrides" keyword:

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Chapter' VB .2NET- BuildingsupportsC# Applicationseach pillar of OOP!

PartImportsTwo - TheCarLibraryC# Programming Language

Chapter' This3 VB- C#typeLanguageis derivingFundamentalsfrom the C# SportsCar.

Public Class PerformanceCar

Chapter 4 - Object-Oriented Programming with C#

Inherits CarLibrary.SportsCar

Chapter 5 - Exceptions and Object Lifetime

' Implementation of abstract Car method.

Chapter 6 - Interfaces and Collections

Public Overrides Sub TurboBoost()

Chapter 7 - Callback Interfaces, Delegates, and Events

MessageBox.Show("Blistering speed", "VB PerformanceCar says")

Chapter 8 - Advanced C# Type Construction Techniques

End Sub

Part Three - Programming with .NET Assemblies

End Class

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

If we update the existing Form to include an additional Button to exercise the performance car, we could

Chapter 12 - Object Serialization and the .NET Remoting Layer write the following test code:

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

PrivateSub btnPreCar_Click(ByVal sender As Object,

Chapter 15 - Programming with Windows Forms Controls

ByVal e As System.EventArgs) Handles btnPerfCar.Click

Chapter 16 - The System.IO Namespace

Dim pc As New PerformanceCar()

Chapter 17 - Data Access with ADO.NETInherited property. pc.PetName = "Hank" '

Part Five' -DisplayWeb Applicationsbase classand XML. Web Services

ChapterMessageBox18 - ASP.NET.WebShow(pcPages.andGetType()Web Controls.BaseType.ToString(),

Chapter 19"Base- ASP.NETclassWeb Applicationsof Perf car")

Chapter'20Custom- XML WebImplementationServices of Car.TurboBoost()

Index pc.TurboBoost()

End Sub

List of Figures

List of Tables

Notice that we are able to identify our base class programmatically (Figure 9-11).

Figure 9-11: Cross-language inheritance in action

Note If you wish to check out the details of the VB .NET programming language, may I humbly recommend my offering in the VB .NET arena: VB .NET and the .NET Platform: An Advanced Guide (Apress 2002).

C# language and then quickly moves to key technical and
Apress © 2003 (1200 pages)

Building an MC++ Subclass

 

C# and the .NET Platform, Second Edition

 

by Andrew Troelsen

ISBN:1590590554

So far, you have a VB .NET class deriving from a C# class. To really drive the point of cross-language

inheritance home, let's build a MC++ subclass that derives from the VB .NET class. Recall that C++ with

This comprehensive text starts with a brief overview of the

Managed Extensions (MC++) is Microsoft's augmentation of the C++ language. For the C++ programming

language to interact with the CLR, several new keywords were introduced. Understand that C++ architectural issues for .NET developers.

programmers are not required to make use of these new .NET specific keywords when they build C++ projects using Visual Studio .NET (ATL, MFC, and Win32 projects are still possible). However, when a

C++ programmer does want to inject .NET functionality into their programs, VS .NET does include several

Table of Contents

new project workspaces. To begin, close down your current project workspace and create a brand-new

C# and the .NET Platform, Second Edition

Managed C++ Console Application (see Figure 9-12).

Introduction

Part One - Introducing C# and the .NET Platform

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part

Chapter

 

Chapter

 

Chapter

Programming

Part FourFigure- Leveraging9-12: An MC++the .NETprojectLibrariesworkspace

 

Chapter 12 - Object Serialization and the .NET Remoting Layer

 

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Of all the languages that are able to produce managed code, MC++ is by far the most cryptic. Therefore, if

Chapter 14 - A Better Painting Framework (GDI+)

you do not have a background in C(++), don't fret over each and every line of syntax. The point to focus on

Chapter 15 - Programming with Windows Forms Controls

is the fact that the MC++ JamesBondCar class is deriving from the VB .NET PerformanceCar (which in

Chapter 16 - The System.IO Namespace

turn derives from the C# SportsCar). Here is the complete code; be sure to set a reference to the

Chapter 17 - Data Access with ADO.NET

VBCarClient.exe and CarLibrary.dll assemblies using the Add Reference dialog (if you are not using VS Part.NETFive2003,- WebbeApplicationssure to readandtheXMLcodeWebcommentServicesin bold!):

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

#pragma once

Chapter 20 - XML Web Services

#include "stdafx.h"

Index

List of Figures

// '#using' is functionally equivalent to the 'Add References' dialog.

List#usingof Tables<mscorlib.dll>

#using <System.Windows.Forms.dll>

//Uncomment these lines (and adjust your path)

//if you are not using VS .NET 2003, as

//VS .NET 2002 did not have an Add Ref dialog! //#using "C:\VbCarClient.exe"

//#using "C:\CarLibrary.dll"

//'using namespace' is identical to the C# "using" keyword.

using namespace CSharpCarClient;

using namespace System;

// __gc (garbage collected) marks this class as managed by the CLR.

__gc class JamesBondCar : public PerformanceCar

{

public:

Chapter 12 - Object Serialization and the .NET Remoting Layer
Part Four - Leveraging the .NET Libraries

JamesBondCar(void){}

C# and the .NET Platform, Second Edition

~JamesBondCar(void){}

 

by Andrew Troelsen

ISBN:1590590554

virtual void TurboBoost()

 

{

Apress © 2003 (1200 pages)

 

This comprehensive text starts with a brief overview of the

 

 

Console::WriteLine("Diving,

flying and drilling...");

C# language and then quickly moves to key technical and

}

architectural issues for .NET developers.

};

// This is the entry point for this application.

#ifdef _UNICODE

Table of Contents

int wmain(void)

C# and the .NET Platform, Second Edition

#else

Introduction

int main(void)

Part One - Introducing C# and the .NET Platform

#endif

Chapter 1 - The Philosophy of .NET

{

Chapter 2 - Building C# Applications

// Make a JamesBondCar.

Part Two - The C# Programming Language

JamesBondCar* jbc = new JamesBondCar();

Chapter 3 - C# Language Fundamentals jbc->PetName = S"Jello";

Chapter 4 - Object-Oriented Programming with C# jbc->TurboBoost();

Chapter 5 - Exceptions and Object Lifetime

Console::Write("Car is called: ");

Chapter 6 - Interfaces and Collections PetName

Console::WriteLine(jbc-> );

ChapterConsole::WriteLine(jbc7 - Callback In erfaces, Delegates,->GetType()and Events->BaseType->ToString());

Chapterreturn8 - Advanced0; C# Type Construction Techniques

Part} Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Before we move on, a few points of interest. First, when an MC++ developer wants to add a reference to

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

an external assembly, he or she may use the Add Reference dialog (available under VS .NET 2003) or make use of the #using preprocessor directive that will import the assembly's metadata for use in the

current application. Also notice that MC++ supports a "using" keyword, which is the functional equivalent to

Chapter 13 - Building a Better Window (Introducing Windows Forms) the VB .NET "Imports" and C# "using" keywords.

Chapter 14 - A Better Painting Framework (GDI+)

ChapterNote15 If- youProgrammingwish to checkwith outWindowsthe syntaxFormsandControlssemantics of the MC++ programming language, I

Chapter 16 recommend- The Systemgetting.IO Namespacecopy of Essential Guide to Managed Extensions for C++ (Challa and

Chapter 17 Laksberg,- Data AccessApresswith2002)ADO.NET.

Part Five - Web Applications and XML Web Services

SOURCE The CarLibrary, CSharpCarClient, VbCarClient, and McPlusPlusClient projects are

Chapter 18 - ASP.NET Web Pages and Web Controls

CODE located under the Chapter 9 subdirectory.

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Exploring theC# andCarLibrary'sthe .NET Platform,ManifestSecond Edition

by Andrew Troelsen

ISBN:1590590554

At this point, you have successfully created a single file code library and various client applications. Your next

Apress © 2003 (1200 pages)

order of business is to gain a deeper understanding of how .NET assemblies are constructed under the hood.

This comprehensive text starts with a brief overview of the

To begin, recall thatC# languageevery assemblyand thencontainsquickly anmovesassociatedto key technicalmanifestand. The manifest contains bits of metadata that specify the namerchitecturaland versioni suesofforthe.NETassembly,deve opersas well. as a listing of all internal and external modules that compose the assembly as a whole.

TableAdditionally,of Contentsa manifest may contain cultural information (used for internationalization), a corresponding C#"strongand thename".NET (requiredPlatfo m, Secondby sharedE itionassemblies), and optional resource information (you examine the .NET

resource format in Chapter 17).Table 9-1 describes some of the key bits of functionality lurking within an

Introduction

assembly manifest.

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Table 9-1: Key Elements of an Assembly Manifest

Chapter 2 - Building C# Applications

 

 

 

 

 

 

 

 

 

Part Two - The C# Programming

 

 

Language

 

 

 

 

Manifest-Centric

 

 

Meaning in Life

 

 

Chapter 3

- C# Language Fundamentals

 

 

 

 

Information

 

 

 

 

 

 

Chapter 4

- Object-Oriented Programming with C#

 

 

 

 

 

 

 

ChapterAssembly5 - nameExceptions and ObjectALifetimetext string specifying the assembly's name.

 

 

 

 

 

 

 

 

 

 

Chapter 6

- Interfaces and Collections

 

 

 

 

Version number

 

 

A major and minor version number, and a revision and build number.

 

 

 

 

Chapter 7

- Callback Interfaces,

 

 

Delegates, and Events

 

 

 

 

 

 

 

ChapterStrong8 name- AdvancedinformationC# Type

 

 

ConstructionIn part, theTechniques"strong name" of an assembly consists of a public key

 

 

Part Three - Programming with .NETmaintainedAssembliesby the publisher of the assembly.

 

 

 

 

 

 

 

 

 

 

Chapter 9

- Understanding .NET

 

 

Assemblies

 

 

 

 

List of all modules in the

 

 

A hash of each module contained in the assembly (in the case of a

 

 

 

Chapter 10

- Processes, AppDomains, Contexts, and Threads

 

 

 

 

assembly

 

 

single file assembly, there will only be a single module listing).

 

 

 

 

 

 

 

 

 

 

 

 

 

Chapter 11

- Type Reflection, Late

 

Binding, and Attribute-Based Programming

 

 

 

Information on referenced

 

 

A list of other assemblies that are statically referenced by the

 

 

Part Four - Leveraging the .NET

 

 

Libraries

 

 

 

 

assemblies

 

 

assembly.

 

 

 

 

Chapter 12

- Object Serialization

 

 

and the .NET Remoting Layer

 

 

 

 

Chapter 13

- Building a Better Window (Introducing Windows Forms)

.NET aware compilers (such as csc.exe) automatically create a manifest at compile time. To illustrate, go

Chapter 14 - A Better Painting Framework (GDI+)

ahead and load the CarLibrary assembly into ildasm.exe. As you can see from Figure 9-13, this tool has read

Chapter 15 - Programming with Windows Forms Controls

the metadata to display relevant information for each type (the MusicMedia enumeration will be added later in

Chapter 16 - The System.IO Namespace this chapter).

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter

Controls

Chapter

 

Chapter

 

Index

 

List of

 

List of

 

Figure 9-13: Your car library as seen via ildasm.exe

Now, open the manifest by double-clicking the MANIFEST icon. The first code block contained in a manifest is used to specify all external assemblies that are required by the current assembly to function correctly. As you recall, CarLibrary.dll made use of mscorlib.dll and System.Windows.Forms.dll, each of which is marked in the manifest using the [.assembly extern] tag:

.assembly extern mscorlib

{

.publickeytoken = (B7 7A 5C 56 19 34 E0 89)

.ver 1:0:3300:0

}

C# and the .NET Platform, Second Edition

 

.assembly extern System.Windows.Forms

ISBN:1590590554

{

by Andrew Troelsen

Apress © 2003 (1200 pages)

 

 

.publickeytoken = (B7 7A 5C 56 19 34 E0 89)

 

This comprehensive text starts with a brief overview of the

 

.ver 1:0:3300:0

 

}

C# language and then quickly moves to key technical and

architectural issues for .NET developers.

 

Here, each [.assembly extern] block is colored by the [.publickeytoken] and [.ver] directives. The

Table of Contents

[.publickeytoken] instruction is only present if the assembly has been configured as a shared assembly (more

C# and the .NET Platform, Second Edition

details later). [.ver] is (of course) the numerical version identifier.

Introduction

PartAfterOneenumerating- Int oducingeachC# ofandthetheexternal.NET Platreferences,o m the manifest then enumerates each module contained in

Chapterthe assembly1 - The. GivenPhilosophythat theof CarLibrary.NET is a single file assembly, you will find exactly one [.module] tag. This Chaptermanifest2 also- Buildinglists aC#numberApplicationsof attributes (marked with the [.custom] tag) such as company name, trademark, Pandrt Twoso forth,- T eallC#ofProgrammingwhich are currentlyLanguageempty (more information on these attributes in Chapter 11):

Chapter 3 - C# Language Fundamentals

Ch.assemblypter 4 - ObjectCarLibrary-Oriented Programming with C#

Chapter{ 5 - Exceptions and Object Lifetime

Chapter// Ignore6 - InterfactheseandattributeCollections declarations for the time being...

.custom instance void [mscorlib]

Chapter 7 - Callback Interfaces, Delegates, and Events

System.Reflection.AssemblyKeyNameAttribute::.ctor(string) = (01 00 00 00 00)

Chapter 8 - Advanced C# Type Construction Techniques

.custom instance void [mscorlib]

Part Three - Programming with .NET Assemblies

System.Reflection.AssemblyKeyFileAttribute::.ctor(string) = (01 00 00 00 00)

Chapter 9 - Understanding .NET Assemblies

.custom instance void [mscorlib]

Chapter 10 - Processes, AppDomains, Contexts, and Threads

System.Reflection.AssemblyDelaySignAttribute::.ctor(bool) = (01 00 00 00 00)

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

.custom instance void [mscorlib]

Part Four - Leveraging the .NET Libraries

System.Reflection.AssemblyTrademarkAttribute::.ctor(string) = (01 00 00 00 00)

Chapter 12 - Object Serialization and the .NET Remoting Layer

.custom instance void [mscorlib]

Chapter 13 - Building a Better Window (Introducing Windows Forms)

System.Reflection.AssemblyCopyrightAttribute::.ctor(string) = (01 00 00 00 00)

Chapter 14 - A Better Painting Framework (GDI+)

.custom instance void [mscorlib]

Chapter 15 - Programming with Windows Forms Controls

System.Reflection.AssemblyProductAttribute::.ctor(string) = (01 00 00 00 00)

Chapter 16 - The System.IO Namespace

.custom instance void [mscorlib]

Chapter 17 - Data Access with ADO.NET

System.Reflection.AssemblyCompanyAttribute::.ctor(string) = (01 00 00 00 00)

Part Five - Web Applications and XML Web Services

.custom instance void [mscorlib]

Chapter 18

- ASP.NET Web Pages and Web Controls

System.Reflection.AssemblyConfigurationAttribute::.ctor(string)=(01 00 00 00 00)

Chapter 19

- ASP.NET Web Applcations

.custom instance void [mscorlib]

Chapter 20

- XML Web Services

System.Reflection.AssemblyDescriptionAttribute::.ctor(string) = (01 00 00 00 00)

Index.custom instance void [mscorlib]

ListSystemof Figures.Reflection.AssemblyTitleAttribute::.ctor(string) = (01 00 00 00 00)

.hash algorithm 0x00008004

List of Tables

.ver 1:0:454:30104

}

.module CarLibrary.dll

Here, you can see that the [.assembly] tag is used to mark the friendly name of your custom assembly (CarLibrary). Like external declarations, the [.ver] tag defines the compatibility version number for this assembly. To summarize the core CIL tokens found within the assembly manifest, ponder Table 9-2.

Table 9-2: Manifest CIL Tokens

 

Manifest

C#

 

andMeaningthe .NETinPlatform,Life Second Edition

 

 

 

Tag

by

 

Andrew Troelsen

ISBN:1590590554

 

 

 

 

 

 

 

 

 

.assembly

Apress © 2003 (1200 pages)

 

 

 

 

 

Marks the assembly declaration, indicating that the file is an assembly.

 

 

 

This

 

comprehensive text starts with a brief overview of the

 

 

 

 

 

 

.file

C#

 

language and then quickly moves to key technical and

 

 

 

 

Marks additional files in a multifile assembly.

 

 

 

architectural issues for .NET developers.

 

 

 

 

 

 

 

.class extern

 

 

Classes exported by the assembly but declared in another module (only used

 

 

 

 

 

with a multifile assembly).

 

 

 

 

 

 

 

 

 

Table of Contents

 

 

Indicates the manifest resources (if any).

 

 

.manifestres

 

 

 

C# and the .NET Platform, Second Edition

 

 

 

.module

 

 

Module declaration, indicating that the file is a module (i.e., a .NET binary with no

 

 

Introduction

 

 

assembly level manifest) and not the primary assembly.

 

Part One - Introducing

 

 

 

C# and the .NET Platform

 

 

 

 

 

 

 

 

 

Chapter 1 - The Philosophy of .NET

 

 

 

.assembly

 

 

The assembly reference indicates another assembly containing items referenced

 

 

Chapter 2 - Building C# Applications

 

 

 

extern

 

 

by this module.

 

 

Part Two - The C#

Programming Language

 

 

Cha.publickeyter 3 - C# LanguageContainsFu damthentalsactual bytes of the public key.

Chapter 4 - Object-Oriented Programming with C#

.publickeytoken

Contains a token of the actual public key.

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Exploring theC# andCarLibrary'sthe .NET Platform,TypesSecond Edition

by Andrew Troelsen

ISBN:1590590554

Recall that an assembly does not contain platform-specific instructions, but rather platform-agnostic CIL.

Apress © 2003 (1200 pages)

When the .NET runtime loads an assembly into memory, the underlying CIL is compiled (using the JIT

This comprehensive text starts with a brief overview of the compiler) into instructionsC# languagethatandcanthenbe understoodquickly movesby theo keytargettechnicalplatformand. .

architectural issues for .NET developers.

If you double-click the TurboBoost() method of the SportsCar class, ildasm.exe will open a new window showing the raw CIL instructions (slightly reformatted for easy reading):

Table of Contents

C# and the .NET Platform, Second Edition

.method public hidebysig virtual instance void

Introduction TurboBoost() cil managed

Part{ One - Introducing C# and the .NET Platform

Chapter// Code1 - ThesizePhilosophy of17.NET(0x11)

Chapter.maxstack2 - Building2 C# Applications

PartILTwo0000:- The C#ldstrProgramming Language"Ramming speed!"

ChapterIL_0005:3 - C# Languageldstr Fundamentals"Faster is better..."

IL_000a: call valuetype [System.Windows.Forms]

Chapter 4 - Object-Oriented Programming with C#

System.Windows.Forms.DialogResult [System.Windows.Forms]

Chapter 5 - Exceptions and Object Lifetime

System.Windows.Forms.MessageBox::Show(string, string)

Chapter 6 - Interfaces and Collections

IL_000f: pop

Chapter 7 - Callback Interfaces, Delegates, and Events

IL_0010: ret

Chapter 8 - Advanced C# Type Construction Techniques

} // end of method SportsCar::TurboBoost

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Notice that the [.method] tag is used to identify (of course) a method defined by the SportsCar type. Public

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

data defined by a type is marked with the [.field] tag. Recall that the Car class defined a set of protected

Part Four - Leveraging the .NET Libraries

data, such as currSpeed (note that the "family" tag signifies protected data).

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

.field family int16 currSpeed

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

ChapterProperties16 -areThealsoSystemmarked.IO Namespacewith the [.property] tag. Here is the CIL describing the public CurrSpeed Chapterproperty17(note- DatatheAccessread/writeith ADOnature.NETof a property is marked by .get and .set tags):

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

.property instance int16 CurrSpeed()

Chapter{ 19 - ASP.NET Web Applications

Chapter.get20instance- XML Web Servicesint16 CarLibrary.Car::get_CurrSpeed()

Index.set instance void CarLibrary.Car::set_CurrSpeed(int16)

} // end of property Car::CurrSpeed

List of Figures

List of Tables

If you now select the Ctrl+M keystroke, ildasm.exe displays the metadata for each type (Figure 9-14).

Chapter 1 - The Philosophy of .NET
Part One - Introducing C# and the .NET Platform

Figure 9-14: Type metadata for the types within carlibrary.dll

C# and the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Using this metadata (which is examined in greater detail in Chapter 11), the .NET runtime is able to locate

Apress © 2003 (1200 pages)

and construct object instances and to invoke methods. Various tools (such as Visual Studio .NET and the

This comprehensive text starts with a brief overview of the

C# compiler itself)C#makel nguageuse ofandmetadatathen quicklyat designmovestimeto keyto validatetechnicaltheandnumber (and types) of parameters during compilationarchitectural. To summarizeissu stheforstory.NET ofdevelopersassemblies. thus far, make sure the following points are clear in your mind:

Table Anof Contentsassembly is a versioned, self-describing set of modules. Each module contains some number of C# andtypesthe .andNEToptionalPlatform,resourcesSecond Edition. Type implementation is realized via CIL.

Introduction

Every assembly contains metadata that describes all types within a given module. The .NET runtime (as well as numerous .NET tools) reads the metadata to locate and create objects, validate method

calls, activate IntelliSense, and so on.

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Every assembly contains a manifest that enumerates the set of all internal and external files required

Chapter 3 - C# Language Fundamentals

by the binary, version information, as well as other assembly-centric details.

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Building a MultifileC# and the .AssemblyNET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Now that we have explored the internals of a single file assembly, let's turn our attention to the process of

Apress © 2003 (1200 pages)

building a multifile assembly. Recall that a multifile assembly will contain a particular *.dll or *.exe file that

This comprehensive text starts with a brief overview of the

contains the assemblyC# languagemanifestand(oftenth termedquickly movesthe primaryto keymoduletechnical). Additionally,and multifile assemblies contain any numberarchitecturalof *.netmoduleissues filesor .NETthatdevelare loadedpers. on demand when referenced by an external client. Do be aware that the use of *.netmodule is simply a naming convention. If you wish, your auxiliary modules could simply take a *.dll file extension.

Table of Contents

C#Atandthe timehe .NETof thisPlatform,writing,SecondVisual EditionStudio .NET does not support a project workspace type that allows you to

build stand-alone *.netmodule files. Therefore, you need to drop down to the level of the raw csc.exe

Introduction

compiler and specify the correct flags manually (be sure to read Chapter 2 if you happened to skip the

Part One - Introducing C# and the .NET Platform

discussion of csc.exe).

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

To keep things simple, let's build some rather basic types contained within a multifile assembly named

Part Two - The C# Programming Language

AirVehicles. The primary airvehicles.dll module will contain CIL and metadata for a single class type

Chapter 3 - C# Language Fundamentals

named Helicopter. The related manifest (also contained in airvehicles.dll) catalogues an additional

Chapter 4 - Object-Oriented Programming with C#

*.netmodule file named ufos.netmodule, which contains another class type named (of course) UFO.

Chapter 5 - Exceptions and Object Lifetime

Although both class types are physically contained in separate binaries, you will group them into a unified

Chapter 6 - Interfaces and Collections

namespace named AirVehicles. Finally, both classes are created using C# (although you could certainly

Chapter 7 - Callback Interfaces, Delegates, and Events mix and match languages if you desire).

Chapter 8 - Advanced C# Type Construction Techniques

To begin, open notepad.exe and create a trivial class definition named UFO within a file named ufo.cs:

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapterusing10System;- Processes, AppDomains, Contexts, and Threads

Chnamespacept r 11 - TypeAirVehiclesReflection, Late Binding, and Attribute-Based Programming

Part{ Four - Leveraging the .NET Libraries

public class UFO

Chapter 12 - Object Serialization and the .NET Remoting Layer

{

Chapter 13 - Building a Better Window (Introducing Windows Forms)

public void AbductHuman()

Chapter 14 - A Better Painting Framework (GDI+)

{

Chapter 15 - Programming with Windows Forms Controls

Console.WriteLine("Resistance is futile");

Chapter 16 - The System.IO Namespace

}

Chapter 17 - Data Access with ADO.NET

}

Part Five - Web Applications and XML Web Services

}

Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

To compile this class into a .NET module, open a command prompt and issue the following command to

IndthexC# compiler (recall the /t: flag is a shorthand notation for /target, while module specifies you wish to

Listbuildof Figura *.netmodules binary, as opposed to the primary module):

List of Tables

csc.exe /t:module ufo.cs

If you now look in the folder containing the ufo.cs file, you should see a new file named ufo.netmodule (go ahead and take a peek). Next, create a new file (using notepad.exe) named helicopter.cs:

using System; namespace AirVehicles

{

public class Helicopter

{

public void TakeOff()

{

Console.WriteLine("Helicopter taking off!");

}

}

}

C# and the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

 

 

Apress © 2003 (1200 pages)

 

 

This comprehensive text starts with a brief overview of the

 

C# language and then quickly m

ves to key technical and

Given that AirVehicles.dll is the primary module of this multifile assembly, you will need to specify the /t:

architectural issues for .NET developers.

library flag. However, as you also want to encode the ufo.net-module binary into the assembly manifest, you must also specify the /addmodule flag. The following command does the trick:

Table of Contents

csc /t:library /addmodule:ufo.netmodule /out:airvehicles.dll helicopter.cs

C# and the .NET Platform, Second Edition Introduction

Part One - Introducing C# and the .NET Platform

Now, check out the directory containing these files. You should see something like what appears in Figure

Chapter 1 - The Philosophy of .NET

9-15.

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Chapter

Chapter

Chapter

Chapter

Chapter

Events

Chapter

Part

Chapter

Chapter Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Figure 9-15: Your multifile assembly

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Exploring the ufo.netmodule

Chapter 14 - A Better Painting Framework (GDI+)

ChapterUsing ildasm15 - Programmi.exe, opengyourwithufoWindows.netmoduleFormsfileControls(see Figure 9-16).

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part

Chapter

Chapter

Chapter

Index

List of

List of

Figure 9-16: The ufo.netmodule

As you can see, *.netmodules contain a module-level manifest; however, its sole purpose in life is to list each external assembly referenced within the code base. Given that the UFO class did little more than make a call to System.Console.WriteLine(), you find the following:

.assembly extern mscorlib

{...}

C# and the .NET Platform, Second Edition

.module ufo.netmodule

by Andrew Troelsen

ISBN:1590590554

Apress © 2003 (1200 pages)

This comprehensive text starts with a brief overview of the

Exploring the airvehicles.dll

C# language and then quickly moves to key technical and architectural issues for .NET developers.

Now, using ildasm.exe, open the assembly manifest contained within airvehicles.dll. As you can see, you now have a [.file] reference to the ufo.netmodule (in addition to the various [.assembly extern] tags). The

Table[.classof Contentsextern] tag is used to mark each external type referenced by the current module.

C# and the .NET Platform, Second Edition

Introduction.assembly extern mscorlib

Part{...One}- Introducing C# and the .NET Platform

Ch.assemblypter 1 - TheairvehiclesPhilosophy of .NET

Chapter{ 2 - Building C# Applications

Part...Two - The C# Programming Language

.hash algorithm 0x00008004

Chapter 3 - C# Language Fundamentals

.ver 0:0:0:0

Chapter 4 - Object-Oriented Programming with C#

}

Chapter 5 - Exceptions and Object Lifetime

.file ufo.netmodule

Chapter 6 - Interfaces and Collections

...

Chapter 7 - Callback Interfaces, Delegates, and Events

.class extern public AirVehicles.UFO

Chapter 8 - Advanced C# Type Construction Techniques

{

Part Three - Programming with .NET Assemblies

.file ufo.netmodule

Chapter 9 - Understanding .NET Assemblies

.class 0x02000002

Chapter 10 - Processes, AppDomains, Contexts, and Threads

}

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

.module airvehicles.dll

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

ChapterAgain, realize13 - Buildingthat thea Betteronly entityW ndowthat(IlinkstroducingtogetherWindowsthe airvehiclesForms) .dll and the ufo.netmodule is the

Chapterassembly14 manifest- A Better. ThesePaintingtwoFrameworkbinary files(GDI+)have not been merged into a single, larger *.dll.

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Using the MultifileC# and theAssembly.NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

The consumers of a multifile assembly could care less that the assembly they are referencing is

Apress © 2003 (1200 pages)

composed of numerous files. To illustrate, let's create a brand new VB .NET Console application (or if you

This comprehensive text starts with a brief overview of the

prefer, a C# application)C# la guage. Set andreferencethen quicklyto themovesprimaryto keymoduletechnicalof thisandmultifile assembly (AirVehicles.dll) and System.Windowsarchitectural.Forms.issuesdll usingforthe.NETAdddevelopersReferences. dialog. Within the VB. NET Module type, create two subroutines that activate a given air vehicle. Within Main(), call each method, placing a message box call between each (in this way you are able to view the loading of the ufo.netmodule). Here is the complete

Table of Contents

VB .NET code:

C# and the .NET Platform, Second Edition

Introduction

Imports AirVehicles

Part One - Introducing C# and the .NET Platform

Imports System.Windows.Forms

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

Module Module1

Part Two - The C# Programming Language

Sub Main()

Chapter 3

- C# Language Fundamentals

 

UseHelicopter()

Chapter 4

- Object-Oriented Programm ng wi h C#

 

MessageBox.Show("Click to load ufo.netmodule")

Chapter 5

- Exceptions and Object Lifetime

 

UseUFO()

Chapter 6

-MessagInterfacesBoxand.Show("Done")Collections

ChapterEnd7

-SubCallback Interfaces, Delegates, and Events

ChapterSub8

-UseHelicopter()Advanced C# Type Construction Techniques

Part Three - ProgrammingDim h As NewwithAirVehicles.Helicopter().NET Assemblies

Chapter 9

-h.TakeOff()Understanding .NET Assemblies

ChapterEnd10

-SubProcesses, AppDomains, Contexts, and Threads

ChapterSub11

-UseUFO()Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging' This willthe .NETloadLibrariesthe *.netmodule on demand.

Chapter 12

-DimObjectu SerializationAs New UFO()and the .NET Remoting Layer

Chapter 13

-u.AbductHuman()Building a Better Window (Introducing Windows Forms)

End Sub

Chapter 14

- A Better Painting Framework (GDI+)

End Module

Chapter 15

- Programming with Windows Forms Controls

Chapter 16

- The System.IO Namespace

Chapter 17

- Data Access with ADO.NET

Now, start a debug session and once the first message box is displayed, open the Modules window (using

ParttheFive"Debug- Web| Windows"Applicationsmenuandselection)XML Web.ServicesAt this point, you should see that airvehicles.dll has been loaded

Chapter(seeFigure18 - 9ASP-17.)NET. Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter

Index

List of

List of

Figure 9-17: A single module of the multifile assembly

Now, dismiss the message box. You should now find that the related ufo.netmodule has been loaded on demand (see Figure 9-18).

Figure 9-18: *.netmodules are loaded on demand.

architectural issues for .NET developers.
C# language and then quickly moves to key technical and

C# and the .NET Platform, Second Edition

 

Again, remember that the point of multifile assemblies is to have a physical collection of files behave as a

by Andrew Troelsen

ISBN:1590590554

singly named (and versioned) unit. In and of themselves, *.netmodules do not have an individual version

Apress © 2003 (1200 pages)

number, cannot be loaded directly by the .NET runtime, and cannot be used as a stand-alone entity.

This comprehensive text starts with a brief overview of the

Individual *.netmodules can only be loaded by the primary module (e.g., the file that contains the assembly manifest).

At this point you should feel comfortable with the process of building both single file and multifile

assemblies. To be completely honest, the chances are that 99.99 percent of your assemblies will be

Table of Contents

single file entities. Nevertheless, multifile assemblies can prove helpful when you wish to break a large

C# and the .NET Platform, Second Edition

physical binary into more modular units (and are quite useful for remote download scenarios).

Introduction

Part OneNote- IntroducingThe .NET SDKC# andsuppliesthe .NETa commandPlatform line tool named al.exe (assembly linker). This tool can also

Chapter 1 be- TheusedPhiltosophybuild multifileof .NET assemblies, and can be quite helpful if you wish to build a multifile

Chapter 2 assembly- Building usingC# Applia compilerations that does not support the equivalent of the csc.exe /addmodule flag.

Part Two - TheYouC#willProgrammingget to know "al"Languagelater in this chapter when you examine the construction of publisher

Chapter 3 policy- C# Lassembliesnguage Fundamentals.

Chapter 4 - Object-Oriented Programming with C#

Next up, you need to distinguish between private and shared assemblies. If you are coming into the .NET

Chapter 5 - Exceptions and Object Lifetime

paradigm from a classic COM perspective, be prepared for some significant changes.

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Int rfaces, Delegates, and Events

SOURCE

The MultiFileAsm and MultiFileClient projects are included under the Chapter 9

ChapterCODE8 - AdvancedsubdirectoryC# Type Construction. Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

UnderstandingC# andPrivatethe .NET Platform,AssembliesSecond Edition

by Andrew Troelsen

ISBN:1590590554

Formally speaking, every assembly is deployed as "private" or "shared." The good news is each variation

Apress © 2003 (1200 pages)

has the same underlying structure (i.e., some number of modules and an associated manifest).

This comprehensive text starts with a brief overview of the

Furthermore, eachC#flavorl nguageof assemblyand thenprovidesquickly movesthe sameto keykindtechnicalof servicesand (access to some number of public types). Thearchitecturalreal differencesissuesbetweenfor .NETadevelopersprivate and. shared assembly boil down to naming conventions, versioning policies, and deployment issues. Let's begin by examining the traits of a private assembly, which is far and away the most common of the two options.

Table of Contents

C#Privateand theassemblies.NET Platfoarem,aSecondcollectionEditionof modules that is only used by the application with which it has been

deployed. For example, CarLibrary.dll is a private assembly used by the CSharpCarClient.exe and

Introduction

VbCarClient.exe applications. When you create and deploy a private assembly, the assumption is that the

Part One - Introducing C# and the .NET Platform

collection of types is only used by the "owning" application, and not shared with other applications on the

Chapter 1 - The Philosophy of .NET

system.

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Private assemblies are required to be located within the same directory as the client application (termed

Chapter 3 - C# Language Fundamentals

theapplication directory) or a subdirectory thereof. For example, recall that when you set a reference to

Chapter 4 - Object-Oriented Programming with C#

the CarLibrary.dll assembly (as you did in the CSharpCarClient.exe and VbCarClient.exe applications), the

Chapter 5 - Exceptions and Object Lifetime

Visual Studio .NET IDE responded by making a full copy of the assembly that was placed in your project's

Chapter 6 - Interfaces and Collections

application directory. This is the default behavior, as private assemblies are assumed to be the

Chapter 7 - Callback Interfaces, Delegates, and Events deployment option of choice.

Chapter 8 - Advanced C# Type Construction Techniques

Note the painfully stark contrast to classic COMthere is no need to register any items under

Part Three - Programming with .NET Assemblies

HKEY_CLASSES_ROOT and no need to enter a hard-coded path to the binary using an InprocServer32

Chapter 9 - Understanding .NET Assemblies

or LocalServer32 registry listing. The resolution and loading of the private CarLibrary.dll happens by virtue

Chapter 10 - Processes, AppDomains, Contexts, and Threads

of the fact that the assembly is placed in the application directory. In fact, if you moved

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

CSharpCarClient.exe and CarLibrary.dll to a new directory, the application would still run. To illustrate this

Part Four - Leveraging the .NET Libraries

point, copy these two files to your desktop and run the client (can you say "XCopy" installation?)

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Uninstalling (or replicating) an application that makes exclusive use of private assemblies is a no-brainer.

Chapter 14 - A Better Painting Framework (GDI+)

Delete (or copy) the application folder. Unlike classic COM, you do not need to worry about dozens of

Chapter 15 - Programmsettingswith Windows Forms Controls

orphaned registry . More important, you do not need to worry that the removal of private Chapterassemblies16 - willThebreakSystemany.IOotherNamesapplicationsace on the machine.

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Probing forC#Privateand the .NETAssembliesPlatform, Second(TheEditionBasics)

by Andrew Troelsen

ISBN:1590590554

Later in this chapter, you are exposed to some gory details regarding location resolution of an assembly.

Apress © 2003 (1200 pages)

Until then, the following overview should help prime the pump. Formally speaking, the .NET runtime

This comprehensive text starts with a brief overview of the

resolves the locationC# languageof a privateandassemblythen quicklyusingmovesa techniqueto key technicaltermedandprobing, which is much less invasive than it sounds. Probingarchitecturalis the issuesprocessforof.NETmappingdevelopersan external. assembly reference (i.e., [.assembly extern]) to the correct corresponding binary file. For example, when the runtime reads the following line from the CSharpCarClient manifest:

Table of Contents

C# and the .NET Platform, Second Edition

.assembly extern CarLibrary

Introduction

{...}

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

PartsearchTwo - isThemadeC# Programmingthe applicationLanguagedirectory for a file named CarLibrary.dll. If a *.dll binary cannot be

Chapterlocated,3 an- attemptC# Languageis madeFundamento locatealsan *.exe version (CarLibrary.exe). If neither of these files can be Chapterlocated4in -theObjectapplication-Orienteddirectory,Programmingthe runtimewith C#throws an exception. However, as you will see in just a bit,

XML configuration files (*.config) can be used to instruct the runtime to probe in other locations beyond the

Chapter 5 - Exceptions and Object Lifetime

application directory.

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

ChaptTherIdentity8 - AdvancedofC#aTypePrivateConstructionAssemblyT chniques

Part Three - Programming with .NET Assemblies

The identity of a private assembly consists of a friendly string name and numerical version, both of which

Chapter 9 - Understanding .NET Assemblies

are recorded in the assembly manifest. The friendly name is created based on the name of the binary

Chapter 10 - Processes, AppDomains, Contexts, and Threads

module that contains the assembly's manifest. For example, if you examine the manifest of the

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

CarLibrary.dll assembly, you find the following (your version will no doubt differ):

Part Four - Leveraging the .NET Libraries

Chapter 12

- Object Serialization and the .NET Remoting Layer

Ch.assemblypter 13 - BuildingCarLibraryBetter Window (Introducing Windows Forms)

Chapter{

14

- A Better Painting Framework (GDI+)

Chapter...

15

- Programming with Windows Forms Controls

Chapter.ver16

-1:0:454:30104The System.IO Namespace

Chapter}

17

- Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18

- ASP.NET Web Pages and Web Controls

However, given the nature of a private assembly, it should make sense that the .NET runtime does not

Chapter 19

- ASP.NET Web Applications

bother to apply any version policies when loading the assembly. The assumption is that private assemblies

Chapter 20

- XML Web Services

do not need to have any elaborate version checking, given that the client application is the only entity that

Index

"knows" of its existence. As an interesting corollary you should understand that it is (very) possible for a Lisinglet of Figuresmachine to have multiple copies of the same private assembly in various application directories.

List of Tables

Part Two - The C# Programming Language
Chapter 2 - Building C# Applications

Private AssembliesC# and the .NETandPlatform,XML ConfigurationSeco d Edition Files

by Andrew Troelsen

ISBN:1590590554

When the .NET runtime is instructed to bind to an assembly, the first step is to determine the presence of

Apress © 2003 (1200 pages)

an application configuration file. These optional files contain XML elements that control the binding

This comprehensive text starts with a brief overview of the

behavior of the launchingC# languapplicationge and then. Byquicklylaw, configurationmoves to key filestechnicalmustandhave the same name as the launching applicationarchitecturand takel issuesa *.configfor .NETfiledevextensionlopers..

As mentioned, configuration files can be used to specify any optional subdirectories to be searched when

Tableprobingof Cforntentsprivate assemblies. As you have seen earlier in this chapter, a .NET application can be C#deployedand thesimply.NET Platform,by placingSecondall assembliesEdition into the same directory as the application directory. Often,

however, you may wish to deploy an application such that the application directory contains a number of

Introduction

related subdirectories, in order to give some meaningful structure to the application as a whole.

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

You see this all the time in commercial software. For example, assume our main directory is called MyRadApplication, which contains a number of subdirectories (\Images, \Bin, \SavedGames,

\OtherCoolStuff). Using application configuration files, you can instruct the runtime where it should probe

Chapter 3 - C# Language Fundamentals

while attempting to locate the set of private assemblies used by the launching application.

Chapter 4 - Object-Oriented Programming with C#

ChapterTo illustrate,5 - Exceptionslet's createandsimpleObject LifetimeXML configuration file for the previous CSharpCarClient application. Our

Chaptergoal is 6to move- Interfacesthe referencedand Collectionsassembly (CarLibrary) from the Debug folder into a new subdirectory

Chnamedpt r 7\MyLibraries- Callback.Interfaces,Go aheadDelegates,and moveandthisEventsfile now (Figure 9-19).

Chapter 8 - Advanced C# Type Construction Techniques

Part

 

Chapter

 

Chapter

and Threads

Chapter

Attribute-Based Programming

Part

 

Chapter

Remoting Layer

Chapter

Windows Forms)

Chapter

 

Chapter

Controls

Chapter

 

Chapter

Part

Figure 9-19: Relocating CarLibrary.dll into a specific subdirectory

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Now, create a new configuration file named CSharpCarClient.exe.config (Notepad will do just fine) and

Chapter 20 - XML Web Services

save it into the same folder containing the CSharpCarClient.exe application, which will most likely be the

Index

Debug folder of the client project (be aware that XML is case sensitive!):

List of Figures

List of Tables

<configuration>

<runtime>

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">

<probing privatePath="MyLibraries"/>

</assemblyBinding>

</runtime>

</configuration>

Notice how *.config files always open with the root <configuration> element. The nested <runtime> element may specify an <assemblyBinding> element, which nests a further element named <probing>. The privatePath attribute is the key, as this is used to specify the list of subdirectories relative to the root.

Multiple subdirectories can be specified using a semicolon-delimited list. We have no need to do so at this time, but here is an example:

<probingprivatePath="MyLibraries;MyOtherLibaries;MyLibraries\Tests"/>

C# and the .NET Platform, Second Edition

by Andrew Troelsen ISBN:1590590554

Once you are done,Apresssave© 2003the file(1200andpages)launch the client by double-clicking the executable using the Windows ExplorerThis. Youcomprehensiveshould find thattextthestartsCSharpCarClientwith a b ief overviewapplicationof theruns without a hitch. As a final test, change the nameC# languageof yourandconfigurationthen quicklyfilemovesand attemptto key technicalto run theandprogram once again. The client

architectural issues for .NET developers.

application should now fail. Remember that configuration files must have the same name as the related client application. Because you have renamed this file, the .NET runtime assumes you do not have a

configuration file, and thus attempts to probe for the referenced assembly directly in the application

Table of Contents

directory (which it cannot locate).

C# and the .NET Platform, Second Edition

Introduction

Configuration Files and VS .NET

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

While you are always able to create a property named XML configuration file by hand (a la Notepad), it is

Chapter 2 - Building C# Applications

worth pointing out that VS .NET does provide a handy alternative. To illustrate, delete the current *.config

Part Two - The C# Programming Language

file and insert a new "Application Configuration File" item using the Project | Add New Item menu

Chapter 3 - C# Language Fundamentals selection.

Chapter 4 - Object-Oriented Programming with C#

ChapterBefore5you- clickExceptionsthe OKandbutton,ObjectbeLifetimesure the name of this new file is app.config (and nothing else). If you Chapterlook in6your- InterfacesSolution Explorerand Collectionswindow, you will now find app.config has been inserted into your current

project (Figure 9-20).

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part

 

Chapter

 

Chapter

and Threads

Chapter

Attribute-Based Programming

Part

 

Chapter

Remoting Layer

Chapter

Windows Forms)

Chapter

 

Chapter

Controls

Chapter

 

Chapter

 

Part

 

Chapter

ChapterFigure19 - 9ASP-20:.NETWorkingWeb Applicationswith the app.config file

Chapter 20 - XML Web Services

At this point, add the necessary XML to your app.config file. Now, here is the cool thing. When you compile

Index

your project, VS .NET will automatically create a new properly named file (clientName.exe.config) and

List of Figures

place it into your \Debug folder. The benefit is that if you rename your project, the *.config file is

List of Tables automatically updated.

You may also notice when you rebuild your project that VS .NET will re-copy the externally referenced CarLibrary.dll to the client's application directory (which sort of defeats the purpose of a client *.config file). To prevent VS .NET from copying externally referenced assemblies on each compile, select the *.dll in question from the Solution Explorer and set the Copy Local property to False (Figure 9-21).

Second Edition

ISBN:1590590554

with a brief overview of the

moves to key technical and

developers.

Table

C# andFigurethe .NET9-21:Platform,PreventingSecondautomaticEdition re-copying of private assemblies

Introduction

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Part Four - Leveraging the .NET Libraries
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Probing forC#Privateand the .NETAssembliesPlatform, Second(TheEditionDetails)

by Andrew Troelsen ISBN:1590590554

To wrap up our discussionApre of private assemblies, let's formalize the specific steps involved in binding to a

© 2003 (1200 pages)

private assembly at runtime. First, a request to load an assembly may be either explicit or implicit. An

This comprehensive text starts with a brief overview of the

implicit load requestC# languageoccurs wheneverand th nthequicklymanifestmovesmakesto keyatechnicaldirect referenceand to some external assembly. As you recall, externalarchitecturalreferencesissuesareformarked.NET developerswith the.[.assembly extern] token:

// An implicit load request...

Table of Contents

.assembly extern CarLibrary

C# and the .NET Platform, Second Edition

{

Introduction

...

Part One - Introducing C# and the .NET Platform

}

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

PartAn Twoexplicit- TheloadC#requestProgrammingoccursLanprogrammaticallyu ge using System.Reflection.Assembly.Load().The Assembly

Chclasspteris3examined- C# Languagein ChapterFundamentals11, but be aware that the Load() method allows you to specify the name, Chapterversion,4public- Objectkey-Orientedtoken, andProgrammiculture informationg with C# syntactically. In its simplest form, the assembly name will

do:

Chapter 5 - Exceptions and Object Lifetime Chapter 6 - Interfaces and Collections

Chapter// An7explicit- Callback Interfaces,load requestDelegates,... and Events

ChaptAssemblyr 8 - Advancedasm = AssemblyC# Type Construction.Load("CarLibrary");Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Collectively, the name, version, public key token, and cultural information is termed an assembly

Chapter 10 - Processes, AppDomains, Contexts, and Threads

reference (or simply AsmRef). The entity in charge of locating the correct assembly based on an AsmRef is termed the assembly resolver, which is a facility of the CLR. If the resolver determines the AsmRef

refers to a private assembly (i.e., no public key token is specified), the following steps are followed:

Chapter 12 - Object Serialization and the .NET Remoting Layer

1.

Chapter

Chapter

Chapter

2.

Chapter

Chapter

First, the assembly resolver attempts to locate the assembly in the client's application directory

13 - Building a Better Window (Introducing Windows Forms)

(looking for a *.dll file on the first pass, followed by an *.exe file).

14 - A Better Painting Framework (GDI+)

15 - Programming with Windows Forms Controls

If the AsmRef cannot be resolved in looking in the application directory, the assembly resolver will

16 - The System.IO Namespace

attempt to locate a configuration file in the application directory. If a configuration file exists, the

17 - Data Access with ADO.NET

runtime will attempt to locate the private assembly using the <probing> element.

Part Five - Web Applications and XML Web Services

Chapter3. If18the- ASPassembly.NET WebcannotPagesbeandfoundWebwithinControlsthe application directory (or a specified subdirectory) the

search stops here and a FileNotFound exception is raised.

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Again, as you can see, the location of a private assembly is fairly simple to resolve. Next up, let's turn our

Index

attention to the construction of shared assemblies.

List of Figures

List of Tables

UnderstandingC# andSharedt e .NET Platform,AssembliesSecond Edition

by Andrew Troelsen

ISBN:1590590554

Like a private assembly, a "shared" assembly is a collection of types and (optional) resources contained

Apress © 2003 (1200 pages)

within some number of modules. The most obvious difference between shared and private assemblies is

This comprehensive text starts with a brief overview of the

the fact that sharedC#assemblieslanguage andcanthenbequicklyused bymovesseveralto keyclientstechnicon alsinglea d machine. By way of a simple example, considerarchitecturalall the applicationsissues forcreated.NET developersin this text. which required you to set a reference to System.Windows.Forms.dll. If you were to look in the application directory of each of these clients, you wouldnot find a private copy of this .NET binary. The reason is that System.Windows.Forms.dll has been

Table of Contents

deployed as a shared assembly. Clearly, if you need to create a machine-wide class library, this is the way

C# and the .NET Platform, Second Edition

to go.

Introduction

As suggested in the previous paragraph, a shared assembly is not deployed within the same directory as

Part One - Introducing C# and the .NET Platform

the application making use of it. Rather, shared assemblies are installed into a machine-wide Global

Chapter 1 - The Philosophy of .NET

Assembly Cache, which lends itself to yet another colorful acronym in the programming universe: the

Chapter 2 - Building C# Applications

GAC. The GAC itself is located under the <drive>: \ %windir%\ Assembly subdirectory (Figure 9-22).

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

Chapter

Chapter

Chapter

Chapter

Chapter

Part

Chapter

 

Chapter

 

Chapter

Programming

Part Four - Leveraging the .NET Libraries

 

Figure 9-22: The Global Assembly Cache

 

Chapter 12 - Object Serialization and the .NET Remoting Layer

 

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Before you deploy an assembly to the GAC, you must assign it a "strong name." Simply put, a strong

Chapter 14 - A Better Painting Framework (GDI+)

name is used to uniquely identify the publisher of a given .NET binary. This publisher could be an

Chapter 15 - Programming with Windows Forms Controls

individual programmer, a department within a given company, or the entire company at large.

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Note Technically speaking, private assemblies may also be assigned a strong name. However, given

Part Five - Web Applications and XML Web Services

that all shared assemblies must have a strong name, you are correct to assume that a vast

Chapter 18 - ASP.NET Web Pages and WebassembliesControls

majority of strongly named are intended to be shared.

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

UnderstandingC# andStrongthe .NET Platform,NamesSecond Edition

by Andrew Troelsen

ISBN:1590590554

A strong name is composed of the following bits of information:

Apress © 2003 (1200 pages)

This comprehensive text starts with a brief overview of the

A friendly string name of the assembly (i.e., the name of the binary without its file extension)

C# language and then quickly moves to key technical and

architectural issues for .NET developers.

A version number of the assembly

A public key (or a token derived from the full public key)

Table of Contents

C# and the .NET Platform,valueS cond Edition

A culture identity (for localization)

Introduction

In some ways, a strong name is the modern day .NET equivalent of the COM AppID. Unlike AppIDs (which

Part One - Introducing C# and the .NET Platform

were simply 128-bit numbers), strong names are based on public/private key cryptography. When you

Chapter 1 - The Philosophy of .NET

create a shared assembly, you must make use of a public/private key pair (which you do momentarily).

Chapter 2 - Building C# Applications

This aspect of a strong name helps ensure that (a) the assembly has not been tampered with since it was

Part Two - The C# Programming Language

shipped, (b) each assembly publisher has a unique identity, and (c) new versions of a specific assembly

Chapter 3 - C# Language Fundamentals

ship from the same publisher.

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

In a nutshell, public/private key cryptography requires two distinct, but interrelated, keys (termed the

Chapter 6 - Interfaces and Collections

"public" key and the "private" key). In terms of .NET, this information is generated by a command line hook

Chapter 7 - Callback Interfaces, Delegates, and Events

(sn.exe) and saved to a file, which by default takes a *.snk file extension (Strong Name Key). This file is Chapterreferenced8 - duringAdvancedtheC#compilationType Constructionof an assemblyTechniquesto embed the public key value in the shared assembly's

PartmanifestThree(identified- Programmwithngthewith[.publickey].NET Assembliestag).

Chapter 9 - Understanding .NET Assemblies

The private key is obviously not listed in the manifest, but rather is used to digitally sign the contents of the

Chapter 10 - Processes, AppDomains, Contexts, and Threads

assembly (in conjunction with a generated hash code). The resulting digital signature is stored in the

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

assembly itself as an embedded blob within the CLR header. Again, the whole idea of making use of

Part Four - Leveraging the .NET Libraries

public/private key cryptograph is to ensure that no two companies, departments, or individuals have the

Chapter 12 - Object Serialization and the .NET Remoting Layer

same identity in the .NET universe. In any case, once the process of assigning a strong name is complete,

Chapter 13 - Building a Better Window (Introducing Windows Forms) the assembly may be installed into the GAC.

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

When a client application using a shared assembly is compiled, a token of the shared assembly's public Chapterkey is recorded16 - The inSystthemclient.IO Namespacemanifest (denoted with the [.publickeytoken] tag). This public key token is a

Chaptershorted17form- Dataof theAccessfull publicwith ADOkey,.NETwhich boils down to a 64-bit hashing of the entire public key value.

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Building a SharedC# nd theAssembly.NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

To illustrate the process of assigning a strong name to an assembly, let's walk through a complete

Apress © 2003 (1200 pages)

example. Assume you have created a new C# Class Library named SharedAssembly, which contains the

This comprehensive text starts with a brief overview of the following class definition:C# language and then quickly moves to key technical and

architectural issues for .NET developers.

public class VWMiniVan

{

Table of Contents

private bool isBustedByTheFuzz = false;

C# and the .NET Platform, Second Edition

Introduction

public VWMiniVan()

Part One - Introducing C# and the .NET Platform

{

Chapter 1 - The Philosophy of .NET

MessageBox.Show("Using version 1.0.0.0!", "Shared Car");

Chapter}2 - Building C# Applications

Part Two - The C# Programming Language

public void Play60sTunes()

Chapter{3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

MessageBox.Show("What a loooong, strange trip it's been...");

Chapter}5 - Exceptions and Object Lifetime

Chapterpublic6 - Interfacesbool Bustedand Collections

Chapter{7 - Callback Interfaces, Delegates, and Events

get { return isBustedByTheFuzz; }

Chapter 8 - Advanced C# Type Construc ion Techniques

set { isBustedByTheFuzz = value; }

Part Three - Programming with .NET Assemblies

Chapter}9 - Understanding .NET Assemblies

}

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

To generate the key file, you need to make use of the sn.exe (strong name) utility. Although this tool has

Chapter 12 - Object Serialization and the .NET Remoting Layer

numerous command line options, all you need to concern yourself with for the moment is the "-k" flag,

Chapter 13 - Building a Better Window (Introducing Windows Forms)

which instructs the tool to generate a new *.snk file that contains the public/private key information (Figure

Chapter 14 - A Better Painting Framework (GDI+)

9-23).

Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace

Chapter

Part

Chapter

Chapter

Chapter

Index

Figure 9-23: Using sn.exe to generate the public/private key pair file

List of Figures

List of Tables

Note Once you have a *.snk file, you may use this same file for all of the shared assemblies you create from here on out. Again, understand that this file contains information that provides you with a unique identity in the world of .NET. Obviously, this key file should be kept in a safe location.

The next step is to inform the C# compiler exactly where the *.snk file is located to record the public key in the assembly manifest. When you create a new C# project workspace, you will notice that one of your initial project files is named "AssemblyInfo.cs".

This file contains a number of attributes that describe the assembly itself (more information on attributes in theChapter 11). One attribute that may appear within this file is named AssemblyKeyFile. Simply update the initial empty value with a string specifying the location of your *.snk file, for example:

[assembly:AssemblyKeyFile(@"C:\MyKey\myKey.snk")]

C# and the .NET Platform, Second Edition

Given that the version of a shared assembly is of prime importance, let's also specify a fixed numerical

value. In the same AssemblyInfo.cs file, you will find another attribute named AssemblyVersion. Initially the

by Andrew Troelsen ISBN:1590590554 value is set to "1.0.*":

Apress © 2003 (1200 pages)

This comprehensive text starts with a brief overview of the

[assembly:AssemblyVersion("1.0.*")]

C# language and then quickly moves to key technical and architectural issues for .NET developers.

Every new C# projects begins life versioned at 1.0.*. Recall that a .NET version number is composed of

the four parts (<major>.<minor>.<build>.<revision>). Until you say otherwise, VS .NET automatically

Table of Contents

increments the build and revision numbers (as marked by the "*" wildcard symbol) as part of each

C# and the .NET Platform, Second Edition

compilation. To enforce a fixed value for the assembly's build version, simply update accordingly:

Introduction

Part One - Introducing C# and the .NET Platform

Ch[assembly:pter 1 - TheAssemblyVersion("Philosophy of .NET 1.0.0.0")]

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Using these two assembly-level attributes, the C# compiler now merges the necessary information into the

Chapter 3 - C# Language Fundamentals

corresponding manifest to establish your strong name, which can be seen using ildasm.exe (note the

Chapter 4 - Object-Oriented Programming with C#

[.publickey] and [.ver] tokens in Figure 9-24).

Chapter 5 - Exceptions and Object Lifetime Chapter 6 - Interfaces and Collections Chapter

Chapter

Part

Chapter

 

Chapter

 

Chapter

Programming

Part

 

Chapter

 

Chapter

Forms)

Figure 9-24: A strongly named assembly documents the public key in the manifest.

Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls

ChapterSOURCE16 - The SystemThe.IOSharedAssemblyN mespace project is located under the Chapter 9 subdirectory.

ChapterCODE17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Соседние файлы в предмете Программирование