Click here to Skip to main content
15,881,719 members
Articles / Programming Languages / C#

WMI Provider Extensions in .NET 3.5

Rate me:
Please Sign up or sign in to vote.
4.89/5 (13 votes)
3 May 2008CPOL12 min read 110.3K   1.6K   54  
In this article, we will write a full-blown WMI provider in managed code and consume that provider from managed code using the WMI extensions in .NET 3.5.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Instrumentation;
using System.ComponentModel;
using System.Diagnostics;
using System.Management;

[assembly: WmiConfiguration(@"root\MyApplication",
    HostingModel = ManagementHostingModel.Decoupled)]

[assembly: Instrumented(@"root\MyApplication")]

namespace WmiProviderExtensions
{
    [RunInstaller(true)]
    public class MyApplicationManagementInstaller :
        DefaultManagementInstaller { }

    [RunInstaller(true)]
    public class OldInstaller :
        DefaultManagementProjectInstaller { }

    [ManagementEntity(Singleton=true)]
    [ManagementQualifier("Description",
        Value="Obtain processor information.")]
    public class ProcessorInformation
    {
	
        [ManagementBind]
        public ProcessorInformation()
        {
        }
	    [ManagementProbe]
        [ManagementQualifier("Descriiption",
            Value="The number of processors.")]
        public int ProcessorCount
        {
            get { return Environment.ProcessorCount; }
        }
    }

    [ManagementEntity]
    public class ProcessInformation
    {
        Process _theProcess;
        [ManagementBind]
        public ProcessInformation(
            [ManagementName("Id")] int id)
        {
            _theProcess = Process.GetProcessById(id);
        }
        [ManagementKey]
        public int Id
        {
            get { return _theProcess.Id; }
        }
        [ManagementProbe]
        public int ThreadCount
        {
            get { return _theProcess.Threads.Count; }
        }
    }

    [ManagementEntity]
    public class BrightnessController
    {
        [ManagementBind]
        public BrightnessController()
        {
            Id = 1; BrightnessLevel = 500;
        }
        [ManagementKey]
        public int Id { get; private set; }
        [ManagementConfiguration]
        public int BrightnessLevel { get; set; }
    }

    [ManagementEntity]
    public class Printer
    {
        [ManagementBind]
        public Printer([ManagementName("Id")] int id)
        {
            Id = id;
        }
        [ManagementKey]
        public int Id;
        [ManagementTask]
        public void PrintToScreen(string s)
        {
            Console.WriteLine(s);
        }
    }

    public class CpuTemperatureAboveThresholdEvent : BaseEvent
    {
        public float ActualTemperature { get; private set; }
        private CpuTemperatureAboveThresholdEvent(
            float actualTemperature)
        {
            ActualTemperature = actualTemperature;
        }
        public static void Publish(float actualTemperature)
        {
            new CpuTemperatureAboveThresholdEvent(
                actualTemperature).Fire();
        }
    }

    [InstrumentationClass(InstrumentationType.Event)]
    public class CpuTemperatureAboveThresholdEvent
    {
        public float ActualTemperature { get; private set; }
        private CpuTemperatureAboveThresholdEvent(
            float actualTemperature)
        {
            ActualTemperature = actualTemperature;
        }
        public static void Publish(float actualTemperature)
        {
            Instrumentation.Fire(
                new CpuTemperatureAboveThresholdEvent(
                    actualTemperature));
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            InstrumentationManager.Publish(new ProcessorInformation());

            foreach (Process p in Process.GetProcesses())
            {
                InstrumentationManager.Publish(
                       new ProcessInformation(p.Id));
            }

            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(@"root\MyApplication",
                    "SELECT * FROM ProcessInformation");
            foreach (ManagementObject obj in searcher.Get())
                Console.WriteLine("Id: " + obj["Id"] +
                    ", ThreadCount: " + obj["ThreadCount"]);

            foreach (ROOT.MYAPPLICATION.ProcessInformation info in
                ROOT.MYAPPLICATION.ProcessInformation.GetInstances())
            {
                Console.WriteLine("Id: " + info.Id +
                    ", ThreadCount: " + info.ThreadCount);
            }

            foreach (ROOT.MYAPPLICATION.BrightnessController
                controller in
                ROOT.MYAPPLICATION.BrightnessController.GetInstances(
                "Id = 1"))
            {
                controller.BrightnessLevel = 400;
            }

            foreach (ROOT.MYAPPLICATION.Printer printer in
                ROOT.MYAPPLICATION.Printer.GetInstances("Id = 2"))
            {
                printer.PrintToScreen("Hello!");
            }

            ManagementEventWatcher watcher =
                new ManagementEventWatcher(@"root\MyApplication",
                    "SELECT * FROM CpuTemperatureAboveThresholdEvent");
            watcher.EventArrived += (o, e) =>
                Console.WriteLine(e.NewEvent["ActualTemperature"]);
            watcher.Start();

            CpuTemperatureAboveThresholdEvent.Publish(85.0f);
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer SELA Group
Israel Israel
Sasha Goldshtein is the CTO of SELA Group, an Israeli company specializing in training, consulting and outsourcing to local and international customers.

Sasha's work is divided across these three primary disciplines. He consults for clients on architecture, development, debugging and performance issues; he actively develops code using the latest bits of technology from Microsoft; and he conducts training classes on a variety of topics, from Windows Internals to .NET Performance.

You can read more about Sasha's work and his latest ventures at his blog: http://blogs.microsoft.co.il/blogs/sasha

Sasha writes from Jerusalem, Israel.

Comments and Discussions