What Makes Up the Microsoft NET Initiative

I've been working with Microsoft and its technologies for many years now. Over the years, I've seen Microsoft introduce all kinds of new technologies and initiatives MS-DOS, Windows, Windows CE, OLE, COM, ActiveX, COM + , Windows DNA, and so on. When I first started hearing about Microsoft's .NET initiative, I was surprised at how solid Microsoft's story seemed to be. It really seemed to me that they had a vision and a plan and that they had rallied the troops to implement the plan. I contrast...

Combining Managed Modules into Assemblies

The CLR doesn't actually work with modules it works with assemblies. An assembly is an abstract concept that can be difficult to grasp initially. First, an assembly is a logical grouping of one or more managed modules or resource files. Second, an assembly is the smallest unit of reuse, security, and versioning. Depending on the choices you make with your compilers or tools, you can produce a single-file or a multifile assembly. In Chapter 2, I'll go over assemblies in great detail, so I don't...

Programming Language Primitive Types

Certain data types are so commonly used that many compilers allow code to manipulate them using simplified syntax. For example, you could allocate an integer using the following syntax System.Int32 a new System.Int32() But I'm sure you'd agree that declaring and initializing an integer using this syntax is rather cumbersome. Fortunately, many compilers (including C ) allow you to use syntax similar to the following instead This syntax certainly makes the code more readable, and, of course, the...

Bind Once Invoke Multiple Times

Type's InvokeMember method gives you access to all a type's members. However, you should be aware that every time you call InvokeMember, it must bind to a particular member and then invoke it. Having the binder select the right member each time you want to invoke a member is time-consuming, and if you do it a lot, your application's performance will suffer. So if you plan on accessing a member frequently, you're better off binding to the desired member once and then accessing that member as...

Reflecting Over a Types Interfaces

To obtain the set of interfaces that a type inherits, you can call Type's FindInterfaces, GetInterface, or GetInterfaces method. All these methods return Type objects that represent an interface. Note that these methods only check interfaces that the type directly inherits these methods won't return interfaces that an interface inherits. To determine an interface's base interface, you must call one of these methods again using the interface type and so on to walk the interface inheritance tree....

Building an Assembly That References a Strongly Named Assembly

Whenever you build an assembly, the assembly will have references to other strongly named assemblies. This is true if only because System.Object is defined in MSCorLib.dll. However, it's likely that an assembly will reference types in other strongly named assemblies published either by Microsoft, by a third party, or by your own organization. In Chapter 2, I showed you how to use CSC.exe's reference command-line switch to specify the assembly filenames you want to reference. If the filename is...

Lnterfaces and lnheritance

When programming, it's useful to think of an object as being of multiple types because the type of an object describes its capabilities and behavior. For example, you could design a SortedList type that maintains a set of objects in a sorted order. You could add any System.Object-derived type into the SortedList as long as the type supported the ability to compare itself to another type. In a sense, the SortedList would like to accept only types that are derived from a hypothetical...

Operator Overload Methods

Some programming languages allow a type to define how operators should manipulate instances of the type. For example, a lot of types (such as System.String) overload the equality ( ) and inequality ( ) operators. The CLR doesn't know anything about operator overloading because it doesn't even know what an operator is. Your programming language defines what each operator symbol means and what code should be generated when these special symbols appear. For example, in C , applying the + symbol to...

Simple Administrative Control Configuration

The user or the administrator can best determine some aspects of an application's execution. For example, an administrator might decide to move an assembly's files on the user's hard disk or to override information contained in the assembly's manifest. Other scenarios also exist related to versioning and remoting I'll talk about some of these in Chapter 3. To allow administrative control over an application, a configuration file can be placed in the application's directory. An application's...

Combining Modules to Form an Assembly

The App.exe file discussed in the previous section is more than just a PE file with metadata it is also an assembly. An assembly is a collection of one or more files containing type definitions and resource files. One of the assembly's files is chosen to hold a manifest. The manifest is another set of metadata tables that basically contain the name of the files that are part of the assembly. They also describe the assembly's version, culture, publisher, publicly exported types, and all the...

The Garbage Collection Algorithm

The garbage collector checks to see whether there are any objects in the heap that are no longer being used by the application. If such objects exist, the memory used by these objects can be reclaimed. (If no more memory is available in the heap, then new throws an OutOfMemoryException exception.) How does the garbage collector know whether or not the application is using an object As you might imagine, this isn't a simple question to answer. Every application has a set of roots. A single root...

Compiling Source Code into Managed Modules

OK, so you've decided to use the .NET Framework as your development platform. Great Your first step is to determine what type of application or component you intend to build. Let's just assume that you've completed this minor detail, everything is designed, the specifications are written, and you're ready to start development. Now you must decide what programming language to use. This task is usually difficult because different languages offer different capabilities. For example, in unmanaged C...

Assembly Version Resource Information

Legaltrademarks

When AL.exe or CSC.exe produces a PE file assembly, it also embeds into the PE file a standard Win32 Version resource. Users can examine this resource by viewing the file's properties. Figure 2-4 shows the Version page of the JeffTypes.dll Properties dialog box. -igure 2-4 Version tab of the JeffTypes.dll Properties dialog box In addition, you can use the resource editor in Visual Studio .NET, shown in Figure 2-5, to view modify the version resource fields. Microsoft Development Environment...

The NET Framework Class Library

Included with the .NET Framework is a set of .NET Framework Class Library (FCL) assemblies that contains several thousand type definitions, where each type exposes some functionality. All in all, the CLR and the FCL allow developers to build the following kinds of applications XML Web services Methods that can be accessed over the Internet very easily. XML Web services are, of course, the main thrust of Microsoft's .NET initiative. Web Forms HTML-based applications (Web sites). Typically, Web...

Designing a Type That Exposes an Event

Let's look at the type definition for MailManager to really understand all the steps you must take to properly define an event member using Microsoft's recommended design pattern The MailMsgEventArgs type is defined within the MailManager type, public class MailMsgEventArgs EventArgs 1. Type defining information passed to receivers of the event public MailMsgEventArgs( String from, String to, String subject, String body) this.from from this.to to this.subject subject this.body body public...

Unhandled Exceptions

As explained in the previous section, when an exception is thrown, the CLR starts searching for a catch filter interested in handling the exception. If no catch filter accepts the exception object, an unhandled exception occurs. An unhandled exception identifies a situation that the application didn't anticipate. When developing an application, you should set a policy for dealing with unhandled exceptions. In addition, it's quite common to have one policy for debug versions of your application...

Calling a Types Method

The easiest way to call a method is to use Type's lnvokeMember method. This method is quite powerful in that it lets you do lots of stuff. There are several overloaded versions of lnvokeMember. I'll discuss the one that has the most parameters the other overloads simply pick defaults for certain parameters, making them easier to call. BindingFlags invokeAttr, How to look up members Binder binder, How to match members and arguments Object target, Object args, CultureInfo culture When you call...

Weak Reference internals

From the preceding discussion, it should be obvious that WeakReference objects don't behave like other object types. Normally, if your application has a root that refers to an object and that object refers to another object, both objects are reachable and the garbage collector can't reclaim the memory either object is using. However, if your application has a root that refers to a WeakReference object, the object referred to by the WeakReference object isn't considered reachable and can be...

Yukon

The next version of Microsoft SQL Server code-named Yukon is an unmanaged application because most of its code is still written in unmanaged C . During initialization, however, Yukon will create a CLR COM server. Yukon allows stored procedures to be written in any managed programming language C , Visual Basic, Smalltalk, and so on . These stored procedures will run in their own AppDomain that has special evidence applied to it prohibiting the stored procedures from adversely affecting the...

Encodings Converting Between Characters and Bytes

In Win32, programmers all too frequently have to write code to convert Unicode characters and strings to Multi-Byte Character Set MBCS characters and strings. I've certainly written my share of this code, and it's very tedious to write and error prone to use. In the CLR, all characters are represented as 16-bit Unicode code values and all strings are composed of 16-bit Unicode code values. This makes working with characters and strings easy at run time. At times, however, you want to save...

Designing a Type That Listens for an Event

The hard work is definitely behind you at this point. In this section, I'll show you how to define a type that uses an event provided by another type. Let's start off by examining the code for the Fax type Pass the MailManager object to the constructor, public Fax MailManager mm Construct an instance of the MailMsgEventHandler delegate that refers to the FaxMsg callback method. Register the callback with MailManager's MailMsg event. mm.MailMsg new This is the method that MailManager will call...

Interoperability with Unmanaged Code

The .NET Framework offers a ton of advantages over other development platforms. However, very few companies can afford to redesign and reimplement all of their existing code. Microsoft realizes this and has constructed the CLR so that it offers mechanisms that allow an application to consist of both managed and unmanaged parts. Specifically, the CLR supports three interoperability scenarios Managed code can call an unmanaged function in a DLL Managed code can easily call functions contained in...

Explicit lnterface Member lmplementations

Interfaces are great because they define a standard way for types to communicate with each other. However, this flexibility comes at the cost of compile-time type safety because most interface methods accept parameters of type System.-Object or return a value whose type is System.Object. Look at the very common lComparable interface This interface defines one method that accepts a parameter of type System.Object. If I define my own type that implements this interface, the type definition might...

Running this program yields the following output

WebName utf-16, HeaderName utf-16, BodyName utf-16 IsBrowserDisplay False, IsBrowserSave True IsMailNewsDisplay False, IsMailNewsSave False WebName unicodeFFFE, HeaderName unicodeFFFE, BodyName unicodeFFFE IsBrowserDisplay False, IsBrowserSave False IsMailNewsDisplay False, IsMailNewsSave False CodePage 65001, WindowsCodePage 1200 WebName utf-8, HeaderName utf-8, BodyName utf-8 IsBrowserDisplay True, IsBrowserSave True IsMailNewsDisplay True, IsMailNewsSave True CodePage 65000, WindowsCodePage...

The Global Assembly Cache

Now that you know how to create a strongly named assembly, it's time to learn how to deploy this assembly and how the CLR uses the information to locate and load the assembly. If an assembly is to be accessed by multiple applications, the assembly must be placed into a well-known directory and the CLR must know to look in this directory automatically when a reference to the assembly is detected. This well-known location is called the global assembly cache GAC , which can usually be found in the...

Explicitly Loading Assemblies

So far, I've shown you how to reflect on the assemblies that are loaded into an AppDomain. Knowing how to do this is useful, but you must remember that the CLR decides when to load an assembly the first time a method is called, the CLR examines the method's IL code to see what types are referenced. The CLR then loads all the assemblies that define the referenced types. If a required assembly is already available in the AppDomain, the CLR knows not to load the assembly again. But let's say you...

Unhandled Exceptions and Windows Forms

In a Windows Forms application, the System.Windows.Forms.Application class has a static Run method that's responsible for the thread's message loop. This loop dispatches window messages to a private method defined by the System.Windows.Forms.NativeWindow type. This method simply sets up a try catch block and inside the try block, the protected WndProc method is called. If a System.Exception-derived unhandled exception occurs while processing a window message, the catch block calls the window...

Controlling What the CLR Does When an Unhandled Exception Occurs

When a managed thread has an unhandled exception, the CLR examines some settings to determine whether it should launch a debugger. To make this determination, the CLR checks the following registry subkey for the DbgJITDebugLaunchSetting value If this value exists, its value must be one of those listed in Table 18-2. Table 18-2 Possible Values of DbgJITDebugLaunchSetting Table 18-2 Possible Values of DbgJITDebugLaunchSetting Display a dialog box asking the user whether he would like to debug the...

Using the Bit Array types indexer is incredibly simple

Allocate a BitArray that can hold 14 bits. BitArray ba new BitArray 14 Turn all the even-numbered bits on by calling the set accessor, for Int32 x 0 x lt 14 x ba x x 2 0 Show the state of all the bits by calling the get accessor. foreach Int32 x 0 x lt 14 x Console.WriteLine Bit x is ba x On Off In the BitArray example, the indexer takes one Int32 parameter, bitPos. All indexers must have at least one parameter, but they can have more. These parameters as well as the return type can be of any...

Obtaining a Reference to a System Type Object

Reflection is most commonly used to learn about types or to manipulate objects using information that is typically known only at run time, not at compile time. Obviously, this dynamic exploring and manipulation of types and objects comes at a performance hit, so you should use it sparingly. In addition, a compiler can't help you locate and fix programming errors related to type safety when you're using reflection. The System.Type type is your starting point for doing type and object...

Loading the Common Language Runtime

Each assembly that you build can be either an executable application or a DLL containing a set of types components for use by an executable application. Of course, the CLR is responsible for managing the execution of code contained within these assemblies. This means that the .NET Framework must be installed on the host machine. Microsoft has created a redistribution package that you can freely ship to install the .NET Framework on your customers' machines. Eventually, the .NET Framework will...

CLR Hosting

The .NET Framework runs on top of Microsoft Windows. This means that the .NET Framework must be built using technologies that Windows understands. For starters, all managed module and assembly files must use the Windows portable executable PE file format and be either a Windows EXE file or a dynamic-link library DLL . When developing the CLR, Microsoft implemented it as a COM server contained inside a DLL that is, Microsoft defined a standard COM interface for the CLR and assigned GUIDs to this...

Repairing a Faulty Application

When a console or Windows Forms application is running under a user account, the CLR keeps a record of the assemblies that the application actually loads a record isn't kept for ASP.NET Web Forms or XML Web services applications. This assembly load information is accumulated in memory and is written to disk when the application terminates. The files that contain this information are written to the following directory C Documents and Settings UserName Local Settings Application Data...