How to get Availability from Win32_PnPEntity - c#

I am trying to get the availability status from a PnP device
I have read through this article: Win32_PnPEntity , and it seems like I should be able to get the value; however it always comes up null and I can't figure out why. Other properties like "Name", "Caption", "ClassGUID", etc are returning good values.
Here is some code showing what I'm trying to do...
ManagementObjectCollection collection;
using (var searcher = new ManagementObjectSearcher(#"SELECT * FROM Win32_PnPEntity WHERE Description LIKE '%USB%'"))
collection = searcher.Get();
Console.WriteLine("Waiting for CmdPort to be available...");
foreach(device in collection)
{
var availableTimeout = 50;
while (availableTimeout > 0)
{
var availability = device["Availability"] ?? -1;
if((int)availability == 3)
break;
Console.WriteLine($"Availability = {availability.ToString()} (timeout = {availableTimeout})")
availableTimeout--;
Thread.Sleep(100);
}
}
I'm expecting availability to come back with a uint16 between 1 and 21

Related

Retrieve LoggedOnUsers on Remote Machine

I'm building a C# application to monitor server and workstation workloads with WMI and WQL queries. I'm using WMI because it seems to be faster in comparison to powershell queries. My hardship starts when I try to retrieve logged on users on a remote machine. I figured I need to use the Win32_LoggedOnUser class. I have tried the following queries:
#"SELECT * FROM Win32_LoggedOnUser"
#"SELECT Antecedent FROM Win32_LoggedOnUser"
What I'm used to is to retrieve the desired value like this:
var cims = connection.getCimInstances(this, queryUser);
if (cims != null)
{
foreach (CimInstance cim in cims)
{
Komponenten.User user = new Komponenten.User();
user.Name = Convert.ToString(cim.CimInstanceProperties["Name"].Value);
users.Add(user);
}
}
where queryUser is one of the strings from above.
In both cases, I get a Win32_Account object in return, which seems to suggest - and the debugger seems to confirm - that I should use CimInstanceProperties["Name"].Value on the returned Win32_Account class again. But that's not working at all. Any ideas on how to get access to the CimInstanceProperties of a Win32_Account stored in a CimInstanceProperity ? I can't find anything on the respective Windows reference page (https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-loggedonuser) nor during my extensive google-search.
Thanks!
I ended up using the ManagementObject-Class and Regex to find the usernames after converting the Antecedent - Object to a string:
var users = new List<Komponenten.User>();
var searcher = this.connection.makeQuery(this, "SELECT * FROM Win32_LoggedOnUser");
if (searcher != null)
{
foreach (ManagementObject queryObj in searcher.Get())
{
Komponenten.User user = new Komponenten.User();
var win32_account = queryObj["Antecedent"].ToString();
string stripped = Regex.Replace(win32_account, "[^a-zA-Z=]+", "", RegexOptions.Compiled);
int end = stripped.LastIndexOf("=");
user.Name = stripped.Substring(end+1);
users.Add(user);
}
this.users = users;
An alternative which takes the LogonSession into account is:
var users = new List<Komponenten.User>();
var searcher = this.connection.makeQuery(this, "SELECT LogonId FROM Win32_LogonSession Where LogonType=2");
var Scope = this.connection.getScope(this, this.connection.getConnection());
if (searcher != null)
{
foreach (ManagementObject queryObj in searcher.Get())
{
ObjectQuery LQuery = new ObjectQuery("Associators of {Win32_LogonSession.LogonId=" + queryObj["LogonId"] + "} Where AssocClass=Win32_LoggedOnUser Role=Dependent");
ManagementObjectSearcher LSearcher = new ManagementObjectSearcher(Scope, LQuery);
foreach (ManagementObject LWmiObject in LSearcher.Get())
{
Komponenten.User user = new Komponenten.User();
user.Name = Convert.ToString(LWmiObject["Name"]);
users.Add(user);
}
}
this.users = users;
}
where this.connection.getConnection is a ConnectionsOption object depending on your respective domain and account data

How to get hard drive unique serial number in C#

I develop an activation for a system. to generate request code, I used HDD ID, Bios ID and Processor ID. I used following code to get hard disk ID.
private string getHardDiskID()
{
string hddID = null;
ManagementClass mc = new ManagementClass("Win32_LogicalDisk");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject strt in moc)
{
hddID += Convert.ToString(strt["VolumeSerialNumber"]);
}
return hddID.Trim().ToString();
}
But if I plug a removable disk, That ID value is changed. How to get the UNIQUE Serial Number of the hard drive...?
Thanks in advance..
You can try from this source:
As said in the source, a better solution is to get the Hard Drive Serial Number given by the Manufacturer. This value won't change even if you format your Hard Drive.
searcher = new
ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
int i = 0;
foreach(ManagementObject wmi_HD in searcher.Get())
{
// get the hard drive from collection
// using index
HardDrive hd = (HardDrive)hdCollection[i];
// get the hardware serial no.
if (wmi_HD["SerialNumber"] == null)
hd.SerialNo = "None";
else
hd.SerialNo = wmi_HD["SerialNumber"].ToString();
++i;
}
ManagementObjectSearcher searcher;
searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
string serial_number="";
foreach (ManagementObject wmi_HD in searcher.Get())
{
serial_number = wmi_HD["SerialNumber"].ToString();
}
MessageBox.Show(serial_number);
Check below code to get HDD Serial
ManagementObjectSearcher objSearcher = new
ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
objSearcher = new
ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
int i = 0;
foreach(ManagementObject wmi_HD in objSearcher.Get())
{
// get the hard drive from collection
// using index
HardDrive hd = (HardDrive)hdCollection[i];
// get the hardware serial no.
if (wmi_HD["SerialNumber"] == null)
hd.SerialNo = "None";
else
hd.SerialNo = wmi_HD["SerialNumber"].ToString();
++i;
}
Also You can type "wbemtest" in windows run. WBEMTEST is tool which
helps in running WQL queries.

Listing USB Devices with C# and WMI

I'm trying to implement a function in my application that lists all the plugged in USB Mass Storage Devices in a computer.
My code works well when launching the application but my problem is that I want the box in my form to refresh automatically when a USB device is removed or attached.
Implementing DBT_DEVICEARRIVAL and DBT_DEVICEREMOVECOMPLETE conditions should work but I get back a "DisconnectedContext was detected" exception.
I learned that I need to use a delegate and set an asyncronous call for this to work correctly.
Here's my code:
public void listUSB()
{
ManagementScope sc = new ManagementScope(wmiUsbList);
ObjectQuery query = new ObjectQuery("select * from Win32_DiskDrive " + "where InterfaceType='USB'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(sc, query);
ManagementObjectCollection result = searcher.Get();
foreach (ManagementObject obj in result)
{
if (obj["DeviceID"] != null)
{
usbListTextBox.AppendText(obj["Model"].ToString());
}
}
}
I'd really like to know how to apply a delegate to my method.
I also looked at this thread on MSDN which provides an excellent example, but as of that example I am not able to understand how to put the deviceList in a textbox.
I'm still Learning so if someone could be so kind to point me to the right direction on one or both of my questions, that would be greatly appreciated.
Thanks!
Try to use ManagementEventWatcher and assign an event handler to the EventArrived.
I don't know how to accomplish exactly this, but here is a watcher that listens to the print events:
string printQuery = "Select * From __InstanceCreationEvent Within 1 Where TargetInstance ISA 'Win32_PrintJob'";
string nspace = #"\\.\root\CIMV2";
var watcher = new ManagementEventWatcher(nspace, printQuery);
Hope it helps.
private usbListArrayDelegate mDeleg;
protected override void WndProc(ref Message m)
{
int devType;
base.WndProc(ref m);
switch (m.WParam.ToInt32())
{
case DBT_DEVICEARRIVAL:
devType = Marshal.ReadInt32(m.LParam, 4);
if (devType == DBT_DEVTYP_VOLUME)
{
// usb device inserted, call the query
mDeleg = new usbListArrayDelegate(usbListArray);
AsyncCallback callback = new AsyncCallback(usbListArrayCallback);
// invoke the thread that will handle getting the friendly names
mDeleg.BeginInvoke(callback, new object());
}
break;
case DBT_DEVICEREMOVECOMPLETE:
devType = Marshal.ReadInt32(m.LParam, 4);
if (devType == DBT_DEVTYP_VOLUME)
{
mDeleg = new usbListArrayDelegate(usbListArray);
AsyncCallback callback = new AsyncCallback(usbListArrayCallback);
// invoke the thread that will handle getting the friendly names
mDeleg.BeginInvoke(callback, new object());
}
break;
}
}
public ArrayList usbListArray()
{
ArrayList deviceList = new ArrayList();
manager = new UsbManager(); ==> about how to implement this please see http://www.codeproject.com/Articles/63878/Enumerate-and-Auto-Detect-USB-Drives
UsbDiskCollection disks = manager.GetAvailableDisks();
foreach (UsbDisk disk in disks)
{
deviceList.Add(disk);
}
return deviceList;
}
// delegate wrapper function for the getFriendlyNameList function
private delegate ArrayList usbListArrayDelegate();
// callback method when the thread returns
private void usbListArrayCallback(IAsyncResult ar)
{
string ArrayData = string.Empty;
// got the returned arrayList, now we can do whatever with it
ArrayList result = mDeleg.EndInvoke(ar);
int count = 0;
foreach (UsbDisk disk in result)
{
++count;
ArrayData += count + ") " + disk.ToString().
}

Getting Hard Disk Speed using C#

It is possible to get Hard Disk Information using C#?
Like spin rate in RPM
Model Number
Company Name
Data Transfer Rate
Seek Time
most importantly spin rate.
I have tried with
ManagementClass driveClass = new ManagementClass("Win32_DiskDrive");
properties but it's not giving spin rate.
Please help me?
Dattatrya Moin
Check this : Reading ATAPI SMART Data from Drives using .NET; Temperature Anyone?
using System.Management;
public string GetHDDSerial()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
foreach (ManagementObject wmi_HD in searcher.Get())
{
// get the hardware serial no.
if (wmi_HD["SerialNumber"] != null)
return wmi_HD["SerialNumber"].ToString();
}
return string.Empty;
}
Read this Win32_DiskDrive and try this:
ArrayList hddCollection = new ArrayList();
try
{
var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
foreach (ManagementObject wmiObj in searcher.Get)
{
HardDrive hdd = new HardDrive();
hdd.model = wmiObj("Model").ToString;
hdd.type = wmiObj("InterfaceType").ToString;
hddCollection.Add(hdd);
break; // TODO: might not be correct. Was : Exit For
}
}
catch (Exception ex)
{
throw ex;
}

How to determine if drive is external drive

How can I determine if a drive is a external drive plugged in through usb ? I checked the DriveInfo.DriveType but with my 1TB external drive plugged in through usb it shows up as a fixed drive.
Thoughts ?
Based on a comment from Floyd Pink I used this link. This allows me to determine whether a device is external or not.
public bool IsProjectOnExternalDisk(string driveLetter)
{
bool retVal = false;
driveLetter = driveLetter.TrimEnd('\\');
// browse all USB WMI physical disks
foreach (ManagementObject drive in new ManagementObjectSearcher("select DeviceID, MediaType,InterfaceType from Win32_DiskDrive").Get())
{
// associate physical disks with partitions
ManagementObjectCollection partitionCollection = new ManagementObjectSearcher(String.Format("associators of {{Win32_DiskDrive.DeviceID='{0}'}} " + "where AssocClass = Win32_DiskDriveToDiskPartition", drive["DeviceID"])).Get();
foreach (ManagementObject partition in partitionCollection)
{
if (partition != null)
{
// associate partitions with logical disks (drive letter volumes)
ManagementObjectCollection logicalCollection = new ManagementObjectSearcher(String.Format("associators of {{Win32_DiskPartition.DeviceID='{0}'}} " + "where AssocClass= Win32_LogicalDiskToPartition", partition["DeviceID"])).Get();
foreach (ManagementObject logical in logicalCollection)
{
if (logical != null)
{
// finally find the logical disk entry
ManagementObjectCollection.ManagementObjectEnumerator volumeEnumerator = new ManagementObjectSearcher(String.Format("select DeviceID from Win32_LogicalDisk " + "where Name='{0}'", logical["Name"])).Get().GetEnumerator();
volumeEnumerator.MoveNext();
ManagementObject volume = (ManagementObject)volumeEnumerator.Current;
if (driveLetter.ToLowerInvariant().Equals(volume["DeviceID"].ToString().ToLowerInvariant()) &&
(drive["MediaType"].ToString().ToLowerInvariant().Contains("external") || drive["InterfaceType"].ToString().ToLowerInvariant().Contains("usb")))
{
retVal = true;
break;
}
}
}
}
}
}
return retVal;
}
Using WMI Select * from Win32_LogicalDisk as in Royi Namir's answer and DriveInfo.DriveType show my external type as 'Local Disk' which I can't use to determine whether the drive is external.
you can use WMI
with
Select * from Win32_LogicalDisk
http://www.jpsoftwaretech.com/vba/using-wmi-services-in-vba/drive-information-local-network-mapped-drives/
there you have
Select Case .DriveType
Case 0
strDriveType = "Unknown"
Case 1
strDriveType = "No Root Directory"
Case 2
strDriveType = "Removable Disk"
Case 3
strDriveType = "Local Disk"
Case 4
strDriveType = "Network Drive"
Case 5
strDriveType = "Compact Disc"
Case 6
strDriveType = "RAM Disk"
End Select
I came across this question looking for a way to get a list of external drives, and I found that I could simplify a lot by updating the syntax. Also, some USB drives are UAS or USB attached SCSI, and the interface for those types of drives will actually show up as SCSI and not USB. From my tests, I've found that just checking for the terms "external" and "removable" in the physical disk's media type is sufficient.
public List<DriveInfo> getExternalDrives()
{
var drives = DriveInfo.GetDrives();
var externalDrives = new List<DriveInfo>();
var allPhysicalDisks = new ManagementObjectSearcher("select MediaType, DeviceID from Win32_DiskDrive").Get();
foreach (var physicalDisk in allPhysicalDisks)
{
var allPartitionsOnPhysicalDisk = new ManagementObjectSearcher($"associators of {{Win32_DiskDrive.DeviceID='{physicalDisk["DeviceID"]}'}} where AssocClass = Win32_DiskDriveToDiskPartition").Get();
foreach(var partition in allPartitionsOnPhysicalDisk)
{
if (partition == null)
continue;
var allLogicalDisksOnPartition = new ManagementObjectSearcher($"associators of {{Win32_DiskPartition.DeviceID='{partition["DeviceID"]}'}} where AssocClass = Win32_LogicalDiskToPartition").Get();
foreach(var logicalDisk in allLogicalDisksOnPartition)
{
if (logicalDisk == null)
continue;
var drive = drives.Where(x => x.Name.StartsWith(logicalDisk["Name"] as string, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
var mediaType = (physicalDisk["MediaType"] as string).ToLowerInvariant();
if (mediaType.Contains("external") || mediaType.Contains("removable"))
externalDrives.Add(drive);
}
}
}
return externalDrives;
}

Categories

Resources