Hey i have some code to generate Hardware Id for identification and it have worked fine for several month but now without any changes it stopped working it stops at all of these
ManagementObjectCollection cpu_Collection = cpu.Get();
ManagementObjectCollection hdd_Collection = hdd.Get();
ManagementObjectCollection bios_Collection = bios.Get();
Can anyone help me fix it this is all of my code to get the hardware id
//public static string test = ReturnHardwareID().ToString();
private static async Task<string> ReturnHardwareID()
{
byte[] bytes;
byte[] hashedBytes;
StringBuilder sb = new StringBuilder();
Task task = Task.Run(() =>
{
ManagementObjectSearcher cpu = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
ManagementObjectCollection cpu_Collection = cpu.Get();
foreach (ManagementObject obj in cpu_Collection)
{
sb.Append(obj["ProcessorId"].ToString().Substring(0, 4));
break;
}
ManagementObjectSearcher hdd = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
ManagementObjectCollection hdd_Collection = hdd.Get();
foreach (ManagementObject obj in hdd_Collection)
{
sb.Append(obj["Model"].ToString().Substring(0, 4));
break;
}
ManagementObjectSearcher bios = new ManagementObjectSearcher("SELECT * FROM Win32_BIOS");
ManagementObjectCollection bios_Collection = bios.Get();
foreach (ManagementObject obj in bios_Collection)
{
sb.Append(obj["Version"].ToString().Substring(0, 4));
break;
}
});
Task.WaitAll(task);
bytes = Encoding.UTF8.GetBytes(sb.ToString());
hashedBytes = SHA256.Create().ComputeHash(bytes);
return await Task.FromResult(Convert.ToBase64String(hashedBytes).Substring(25));
}
Related
I am trying to get the CPU serial number but I cannot do it. I can get board and harddisk but not cpu.
here is my code below. what am I doing wrong?
public static void GetClientComputerInfo()
{
HDDSerial = "0";
BoardSerial = "0";
CPUSerial = "0";
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_DiskDrive");
foreach (ManagementObject share in searcher.Get())
{
foreach (PropertyData PC in share.Properties)
{
if (PC.Name == "SerialNumber")
{
HDDSerial = PC.Value.ToString();
}
if (PC.Name == "SerialNumber")
{
BoardSerial = PC.Value.ToString();
}
if (PC.Name == "ProcessorID")
{
CPUSerial = PC.Value.ToString();
}
}
}
}
catch
{
}
}
Try this one
string cpuInfo = string.Empty;
ManagementClass mc = new ManagementClass("win32_processor");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
cpuInfo = mo.Properties["processorID"].Value.ToString();
break;
}
Code Extracted from here
I've created this VBScript WMI script:
On Error Resume Next
Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20
Set objWMIService = GetObject("winmgmts:\\localhost\root\MicrosoftIISv2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM IIsWebVirtualDirSetting", _
"WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)
For Each objItem In colItems
WScript.Echo "Path: " & objItem.Path
WScript.Echo
Next
Which returns the physical path (C:\inetpub\wwwroot\webapplication1) to all the applications in IIS.
Now I'm trying to use C# to populate a combobox with those values:
public static ArrayList Test2()
{
ArrayList WebSiteListArray = new ArrayList();
ConnectionOptions connection = new ConnectionOptions();
ManagementScope scope =
new ManagementScope(#"\\" + "localhost" + #"\root\MicrosoftIISV2",
connection);
scope.Connect();
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(scope,
new ObjectQuery("SELECT * FROM IIsWebVirtualDirSetting"), null);
ManagementObjectCollection webSites = searcher.Get();
foreach (ManagementObject webSite in webSites)
{
WebSiteListArray.Add(webSite.Path);
}
return WebSiteListArray;
}
But the output is the virtual path:
(`IIsWebVirtualDirSetting.Name="W3SVC/1/ROOT/webapplication1"`)
What needs to be changed in my query?
Note: I need to support IIS6 and .NET 4.0
Finally got it...
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\MicrosoftIISv2",
"SELECT * FROM IIsWebVirtualDirSetting");
foreach (ManagementObject queryObj in searcher.Get())
{
result.Add(queryObj["Path"]);
}
I prefer like this:
Connect at my local network server SOMEREMOTESERVER:
ConnectionOptions connection = new ConnectionOptions();
connection.Authentication = System.Management.AuthenticationLevel.PacketPrivacy;
ManagementScope scope =
new ManagementScope(#"\\SOMEREMOTESERVER\root\MicrosoftIISV2",
connection);
scope.Connect();
ObjectQuery query = new ObjectQuery("SELECT * FROM IISWebServerSetting");
var collection = new ManagementObjectSearcher(scope, query).Get();
foreach (ManagementObject item in collection)
{
var value = item.Properties["ServerBindings"].Value;
if (value is Array)
{
foreach (ManagementBaseObject a in value as Array)
{
Console.WriteLine(a["Hostname"]);
}
}
ManagementObject maObjPath = new ManagementObject(item.Scope,
new ManagementPath(
string.Format("IISWebVirtualDirSetting='{0}/root'", item["Name"])),
null);
PropertyDataCollection properties = maObjPath.Properties;
Console.WriteLine(properties["path"].Value);
Console.WriteLine(item["ServerComment"]);
Console.WriteLine(item["Name"]);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
}
I wanted to write a code in C# to list all the users/groups having access (Read/Write/Full) to a shared folder on a server.
For Example: I have a shared folder \servername\MyData. Now I wanted to list the users/groups who have access to this folder.
This should get you pointed in the right direction, I can't test it atm but should be something similar.
private bool CheckAccess(DirectoryInfo directory)
{
// Get the collection of authorization rules that apply to the current directory
AuthorizationRuleCollection acl = directory.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
foreach (var rule in acl)
{
// do something here
}
}
private DataTable GetSharedFolderAccessRule()
{
DataTable DT = new DataTable();
try
{
DT.Columns.Add("ShareName");
DT.Columns.Add("Caption");
DT.Columns.Add("Path");
DT.Columns.Add("Domain");
DT.Columns.Add("User");
DT.Columns.Add("AccessMask");
DT.Columns.Add("AceType");
ManagementScope Scope = new ManagementScope(#"\\.\root\cimv2");
Scope.Connect();
ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_LogicalShareSecuritySetting");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
ManagementObjectCollection QueryCollection = Searcher.Get();
foreach (ManagementObject SharedFolder in QueryCollection)
{
{
String ShareName = (String) SharedFolder["Name"];
String Caption = (String)SharedFolder["Caption"];
String LocalPath = String.Empty;
ManagementObjectSearcher Win32Share = new ManagementObjectSearcher("SELECT Path FROM Win32_share WHERE Name = '" + ShareName + "'");
foreach (ManagementObject ShareData in Win32Share.Get())
{
LocalPath = (String) ShareData["Path"];
}
ManagementBaseObject Method = SharedFolder.InvokeMethod("GetSecurityDescriptor", null, new InvokeMethodOptions());
ManagementBaseObject Descriptor = (ManagementBaseObject)Method["Descriptor"];
ManagementBaseObject[] DACL = (ManagementBaseObject[])Descriptor["DACL"];
foreach (ManagementBaseObject ACE in DACL)
{
ManagementBaseObject Trustee = (ManagementBaseObject)ACE["Trustee"];
DataRow Row = DT.NewRow();
Row["ShareName"] = ShareName;
Row["Caption"] = Caption;
Row["Path"] = LocalPath;
Row["Domain"] = (String) Trustee["Domain"];
Row["User"] = (String) Trustee["Name"];
Row["AccessMask"] = (UInt32) ACE["AccessMask"];
Row["AceType"] = (UInt32)ACE["AceType"];
DT.Rows.Add(Row);
DT.AcceptChanges();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, ex.Message);
}
return DT;
}
I'm using this little code snippet to catch Java processes with certain parameters:
string query = "Select * From Win32_Process Where Name = 'javaw.exe'";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();
foreach (ManagementObject obj in processList)
{
string cmdLine = obj.GetPropertyValue("CommandLine").ToString();
if (cmdLine.IndexOf("someapplication") != -1)
{
// ...
}
}
This code worked like a charm just a couple of days ago when I didn't have SP1 for VS2010. Now it throws a null pointer exception on line 7. I'm trying to compile for .NET Framework 2.0.
Help!? :/
if (cmdLine != null && cmdLine.IndexOf("someapplication") != -1)
It probably has less to do with SP1 and more to do with a Java update. Just check for null:
string query = "Select * From Win32_Process Where Name = 'javaw.exe'";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();
foreach (ManagementObject obj in processList)
{
object cmdLineValue = obj.GetPropertyValue("CommandLine");
if(cmdLineValue != null) {
string cmdLine = cmdLineValue.ToString();
if (cmdLine.IndexOf("someapplication") != -1)
{
// ...
}
}
}
i had written a code to display the description(Name) of connected USB devices.once i removed a device,then i need to refresh the ManagementObject and have to display the connected device description.
Here is my Code,
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("SELECT * FROM Win32_USBControllerDevice");
foreach (ManagementObject mo in searcher.Get())
{
string str1 = mo["CurrentRefreshRate"].ToString();
Console.WriteLine(str1);
string dependent = mo["Dependent"].ToString();
string deviceId = dependent.Split('=')[1];
deviceId = deviceId.Replace('\"', '\'');
ManagementObjectSearcher searcher2 =
new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity Where DeviceID = " + deviceId);
foreach (ManagementObject mo2 in searcher2.Get())
{
HardwareDetails Detail = new HardwareDetails();
Detail.Description = mo2["Description"].ToString();
Detail.DeviceId = mo2["DeviceId"].ToString();
string[] str = Detail.DeviceId.Split('\\');
string Id = str[1];
if (Id.Contains('&'))
{
string[] separate = Id.Split('&');
Detail.Vid = separate[0].Contains('_') ? separate[0].Split('_')[1] : separate[0].Split('D')[1];
Detail.Pid = separate[1].Contains('_') ? separate[1].Split('_')[1] : separate[1].Split('D')[1];
//Detail.Pid = pid1[1];
}
else
{
Detail.Vid = "";
Detail.Pid = "";
}
if (list.Count > 0)
{
foreach (HardwareDetails h in list)
{
if (!(h.Description == Detail.Description))
{
list.Add(Detail);
break;
}
}
}
else
list.Add(Detail);
}
}
// remove duplicates, sort alphabetically and convert to array
HardwareDetails[] usbDevices = list.ToArray();
return usbDevices;
Did you try this?
WqlEventQuery query = new WqlEventQuery(
"SELECT * FROM Win32_DeviceChangeEvent");
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
watcher.EventArrived +=
new EventArrivedEventHandler(HandleEvent);
// Start listening for events
watcher.Start();
.........
// Stop listening for events
watcher.Stop();
And in the HandleEvent add or remove device from the list
Hope this helps!