I’ve seen numerous handy WMI scripts and code samples from fellow BizTalk bloggers and from the BizTalk help. Amazingly every one of these samples use late-bound objects calls to invoke methods and access properties from the BizTalk management objects. This makes the code rather verbose, it’s very inconvenient and also very error prone. There’s a better way to write your WMI code. Therefore you have to download first and then install the ‘Management (WMI) Extensions for Visual Studio .NET 2003 Server Explorer’. This tool makes WMI programming much easier and enjoyable (at least for me). It’s no rocket science or anything but it comes in very handy for making your first steps on the WMI moon. You don’t have to take my word on it, look for yourself:
After having installed the extension you can go into your Visual Studio’s Server Explorer and select the namespace you want to add management classes from (select ‘add classes’ from the context menu).
After selecting the desired classes from your namespace (‘root \MicrosoftBizTalkServer’ I assume) the Server Explorer window will contain a list of the selected management object-types. It also shows a list of all instances for a given class when you click it. When having selected an instance, all of its properties will be shown inside the property-window (you could modify them from there too, but I wouldn’t recommend doing it this way).
Also methods can be invoked on classes and instances; this is nice for testing purposes. *No big deal* you are thinking of course; now pay attention:
When selecting ‘Generate Managed Class’ from the menu, the extension will automatically generate a wrapper class and add it to your solution’s startup project (it targets your .net project language).
The generated classes have strongly typed properties and methods, so you have access to and can invoke by simply using their name (even enum-types are created). You benefit from good old Intellisense again. Behind the covers the generated wrapper classes still use late-bound objects and calls of course, but you don’t have to care at least about this, nor write ugly late binding code. Now you can write clean high-level WMI code a lot faster.
Take a look at this little WMI sample (where I make a call to ‘GetInstances’: this overloaded method is created automatically and it requires only the where-part of the WQL query to return a typed collection of your WMI object-type).
Try to rewrite the following method (please don’t focus on the language change; it’s purely for educational purposes. I’ve never executed a single line of this code 🙂
Which one do you prefer?