Running WMI Query results in COMException (0x80080005) - c#

I have been working on a small WMI Info grabber for my job as I work with hundreds of servers and being able to grab certain information can be quite beneficial when having to get it on more than 5 servers.
List<string> output = new List<string>();
ObjectQuery query = new ObjectQuery("SELECT * FROM ComputerSystem");
ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher(ServerConnect.HardwareScope, query);
ManagementObjectCollection retObject = objectSearcher.Get();
foreach (ManagementObject manObj in retObject)
{
string[] data = ((string)manObj["Description"]).Split('-');
string IPMI = data[1].Substring(7);
string firmware = data[2].Substring(5);
output.Add("IPMI Version: " + IPMI);
output.Add("BMC Firmware Version: " + firmware);
}
return output;
This is currently what I am using to grab some basic data from the ComputerSystem, this which works on some servers but crashes on others obtains the correct information that I am wanting; however, I need to prevent it from crashing with a COMException.
It says it breaks out with the System.Runtime.InteropServices.COMException at the following line of code:
foreach (ManagementObject manObj in retObject)
I have been trying to solve this issue as to why some servers get this exception returned rather than being able to grab the information and if it is possible to fix it.
I have been trying to fix this for the last couple weeks and have finally decided to ask for help about this specific problem that I am having.
UPDATE
I have ran the same name space and selection for the servers giving me issues in WMI Code Creator ( http://www.microsoft.com/en-us/download/confirmation.aspx?id=8572 ) and it is able to obtain the data I need however when ran through my program it gives the COMException. I have gone over the code that Code Creator makes, and my code and have modified some of it and it still gives me the error.

Related

how can i get the info of ssd in asp.net code?

i have this code
managementObjectSearcher ComponentInfo = new ManagementObjectSearcher ("SELECT * FROM Win32_DiskDrive");
What should i do to get the info of the ssd
?
What kind of info are you looking for exactly? There's a lot of info here: https://learn.microsoft.com/en-us/windows/desktop/cimwin32prov/win32-diskdrive
and also here: https://learn.microsoft.com/en-us/windows/desktop/cimwin32prov/win32-logicaldisk. You can run any query you want by running a foreach as such:
foreach (managementobject os in ComponentInfo.Get())
{
//useful query information from os here...
}
I've actually just finished using this code to get the partitions of each drive and their relative free space to calculate the percent free space. I've also used it to get the model and serial number of the drives. You can do a lot here, just point and shoot.

Cant query WMI when in Administrator mode

I took half a day to realize that all my queries to WMI were returning with a count of 0 whenever the program (c#) was running in administrator mode, however whenever it was run normally it would receive the count of 7 (which is the right count value I should be getting) and its associated values. This problem also happens under debugging mode if VS is running in ADMIN mode.
This is under windows 10 final (and complete updated as of 31-07-2015). Tried different frameworks (4.0->4.6) in case it had anything to do with that, although obviously it did not.
Here is the code that works under normal circumstances, but not under ADMIN mode:
public static Dictionary<String, String> GetNetworkDrives()
{
Dictionary<String, String> RetuningDic = new Dictionary<string, string>();
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_MappedLogicalDisk");
MessageBox.Show("Query count: " + searcher.Get().Count.ToString());
foreach (ManagementObject queryObj in searcher.Get())
{
//Console.WriteLine("-----------------------------------");
//Console.WriteLine("Win32_MappedLogicalDisk instance");
//Console.WriteLine("-----------------------------------");
MessageBox.Show(queryObj["VolumeName"] + "||" + queryObj["DeviceID"]);
//String stuff = queryObj["ProviderName"] + "||" + queryObj["DeviceID"]; //queryObj["VolumeName"]
//Console.WriteLine(stuff);
}
MessageBox.Show("No errors");
}
catch (ManagementException e)
{
//Console.WriteLine("Error");
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
return RetuningDic;
}
Clarification of the code: Return on a messagebox the letter and the folder/volume name of a mapped network location.
See the remarks of Win32_MappedLogicalDisk, especially:
However, whether instances are returned depends on the Local Security Policy settings in the Control Panel Administrative Tools. If the following policy is set to "Object Creator", then no mapped drive instances are returned, even if A is a member of the Administrators group:
"System object: default owner for objects created by members of the administrators group."
and
If there is more than one session for user A on the machine, then no mapped drive instances are returned (because the provider has no reasonable way of deciding which session to use).
So there are some situations where Win32_MappedLogicalDisk does not return drives even though they are added. I would probably check for security settings, policies, etc.

ManagementObjectSearcher throws FileNotFoundException when iterating its objects in foreach loop

I try to obtain some system information with several classes from System.Management namespace but any attempt to use ManagementObjectSearcher or ManagementObjectCollection collection items results in FileNotFoundException.
Below I present the problematic piece of code:
public static string GetProcessorID() {
var processorID = "";
var query = "SELECT ProcessorId FROM Win32_Processor";
var oManagementObjectSearcher = new ManagementObjectSearcher(query);
foreach (var oManagementObject in oManagementObjectSearcher.Get()) {
processorID = (string)oManagementObject["ProcessorId"];
break;
}
return processorID;
}
Exception is thrown in 'foreach' line, when trying to obtain next item from the collection.
It is observed on machine with windows xp professional sp3, with visual studio 2008 professional. I suppose that it can be something with my cpu, which is intel dual core - the same program on other machine with similar environment works perfect. The main difference between those machines is cpu.
Other parameters like MACAddress and SystemDrive provides the same problem, which suggests that it might be rather software issue (WMI?)
Very similar problem is described here -> http://news.softpedia.com/news/XP-SP3-Win32-Processor-Class-Labels-Intel-Core-2-Duo-CPUs-Incorectly-90201.shtml but the solution did not solved it.
Any ideas? Thanks in advance.
Dawid
I know my answer is a bit late, but because it's the first hit on google when i searched my error i guess i put a link to the topic solving it for me.
System.Management.ManagementException: Not found
Basicly what you have to do is resolve your error's with WMI.
I have the same problem.
And it don't crash on 'in word but on
oManagementObjectSearcher.Get().
Check the stack trace:
System.IO.FileNotFoundException - Nie można odnaleźć określonego modułu. (Wyjątek od HRESULT: 0x8007007E)
Stack trace:
w System.Management.ThreadDispatch.Start()
w System.Management.ManagementScope.Initialize()
w System.Management.ManagementObjectSearcher.Initialize()
w System.Management.ManagementObjectSearcher.Get()
[...]
When I moved to the My computer / right click / manage / services / WMI configration / right click / properties -> I got message that there is an error with message "Win32: Couldn't find module"

Using System.Management to Query a VMware Server

Summary: is it possible to specify a port to use when querying WMI using System.Management;
I have a python script under Linux that queries, using WBEM, classes on a number of ESXi servers to check for warnings or errors on various subsystems. Previously, separately, I have written a WPF application that queries a number of WinTel boxes for their disk consumption etc. using WMI.
I am wanting to write a new WPF application that will perform the same function as the script and I thought I would be able to do this with WMI. Below is my testing code with the error handling removed for brevity, SetOptions is a private function that provides the username and password:
foreach (string hostname in Properties.Settings.Default.Hosts)
foreach (string WMIclass in Properties.Settings.Default.Classes)
{
ObjectQuery Query = new ObjectQuery("SELECT * FROM " + WMIclass);
ManagementObjectSearcher mos = GetMos(Query, hostname);
foreach (ManagementObject mo in mos.Get())
foreach (PropertyData pdc in mo.Properties)
Debug.WriteLine(pdc.Name + " \t\t: " + pdc.Value);
}
private ManagementObjectSearcher GetMos(ObjectQuery Query, string Hostname)
{
ConnectionOptions Options = SetOptions();
ManagementScope Scope = new ManagementScope("\\\\" + Hostname + "\\root\\cimv2", Options);
return new ManagementObjectSearcher(Scope, Query);
}
The trouble is I get a RPC unavailable on the remote server. I think that is because I am first trying to establish a RPC call on 135 which is not hosted by an ESX server. My question is how can one specify the port 5989 or is there something straightforward I can use in .net to perform what I need to do. Naively I'm thinking the class structure looks the same between WMI/WBEM surely it can be done :-/
System.Management can only be used to connect to other Windows machines running WMI, and doesn't support WBEM. The only C# WBEM client library I seen is http://code.google.com/p/wbemtools/, but it doesn't look very mature.
As said WMI Classes in .net don't support WBEM. In the end I ended up writing some code around the VMware.Vim.dll which has some good documentation on what I needed to do.

List of valid resolutions for a given Screen?

Is there a way to get ALL valid resolutions for a given screen?
I currently have a dropdown that is populated with all valid screens (using Screen.AllScreens). When the user selects a screen, I'd like to present them with a second dropdown listing all valid resolutions for that display (not just the current resolution).
I think it should be possible to get the information using Windows Management Instrumentation (WMI). WMI is accessible from .NET using the classes from them System.Management namespace.
A solution will look similar to the following. I don't know WMI well and could not immediately find the information you are looking for, but I found the WMI class for the resolutions supported by the video card. The code requires referencing System.Management.dll and importing the System.Management namespace.
var scope = new ManagementScope();
var query = new ObjectQuery("SELECT * FROM CIM_VideoControllerResolution");
using (var searcher = new ManagementObjectSearcher(scope, query))
{
var results = searcher.Get();
foreach (var result in results)
{
Console.WriteLine(
"caption={0}, description={1} resolution={2}x{3} " +
"colors={4} refresh rate={5}|{6}|{7} scan mode={8}",
result["Caption"], result["Description"],
result["HorizontalResolution"],
result["VerticalResolution"],
result["NumberOfColors"],
result["MinRefreshRate"],
result["RefreshRate"],
result["MaxRefreshRate"],
result["ScanMode"]);
}
}
The following link contains detailed code examples for this:
Task 2: Changing the Display Resolution
http://msdn.microsoft.com/en-us/library/aa719104(VS.71).aspx#docum_topic2
The accepted answer doesn't seem to work on Windows 8.1, at least on my machine. The query runs fine but there are 0 entries in the results. And considering Bijoy K Jose's comment I suppose that I am not the only one.
However the validated answer for the following question worked out just fine :
How to list available video modes using C#?
Thanks to Vimvq1987

Categories