views:

269

answers:

2

The following WMI query throws an exception at serverProtocolsManagement.Get() when sqlHost is an invalid server name (as expected. However, if I try to invoke this code again with the same invalid parameter, the ManagementScope constructor hangs indefinitely (never returns or throws an error, just hangs). Is there a reasonable explanation for this?

try {

        ManagementScope managementScope = new ManagementScope(@"\\" + sqlHost + @"\root\Microsoft\SqlServer\ComputerManagement");
        using (ManagementClass serverProtocolsManagement = new ManagementClass(managementScope, new ManagementPath("ServerNetworkProtocol"), null)) {

            serverProtocolsManagement.Get();

            using (ManagementObjectCollection protocols = serverProtocolsManagement.GetInstances()) {
                foreach (ManagementObject protocol in protocols ) {
                    protocol.Get();

                    if ((string)protocol.GetPropertyValue("ProtocolName") == "Tcp" &&
                        (string)protocol.GetPropertyValue("InstanceName") == sqlInstanceName) {

                        protocol.InvokeMethod("SetEnable", null);
                    }
                }
            }
        }
    } catch (COMException ex) {
        MessageBox.Show(ex.ToString());
    }

Edit:

I've tried messing around with different timeout options (by passing a ConnectionOptions object to the ManagementScope constructor), but to no avail.

Edit #2:

I don't know why I didn't think of this (although it still shouldn't be a problem): I was calling this code from the Immediate Window in VS while debugging. There must have been some sort of threading issue, because once I linked this code to a Windows Forms button, everything worked just fine. Thanks for the help!!

A: 

Do you have the same problem when you use the ManagementClass constructor (with the string scope instead of the ManagementScope object)?

(therefor skipping the whole ManagementScope step)

Zyphrax
I tried your suggestion, and yes, I have the same problem. I also have the same problem using the ManagementObjectSearcher object instead of the ManagementClass object. Very odd...
Pwninstein
A: 

Apparently running WMI queries from the Immediate Window while debugging is a no-no. Executing the query as a result of a button press instead fixed the problem.

Pwninstein