2

I want to access WMI using the AutomationFactory in a Silverlight OOB application.

dynamic locator = AutomationFactory.CreateObject("WbemScripting.SWbemLocator");
dynamic wmi = locator.ConnectServer(".", "\\root\\cimv2");

I now want to add error handling to this.

MSDN states that the return value is a reference to the connected object if the call is successful and that in case of an error I should check the Err object. However, there are two questions I have with this:

  • What is the return value if the call is not successful? null? Some arbitrary pointer that I cannot use?
  • How can I access the Err object in Silverlight?
  • How can I detect if the call was successful? May there be any exceptions which I have to catch?
  • I've seen some examples using the using statement, and some without. Do I have to dispose the dynamic objects manually after I've used them?
AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
Etan
  • 17,014
  • 17
  • 89
  • 148

1 Answers1

1
  • What is the return value if the call is not successful? null? Some arbitrary pointer that I cannot use?

No value is return and the LHS of an assignment is unmodified when a call into a COM component fails. Instead the COMException is thrown.

  • How can I access the Err object in Silverlight?

This is no "Err" object, that is a VB(Script) construct, it doesn't exist in C#. However the infor you are after will be available as the properties of the COMException thrown when a call fails.

  • How can I detect if the call was successful? May there be any exceptions which I have to catch?

Yup, see above.

  • I've seen some examples using the using statement, and some without. Do I have to dispose the dynamic objects manually after I've used them?

Attempts to manage COM object lifetimes using Dispose have varied results. Personally I'd make sure that anything that has something like a "Close" method has that "Close" method call and leave it at that.

If you really want to make user COM objects are released then at an appropriate point (and not too frequently) call GC.Collect.

AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
  • Thanks for the detailed answer. One last question: may you add sources to your answer, like MSDN pages where you have got your info? – Etan Sep 30 '11 at 09:52
  • @Etan: I'll give you this http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.comexception.aspx but I'm sure you could have looked that up yourself. Its difficult giving references to things that are this fundemental. In order to return anything a method needs to have completed without throwing an exception, this is so basic I'm not sure where I'd look to find the MSDN pages. I'm not be inclined to looking either. I "got my info" from experience. – AnthonyWJones Oct 02 '11 at 19:41