Error while fetching Hardware Info in Visual Studio 2010 - c#

I have a C# project where I am trying to deploy a protection mechanism by registering a combination of the Hardware IDs.
I am using the ManagementObjectSearcher Class for the same. Here are some of the commands:
ManagementObjectSearcher cpuget = new ManagementObjectSearcher("Select * From Win32_processor");
ManagementObjectSearcher mainboardget = new ManagementObjectSearcher("SELECT * FROM Win32_BaseBoard");
ManagementObjectSearcher biosget = new ManagementObjectSearcher("Select * From Win32_BIOS");
For fetching the IDs I have:
foreach (ManagementObject mo in cpuList)
{
cpuid = mo["ProcessorID"].ToString();
}
foreach (ManagementObject mo in mainboardlist)
{
mbid = mo["SerialNumber"].ToString();
}
This has been working fine. However, *in some machines(I tested on 10 PCs and two were defaulters)* the error message showed up.
Reference not set to Instance of an Object
Why so? Please Help.

The most difficult problems have the silliest of Answers. Period.
All I had to do was Check for a null component in the management object class.
foreach (ManagementObject mo in cpuget.Get())
{
if (mo["ProcessorID"] != null)
cpuid = mo.GetPropertyValue("ProcessorID").ToString();
}
The similar would be for mbid.
What a dufus? :|
P.S.: #L.B suggested this. More power to him.

Related

C# Application: Get Network Shares On Another Computer

First of all, apologies if this doesn't make sense, and/or it has already been asked (although searching didn't find anything).
I have an application which sets default printers for our end users but I would like to expand it by also making it able to install printers from a remote machine as well.
What I need to do is on Form_Load populate a Combo Box with all network shares from the print server.
I am shooting in the dark and am wondering if anyone can shed some light.
I believe this works.
This isnt my code originally but I cant remember where it came from.
using System.Management;
private void btnGetPrinters_Click(object sender, EventArgs e) {
// Use the ObjectQuery to get the list of configured printers.
ObjectQuery oquery = new ObjectQuery("SELECT * FROM Win32_Printer");
ManagementObjectSearcher mosearcher = new ManagementObjectSearcher(oquery);
ManagementObjectCollection moc = mosearcher.Get();
foreach (ManagementObject mo in moc)
{
PropertyDataCollection pdc = mo.Properties;
foreach (System.Management.PropertyData pd in pdc)
{
if ((bool)mo["Network"])
{
cmbPrinters.Items.Add(mo[pd.Name]);
}
}
}
}

How to find All Graphic Cards? C#

I used this code for finding graphic cards:
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("SELECT * FROM Win32_DisplayConfiguration");
string graphicsCard = "";
foreach (ManagementObject mo in searcher.Get())
{
foreach (PropertyData property in mo.Properties)
{
if (property.Name == "Description")
{
graphicsCard += property.Value.ToString();
}
}
}
but result is: Nvidia Quadro K6000
How to find all Graphic cards?
The very first line of the MSDN page reads:
[The Win32_DisplayConfiguration WMI class is no longer available for use as of Windows Server 2008. Instead, use the properties in the Win32_VideoController, Win32_DesktopMonitor, and CIM_VideoControllerResolution classes.]
So I suggest you start out with Win32_VideoController.

Enumerating list of applications installed using .NET

I use the following code to enumerate applications installed in my system:
ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_Product");
ManagementObjectCollection collection = mos.Get();
List<string> appList = new List<string>();
foreach (ManagementObject mo in collection)
{
try
{
string appName = mo["Name"].ToString();
appList.Add(appName);
}
catch (Exception ex)
{
}
}
When I use this code in console or a WPF application, I get the exact list of apps. But when I use it in a windows service, I'm not getting the entire list. In my case its 1 application less. Is there a limitation to use this in Windows Service?

How to detect Cameras attached to my machine using C#

I am able to know the sound devices and USB Devices attached to my PC but not getting any way to find Cameras attached to my machine.
Used below code to get Sound Devices
Console.WriteLine("Win32 SoundDevices\r\n===============================");
ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * from Win32_SoundDevice");
foreach (ManagementObject soundDevice in searcher.Get())
{
//Console.WriteLine("Device found: {0}\n", soundDevice.ToString());
Console.WriteLine("Device found: {0}\n", soundDevice.GetPropertyValue("ProductName"));
}
Console.WriteLine("Search complete.");
I wrote a solution that worked well for me. This method found two USB cameras and an integrated camera on my laptop.
private static async Task ListAllCamerasAsync()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM win32_PNPEntity WHERE PnPClass='Camera'");
var collection = await Task.Run(() => { return searcher.Get(); });
var cameraIndex = 0;
foreach (ManagementObject cameraDevice in collection)
{
Console.WriteLine($"Camera {cameraIndex}: {cameraDevice["Name"]}");
cameraIndex++;
}
}
This tool will prove helpful:
http://www.microsoft.com/en-us/download/details.aspx?id=8572
I'm fairly certain there's no equivalent string you can send to ManagementObjectSearcher() for webcams specifically. There is the "Win32_USBControllerDevice" which you can then determine if it is a webcam or not.
A better solution altogether is to take advantage of DirectShow.NET

How to list all local computer user profiles in a combo box?

I need to enumerate all user profiles on a local computer and list them in a combo box. Any special accounts need to be filtered out. I'm only concerned about actual user profiles on the computer where the app is running. I have done some searching but I haven't found a clear answer posted anywhere. I did find some code that might work but SelectQuery and ManagementObjectSearcher are displaying errors in VS and I'm not sure what I need to do to make this work.
using System.Management;
SelectQuery query = new SelectQuery("Win32_UserAccount");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject envVar in searcher.Get())
{
Console.WriteLine("Username : {0}", envVar["Name"]);
}
By saying "SelectQuery and ManagementObjectSearcher are displaying errors" I guess you didn't reference the System.Management dll.
You should right click References in your solution and add System.Management.
Then, with your using statement, the errors should disappear.
Anyway, including the error next time will assist everyone to help you :)
The mentioned code is great but when I tried on a machine connected to a Active Directory Domain all the usernames where returned for the domain. I was able to tweak the code a bit to only return the users that actually have a local directory on the current machine. If a better C# developer can refactor the code to make it cleaner - please help!
var localDrives = Environment.GetLogicalDrives();
var localUsers = new List<string>();
var query = new SelectQuery("Win32_UserAccount") { Condition = "SIDType = 1 AND AccountType = 512" };
var searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject envVar in searcher.Get())
{
foreach (string drive in localDrives)
{
var dir = Path.Combine(String.Format("{0}Users", drive), envVar["name"].ToString());
if (Directory.Exists(dir))
{
localUsers.Add(envVar["name"].ToString());
}
}
}
Once you have the localUsers variable you can set this as the data source to your ComboBox control of our choice.

Categories