ManagementObjectSearcher throws FileNotFoundException when iterating its objects in foreach loop - c#

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"

Related

Cannot read all users from Active Directory - [DirectoryServicesCOMException] MoveNext()

My team is using a program written in C# to read all users from a specific OU. The program behaves very strange. Sometimes it is working for a couple of weeks and then without any big changes on our AD or any other related component, it throws an exception. Then it is not working for a couple of weeks and after some time it start to run normally again.
Code
DirectoryEntry searchRoot = new DirectoryEntry("<LDAP string>")
searchRoot.AuthenticationType = AuthenticationTypes.None;
DirectorySearcher search = new DirectorySearcher(searchRoot);
search.Filter = <our filter>;
search.PropertiesToLoad.Add("<some property>");
search.PageSize = 1;
SearchResult result;
SearchResultCollection resultCol = null;
try
{
resultCol = search.FindAll();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
if (resultCol != null)
{
Console.WriteLine("Result Count: " + resultCol.Count); //.Count throws the Exception
}
Exception
Unhandled Exception: System.DirectoryServices.DirectoryServicesCOMException: An operations error occurred.
at System.DirectoryServices.SearchResultCollection.ResultsEnumerator.MoveNext()
at System.DirectoryServices.SearchResultCollection.get_InnerList()
at System.DirectoryServices.SearchResultCollection.get_Count()
Data: System.Collections.ListDictionaryInternal
Error Code: -2147016672
Extended Error: 8431
Extended Error Message: 000020EF: SvcErr: DSID-020A07A7, problem 5012 (DIR_ERROR), data -1018
HResult: -2147016672
Message: An operations error occured.
Source: System.DirectoryServices
Stack Trace: at System.DirectoryServices.SearchResultCollection.ResultsEnumerator.MoveNext()
Target Site: Boolean MoveNext()
Additional Information
Target Framework: .Net Framework 4.6.1 (no additional libraries)
The program is executed on a domain controller
What I have tried
I have created a loop to use the MoveNext() function of the
enumerator and found out that it loads results up to a specific
element and then crashes
It is always the same element
After the first exception all retries fail as well
The user that starts it is a domain admin (but I
have also tried it with an enterprise admin account, so it is
probably not a permission issue)
I have deleted the user that should be read when the exception happens but dring the next run the exception was thrown for a previous user
I have come to a point, where I have no more ideas on solving this problem. I would appreciate all your support.
This answer just summarizes our conversation in comments.
This thread partially matches the error you are getting:
problem 5012 (DIR_ERROR) data -1018
And the answer from a Microsoft MVP is:
That is a checksum error in the database, you have corruption in your
database which is usually due to a failing disk or disk subsystem or
possibly a system crash and data not being written from a write cache.
So it sounds like you might have the same thing going on.
But it may only be one DC that has the problem. So to help you narrow down which one, you can specify the DC in the LDAP path like so:
LDAP://dc1.example.com/OU=Target,OU=My User Group,OU=My Users,DC=example,DC=com
This can help you in two ways:
It can identify the bad DC so you know which one you need to fix (and possibly take it offline until it is fixed), and
You can specifically target a good DC so your script will keep working.

"DTD is prohibited" error when accessing sharepoint 2013/office365 list (but not openly aware of using XML)

I've been getting a list of folders and files from Sharepoint (on Office 365) by using the following code...
...
var folders = ListFolders(libraryName, clientContext, web);
...
public List<Folder> ListFolders(string libraryName, ClientContext clientContext, Web web)
{
var list = GetDocumentLibrary(libraryName, clientContext, web);
var folders = list.RootFolder.Folders;
clientContext.Load(folders);
clientContext.ExecuteQuery();
return folders.ToList();
}
public List GetDocumentLibrary(string libraryName, ClientContext clientContext, Web web)
{
var query = clientContext.LoadQuery(web.Lists.Where(p => p.Title == libraryName));
clientContext.ExecuteQuery();
return query.FirstOrDefault();
}
It was working fine until I rebooted my computer (it installed a Windows Update), I strongly suspect, based on some testing I've done, it seems this is caused by http://support.microsoft.com/kb/2964358.
When the clientContext.ExecuteQuery() statement is reached in GetDocumentLibrary(), the
following exception is thrown.
An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll
Additional information: For security reasons DTD is prohibited in this XML document. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method.
I'm wondering how I can work around this, as I'm not consciously using System.XML, it's a background function or process when the ExecuteQuery runs.
Can I pass some additional XMLReader info to this or clientContext (I'm assuming not), so I'm not sure how to execute this query to prevent the DTD error. I have also tried accessing the list in a different manner, by using this code... (from Microsoft's MSDN pages)
List list = clientContext.Web.Lists.GetByTitle(libraryName);
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View/>";
ListItemCollection listItems = list.GetItems(camlQuery);
clientContext.Load(list); clientContext.Load(listItems);
clientContext.ExecuteQuery();
This works on a computer without the KB above, however on my PC it doesn't (I get the same exception as my other code) , obviously uninstalling the KB will make things work in the short term, but its no good in the longer term. Any advice on how to avoid this error would be greatly appreciated. I can only assume there will be a "preferred" way from Microsoft for accessing lists now this KB is implemented, but I'm clueless as to what it is.
Thanks
Dougie
I was using a 2nd router as a WiFi extender, this seemed to have an odd, but reproducable effect when connecting to sharepoint, I stopped using it and used my main router/wifi box and my problem disappeared.
I had this same issue on a Virgin Media (UK based ISP) internet connection. It turns out that Virgin Media intercept web calls for the purpose of "advanced network error search". Luckily you can opt out from this. As soon as I did that it worked fine.
More details on the cause and how to opt out from Virgin Media's advanced search here: http://pryankrohilla.blogspot.co.uk/2014/05/error-resolved-connect-sposervice-for.html
I'm not happy about this, I left tweaking my program with a view to doing more diagnostics this morning, but now the issue seems to have mysteriously stopped happening, whether this has been tweaking at the MS end or not, or perhaps a glitch in SharePoint I've no idea, I don't think it's been my laptop since it's been on since I had the issue.

Running WMI Query results in COMException (0x80080005)

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.

How to obtain DefragAnalysis using C#

I am currently developing an application in C# (.NET 4.0) that should have as a part of its functionality the ability to determine the percentage of fragmentation on a particular volume. All the other features have been tested and are working fine but I’ve hit a snag trying to access this data. I would ideally prefer to use WMI as this matches the format I’m using for the other features but at this point I’m willing to use anything that can be efficiently integrated into the application, even if I have to use RegEx to filter the data. I am currently doing the development on a Windows 7 Professional (x64) machine. I have tested the following Powershell snippet using Administrator rights and it works flawlessly.
$drive = Get-WmiObject -Class Win32_Volume -Namespace root\CIMV2 -ComputerName . | Where-Object { $_.DriveLetter -eq 'D:' }
$drive.DefragAnalysis().DefragAnalysis
This is the method I’m using in C# to accomplish the same thing, but the InvokeMethod keeps returning 11 (0xB).
public static Fragmentation GetVolumeFragmentationAnalysis(string drive)
{
//Fragmenation object initialization removed for simplicity
try
{
ConnectionOptions mgmtConnOptions = new ConnectionOptions { EnablePrivileges = true };
ManagementScope scope = new ManagementScope(new ManagementPath(string.Format(#"\\{0}\root\CIMV2", Environment.MachineName)), mgmtConnOptions);
ObjectQuery query = new ObjectQuery(string.Format(#"SELECT * FROM Win32_Volume WHERE Name = '{0}\\'", drive));
scope.Connect();
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
{
object[] outputArgs = new object[2];
foreach (ManagementObject moVolume in searcher.Get())
{
// Execution stops at this line as the result is always 11
UInt32 result = (UInt32)moVolume.InvokeMethod("DefragAnalysis", outputArgs);
if (result == 0)
{
Console.WriteLine("Defrag Needed: = {0}\n", outputArgs[0]);
ManagementBaseObject mboDefragAnalysis = outputArgs[1] as ManagementBaseObject;
if (null != mboDefragAnalysis)
{
Console.WriteLine(mboDefragAnalysis["TotalPercentFragmentation"].ToString());
}
}
else
{
Console.WriteLine("Return Code: = {0}", result);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Could not acquire fragmentation data.\n" + ex);
}
return result;
}
I have even added the following line to the app.manifest but still nothing.
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
Could somebody please tell me what I’m overlooking? Failure is not an option for me on this, so if it cannot be done using C# I don’t mind creating a DLL in another language (even if I have to learn it), that will give me the results I need. Ideally the application should be able work on any OS from XP upwards and must be totally transparent to the user.
These are the resources I have already used. I wanted to add the jeffrey_wall blog on msdn as well but as a new user I can only add 2 hyperlinks at a time. Thanks again.
http://www.codeproject.com/Messages/2901324/Re-the-result-of-DefragAnalysis-method-in-csharp.aspx
http://social.technet.microsoft.com/Forums/vi-VN/winserverfiles/thread/9d56bfad-dcf5-4258-90cf-4ba9247200da
Try building your application targeting 'Any CPU' - on the Build tab of the project properties. I suspect you're using a target of x86. I get the same error code on my Win7 x64 machine if I do that.
In fact, running your PowerShell snippet in the x86 version of PowerShell gives an empty set of results, too.
You get the same error if you run either piece of code without full Administrator privileges, as you've found, so also ensure your app.manifest is correct. A UAC prompt is a handy hint that it's taking effect!
No idea why this WMI query doesn't like running under WoW64, I'm afraid, but hopefully this will give you a head-start.
You could simply call the PowerShell command you mentioned in your post, since you said the PowerShell code works. From C# you would want to follow this workflow:
Instantiate a PowerShell RunSpace
Open the RunSpace
Add a script to the Commands property
Invoke the command list
Here is an example of how to achieve this, and process the resulting object output.
http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C
For Windows XP and Windows Vista, you would have to ensure that PowerShell was installed on each of the systems you want to run your program on. Not a bad prerequisite to have, but something to keep in mind as a dependency.
Hope this helps.
The 32-bit WMI provider for Win32_Volume doesn't seem to be able to start the defragsvc for whatever reason. You can force the 64-bit WMI provider even in a 32-bit client running under WOW64 by changing your code to add an additional WMI connection option:
ConnectionOptions mgmtConnOptions = new ConnectionOptions {
EnablePrivileges = true,
Context = new ManagementNamedValueCollection() {
{ "__ProviderArchitecture", 64 }
}
};

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