Enumerating list of applications installed using .NET - c#

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?

Related

C# Update Network Adapter Name partially working (WinReg good, ipconfig bad)

Given the following function:
private void UpdateNetworkAdapterName(string pnpDevID, string oldAdpterName, string newAdapterName)
{
string guid = "";
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_NetworkAdapter");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject m in queryCollection)
{
if (string.Equals(m["PNPDeviceID"].ToString(), pnpDevID))
{
guid = m["GUID"].ToString();
break;
}
}
RegistryKey regKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, Environment.MachineName, RegistryView.Registry64);
regKey = regKey.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" + guid + "\\Connection", true);
regKey.SetValue("Name", newAdapterName);
bool successful = false;
foreach (NetworkInterface netAd in NetworkInterface.GetAllNetworkInterfaces())
{
if (netAd.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
if (string.Equals(netAd.Name, newAdapterName))
{
Console.WriteLine($"Successfully updated network adapter from {oldAdpterName} to {newAdapterName}");
successful = true;
break;
}
}
}
if (!successful)
{
Console.WriteLine($"Failed to updated network adapter from {oldAdpterName} to {newAdapterName}");
}
}
This successfully updated the correct adapter 'Name' data within Windows Registry and the correct adapter name in the Network and Sharing Centre.
However, I get the failed message internally from the code (no exceptions thrown though (have removed exception handling code for readability)) and doing an ipconfig shows that the adpater name has not been updated.
Environment is Windows10 (needs to also work on Windows7), both 64bit architectures, application built as a 32bit application.
Any ideas what is going on? I am at a total loss at this point.
Thanks in advance.
Just realised that I have all the information to just do a netsh command:
netsh interface set interface name="" newname=""

Error while fetching Hardware Info in Visual Studio 2010

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.

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

Getting CPU ID on virtual machine

I am trying to use this code:
public string GetCPUId()
{
string cpuInfo = String.Empty;
string temp = String.Empty;
ManagementClass mc = new ManagementClass("Win32_Processor");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if (cpuInfo == String.Empty)
{
cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
}
}
return cpuInfo;
}
To get a hw uid on a XP virtual machine (virtualbox), but I am only getting a messagebox that says:
Object reference not set to an instance of an object.
Is it because it's a virtual machine or what?
Yes, it is because you are running a virtual machine. mo.Properties["ProcessorId"] will return null. See the answers here.
I've just found a faster solution here :
http://www.dotnetspark.com/kb/24-get-processor-id-using-c-sharp.aspx
it works faster than yours.and IT WORKS IN MY VIRTUAL WINDOWS(using VMware Workstation 7.0.0 with WINDOWS XP installed virtually) as both codes use the same library yours should work as well! try including dll file in project output it MIGHT Help.
UPDATE (2022): Since the linked page is not working any more I am pasting the code :
public static string GetProcessorID()
{
string sProcessorID = "";
string sQuery = "SELECT ProcessorId FROM Win32_Processor";
ManagementObjectSearcher oManagementObjectSearcher = new ManagementObjectSearcher(sQuery);
ManagementObjectCollection oCollection = oManagementObjectSearcher.Get();
foreach (ManagementObject oManagementObject in oCollection)
{
sProcessorID = (string)oManagementObject["ProcessorId"];
}
return (sProcessorID);
}
That should work just fine on a VM. The CPU ID presented by the virtual CPU may or may not match the physical CPU, though.

Detect Server Display Resolution

On windows server 2008 can I have a web service or something I can query from a C# application as to the display properties (resolution (height & width)). The C# application does not run on the server so I cannot just detect it from the application itself.
Addition to help explain why:
I will have a user named "display" and that will be logged on displaying a website (on the server) and I want to be able to check the display from the desktop application so the user knows what resolution to design a template for. The resolution will change from different displays so it can't be a set value.
I'd recommend just querying the server using WMI. Check the third example here:
http://msdn.microsoft.com/en-us/library/aa394591%28v=vs.85%29.aspx
My Code
This is the code that I used to solve the problem:
System.Management.ConnectionOptions oConnectionOptions = new System.Management.ConnectionOptions();
{
oConnectionOptions.Username = ServerManagement.GetServerUser();
oConnectionOptions.Password = ServerManagement.GetServerPassword();
}
ManagementPath oPath = new ManagementPath("\\\\" + ServerManagement.GetServerAddress() + "\\root\\cimv2");
ManagementScope oScope = new ManagementScope(oPath, oConnectionOptions);
try
{
oScope.Connect();
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DesktopMonitor");
ManagementObjectCollection obj = searcher.Get();
foreach (ManagementObject service in obj)
{
this.DisplayHeight = Convert.ToInt16(service["ScreenHeight"]);
this.DisplayWidth = Convert.ToInt16(service["ScreenWidth"]);
}
}
catch (Exception)
{
MessageBox.Show("Cannot connect to server, please try again later.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}

Categories