0

I know how to gain access to management-objects. Lets say this one:

var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter");            
foreach (var nic in searcher.Get())
{                
    Console.WriteLine(nic["caption"]);
}

Now this nic[]-synthax is very bad to use. If I take a look at visual studios server explorer I see, that it fills up a property grid for each object I select. Smells like they are creating bindable classes there. Are there any libs or approaches to do the same? I would like to get a syntax like

var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter");            
foreach (var nic in searcher.Get())
{                
    Console.WriteLine((nic as Win32NetworkAdapter).Caption);
}

I just don't want to waste my time implementing something new which was invented already!

Alexander Schmidt
  • 5,631
  • 4
  • 39
  • 79

3 Answers3

2

Why not use the Mgmtclassgen.exe (Management Strongly Typed Class Generator) which is part of Visual Studio?

Phil Bolduc
  • 1,586
  • 1
  • 11
  • 19
1

WMI takes a query and returns an indeterminate set of results. The query is SQL-like, so it may return only certain columns. The properties grid simply enumerates each returned value into separate names and values. There's no fixed column set for any query result. For this reason, you'll need to explicitly fetch each one from the returned list.

Polynomial
  • 27,674
  • 12
  • 80
  • 107
  • Thank you for clearing that out. I did understand the default behavior. So, you say, that there is no "wrapper"-library which for instance generates proxy-classes like Win32NetworkAdapter? – Alexander Schmidt Nov 21 '11 at 17:05
  • I've spent the last 4+ months dealing primarily with WMI in C#, and I've never come across such a class. The major problem is that certain fields won't exist on certain operating systems. You'll have to test the existance and validity of each one yourself. – Polynomial Nov 21 '11 at 17:06
0

Just to make others happy like me, I've created a T4 for solving my problem. It's documented at http://www.codingfreaks.de/2011/11/22/t4-fur-wmi-zugriff/ (in German!!!) and can be obtained at http://www.codingfreaks.de/files/wmi01/WmiHelper.tt. To make it work, just

  1. Add it to your Project in VS.
  2. Add a text-file named "Classes.txt".
  3. Add a line for each WMI-Class you want to use in "Classes.txt" (e.g. "Win32_NetworkAdapter")
  4. Right-click the tt-file in the project and use "user-defined tool".
  5. Go to your code and type WmiHelper.*

Enjoy!

Alexander Schmidt
  • 5,631
  • 4
  • 39
  • 79