Problem
Recently one of my work projects presented a good scenario for a management console that could help configure servers using WMI. The requirements themselves were simplistic as the utility would only need to manage a server list and update system-level environment variables based on the servers category.
To check the feasibility for building such a solution i started to research example applications that automate WMI using C#/.net 2.0 and found many straightforward candidates. The samples used the ManagementObject and seemed to do what i needed.
Coding my first prototype everything seemed to go well until i attempted to execute enough code to actually update the environmental variable which immediately hit an Exception on the .Put() method of the ManagementObject, the exception being "Attempt to put an instance with no defined key".
My first instinct was to Google the exact error but to my horror zero results were returned. Trying MSDN and LIVE search also resulted in zero documented cases of this Exception. As most Software Engineers today i am spoiled by Google's ability to provide me an answer to all programming questions and this particular case bothered me greatly as it seemed like a simplistic 10 lines of code that someone must have coded before.
Solution
After many hours of trying to debug this strange Exception and looking at other peoples samples i realized that the MSDN's example was actually very close to my code except it used a different overload on the line which would query the variables:
MSDN Code: SelectQuery wmiQueryObject = new SelectQuery("Win32_Environment", "UserName=\"\" and Name=\"SystemRoot\"");
My Code: SelectQuery wmiQueryObject = new SelectQuery("select VariableValue from Win32_Environment where name = \"SystemRoot\"");
In hopes this would solve my problem I decided to try their method overload instead my WQL variant while leaving the rest of the code alone and it worked perfectly! I really do not understand why switching the overload causes the .Put() method to work but at least i was able to get beyond an Exception that is not even documented and my project moves forward. I hope this Blog entry or my MSDN Wiki content posting saves someone time and documents this Exception.
In general i believe this is a great example of why the source code for .NET should be released, and thankfully this is happening in .NET 3.5! (to read more see Scott Gu's blog posting on this subject)
Reference
My MSDN Wiki Post
http://msdn2.microsoft.com/en-us/library/system.management.managementobject_methods.aspx
Helpful WMI Link
http://www.csharphelp.com/archives2/archive334.html (By Kevin Matthew Goss)
http://msdn2.microsoft.com/en-us/library/aa720264(VS.71).aspx (Managing Applications Using WMI on MSDN)
http://en.wikipedia.org/wiki/Windows_Management_Instrumentation (WMI Overview on Wikipedia)