App Domains

When the CLR COM server is loaded into a Windows process, it initializes. Part of this initialization is to create the managed heap that all reference objects get allocated in and garbage collected from. In addition, the CLR creates a thread pool usable by any of the managed types whose assemblies are loaded into the process. While initializing, the CLR also creates an AppDomain. An AppDomain is a logical container for a set of assemblies. The first AppDomain created when the CLR initializes is...

App Domain Events

I want to briefly mention that each AppDomain exposes a number of events that can be incredibly useful. Table 20-1 lists the events that your code can register interest in. I want to briefly mention that each AppDomain exposes a number of events that can be incredibly useful. Table 20-1 lists the events that your code can register interest in. This event is fired every time the CLR loads an assembly into the AppDomain. The handler receives a System.Reflection.Assembly object identifying the...

Comparing Strings

Comparing is probably the most common operation performed on strings. Fortunately, the String type offers several static and instance methods that allow you to compare strings in very useful ways. Table 12-1 summarizes these methods. Table 12-1 Methods for Comparing Strings Returns how two strings should be sorted with respect to each other. Unlike the CompareTo method, this method gives you control over the culture used (via a CultureInfo object) and case sensitivity. If you need more advanced...

What Causes Finalize Methods to Get Called

Four events cause an object to have its Finalize method called Generation 0 is full This event is by far the most common way for Finalize methods to be called because it occurs naturally as the application code runs, allocating new objects. Code explicitly calls system.GC's static Collect method Code can explicitly request that the CLR perform a collection. Although Microsoft strongly discourages such requests, at times it might make sense for an application to force a collection. (I'll talk...

Parameterless Properties

Many types define state information that can be retrieved or altered. Frequently, this state information is implemented as field members of the type. For example, here's a type definition that contains two fields public String Name The employee's name public Int32 Age The employee's age If you were to create an instance of this type, you could easily get or set any of this state information with code similar to the following e.Name Jeffrey Richter Set the employee's Name. e.Age 35 Set the...

Constructing a String Builder Object

Unlike with the String class, the CLR has no special knowledge of the StringBuilder class. In addition, most languages (including C ) don't consider the StringBuilder class to be a primitive type. You construct a StringBuilder object as you would any other nonprimitive type StringBuilder sb new StringBuilder( ) The StringBuilder type offers many constructors. The job of each constructor is to allocate and initialize the three internal fields maintained by each StringBuilder object Maximum...

What Exactly Is an Exception

Over the years, I've run into many developers who think that an exception identifies something that rarely happens an exceptional event. I always ask them to define exceptional event. They respond, You know, something you don't expect to happen. Then they add, If you're reading bytes from a file, eventually you'll reach the end of the file. So because you expect this, an exception shouldn't be raised when you reach the end of the file. Instead, the Read method should return some special value...

Accessing Objects Across App Domain Boundaries

Code in one AppDomain can communicate with types and objects contained in another AppDomain. However, the access to these types and objects is only through well-defined mechanisms. Most types are marshaled by value across AppDomain boundaries. In other words, if an object is constructed in one AppDomain and a reference to this object is passed to another AppDomain, the CLR must first serialize the object's fields into a block of memory. This block of memory is then passed to the other...

Probing for Assembly Files

When the CLR needs to locate an assembly, it scans several subdirectories. Here is the order in which directories are probed for a culture-neutral assembly AppBase AsmName.dll AppBase AsmName AsmName.dll AppBase privatePath1 AsmName.dll AppBase privatePath1 AsmName AsmName.dll AppBase privatePath2 AsmName.dll In the example above, no configuration file would be needed if the JeffTypes assembly files were deployed to a subdirectory called JeffTypes since the CLR would automatically scan for a...

The Common Language Specification

Common Language Specification

COM allows objects created in different languages to communicate with one another. On the other hand, the CLR now integrates all languages and allows objects created in one language to be treated as equal citizens by code written in a completely different language. This integration is possible because of the CLR's standard set of types, self-describing type information metadata , and common execution environment. While this language integration is a fantastic goal, the truth of the matter is...

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...

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...

Providing Your Own Custom Formatter

By now it should be clear that the formatting capabilities in the .NET Framework were designed to offer you a great deal of flexibility and control. However, we're not quite done. It's possible for you to define a method that StringBuilder's AppendFormat method will call whenever any object is being formatted into a string. In other words, instead of calling ToString for each object, AppendFormat can call a function that you define, allowing you to format any or all of the objects any way you...

The Dispose Pattern Forcing an Object to Clean Up

The Finalize method is incredibly useful because it ensures that unmanaged resources aren't leaked when managed objects have their memory reclaimed. However, the problem with the Finalize method is that you have no guarantee when it will be called, and because it isn't a public method, a user of the class can't call it explicitly. The capability to deterministically dispose of or close an object is frequently useful when you're working with unmanaged resources such as mutexes and bitmaps this...

Building Packaging Deploying and Administering Applications and Types

Figure 2-1 A multifile assembly consisting of two managed modules, one with a manifest Figure 2-2 Add Reference dialog box in Visual Studio .NET Figure 2-3 A multifile assembly consisting of three managed modules, one with a manifest Figure 2-4 Version tab of the JeffTypes.dll Properties dialog box Figure 2-5 Resource editor in Visual Studio .NET Figure 2-6 Applications node of the Microsoft .NET Framework Configuration tool Figure 2-7 Configuring an application using the Microsoft .NET...

Finalization Internals

On the surface, finalization seems pretty straightforward you create an object when the object is collected, the object's Finalize method is called. But once you dig in, finalization is more complicated than this. When an application creates a new object, the new operator allocates the memory from the heap. If the object's type defines a Finalize method, a pointer to the object is placed on the finalization list just before the type's instance constructor is called. The finalization list is an...

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...

Explicitly Unloading Assemblies Unloading an App Domain

The CLR doesn't support the ability to unload an assembly. Instead, you can unload an AppDomain, which causes all the assemblies contained within it to be unloaded. Unloading an AppDomain is very easy you just call AppDomain's static Unload method, passing it a reference to the AppDomain you want unloaded. Note As I mentioned previously, assemblies that are loaded in a domain-neutral fashion can never be unloaded from an AppDomain. To unload these assemblies, the process must be terminated. The...

Operators and Programming Language Interoperability

Operator overloading can be a very useful tool, allowing developers to express their thoughts with succinct code. However, not all programming languages support operator overloading. For example, Visual Basic and Java don't. So when a Visual Basic developer applies the operator to a type that Visual Basic doesn't consider to be a primitive, the compiler generates an error and won't compile the code. So here's the problem that needs to be solved How can a developer using a language that doesn't...

Fast Array Access

Each time an element of an array is accessed, the CLR ensures that the index is within the array's bounds. This prevents you from accessing memory that is outside of the array, which would potentially corrupt other objects. If an invalid index is used to access an array element, the CLR throws a System.IndexOut-OfRangeException exception. As you might expect, the CLR's index checking comes at a performance cost. If you have confidence in your code and if you don't mind resorting to...

Parameterful Properties

In the previous section, the get accessor methods for the properties accepted no parameters. For this reason, I called these properties parameterless properties. These properties are easy to understand because they have the feel of accessing a field. In addition to these fieldlike properties, the CLR also supports what I call parameterful properties, whose get access methods accept one or more parameters. Different programming languages expose parameterful properties in different ways. Also,...

The Common Type System

By now, it should be obvi ous to you that the CLR is all about types. Types expose functionality to your applications and components. Types are the mechanism by which code written in one programming language can talk to code written in a different programming language. Because types are at the root of the CLR, Microsoft created a formal specification the Common Type System CTS that describes how types are defined and how they behave. The CTS specification states that a type can contain zero or...

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 WserA we Local Settings Application Data...

Unhandled Exceptions

Powerpoint Send Report

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...

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 HKEY LOCAL If this value exists, its value must be one of those listed in Table 18-2. Table 18-2 Possible Values of DbgJITDebugLaunchSetting If this value exists, its value must be one of those listed in Table 18-2. Table 18-2 Possible Values of...

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...

Calling a Types Method

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