Showing posts with label .NET Framework. Show all posts
Showing posts with label .NET Framework. Show all posts

The WMI Performance Counter Provider

Perhaps, the most significant performance implication of using the Performance Monitoring provider is the necessity to marshal fairly large amounts of data. The Performance Monitoring provider is a conventional, old-fashioned WMI provider that is always loaded out-of-process respective to the client application, hence the need for marshalling the performance data across the process boundaries.

High-Performance Providers
To alleviate the performance problem often associated with conventional providers, Microsoft introduced a so-called high-performance provider API— a set of interfaces designed to increase the efficiency of communication between a client WMI application and a data provider. The basic idea behind the high-performance provider API is simple. As opposed to conventional providers, high-performance providers, if located on the same machine as the client application, are loaded in-process to the client, thus eliminating the need for cross-process data marshalling. Even when a client and a provider are located on different computers, the high-performance API is still a superior communication vehicle because it allows for caching the data on the remote machine and transmits only the minimal required data back to the client.

Because performance data providers need to handle vast amounts of frequently changing statistical data, choosing them to be implemented as high-performance providers is a good idea. Thus, starting with Windows 2000, the WMI distribution includes a high-performance alternative to the Performance Monitoring provider: the Performance Counter provider, also referred to as the Raw Performance Counter provider.

The Performance Counter Provider and the ADAP Process
Besides addressing performance issues, the Performance Counter provider eliminates the need to manually define the WMI classes that represent various performance objects. More precisely, it is not the provider itself, but rather the WMI AutoDiscovery/AutoPurge (ADAP) process that allows you to automatically import the definitions for Windows performance objects into the CIM Repository. The sole purpose of ADAP is to monitor the state of performance objects on a given computer and ensure that the definitions for these objects remain synchronized with their respective WMI performance class definitions.

On Windows 2000 and XP platforms, the ADAP process is launched automatically as soon as the WinMgmt service starts; unfortunately, neither the ADAP functionality nor the Performance Counter provider are available on any other Windows platforms. Upon startup, ADAP examines all currently installed performance DLLs and generates a list of all currently available performance objects. This list is then compared to a list of WMI performance classes and necessary adjustments are made.

Under Windows 2000 and XP, you can add custom performance objects and counters by implementing a performance DLL and registering it using lodctr.exe utility. Obviously, installing a new performance library is likely to render the WMI performance class definitions outdated or incomplete. That is why lodctr.exe and its counterpart unlodctr.exe, which is used to de-register the performance libraries, both invoke the ADAP process, thus making sure that WMI's CIM Repository remains synchronized with the actual performance objects.

ADAP can also be invoked manually via the /resyncperf command-line switch of winmgmt.exe:

winmgmt.exe /resyncperf

On Windows 2000, ADAP is implemented as part of winmgmt.exe; however, under Windows XP, it is a separate executable called wmiadap.exe.



wmiadap.exe Command-Line Options
/f Instructs wmiadap.exe to parse all performance DLLs on a given system and synchronize the WMI performance class definitions

/c Causes wmiadap.exe to clear the status of all currently available performance libraries

/r Instructs wmiadap.exe to parse all the Windows Driver Model (WDM) drives on a given system and synchronize the WMI performance class definitions

/t Throttles the ADAP process as soon as the user operates a keyboard or mouse




It is, therefore, possible to invoke the ADAP process manually as follows:

wmiadap.exe /f

The ADAP process maintains an error log, which can be found in %SystemRoot%\System32\Wbem\Logs\Wmiadap.log. The log is used to record various events triggered during the execution of the ADAP process, such as indications of the process's startup and shutdown as well as certain error conditions. In addition to the log file, all errors related to loading and parsing the performance DLLs are recorded in the Windows event log and can be viewed with the Event Viewer (eventvwr.exe). ADAP error messages can be found in the application log—you can filter errors based on the value of the Source column, which should be set to WinMgmt for ADAP messages. The application log messages are worth looking at because, on occasion, they may explain why certain performance counters are not being correctly transferred to the CIM Repository.

Finally, WMI system class, __ADAPStatus, located in the root\DEFAULT namespace, offers a way to programmatically determine the status of the ADAP process. This class has the following definition:

class __ADAPStatus : __SystemClass {
uint32 Status;
datetime LastStartTime;
datetime LastStopTime;
};


Its LastStartTime and LastStopTime properties are self-explanatory and reflect the last time the ADAP process was started and shut down respectively. The Status property is a bit more interesting—it is an integer value that defines the current state of the ADAP process.



__ADAPStatus.Status Constants
0 - The ADAP process has never been run on the computer.
1 - The ADAP process is currently running.
2 - The ADAP process is currently processing a performance library.
3 - The ADAP process is currently updating the CIM Repository.
4 - The ADAP process has finished.



To programmatically determine the status of the ADAP process, you can write code similar to the following:

using System;
using System.Management;

class ADAPStatus {
public static void Main(string[] args) {
ManagementObject mo =
new ManagementObject(@"\\.\root\DEFAULT:__ADAPStatus=@");
Console.WriteLine("Status: {0}", mo["Status"]);
Console.WriteLine("Last started: {0}", mo["LastStartTime"]);
Console.WriteLine("Last stopped: {0}", mo["LastStopTime"]);
}
}
The only thing to notice here is that the __ADAPStatus object is singleton and, therefore, has to be accessed using the @ symbol.

When the ADAP process successfully finishes, the WMI CIM Repository will be updated with the definitions of WMI classes that represent the performance objects. All such WMI classes will be derived from either Win32_PerfRawData or Win32_PerfFormattedData—preinstalled abstract classes that are used as superclasses for raw and "cooked" performance objects. The majority of the performance classes will be imported into the root\CIMV2 namespace; however, those classes that represent the performance objects for WDM drivers will be loaded into the root\WMI namespace, instead.

The remainder of this section will concentrate on non-WDM performance objects that are backed by the Raw Performance Counter provider and derived from the Win32_PerfRawData class. The following section will cover the Cooked Counter provider, which supports the classes, derived from Win32_PerfFormattedData.

Source of Information :
Dot NET System Management Services - Apress

An interesting alternative to the instance-centric approach, outlined above, is using the Performance Monitoring provider as a property provider. Just as it is the case with the instance provider, to make the property provider work, you have to define the WMI classes to represent the performance data. Additionally, instances of these classes also have to be defined manually, since the property provider is not capable of returning the instance-level data to its clients. Consider the following sample MOF code:

class PerfMonProp_TCP {
[Key]
string KeyProp;
real32 ConnectionsEstablished;
real32 ConnectionsActive;
real32 ConnectionsPassive;
};
[DYNPROPS]
instance of PerfMonProp_TCP {
KeyProp = "tcp1";
[PropertyContext("local|TCP|Connections Established"),
Dynamic, Provider("PerformanceMonitorPropProvider")]
ConnectionsEstablished;
[PropertyContext("local|TCP|Connections Active"),
Dynamic, Provider("PerformanceMonitorPropProvider")]
ConnectionsActive;
[PropertyContext("local|TCP|Connections Passive"),
Dynamic, Provider("PerformanceMonitorPropProvider")]
ConnectionsPassive;
};

The class definition for PerfMonProp_TCP is fairly straightforward and does not include any special qualifiers. The class has a key property KeyProp, although it is not, strictly speaking, necessary. Since properties of this class refer to global performance counters, the class may as well be marked as a singleton.

The instance definition is a bit more interesting. First, the instance is decorated with the DYNPROPS qualifier, which simply indicates that the instance is to house the values, backed by a property provider. The KeyProp property is initialized to an arbitrary value to guarantee the uniqueness of the instance identity. Finally, each of the instance's properties is marked with the already familiar PropertyContext qualifier. However, rather then simply referring to the display names of the associated performance counters, these PropertyContext qualifiers include the machine and performance object names as part of their initialization strings. This information is necessary in order for the property provider to bind to a correct performance object for each property. Additionally, each property is decorated with the Dynamic qualifier to indicate that a property provider backs it, and with the Provider qualifier, which refers to the proper provider registration entry.

Using the PerfMonProp_TCP class is no different than using the previously defined PerfMon_TCP class. There is, however, an interesting twist. Since the performance data is provided at the property level rather than the instance level, the WMI class definition no longer has to correspond to a single performance object. In fact, it is perfectly legitimate to define a class that combines the performance counters from multiple categories into a single package:

class PerfMonProp_Combo {
[Key]
string KeyProp;
real32 ConnectionsEstablished;
real32 AvailableBytes;
};
[DYNPROPS]
instance of PerfMonProp_Combo {
KeyProp = "combo1";
[PropertyContext("local|TCP|Connections Established"),
Dynamic, Provider("PerformanceMonitorPropProvider")]
ConnectionsEstablished;
[PropertyContext("local|Memory|Available Bytes"),
Dynamic, Provider("PerformanceMonitorPropProvider")]
AvailableBytes;
};

This is certainly convenient because the management application is afforded the luxury of defining its single performance monitoring class, which includes all counters of interest. Unfortunately, there does not appear to be a way to retrieve nonglobal performance counters with the property provider. For instance, it is not possible to alter the definition of the WMI class above to refer to, say, the "% Processor Time" counter for CPU 0.

Source of Information : Dot NET System Management Services - Apress

When the Performance Monitoring provider is being used as an instance provider, the WMI class that is to house the performance data should roughly correspond to a given Performance Monitor object. Therefore, if your objective is to monitor the CPU performance, a WMI class should look like the Processor object in Performance Monitor. Then each property of the WMI class will relate to the respective counter name within the Processor object. For instance, in order to be able to retrieve the value of the "% User Time" counter, the WMI class definition should contain a property that corresponds to this counter.

Although you can certainly look up the counter names and their associated descriptions using the Performance Monitor GUI, doing this programmatically is a lot more fun. Coincidentally, the System.Diagnostics namespace contains a few types that come in very handy when you are working with performance counters. For example, the following code snippet will print out the names and descriptions of all performance counters that make up the Processor object:

using System;
using System.Diagnostics;
class CounterHelper {
public static void Main(string[] args) {
PerformanceCounterCategory cat =
new PerformanceCounterCategory("Processor");
foreach(PerformanceCounter cntr in cat.GetCounters("0")) {
Console.WriteLine("{0}: {1}", cntr.CounterName, cntr.CounterHelp);
}
}
}

This code is extremely simple. First, it creates an instance of PerformanceCounterCategory type, which refers to the Processor object of Performance Monitor. It then enumerates all counters within the Processor object that are returned by the GetCounters method of the PerformanceCounterCategory object. This method takes a single string parameter, which represents the name of the performance object instance. It is always safe to use "0" when dealing with Processor objects because any machine will always have at least one CPU. Finally, for each counter object returned, the code prints out the values of two properties: CounterName, which contains the display name of the counter, and CounterHelp, which is essentially a counter description. The output produced by this code resembles the following:

% Processor Time: Processor Time is expressed as a percentage of the elapsed
time that a processor is busy executing a non-Idle thread. It can be viewed as
the fraction of the time spent doing useful work. Each processor is assigned an
Idle thread in the Idle process, which consumes those unproductive processor
cycles not used by any other threads.
% User Time: User Time is the percentage of processor time spent in User Mode in
non-Idle threads. All application code and subsystem code executes in User
Mode. The graphics engine, graphics device drivers, printer device drivers,
and the window manager also execute in User Mode....

Once all required properties of a WMI class are identified, the class can be defined as follows:

[Dynamic, Provider("PerformanceMonitorProvider"),
ClassContext("local|Processor")]
class PerfMon_Processor {
[key]
string Processor;
[PropertyContext("% Processor Time")]
real32 ProcessorTime;
[PropertyContext("% User Time")]
real32 UserTime;
[PropertyContext("% Privileged Time")]
real32 PrivilegedTime;
[PropertyContext("Interrupts/sec")]
real32 Interrupts;
[PropertyContext("% DPC Time")]
real32 DPCTime;
[PropertyContext("% Interrupt Time")]
real32 InterruptTime;
[PropertyContext("DPCs Queued/sec")]
real32 DPCsQueued;
[PropertyContext("DPC Rate")]
real32 DPCRate;
[PropertyContext("DPC Bypasses/sec")]
real32 DPCBypasses;
[PropertyContext("APC Bypasses/sec")]
real32 APCBypasses;
};

Note, it is not really necessary for a WMI class definition to include the properties that refer to each and every counter within a given performance object. You can simply pick just those properties in which you are interested.

You may have noticed a couple of class and property qualifiers here that may seem unfamiliar. The first one is the Dynamic class qualifier; it simply indicates that a provider backs instances of a particular class. The Provider qualifier establishes the binding between the class and its provider; its string parameter refers to the name of __Win32Provider instance, which represents the provider registration. The ClassContext qualifier establishes the mapping between the WMI class and a particular performance object. Its parameter is a string that may contain a number of tokens separated by a vertical bar (|). The first token represents the name of the computer that houses the performance object of interest. The second token is the name of the performance object to bind to. Finally, there is the PropertyContext qualifier, which establishes the binding between a particular property of the WMI class and its respective performance counter. This qualifier's parameter is a display name of the associated performance counter.

Yet another thing to notice is the Processor property, marked with the Key qualifier. Since performance objects are represented by instances of WMI classes, every such instance must have a unique identity. Thus, the Performance Monitoring provider will automatically set the Processor property to the instance ID of the respective CPU. For instance, on a dual-CPU machine, the provider will create two instances of the PerfMon_Processor class, with their Processor properties set to 0 and 1 respectively.

Once compiled and saved into the CIM Repository, the PerfMon_Processor class is ready to be used. Accessing the performance data is no different from accessing instances of any other WMI classes. Thus, the following snippet of code continuously prints out some statistics for CPU 0:

using System;
using System.Management;

class CPUMonitor {
public static void Main(string[] args) {
while(true) {
ManagementObject mo = new ManagementObject("PerfMon_Processor='0'");
Console.WriteLine("% Processor Time: {0}", mo["ProcessorTime"]);
Console.WriteLine("% User Time: {0}", mo["UserTime"]);
Console.WriteLine("% Privileged Time: {0}", mo["PrivilegedTime"]);
System.Threading.Thread.Sleep(5000);
}
}
}

Note that every iteration of the while loop recreates the instance of ManagementObject type. Although seemingly inefficient at first, this is necessary in order to refresh the performance data. As you may remember, a property access operation invokes the IWbemClassObject::Get method, which always fetches the locally cached property value. Therefore, unless the instance of the ManagementObject type is rebound to its underlying WMI object, its properties will not be refreshed.

Generally, mapping performance objects to WMI classes is straightforward—a particular performance object category corresponds to a WMI class, counters correspond to the class properties, and performance objects map to instances of WMI classes. However, there are certain performance objects that do not easily yield themselves to this kind of modeling. The TCP object, for instance, which contains a slew of TCP/IP statistical counters, does not have any instances. Consider the following WMI class, which may be used to retrieve TCP/IP performance data:

[Dynamic, Provider("PerformanceMonitorProvider"), ClassContext("local|TCP")]
class PerfMon_TCP {
[Key]
string KeyProp;
[PropertyContext("Segments/sec")]
real32 Segments;
[PropertyContext("Connections Established")]
real32 ConnectionsEstablished;
[PropertyContext("Connections Active")]
real32 ConnectionsActive;
[PropertyContext("Connections Passive")]
real32 ConnectionsPassive;
[PropertyContext("Connection Failures")]
real32 ConnectionFailures;
[PropertyContext("Connections Reset")]
real32 ConnectionsReset;
[PropertyContext("Segments Received/sec")]
real32 SegmentsReceived;
[PropertyContext("Segments Sent/sec")]
real32 SegmentsSent;
[PropertyContext("Segments Retransmitted/sec")]
real32 SegmentsRetransmitted;
};

The class definitions in this code look very similar to those for the performance Processor object; however, it is unclear how you can access the individual instances of this class since the TCP performance object is global. One way to do this is to bind to a class and then enumerate its instances:

using System;
using System.Management;

class TCPMonitor {
public static void Main(string[] args) {
ManagementClass mc = new ManagementClass("PerfMon_TCP");
foreach(ManagementObject mo in mc.GetInstances()) {
Console.WriteLine("Key: {0}", mo["KeyProp"]);
}
}
}

Running the preceding code reveals a single instance with its KeyProp key property set to @. This means that the TCP performance object essentially maps to a singleton WMI class. Therefore, the WMI class definition above should be changed as follows:

[Singleton, Dynamic, Provider("PerformanceMonitorProvider"), ClassContext("local|TCP")]
class PerfMon_TCP {
[PropertyContext("Segments/sec")]
real32 Segments;
[PropertyContext("Connections Established")]
real32 ConnectionsEstablished;
[PropertyContext("Connections Active")]
real32 ConnectionsActive;
[PropertyContext("Connections Passive")]
real32 ConnectionsPassive;
[PropertyContext("Connection Failures")]
real32 ConnectionFailures;
[PropertyContext("Connections Reset")]
real32 ConnectionsReset;
[PropertyContext("Segments Received/sec")]
real32 SegmentsReceived;
[PropertyContext("Segments Sent/sec")]
real32 SegmentsSent;
[PropertyContext("Segments Retransmitted/sec")]
real32 SegmentsRetransmitted;
};
There are two things to notice here: first, the class is marked with the Singleton qualifier; second, there is no key property because singletons are not required to have a unique identity. Therefore, the code to retrieve the TCP performance data can be simplified as follows:

using System;
using System.Management;

class TCPMonitor {
public static void Main(string[] args) {
while(true) {
ManagementObject mo = new ManagementObject("PerfMon_TCP=@");
Console.WriteLine("Connections Established: {0}",
mo["ConnectionsEstablished"]);
Console.WriteLine("Connections Active: {0}", mo["ConnectionsActive"]);
Console.WriteLine("Connections Passive: {0}", mo["ConnectionsPassive"]);
System.Threading.Thread.Sleep(5000);
}
}
}

Source of Information : Dot NET System Management Services - Apress

WMI The Performance Monitoring Provider

The Performance Monitoring provider is a conventional WMI provider that is available under Windows NT 4.0 and Windows 2000 platforms. It is not available on Windows 95, Windows 98, or Windows Me platforms. The Performance Monitoring provider is comprised of two WMI providers: instance and property providers. The instance provider supplies the performance data in the form of instances of CIM classes. The property provider updates the properties of the specific instances of these classes.

Installing the Performance Monitoring Provider
This provider is not registered by default when the WMI SDK is installed. In order to request its services, you have to carry out all registration-related tasks by hand. Since there are really two providers—instance and property—you can perform the registration in two ways. To register the provider as instance provider, you must create instances of two WMI classes, __Win32Provider and __InstanceProviderRegistration, and save them to the CIM Repository. The following MOF code can be used to register the Performance Monitoring provider as an instance provider:

instance of __Win32Provider as $ProvInstance {
Name = "PerformanceMonitorProvider";
ClsId = "{f00b4404-f8f1-11ce-a5b6-00aa00680c3f}";
};
instance of __InstanceProviderRegistration {
Provider = $ProvInstance;
SupportsPut = FALSE;
SupportsGet = TRUE;
SupportsDelete = FALSE;
SupportsEnumeration = TRUE;
};

Note that the ClsId property of the __Win32Provider instance refers to the provider's COM object, which is implemented within stdprov.dll. This DLL, which can be found in the %SystemRoot%\System32\WBEM directory, has to be correctly registered on your system for the provider to function.

Registering the provider as a property provider is very similar to registering the instance provider. In fact, the only difference is that you need to use an instance of the __PropertyProviderRegistration system class instead of the __InstanceProviderRegistration instance:

instance of __Win32Provider as $ProvInstance {
Name = "PerformanceMonitorPropProvider";
Clsid = "{72967903-68EC-11d0-B729-00AA0062CBB7}";
};
instance of __PropertyProviderRegistration {
Provider = $ProvInstance;
SupportsGet = TRUE;
SupportsPut = FALSE;
};

Here, the ClsId property of the __Win32Provider instance also refers to a COM object implemented within the same stdprov.dll.

Once registration is complete, the provider is fully operational. However, you will find that it is not obvious how to access the performance data since the CIM Repository does not seem to contain any classes that are backed by the Performance Monitoring provider. It turns out that these classes also have to be created manually. Depending on whether the instance or property provider is used, the definition for a class, which represents a performance counter, may be different.

Source of Information : Dot NET System Management Services - Apress

WMI Performance Data Providers

Monitoring system and application performance is one of the most critical tasks with which many system managers concern themselves. Although there are many performance monitoring tools available, you will find that being able to review the performance data via WMI is very attractive. First, you can effectively use the existing WMI-based management tools, such as WMI Studio, to monitor the performance. Second, once you become familiar with various WMI client APIs, you will learn to appreciate the unlimited flexibility of programmatic access to the performance data that they afford.

The system and application performance data is delivered to WMI by several providers. In fact, there are three available providers that can collect the performance data from local or remote computers:

• Performance Monitoring provider: This provider supplies performance information in the form of instances of CIM classes that represent the performance counters of interest.

• Performance Counter provider: This provider supplies raw performance counter data so that the management applications often have to apply special calculation algorithms to derive meaningful performance data.

• Cooked Counter provider: This provider supplies calculated or "cooked" performance data, similar to the data that appears in the System Performance Monitor.

Although all of these providers can be used to retrieve just about any kind of system or application performance information, there are certain advantages and disadvantages in using a particular provider to satisfy certain monitoring requirements. The remainder of this section is dedicated to providing more details on the operations and the usage patterns of each of these providers.

Source of Information : Dot NET System Management Services - Apress

WMI Providers Overview

Microsoft favors provider-based architectures. There are OLE DB providers, cryptographic providers that are designed to work together with Microsoft Crypto API, and finally, there are WMI providers. The reasons for Microsoft's affection are more than just sentimental. Today's competition-driven world of software development is ridiculously diverse when it comes to technology, which often renders conventional architectures useless.

Take relational databases, for instance. Over the past few years, fierce competition has successfully annihilated many aspiring database vendors; however, there are still enough database products around to turn the lives of IT strategists into a never-ending nightmare. While this market segment is certainly dominated by such giants as Microsoft SQL Server and Oracle, die-hard Sybase is still out there, holding many Wall Street firms hostage, and even DB2, despite its Jurassic mainframe past, is making headway in the modern computing world. Moreover, regardless of the market dynamics, databases tend to have a much longer life span when compared to other software products. Once committed to a particular database infrastructure, you are basically trapped, since replacing such an infrastructure is generally a very time-consuming and extremely expensive exercise.

For in-house software developers, database independence may remain a subject for a theoretical discussion. However, for numerous commercial software vendors, it is a constant source of grief. Database affinity severely limits the product's market penetration abilities and may easily amount to an extensive loss of revenue.

This is where provider-based architectures come to the rescue. By building a layer of abstraction between the underlying database API and the application, you can afford the luxury of coding to a standard set of interfaces and then rely on plug-in components or providers to translate the application's requests into the database API calls. The advantages are apparent—an application, which utilizes such a provider architecture, can be ported from one database to another in seconds, without changing a single line of code. All you need to do is replace the database provider component—this can usually be achieved simply by changing a configuration file.

When it comes to database access, provider-based frameworks do not surprise anyone. In fact, many such frameworks have existed for years, especially on Windows platforms. OLE DB and its predecessor, ODBC, have always been, and remain, the primary vehicles for dealing with relational and non-relational data sources for just about any Windows-based software system. These technologies have proven themselves to be so successful that many software vendors, in addition to Microsoft, have made numerous attempts to utilize the same architectural principles. Thus, Rogue Wave Software offers the SourcePro DB (and now-defunct DBTools++) library, which is designed to solve the database independence problem through the use of plug-in database drivers. The Perl DBI database interface is built upon the same idea of providing a generalized interface that internally communicates with database-specific replaceable components. Even Sun Microsystems ported ODBC to their premier Solaris operating environment.

Today the apparent success of provider-based architectures has attracted the close attention of many software engineers who are looking to solve problems other than those of database access. Although this architectural principle may easily and beneficially be applied to many aspects of modern software development, the area of systems management certainly deserves special attention. By definition, a good management system must be able to deal with the wide variety of hardware and software technologies that make up today's complex computing universe. Unfortunately, inventing a generalized approach to managing thousands of dissimilar entities is extremely difficult; that is why most management systems tend to concentrate on certain aspects of the managed universe. For example, the Simple Network Management Protocol (SNMP) is almost solely dedicated to network management and most of the attempts to adopt it to address other areas of systems management never gained much popularity.
WMI is unique in that its goal is to cover all aspects of the management domain. The industry experience accumulated over the last couple of years indicates that WMI is fairly successful at achieving this goal. You should understand that one of the critical factors that determines WMI's success is its provider-based architecture. WMI itself is just a framework for collecting, disseminating, and managing the data, and its value is directly related to the availability of providers that are capable of dealing with various facets of the management domain.

Fortunately, there are plenty of providers. First, the WMI SDK includes a number of providers that allow you to manage the most common aspects of computer systems, such as disks, networks, processors and so on. To address more esoteric management needs, there are providers that collect various systems statistics; providers that allow you to integrate legacy systems, such as SNMP into WMI; and providers that deal with specific Windows technologies, such as Active Directory. Finally, there are tools and wizards for building custom providers that can do just about anything imaginable. The fact that WMI makes such diverse and versatile providers available is the main reason for its growing popularity.


Source of Information : Dot NET System Management Services - Apress

WMI - Enabling Privileges

Some operations that can be carried out through WMI may require the user to hold certain system privileges. For instance, the ability to reboot a computer is dependent on SeShutdownPrivilege or SeRemoteShutdownPrivilege, which must not only be granted to the user, but must also be enabled for the process that is attempting the reboot. The privileges can be granted using the local security policy editor.

Once the privileges are granted, they have to be explicitly enabled by the process attempting the privileged operation. Thus, in order to reboot a remote computer you may write code similar to the following:

ManagementClass mc = new ManagementClass(
@"\\BCK_OFFICE\root\CIMV2:Win32_OperatingSystem");
foreach(ManagementObject mo in mc.GetInstances()) {
mo.Scope.Options.Username = "username";
mo.Scope.Options.Password = "password";
mo.Scope.Options.EnablePrivileges = true;
mo.InvokeMethod("Reboot", new Object [] {0});
}

This code binds to the Win32_OperatingSystem WMI class, enumerates its instances, and invokes the Reboot method for each operating system. Of course in most cases, there would be a single instance of the Win32_OperatingSystem class and it is probably easier to just locate such an instance directly based on its key. Unfortunately, the key of this class is the name of the OS, which is often very long and easy to mistype, therefore, I chose to use the enumeration approach. The thing you should notice here is the line of code that sets the EnablePrivileges property of the ConnectionOptions object to true. Unlike the AdjustTokenPrivileges function, which allows you to enable and disable individual privileges, setting the EnablePrivileges property to true enables all privileges granted to a given user or group. In effect, assigning this property to true is equivalent to obtaining the set of privileges associated with the access token via the GetTokenInformation function; iterating through the returned array of token privileges to set the enabled attribute for each of them; and then invoking AdjustTokenPrivileges. Here again the designers of the System.Management namespace chose to trade flexibility for simplicity by disallowing access to individual user and group privileges.

Lastly, there is still the question of figuring out which WMI operations are privileged and exactly what privileges are required to perform such operations. Although it is always possible to get the answer by digging through the mess of WMI security documentation, there is an easier way. It turns out that all WMI methods that require certain privileges are marked as such using the Privileges qualifier. For instance, take a look at the partial MOF definition for the Win32_OperatingSystem class:

class Win32_OperatingSystem : CIM_OperatingSystem {
...
[Privileges{"SeShutdownPrivilege"}: ToSubClass]
uint32 Reboot();
[Privileges{"SeShutdownPrivilege"}: ToSubClass]
uint32 Shutdown();
[Privileges{"SeShutdownPrivilege"}: ToSubClass]
uint32 Win32Shutdown(sint32 Flags, sint32 Reserved = 0);
};

Here the Privileges qualifier is parameterized with the string value of the required privilege. In reality, the qualifier value is really an array of strings, so it is possible to account for methods that require multiple privileges to be enabled. Therefore, by examining the qualifiers associated with a given method, you can determine whether it is necessary to enable the privileges before attempting to execute the method. Note that it is not even necessary to check the qualifier value (since individual privileges cannot be controlled via the System.Management types anyway)—the mere presence of the Privileges qualifier is indicative of a privileged operation.

Source of Information : Dot NET System Management Services - Apress

Securing WMI Connections

At the beginning of this chapter, I mentioned that in order to establish the proper security settings for a WMI session, the client process should call several security API functions such as CoInitializeSecurity and CoSetProxyBlanket. Fortunately, it is not something that a developer of the management applications has to do manually. Here again, the initialization logic of the ManagementScope type kindly takes care of setting the appropriate authentication and impersonation levels for the process. A developer however, is afforded the luxury of controlling both the authentication and the impersonation settings through the instance of the ConnectionOptions type, associated with the ManagementScope object. This type, briefly mentioned above, has the following properties:

• Authentication: Gets or sets the COM authentication level to be used for the WMI connection

• Impersonation: Gets or sets the COM impersonation level to be used for the WMI connection

• Authority: Gets or sets the authority value to be used for the WMI connection

• Locale: Gets or sets the locale value to be used for the WMI connection

• Username: Gets or sets the name of the security principal to be used for theWMI connection

• Password: Gets or sets the password to be used for the WMI connection

• EnablePrivileges: Gets or sets a Boolean flag that indicates whether the privileges are to be enabled for the WMI connection

As you can see, all of these properties, with the exception of the EnablePrivileges, which is discussed later in this chapter, map directly to the parameters of the IWbemLocator::ConnectServer method. However, these properties are also used by the private Secure method of the ManagementScope type, which, during the initialization phase, sets the appropriate authentication and impersonation levels for the process and "blesses" the retrieved IWbemServices interface pointer.

The Username, Password, Locale, and Authority properties of the ConnectionOptions type are governed by the same rules as the respective parameters of the IWbemLocator::ConnectServer method. The Impersonation and Authentication properties, however, are of enumeration types ImpersonationLevel and AuthenticationLevel respectively, which means that you must use a member of the appropriate enumeration when initializing these properties. It should come as no surprise that the members of these enumeration types map one-to-one to the respective COM authentication and impersonation level constants.


Members of AuthenticationLevel Enumeration
MEMBER : Default
COM CONSTANT : RPC_C_AUTH_LEVEL_DEFAULT
DESCRIPTION : Under Windows NT 4.0, this value defaults to RPC_C_AUTH_LEVEL_CONNECT. Under Windows 2000 and later, this value instructs COM to select an appropriate authentication level using its normal security blanket negotiation algorithm.

None
RPC_C_AUTH_LEVEL_NONE
Instructs COM not to perform any authentication.

Connect
RPC_C_AUTH_LEVEL_CONNECT
Causes COM to authenticate the credentials of the client only when the client establishes a session with the server.

Call
RPC_C_AUTH_LEVEL_CALL
Instructs COM to authenticate the client at the beginning of each RPC when the server receives the request.

Packet
RPC_C_AUTH_LEVEL_PKT
Instructs COM to ensure that the data is received from the authenticated client.

PacketIntegrity
RPC_C_AUTH_LEVEL_PKT_INTEGRITY
Causes COM to ensure the integrity of the data received from the client.

PacketPrivacy
RPC_C_AUTH_LEVEL_PKT_PRIVACY
Instructs COM to perform all types of authentication referred to in this table and encrypt all RPC arguments.

Unchanged
The authentication level remains unchanged.




Members of ImpersonationLevel Enumeration
MEMBER : Default
COM CONSTANT : RPC_C_IMP_LEVEL_DEFAULT
DESCRIPTION : This value can be used with Windows 2000 and later. It instructs COM to select an appropriate impersonation level using its normal security blanket negotiation algorithm.

Anonymous
RPC_C_IMT_LEVEL_ANONYMOUS
The client remains anonymous to the server. The impersonation is possible, but since the server's impersonation token will not contain any client security information, the server will not be able to perform any tasks under the security context of the client.

Identity
RPC_C_IMP_LEVEL_IDENTITY
The server's impersonation token will include the client's identity, which implies that the server will be able to impersonate the client for ACL checking. However, the server will not be able to access the system objects on behalf of the client.

Impersonate
RPC_C_IMP_LEVEL_IMPERSONATE
The server may impersonate the client's security context, but only while it is accessing the resources on the local machine on behalf of the client. In other words, the impersonation token cannot be used across the machines' boundaries.

Delegate
RPC_C_IMP_LEVEL_DELEGATE
The server may impersonate the client's security context while accessing the resources on local or remote machines on behalf of the client. The impersonation token can be passed across the machines' boundaries. This impersonation level is available under Windows 2000 and later.

By constructing an instance of the ConnectionOptions type and associating it with the management scope, you may effectively control the security settings for a WMI client process:

ConnectionOptions co = new ConnectionOptions();
co.Username = "Administrator";
co.Password = "password";
co.Authentication = AuthenticationLevel.PacketPrivacy;
co.Impersonation = ImpersonationLevel.Impersonate;
ManagementScope ms = new ManagementScope(@"\\BCK_OFFICE\root\CIMV2", co);
ManagementObject mo = new ManagementObject(@" Win32_Process=100");
mo.Scope = ms;
Console.WriteLine(mo["__CLASS"]);

Unless the ConnectionOptions object is explicitly associated with an instance of the ManagementScope, the latter constructs a default ConnectionOptions instance during its initialization. Therefore, you can use the default object to control the security settings of the process:

ManagementScope ms = new ManagementScope();
ms.Path = new ManagementPath(@"\\BCK_OFFICE\root\CIMV2");
ms.Options.Username = "Administrator";
ms.Options.Password = "password";
ms.Options.Authentication = AuthenticationLevel.PacketPrivacy;
ms.Options.Impersonation = ImpersonationLevel.Impersonate;
ManagementObject mo = new ManagementObject(@" Win32_Process=100");
mo.Scope = ms;
Console.WriteLine(mo["__CLASS"]);

Finally, the ConnectionOptions type is equipped with a convenient constructor method that allows you to set all of the object properties at once. This constructor has the following signature:

public ConnectionOptions (
string locale,
string username,
string password,
string authority,
ImpersonationLevel impersonation,
AuthenticationLevel authentication,
bool enablePrivileges,
ManagementNamedValueCollection context,
TimeSpan timeout
);

where
• locale: A string that specifies the locale (i.e., MS_xxx) to be used for the WMI connection

• username: A string that specifies the name of the user to be used for the WMI connection

• password: A string that specifies the password to be used for the WMI connection

• authority: A string that specifies the authority to be used for the WMI connection

• impersonation: A member of the ImpersonationLevel enumeration that indicates the impersonation level to be used for the WMI connection.

• authentication: A member of the AuthenticationLevel enumeration that indicates the authentication level to be used for the WMI connection

• enablePrivileges: A Boolean flag that indicates whether the privileges are to be enabled for the WMI connection

• context: A ManagementNamedValueCollection that contains providerspecific context values

• timeout: A TimeSpan object that sets the timeout value for the connection operation


Using this constructor, the earlier code may be changed as follows:

ConnectionOptions co = new ConnectionOptions(
null, "Administrator", "password", null, ImpersonationLevel.Impersonate,
AuthenticationLevel.PacketPrivacy, false, null, new TimeSpan());
ManagementScope ms = new ManagementScope(@"\\BCK_OFFICE\root\CIMV2", co);
ManagementObject mo = new ManagementObject(@" Win32_Process=100");
mo.Scope = ms;
Console.WriteLine(mo["__CLASS"]);

Although using this constructor may save you a bit of typing, it certainly does not promote code readability and lacks in clarity when compared to setting the properties of the ConnectionOptions object explicitly.

Source of Information : Dot NET System Management Services - Apress

Establishing WMI Connections

Throughout all of the code examples, shown earlier in this book, I consistently and consciously neglected most of the issues related to WMI security, crudely assuming that these examples are being executed by a user with administrative privileges. Moreover, when I described the process of connecting to WMI, I barely scratched the surface and chose to rely on the ability of System.Management types to automatically establish a connection on an as-needed basis. Thus, all of the code examples used something similar to the following boilerplate code to bind to a WMI class or object:

ManagementObject mo = new ManagementObject(@"\\.\root\CIMV2:Win32_Process=100");
Console.WriteLine(mo["__CLASS"]);
...

This code looks deceivingly simple and you may not realize what is really going on behind the scenes.

Before the newly constructed object can be used, a valid connection to WMI must be established and the instance of the ManagementObject type must be bound to the underlying WMI object. However, the code does not seem to be doing either of these things—instead, it simply instantiates the object and prints out its properties. Such simplicity and ease of use is afforded by the ability of the System.Management ManagementObject type to initialize itself and establish the appropriate connections in a lazy fashion. In fact, none of the type constructors issue any COM API calls, and therefore, they do not even attempt to contact WMI. Instead, when an instance of a type is first accessed, it undergoes the initialization stage. The initialization code typically checks whether the instance is already connected to WMI, and if necessary, it invokes the initialization sequence. As part of the initialization, the object of type ManagementScope is created and then its initialization code is invoked. The ManagementScope's InitializeGuts method, obtains a pointer to IWbemLocator object and calls its ConnectServer method to retrieve the IWbemServices interface pointer. The IWbemLocator::ConnectServer method has the following signature:

HRESULT IWbemLocator::ConnectServer(
const BSTR strNetworkResource,
const BSTR strUser,
const BSTR strPassword,
const BSTR strLocale,
LONG lSecurityFlags,
const BSTR strAuthority,
IWbemContext* pCtx,
IWbemServices** ppNamespace
);

where
• strNetworkResource: A pointer to a valid BSTR that contains a WMI path to the target object.

• strUser: A pointer to a valid BSTR that contains the name of the security principal to be used to establish the connection to WMI. If this parameter is set to NULL, ConnectServer will use the name of the currently logged on user. When using the user name from a domain other than the current domain, the name should be prefixed with the domain name and a double backslash separator—i.e., \\.

• strPassword: A pointer to a valid BSTR that contains a password to be used to establish the connection to WMI. If this parameter is set to NULL, ConnectServer will use the password of the currently logged on user. An empty string is considered to be a valid password of zero length.

• strLocale: A pointer to a valid BSTR that specifies the locale (i.e., MS_xxx) to be used to retrieve the information from WMI. If this parameter is set to NULL, the current locale is used.

• lSecurityFlags: Reserved for future use. Must be set to zero.

• strAuthority: A pointer to a valid BSTR that contains a designation of the authentication method to be used for establishing the connection, as well as the name of the domain in which to obtain the user information for authentication. If this parameter begins with string "Kerberos:", Kerberos authentication is used and the remainder of the string must contain a valid Kerberos principal name. If the parameter begins with "NTLMDOMAIN:", then Windows NT Challenge/Response authentication protocol (also known as Windows NT LAN Manager or NTLM protocol) is used and the remainder of the string must contain a valid NTLM domain name. If the parameter is set to NULL, ConnectServer uses NTLM authentication and the NTLM domain of the currently logged on user. Note that the name of the domain cannot be specified simultaneously in two places (i.e., strUser and strAuthority parameters); doing so will cause ConnectServer to fail.

• pCtx: A pointer to the IWbemContext object used to provide additional information to certain WMI providers. This parameter is typically set to NULL.

• ppNamespace: An output parameter used to receive the pointer to a valid IWbemServices object.

As you can deduce from the method signature, it is possible to control many aspects of the connection establishment process, such as the name of the connecting user and domain as well as the authentication method. Unfortunately, the lazy initialization sequence of the ManagementObject type constructs a default instance of the ManagementScope type so that the IWbemLocator::ConnectServer method is called with most of its parameters set to NULL values. Obviously, this causes WMI to use the NTLM authentication along with the name and domain of the currently logged on user. While adequate for some of the management scenarios, this may result in access-denied errors when the current user is not granted full administrative access to the target WMI resources.

The good news is that you can override the default behavior by explicitly constructing an instance of the ManagementScope type and associating it with the ManagementObject. Take a look at the following code snippet:

ManagementScope ms = new ManagementScope();
ms.Path = new ManagementPath(@"\\BCK_OFFICE\root\CIMV2");
ms.Options.Username = "Administrator";
ms.Options.Password = "password";
ManagementObject mo = new ManagementObject(@" Win32_Process=100");
mo.Scope = ms;
Console.WriteLine(mo["__CLASS"]);

Here, the Path property of the newly created ManagementScope object is assigned to the instance of the ManagementPath type, which specifies the remote WMI namespace to connect to. Then, the Username and Password properties of the ConnectionOptions object, pointed to by the Options property of the ManagementScope object, are initialized to the name of the user and the password to be used for establishing a connection. Finally, the new instance of the ManagementObject type is created and associated with the ManagementScope object by setting its Scope property. When the ManagementObject instance is accessed by the WriteLine method, rather than constructing a default ManagementScope object, the initialization code of the ManagementObject type uses the ManagementScope instance associated with the object. Interestingly, in this case, all information that pertains to the WMI connection—not only the user name and the password, but also the namespace path—is always extracted from the associated ManagementScope object. Thus, the following code is incorrect and will generate an error:

ManagementScope ms = new ManagementScope();
ms.Options.Username = "Administrator";
ms.Options.Password = "password";
ManagementObject mo = new ManagementObject(
@"\\BCK_OFFICE\root\CIMV2:Win32_Process=100");
mo.Scope = ms;
Console.WriteLine(mo["__CLASS"]);

Here, rather than setting the Path property of the ManagementScope object, we supply a full namespace and an object path to the constructor of the ManagementObject type. Therefore, the resulting ManagementScope object contains a default namespace path \\.\root\CIMV2. Upon setting the Scope property of the ManagementObject instance, the namespace path of ManagementObject essentially is overridden by the namespace path of the associated ManagementScope object. Asa result, rather than binding to the remote namespace \\BCK_OFFICE\root\CIMV2, the initialization code of the ManagementObject type binds to the local \\.\root\CIMV2 namespace. For security reasons, it is not allowed to change the user credentials when it connects to a local namespace; therefore, the preceding code throws a ManagementException, complaining that user credentials cannot be used for local connections.

The coding pattern just discussed is not the only way to create a ManagementScope object and associate it with an appropriate System.Management type. One of the constructors of the ManagementObject type, for instance, accepts the instance of ManagementScope as a parameter:

ManagementScope ms = new ManagementScope();
ms.Path = new ManagementPath(@"\\BCK_OFFICE\root\CIMV2");
ms.Options.Username = "Administrator";
ms.Options.Password = "password";
ManagementPath mp = new ManagementPath("Win32_Process=100");
ManagementObject mo = new ManagementObject(ms, mp, null);
Console.WriteLine(mo["__CLASS"]);

Here, the ManagementScope object is the first parameter of the ManagementObject type constructor. The second parameter is an object of type ManagementPath, which points to an appropriate WMI Win32_Process object to bind to. Finally, the last parameter is an instance of ObjectGetOptions type, which, for the purposes of this discussion, may simply be ignored, hence it is set to null. Note that this code behaves similarly to the code snippet, shown earlier—in other words, the namespace path of the ManagementScope instance overrides the namespace path of the ManagementPath object. Thus, if you forget to initialize the Path property of the ManagementScope object, the code will generate an error.

Since the default ManagementScope object is constructed during the initialization of the ManagementObject unless the ManagementScope parameter is supplied to the type constructor, it is entirely possible to use the default object rather than constructing a brand new one:

ManagementObject mo = new ManagementObject(
@"\\BCK_OFFICE\root\CIMV2:Win32_Process=100");
mo.Scope.Options.Username = "Administrator";
mo.Scope.Options.Password = "password";
Console.WriteLine(mo["__CLASS"]);

This code is certainly more concise and, perhaps, a bit more efficient than my first example because it alleviates the need for allocating a new instance of the ManagementScope type.

Finally, you do not need to rely on the initialization code of the ManagementObject type to implicitly establish a connection to WMI. With the ManagementScope, you can request a connection explicitly:

ManagementScope ms = new ManagementScope();
ms.Path = new ManagementPath(@"\\BCK_OFFICE\root\CIMV2");
ms.Options.Username = "Administrator";
ms.Options.Password = "password";
ms.Connect();
ManagementObject mo = new ManagementObject(@" Win32_Process=100");
mo.Scope = ms;
Console.WriteLine(mo["__CLASS"]);

As I already mentioned, the initialization sequence of the ManagementObject type first checks if there is a valid WMI connection and then attempts to use it if such a connection exists. Here, since the ManagementScope object is already connected to WMI by the time the ManagementObject initialization code is invoked, the entire connection establishment process is bypassed and the ManagementScope's connection is used instead. The apparent benefit of such an approach is that you can reuse a single connected ManagementScope object with multiple instances of the ManagementObject, thus achieving a marginal performance gain.

The ManagementObject type is not the only System.Management type designed to work in conjunction with ManagementScope. In fact, all System.Management types that represent WMI entities, such as ManagementClass, ManagementEventWatcher, and ManagementObjectSearcher, offer the same functionality. Thus, each of these types is equipped with a constructor that takes the ManagementScope object as a parameter and the Scope property, which exposes the associated instance of the ManagementScope type.

Source of Information :
Dot NET System Management Services - Apress

WMI and COM Security

All client applications access WMI services via COM interfaces. It is true that WMI Scripting API or .NET System Management Framework may shield the developers from the complexities of COM. However, regardless of the development platform, at run time, all service requests issued by a management application are routed to WMI via an arbitrary COM interface. Thus, from the prospective of a client application, WMI security is synonymous with COM security.

COM security revolves around the concepts of authentication and impersonation. The former is a process that verifies the authenticity of the client's identity, while the latter is the ability of a thread to execute in a security context different from that of the process that owns the thread. Since different processes may require different levels of security, the authentication and impersonation requirements may vary from application to application. Therefore, COM clients are given the ability to control the security levels, or levels of authentication and impersonation, for their processes.

The default security levels for a process are set via the CoInitializeSecurity function. Among a few other parameters, this function accepts two DWORD values that specify the default authentication and impersonation levels. The first of these values controls the degree of protection applied to the communications between the COM client and the server. Currently, COM defines seven different authentication levels.


COM Authentication Levels
RPC_C_AUTH_LEVEL_DEFAULT .
Under Windows NT 4.0, this value defaults to RPC_C_AUTH_LEVEL_CONNECT. Under Windows 2000 and later, this value instructs COM to select an appropriate authentication level using its normal security blanket negotiation algorithm.

RPC_C_AUTH_LEVEL_NONE
Instructs COM not to perform any authentication

RPC_C_AUTH_LEVEL_CONNECT
Causes COM to authenticate the credentials of the client only when the client establishes a session with the server.

RPC_C_AUTH_LEVEL_CALL
Instructs COM to authenticate the client at the beginning of each remote procedure call (RPC) when the server receives the request.

RPC_C_AUTH_LEVEL_PKT
Instructs COM to ensure that the data is received from the authenticated client.

RPC_C_AUTH_LEVEL_PKT_INTEGRITY
Causes COM to ensure the integrity of the data received from the client.

RPC_C_AUTH_LEVEL_PKT_PRIVACY
Instructs COM to perform all the types of authentication referred to in this table and encrypt all RPC arguments.

Again, CoInitializeSecurity sets the default authentication level for the process so that all subsequently arriving COM requests with lower authentication levels will fail.

The impersonation level specifies the amount of authority granted to the server when it performs tasks on behalf of the client.


COM Impersonation Levels
RPC_C_IMP_LEVEL_DEFAULT
This value can be used with Windows 2000 and later. It instructs COM to select an appropriate impersonation level using its normal security blanket negotiation algorithm.

RPC_C_IMT_LEVEL_ANONYMOUS
The client remains anonymous to the server. The impersonation is possible, but since the server's impersonation token will not contain any client security information, the server will not be able to perform any tasks under the security context of the client.

RPC_C_IMP_LEVEL_IDENTITY
The server's impersonation token will include the client's identity, which implies that the server will be able to impersonate the client during ACL checking. However, the server will not be able to access the system objects on behalf of the client.

RPC_C_IMP_LEVEL_IMPERSONATE
The server may impersonate the client's security context, but only while it accesses the resources on local machines on behalf of the client. In other words, the impersonation token cannot be used across the machines' boundaries.

RPC_C_IMP_LEVEL_DELEGATE
The server may impersonate the client's security context while accessing the resources on local or remote machines on behalf of the client. The impersonation token can be passed across the machines' boundaries. This impersonation level is available under Windows 2000 and later.

Calling CoInitializeSecurity is optional. If a client application chooses not to invoke this function, COM will automatically initialize and manage the security settings for a process. In such cases, in order to establish the default security settings for a process, COM uses a set of default values, stored in the system registry. Thus, the default authentication level is set based on the registry value HKLM\SOFTWARE\MICROSOFT\OLE\LegacyAuthenticationLevel. Similarly, the default impersonation level is chosen based on the value of HKLM\SOFTWARE\MICROSOFT\OLE\LegacyImpersonationLevel. If these values are not found in the registry, COM will use RPC_C_AUTH_LEVEL_CONNECT and RPC_C_IMP_LEVEL_IDENTITY for the default authentication and impersonation levels respectively.

As you may remember, once connected to WMI, a client application receives an out-of-process pointer to the IWbemServices interface, which can subsequently be used to engage various WMI services. This pointer has the identity of a client process rather than the WMI IWbemServices process. Thus, if the client attempts to use the pointer to invoke the services of WMI it may receive an access-denied error, since the access check will be carried out with the client's identity. To avoid such errors, the WMI client applications must call the CoSetProxyBlanket function in order to set the identity of a newly obtained pointer. Once the pointer identity is set, it can be used to call into WMI.

Finally, whenever a client attempts to perform an operation marked as privileged, such as a system reboot, it must enable its privileges. This is achieved via the AdjustTokenPrivileges function. This function takes the access token of the client process as a parameter and, depending on the type of the request, enables or disables the privileges associated with the token. Note that before a particular privilege can be enabled, an administrator should explicitly grant it to the user or group.

Source of Information : Dot NET System Management Services - Apress

Securing WMI Namespaces

On Windows NT, 2000, and XP platforms, each user and group is given unique security identifiers (SIDs). A SID is a variable length value that is assigned to a user or group account when such an account is created. SIDs are always unique within the scope of the account to which they belong. Thus, a SID for a local account is always unique within the computer system to which the account belongs, and a SID for a domain account is unique within that domain. SIDs are also unique in time, meaning that the system does not reuse the SID values under any circumstances. Therefore, if an account is deleted and then recreated, it is assigned a brand new SID despite the fact that the account name stays the same.

SIDs are used extensively by the Windows security framework. For instance, each access token—an object that described the security context of a process or a thread—has an embedded SID, which represents a user or a group associated with the token. Another security structure—the security descriptor (SD), which contains all relevant security information for a securable object—also contains SIDs that identify the owner of the associated object and the primary group of the owner. Finally, access control entries (ACEs), which govern access to a particular securable object, house SIDs that identify the users and groups to whom access is granted or denied.

A SD is, perhaps, the most notable structure within the Windows security model. As its name implies, it describes the security-related traits of a given object, such as its ownership and access restrictions. A Security Descriptor structure (SECURITY_DESCRIPTOR), consists of the following elements:

• SID of the object's owner

• SID of the group to which the object's owner belongs

• Discretionary access control list (DACL) that specifies the levels of access that particular users or groups may have to the object

• System access control list (SACL) that controls the generation of the audit messages, logging the attempts to access the object

• Security descriptor control information, packaged into the SECURITY_DESCRIPTOR_CONTROL structure. This is a set of bit flags that qualify the semantics of the individual components of the security descriptor.

An access control list (ACL) is a list of zero or more access control entries (ACEs) that are used as a basis for determining the access control and audit rights for a particular security principal. Each ACE contains the following information:

• A SID that uniquely identifies a security principal (user or group) to which the ACE applies.

• An access mask—a 32-bit value that specifies the rights that are denied or allowed by the ACE.

• A flag that indicates the type of the ACE: access-denied ACE, accessallowed ACE, or system-audit ACE.

• Bit flags that specify whether the child objects are allowed to inherit the ACE from the primary object to which the ACE applies.

The access rights, specified by the access mask field, can be divided into four categories: generic, standard, SACL access, and Directory Services (DS) access rights.

A combination of access rights is packaged into a 32-bit field so that the loworder 16 bits of the access mask reflect the object-specific rights, the next 7 bits are reserved for the standard rights, bit 23 represents the right to access the SACL, and finally, the 4 high-order bits are used for the generic access rights.

Another structure that plays a very important role within the Windows security infrastructure is the access token. An access token is assigned to a user whenever a user logs into the system. When a logon session is initiated, the system authenticates the user's password against the security database and issues an access token, which subsequently gets attached to every process executed on behalf of the user. Then, the system uses the access token to establish the user's identity and level of access every time the user issues a request to access a securable object. An access token contains the following information:

• A SID of the user's account.

• A collection of SIDs for each group to which the user belongs.

• A logon SID that uniquely identifies the logon session.

• A list of privileges granted to a user or the user's groups.

• An owner SID.

• A SID of the primary group.

• The source of the access token.

• The flag that indicates whether it is a primary or impersonation token. The primary token is created by the Windows executive layer and typically represents the default security settings for the process. The impersonation token is created to capture the security settings of an arbitrary process, thus allowing the current process to "impersonate" the latter.

• A list of restricting SIDs. The restricting SIDs are used when a process is running under a restricted security context. In such cases, the system checks not only the primary SID but also the restricted SIDs before it grants access to a securable object.

• Current impersonation levels.

• Miscellaneous statistics.

Besides carrying the user's identity, an access token also includes all privileges granted to a user or the user's groups. A privilege is a right granted to a security principal that enables the latter to perform certain administrative functions on a local computer. Such administrative functions may include shutting down the system, modifying the system's date and time settings, and loading and unloading the device drivers. As opposed to access rights, which control access to securable objects, privileges govern access to system resources and tasks.

Each user and group account is associated with a set of privileges that is stored in Windows security database. Whenever a user logs into a system, the privileges are incorporated into the user's access token. Note that such privileges will only apply to a local computer system, since domain accounts may have different sets of privileges on different machines. When a user attempts to perform an operation that is marked as privileged, the system checks the privileges embedded into the user's access token. If the appropriate privileges are granted and enabled, the system allows the operation; otherwise the operation fails. Interestingly, the privileges, even if granted, are disabled by default so that the user has to explicitly enable them prior to requesting a privileged operation. A privilege can be enabled using the AdjustTokenPrivileges function of the Win32 API.

To summarize, every access check carried out by the system essentially boils down to matching the user's security information, which is encoded into the access token, against the SD of a securable object. Thus, in order to secure an arbitrary resource, the resource has to be assigned an appropriate SD that incorporates the necessary ACEs. Securing the WMI namespaces is no exception. In fact, each namespace is associated with an SD that carries all the security information needed to ensure the proper access checks. The SD of a namespace can be manipulated using the WMI MMC snap-in.
Using the security configuration page of the snap-in is as trivial as using the Properties dialog when securing files. All you need to do is select a namespace to secure and modify the associated user's or group's permissions.

In the true spirit of WMI, the SD for a namespace can also be retrieved and manipulated programmatically. A system class called __SystemSecurity provides such programmatic access to namespace security settings. This class has the following definition:

class __SystemSecurity {
[Static] uint32 GetSD([out] uint8 SD[]);
[Static] uint32 Get9XUserList([out] __ntlmuser9x ul[]);
[Static] uint32 SetSD([in] uint8 SD[]);
[Static] uint32 Set9XUserList([in] __ntlmuser9x ul[]);
[Static] uint32 GetCallerAccessRights([out] sint32 rights);
};

This class is fairly unusual because it does not contain any properties. Rather than exposing all of the SD or its individual parts as properties of an object, the designers of WMI turned the __SystemSecurity class into a singleton and equipped it with a number of static methods for reading the security descriptor and writing the modified version of it back to the CIM Repository. As you can see in the definition above, the class has the following methods:

• GetSD: Used to get an SD associated with a namespace to which the user is currently connected. The SD is returned as an array of unsigned bytes and it has to be cast into an appropriate structure to be manipulated. This method is only available on Windows NT, Windows 2000, and Windows XP platforms.

• Get9XUserList: Used to retrieve a list of users who are allowed to access the namespace. This method is only available on Windows 9X platforms, and it returns an array of instances of the __Win9XUser class. This is done to simulate the functionality of SDs on Windows 9X systems.

• SetSD: Writes the modified SD for a namespace back to the CIM Repository. The SD is represented by an array of unsigned bytes. This method is only available on Windows NT, Windows 2000, and Windows XP platforms.

• Set9XUserList: Writes the list of users who are allowed to access the namespace back to the CIM Repository. This method is only available on Windows 9X platforms.

• GetCallerAccessRights: Retrieves the access masks for a client process. The mask is a 32-bit value where each bit represents an individual access right. This method is available on all Windows platforms.

Unfortunately, the methods of the __SystemSecurity class can only be used to retrieve or save an SD, but they cannot be utilized for SD manipulation. Also, it is not recommended to manipulate the SD byte array directly. Instead, the functions of the Win32 API should be used to extract or set the individual values within an SD. For instance, to convert a binary SD into a human-consumable form (an SDDL string representation), you may use the ConvertSecurityDescriptorToStringSecurityDescriptor function (that is, if you manage to spell the name of the function correctly).

By default, the security settings for a namespace are inherited by all its children namespaces. This means that by setting the permissions for the \root namespace, you may have these permissions propagated to each WMI namespace. You can also change the default behavior and turn the inheritance off by setting the CONTAINER_INHERIT_ACE (0x2) flag in the ACEs that are associated with a security descriptor for a namespace. It is also possible to determine whether a particular ACE is inherited by checking for the INHERITED_ACE (0x10) flag within the ACE for a namespace.

Source of Information : Dot NET System Management Services - Apress

WMI Security Fundamentals

As just mentioned, the Windows security model is the foundation of WMI security. As is true for most security frameworks in existence today, Windows security revolves around user IDs or names, and the associated passwords. Simply put, the operating system associates every object within the enterprise with a list of users authorized to access it. Every user request is checked against this list before access to the object is granted. WMI employs a similar strategy: it maintains a list of authorized users for each namespace.

In addition to controlling access to WMI namespaces, the system has to be able to verify the user's identity before allowing the client application to connect to WMI services. The process of confirming the identity of the user who is running the management client application is referred to as authentication. In order to authenticate the client requests for services, WMI relies on the Component Object Model (COM) authentication mechanism. The COM authentication scheme is password-based and it provides for not only verifying the identity of the requestor, but also protecting the communications between the client and the server by encrypting the network packets.

WMI is designed for remote administration, which means that management requests from a remote management client are carried out by the WMI service that is running on the local machine. Since the WMI service operates on behalf of the remote user, there has to be a way to ensure that the user possesses adequate permissions to complete certain management actions. This essentially means that each client's request has to be carried out by the WMI service under the security context of the client and perhaps by using the client's identity. This is achieved by using the COM impersonation mechanism, which allows the client to grant certain authority to the WMI service so that the latter may perform the requested operations on the client's behalf.

Source of Information : Dot NET System Management Services - Apress

WMI Security

Windows Management Instrumentation (WMI), like any power tool, is a doubleedged sword. To system administrators, WMI is an indispensable part of the system management arsenal that allows them to oversee and alter all aspects of the entire management domain from a single, centralized management console. However, if misconfigured, such a system may just as easily enable a malicious hacker not only to sniff out the valuable and sensitive system configuration and operational data, but also severely disrupt the operations of the entire enterprise, and even damage or destroy some of its components. The ability to rename and delete files, start and stop services, manage processes, and reboot computers from a centralized remote location is the dream of any system manager, and although WMI certainly turns this dream into a reality, there is a clear and present danger if all this power falls into the wrong hands.

Thus, it should be clear to anyone that for a system such as WMI, strong security capabilities are not just a luxury, but an essential measure of success. In fact, a few otherwise very powerful and flexible management systems have been receiving bad press for years, solely due to their lack of sufficient security protection. For instance, many industry professionals attribute the slow adaptation of the Simple Network Management Protocol (SNMP) to its less then robust security features; in fact, some organizations and individuals consider using the SNMP-based management tools a potential security risk.

Therefore, it will not surprise you to discover that extensive support for securing access to the enterprise is built into the very core of WMI. Unlike other management solutions, WMI is not equipped with a standalone security framework; instead it relies on the security features of the Windows operating system and the Distributed Component Object Model (DCOM) security mechanism. Such an approach to securing the management operations via tight integration with Windows and DCOM security frameworks is well justified. In addition to easing the configuration and management of the system's security attributes by sharing APIs and configuration utilities, both Windows and DCOM security models are well reputed and are considered to be among the most reliable security frameworks around.

Unfortunately, flexibility and robustness often come at a price—high complexity—which is definitely the case with Windows and DCOM security. DCOM, for instance, has more security features than any other system known to man; however, it is often misunderstood and even more often misconfigured, thus creating security holes that naturally defeat its very purpose. But lowering the complexity is not an acceptable option either, since ensuring the proper degree of protection in a distributed environment is, by definition, very complex and cannot be achieved by simple means. In fact, industry experience shows that simplistic distributed security systems are either far too restrictive and inflexible, or are plainly unreliable and risky. Hence Windows and DCOM security.

Ignoring the security implications that result from using WMI as an enterprise-wide management solution is not a smart choice. Also, attempting to configure the system blindfolded without understanding its security features is not really a choice at all—it simply will not work. Thus, any system administrator searching for a successful management solution must be somewhat familiar with Windows and DCOM security and WMI's integration with these security models.

The purpose of this chapter is to expose you to the most important security features of WMI and to help you build a foundation on which to develop secure management applications. Although I will provide a basic overview of the Windows and DCOM security topics relevant to WMI, it is not my intention to turn this chapter into a tutorial on distributed security. As I already mentioned, this subject is very complex and delving into its intricacies could easily add a thousand pages to this book. Remember, the primary focus of this chapter is building secure management clients with .NET, and therefore, some WMI security issues, especially those related to provider development, will not be addressed. Fortunately, WMI and Platform SDK documentation seem to contain enough information on the most obscure aspects of WMI security that you can dig into to satisfy your curiosity.

Source of Information : Dot NET System Management Services - Apress

To better understand how the Performance Counter provider works, take a close look at one of the performance classes imported into the CIM Repository by the ADAP process. The Win32_PerfRawData_PerfOS_Processor class relates to the Processor Performance category and each of its instances corresponds to one of the Processor performance objects:

[perfdefault, dynamic, provider("Nt5_GenericPerfProvider_V1"),
registrykey("PerfOS"), perfindex(238), helpindex(239),
perfdetail(100), genericperfctr]
class Win32_PerfRawData_PerfOS_Processor : Win32_PerfRawData {
[key] string Name = NULL;
[perfdefault, DisplayName("% Processor Time"),
countertype(558957824), perfindex(6), helpindex(7),
defaultscale(0), perfdetail(100)]
uint64 PercentProcessorTime;
[DisplayName("% User Time"), countertype(542180608),
perfindex(142), helpindex(143),
defaultscale(0), perfdetail(200)]
uint64 PercentUserTime;
[DisplayName("% Privileged Time"), countertype(542180608),
perfindex(144), helpindex(145),
defaultscale(0), perfdetail(200)]
uint64 PercentPrivilegedTime;
[DisplayName("Interrupts/sec"), countertype(272696320),
perfindex(148), helpindex(149), defaultscale(-2),
perfdetail(100)]
uint32 InterruptsPersec;
[DisplayName("% DPC Time"), countertype(542180608),
perfindex(696), helpindex(339),
defaultscale(0), perfdetail(200)]
uint64 PercentDPCTime;
[DisplayName("% Interrupt Time"), countertype(542180608),
perfindex(698), helpindex(397),
defaultscale(0), perfdetail(200)]
uint64 PercentInterruptTime;
[DisplayName("DPCs Queued/sec"), countertype(272696320),
perfindex(1334), helpindex(1335),
defaultscale(0), perfdetail(200)]
uint32 DPCsQueuedPersec;
[DisplayName("DPC Rate"), countertype(65536),
perfindex(1336), helpindex(1337),
defaultscale(0), perfdetail(200)]
uint32 DPCRate;
[DisplayName("DPC Bypasses/sec"), countertype(272696320),
perfindex(1338), helpindex(1339),
defaultscale(0), perfdetail(200)]
uint32 DPCBypassesPersec;
[DisplayName("APC Bypasses/sec"), countertype(272696320),
perfindex(1340), helpindex(1341),
defaultscale(0), perfdetail(200)]
uint32 APCBypassesPersec;
};

At first glance, the definition for this class seems to be very similar to that of the PerfMon_Processor class used earlier in this chapter to illustrate the operations of the Performance Monitoring provider. Indeed, the concept is the same—the class itself corresponds to the Process Performance category, while each of its properties relates to a single performance counter within the category. Yet another similarity is a key property, Name, which is set to the unique ID of the Processor instance by the provider.

However, this class, as well as all of its properties, is decorated with various qualifiers that are different from those of the PerfMon_Processor class. These qualifiers are required by the Performance Counter provider in order to locate the respective performance objects and associate them with the properties of the WMI class. The list of class qualifiers along with their descriptions is presented below.



Class Qualifiers Used by the Performance Counter Provider
Costly
If set, indicates that retrieving instances of this class is an expensive operation in terms of resource consumption. ADAP automatically adds this qualifier to a WMI class definition for a performance object that is marked as costly (see the Platform SDK documentation for more information on creating Performance Extension DLLs). Additionally, ADAP adds the _Costly suffix to the name of the WMI class. Example:
Win32_PerfRawData_PerfProc_ThreadDetails_Costly.

GenericPerfCounter
If set, indicates that the WMI class corresponds to a performance object backed by a legacy performance DLL.

HelpIndex
Specifies the index of the object's help text in the performance names database.

HiPerf
Marks the WMI class as a high-performance class.

PerfDefault
If set, indicates that the WMI class is to be used as a default selection in a list box in a graphical application.

PerfDetail
Indicates the level of knowledge the audience is required to possess. This qualifier can take the following values:
PERF_DETAIL_NOVICE (0x00000064)—For novice users
PERF_DETAIL_ADVANCED (0x000000C8) —For advanced users
PERF_DETAIL_EXPERT (0x0000012C) —For expert users
PERF_DETAIL_WIZARD (0x00000190) —For system designers

PerfIndex
Specifies the index of the object's display name in the performance names database.

RegistryKey
Specifies the name of the registry subkey under HKLM\System\CurrentControlSet\Services under which the performance counter definitions are located.



Besides the qualifiers specific to the Performance Counter provider the class is marked with the Dynamic qualifier, indicating that its instances are supplied dynamically by the provider; as well as by the Provider qualifier, which establishes the link to the appropriate provider registration entry.

The actual binding between the WMI class and the respective performance counters is achieved through the property qualifiers that ADAP adds to the class definition.



Property Qualifiers Used by the Performance Counter Provider
CounterType
Indicates the type of performance counter associated with a given property. Since the Performance Counter provider exposes raw, uncalculated performance data, the CounterType qualifier is used by WMI clients to determine the formula for calculating the performance values that are meaningful to the end users. A detailed description of the available counter types is presented later in this section.

DefaultScale
The scale value used by graphical display applications such as System Performance Monitor to scale the performance chart lines.

DisplayName
Although this qualifier is not really specific to the Performance Counter provider, here it plays dual role. In addition to specifying the UI display name for the property, it is used to establish an association between a performance counter object and a property of its respective WMI class.

HelpIndex
Specifies the index of the object's help text in the performance names database.

PerfDefault
If set, indicates that WMI class property is to be used as a default selection in a list box in a graphical application.

PerfDetail
Indicates the level of knowledge the audience is required to possess.

PerfIndex
Specifies the index of the object's display name in the performance names database.



Most of these qualifiers are fairly self-explanatory. CounterType, however, is a key to deciphering the performance data exposed by the Performance Counter provider, and so it is a bit more complicated. As I already mentioned, this provider supplies uncalculated data, which, in its raw form, does not make much sense to the end users. For instance, the Interrupts/sec performance counter has the type of PERF_COUNTER_COUNTER (with a CounterType of 272696320), which means that at any given time, it will hold a value that reflects the total rate of interrupts for a processor. Thus, to derive the interrupt rate per second, you would have to take snapshots of the counter value over some time interval and perform the calculation based on the following formula:

Interrupts/sec = (V1 - V0)/((T1 - T0)/TB)

where
V1: Counter value at the end of the monitoring interval
V0: Counter value at the beginning of the monitoring interval
T1: Number of processor ticks at the end of the monitoring interval
T0: Number of processor ticks at the beginning of the monitoring interval
TB: Time base or frequency of the processor ticks

In this case, the expression (V1 – V0) evaluates to the number of interrupts that take place within a certain monitoring interval. The other expression, (T1 – T0), reflects the length of the monitoring interval in units of processor ticks. Considering that tick frequency is expressed in numbers of ticks per second; ((T1 – T0)/TB) evaluates to the number of seconds elapsed during the monitoring interval. Thus, the entire calculation yields a value that reflects an average number of processor interrupts per second.

There are many different counter types that govern the calculations of the performance values. Based on the counter usage pattern and required computation algorithm, all counter types can be divided into the following categories:

• Noncomputational counters
• Base counters
• Basic Algorithm counters
• Counter Algorithm counters
• Timer Algorithm counters
• Precision Timer Algorithm counters
• Queue-Length Algorithm counters
• Statistical counters

Source of Information : Dot NET System Management Services - Apress

What Is WCF ?

WCF is a technology that enables you to create services that you can access from other applications across process, machine, and network boundaries. You can use these services to share functionality across multiple applications, to expose data sources, or to abstract complicated processes. As with Web services, the functionality that WCF services offer is encapsulated as individual methods that are exposed by the service. Each method — or, in WCF terminology, each operation — has an endpoint that you exchange data with in order to use it. At this point, WCF differs from Web services. With Web services, you can only communicate with an endpoint with SOAP over HTTP. With CF services, you have a choice of protocols that you can use. You can even have endpoints that communicate through more than one protocol, depending on the network that you connect to the service through and your specific requirements.

In WCF, an endpoint can have multiple bindings , each of which specifies a means of communication. Bindings can also specify additional information, such as what security requirements must be met to communicate with the endpoint. A binding might require username and password authentication or a Windows user account token, for example. When you connect to an endpoint, the protocol that the binding uses affects the address that you use, as you will see shortly. Once you have connected to an endpoint, you can communicate with it by using SOAP messages. The form of the messages that you use depends on the operation that you are using, and the data structures that are required to send messages to and receive messages from that operation. WCF uses contracts to specify all of this. You can discover contracts through metadata exchange with a service. This is analogous to the way Web services use WSDL to describe their functionality. In fact, you can get information about a WCF service in WSDL format, although WCF services can also be described in other ways.

When you have identified a service and endpoint that you want to use, and after you know what binding you use and what contracts to adhere to, you can communicate with a WCF service as easily as with an object that you have defined locally. Communications with WCF services can be simple, one - way transactions, request/response messages, or full - duplex communications that can be initiated from either end of the communication channel. You can also use message payload optimization techniques, such as Message Transmission Optimization Mechanism (MTOM) to package data if required.

The WCF service itself may be running in one of a number of different processes on the computer where it is hosted. Unlike Web services, which always run in IIS, you can choose a host process that is appropriate to your situation. You can use IIS to host WCF services, but you can also use Windows services or executables. If you are using TCP to communicate with a WCF service over a local network, there is no need even to have IIS installed on the PC that is hosting the service.

The WCF framework has been designed to enable you to customize nearly everything you have read about in this section. Now that you have covered the basics about WCF services, you will look in more detail at these concepts
in the following sections.

Source of Information : Wrox Beginning Microsoft Visual C Sharp 2008

The Role of the Common Intermediate Language
Let’s examine CIL code, type metadata, and the assembly manifest in a bit more detail. CIL is a language that sits above any particular platform-specific instruction set. Once you compile code file using the C# compiler (csc.exe), you end up with a single-file *.exe assembly that contains a manifest, CIL instructions, and metadata describing each aspect of the Program classes.

Benefits of CIL
At this point, you might be wondering exactly what is gained by compiling source code into CIL rather than directly to a specific instruction set. One benefit is language integration. As you have already seen, each .NET-aware compiler produces nearly identical CIL instructions. Therefore, all languages are able to interact within a well-defined binary arena. Furthermore, given that CIL is platform-agnostic, the .NET Framework itself is platformagnostic, providing the same benefits Java developers have grown accustomed to (i.e., a single code base running on numerous operating systems).

In fact, there is an international standard for the C# language, and a large subset of the .NET platform and implementations already exist for many non-Windows operating systems. In contrast to Java, however, .NET allows you to build applications using your language of choice.

Compiling CIL to Platform-Specific Instructions
Due to the fact that assemblies contain CIL instructions, rather than platform-specific instructions, CIL code must be compiled on the fly before use. The entity that compiles CIL code into meaningful CPU instructions is termed a just-in-time (JIT) compiler, which sometimes goes by the friendly name of Jitter. The .NET runtime environment leverages a JIT compiler for each CPU targeting the runtime, each optimized for the underlying platform. For example, if you are building a .NET application that is to be deployed to a handheld device (such as a Pocket PC), the corresponding Jitter is well equipped to run within a low-memory environment.

On the other hand, if you are deploying your assembly to a back-end server (where memory is seldom an issue), the Jitter will be optimized to function in a high-memory environment. In this way, developers can write a single body of code that can be efficiently JIT-compiled and executed on machines with different architectures. Furthermore, as a given Jitter compiles CIL instructions into corresponding machine code, it will cache the results in memory in a manner suited to the target operating system. In this way, if a call is made to a method named PrintDocument(), the CIL instructions are compiled into platformspecific instructions on the first invocation and retained in memory for later use. Therefore, the next time PrintDocument() is called, there is no need to recompile the CIL.


The Role of .NET Type Metadata
In addition to CIL instructions, a .NET assembly contains full, complete, and accurate metadata, which describes each and every type (class, structure, enumeration, and so forth) defined in the binary, as well as the members of each type (properties, methods, events, and so on). Thankfully, it is always the job of the compiler (not the programmer) to emit the latest and greatest type metadata. Because .NET metadata is so wickedly meticulous, assemblies are completely self-describing entities.

Metadata is used by numerous aspects of the .NET runtime environment, as well as by various development tools. For example, the IntelliSense feature provided by tools such as Visual Studio 2008 is made possible by reading an assembly’s metadata at design time. Metadata is also used by various object browsing utilities, debugging tools, and the C# compiler itself. To be sure, metadata is the backbone of numerous .NET technologies including Windows Communication Foundation (WCF), XML web services/the .NET remoting layer, reflection, late binding, and object serialization.


The Role of the Assembly Manifest
Last but not least, remember that a .NET assembly also contains metadata that describes the assembly itself (technically termed a manifest). Among other details, the manifest documents all external assemblies required by the current assembly to function correctly, the assembly’s version number, copyright information, and so forth. Like type metadata, it is always the job of the compiler to generate the assembly’s manifest.

Source of Information : Pro C# 2008 and the NET 3.5 Platform Fourth Edition


Subscribe to Developer Techno ?
Enter your email address:

Delivered by FeedBurner