Export (0) Print
Expand All

How To: Use Strongly-Typed Objects 

.NET Framework 2.0

To serve customer extensibility needs, WMI objects are typically late-bound, which does not force strong typing. In the .NET Framework environment, WMI provides the ability to automatically generate early-bound wrappers for WMI objects.

Strongly-typed wrappers allow applications to take advantage of all the available Microsoft Visual Studio assistance features, such as Intellisense and object browsing, for strongly-typed objects. For example, you can generate an early-bound wrapper for the Win32_Service class so that you can use Intellisense to quickly find the class members in the Win32_Service class. The following list contains the tools and methods that generate wrappers for WMI objects.

The wrappers are implemented as managed code classes, and as such provide multilanguage support so that they can be used with any programming language.

Example

The following code example includes the strongly-typed Service class, which is a wrapper for the Win32_Service class. Before running this example, you must generate a specific class using the following command in the Visual Studio 2005 command prompt (change the value of the code language depending on whether you want to generate a C# or Visual Basic .NET code file):

C:\> MgmtClassGen Win32_Service /L CS /N root\cimv2 /P C:\temp\service.cs

The output of the generator tool will be the service.cs code file, which you should then add to your project along with the code below. Notice the usage of the strongly typed "Service" class in the foreach statement instead of the generic ManagementObject class, and the simplified standard dot notation access to the properties of the returned objects.

using System;
using ROOT.CIMV2.Win32;
// Contains the strongly typed generated class "Service" 
// in ROOT.CIMV2.Win32 namespace. This namespace was
// generated using the MgmtClassGen tool for
// the Win32_Service class
   
class Sample 
{
    // Enumerate instances of Win32_Service class
    void EnumerateServices() 
    {
        Console.WriteLine("List services and their state");
        foreach(Service ser in Service.GetInstances())
        Console.WriteLine(
            "Service: "+ ser.Name + " is " + ser.State);
    }
   
    public static void Main(string[] args) 
    {
        Sample test = new Sample();
        test.EnumerateServices();
        return;
    }
}

Compiling the Code

The example requires references to the System namespace.

See Also

Community Additions

ADD
Show:
© 2014 Microsoft