I need to check whether the OS needs activation,
my following code displays a multitude of "channels".
static void Main(string[] args)
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher
(
"root\\CIMV2",
"SELECT
Description,
LicenseIsAddon,
LicenseStatus
FROM SoftwareLicensingProduct
WHERE LicenseIsAddon = False"
);
foreach (ManagementObject queryObj in searcher.Get())
{
if (queryObj["Description"].ToString().ToLower().Contains("operating"))
{
foreach (var item in queryObj.Properties)
{
Console.WriteLine(item.Value);
}
}
}
Console.Write("***done***");
Console.ReadLine();
}
How do i know which one to check in order to determine if i need to activate the OS?
Or is my only way to see, if i have any LicenseStatus = 1 in there? Which of course can be wrong if there is one activated and one not activated OS installed.
Thanks
For the time being i filtered the channels a bit more and concluded, that this is good enough:
private void getOSActivation()
{
try
{
ManagementObjectSearcher LicenseSearcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT LicenseStatus,Description FROM SoftwareLicensingProduct");
foreach (ManagementObject LSObj in LicenseSearcher.Get())
{
OStestString = LSObj["Description"].ToString().ToLower();
if (
OStestString.Contains("operating")
&&
// next line is new
(OStestString.Contains("slp") || OStestString.Contains("dm"))
)
{
foreach (var item in LSObj.Properties)
{
OSresults.Add(LSObj["LicenseStatus"].ToString());
}
}
}
}
catch (Exception LSOexception)
{
Console.WriteLine(LSOexception.Message);
}
}
Related
I wrote an application using a webservice and I want to simulate a network failure for test purposes. I know I could turn off the network manually, but it would be awesome if it would be automatically.
I tried the solution from: How to simulate network failure for test purposes (in C#)? from Larsenal but it doesn't recognize the ManagementClass/ObjectCollection/... and I don't know why (i used System.Managment.Man... and it still didn't work. I imported the required references - didn't work. I have no idea what I am doing wrong)
It should work something like this:
[TestMethod]
public void Service_Login_NoInternetConnection()
{
// Some code...
TurnOffNetworkConnection();
// More code...
TurnOnNetworkConnection();
// Blablabla code...
}
You can use WMI for it.
First make sure you add reference : System.Management
Then I get all devices with :
"ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_NetworkAdapterConfiguration");"
Now i need to check if a device got DHCPLeaseObtained.
So I use foreach to check every network device in the searcher :
String Check = Convert.ToString(queryObj["DHCPLeaseObtained"]);
If the device has no DHCPLeaseObtained the string will be emty.
So I check if the string is emty :
if (String.IsNullOrEmpty(Check))
Then you can use ReleaseDHCPLease and RenewDHCPLease in the else.
ManagementBaseObject outParams = queryObj.InvokeMethod("ReleaseDHCPLease", null, null);
or
ManagementBaseObject outParams = queryObj.InvokeMethod("RenewDHCPLease", null, null);
using System.Management;
public void TurnOnNetworkConnection()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_NetworkAdapterConfiguration");
foreach (ManagementObject queryObj in searcher.Get())
{
String Check = Convert.ToString(queryObj["DHCPLeaseObtained"]);
if (String.IsNullOrEmpty(Check))
{
}
else
{
ManagementBaseObject outParams = queryObj.InvokeMethod("RenewDHCPLease", null, null);
}
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
}
public void TurnOffNetworkConnection()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_NetworkAdapterConfiguration");
foreach (ManagementObject queryObj in searcher.Get())
{
String Check = Convert.ToString(queryObj["DHCPLeaseObtained"]);
if (String.IsNullOrEmpty(Check))
{
}
else
{
ManagementBaseObject outParams = queryObj.InvokeMethod("ReleaseDHCPLease", null, null);
}
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
}
i have a windows application which insert client machine's default printer to database on application launch. It works perfectly in my solution. I use the following code to save this.
string GetDefaultPrinter()
{
string defaultprinter = "";
try
{
PrinterSettings settings = new PrinterSettings();
foreach (string printer in PrinterSettings.InstalledPrinters)
{
settings.PrinterName = printer;
if (settings.IsDefaultPrinter)
{
defaultprinter = printer;
string[] array_printer= defaultprinter.Split('\\');
defaultprinter= array_printer[3].ToString();
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", defaultprinter);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection coll = searcher.Get();
foreach (ManagementObject localprinter in coll)
{
foreach (PropertyData property in localprinter.Properties)
{
// Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
//MessageBox.Show(property.Name+"-"+ property.Value);
if (property.Name == "ShareName")
{
defaultprinter = property.Value.ToString().Trim();
}
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("defaltprinter- "+defaultprinter+"-" + ex.Message);
}
return defaultprinter;
}<br>
If I host this application in citrix, then what should I do to perform the same function?
regards,
Sivajith S.
I'm trying to list all the children of a given process (given it's process ID).
After some research I have come to this:
static void Main(string[] args)
{
listChildProcesses(0);
Console.ReadKey();
}
public static void listChildProcesses(int parentProcessId)
{
String myQuery = string.Format("select * from win32_process where ParentProcessId={0}", parentProcessId);
ObjectQuery objQuery = new ObjectQuery(myQuery);
ManagementObjectSearcher objSearcher = new ManagementObjectSearcher(objQuery);
ManagementObjectCollection processList = objSearcher.Get();
foreach (ManagementObject item in processList)
{
try
{
int processId = Convert.ToInt32(item["ProcessId"].ToString());
Console.WriteLine("processId:{0} name:{1} {2}",
item["ProcessId"],
item["Name"],
item["ParentProcessId"]
);
// recursive call
if (processId != parentProcessId)
listChildProcesses(processId);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e);
}
}
}
I was hoping this would allow me to display all processes (since the method starts at PID=0 and then is recursively called on each PID found from there).
But here is the output I get on my Windows 8 (x86):
processId:0 name:System Idle Process 0
processId:4 name:System 0
processId:300 name:smss.exe 4
It stops there. I would expect it to keep going on with each child of System and then each child of those children.
You're not doing what you're thinking...
that way you're just listing children. And you're accessing the idle one by '0'.
Try something like this to get all processes...
ManagementClass mngcls = new ManagementClass("Win32_Process");
foreach (ManagementObject instance in mngcls.GetInstances())
{
Console.Write("ID: " + instance["ProcessId"]);
}
...then what you're doing.
I need to return the DeviceID of the System Reserved partition. I should be able to do this with the Win32_Volume class by first getting the Label property, and if it matches "System Reserved" then get the DeviceID property. The following code crashes with a null reference exception:
static void Main(string[] args)
{
ManagementObjectSearcher ms = new ManagementObjectSearcher("Select * From Win32_Volume");
foreach (ManagementObject mo in ms.Get())
{
if (mo["Label"].ToString() == "System Reserved")
{
Console.WriteLine(mo["DeviceID"].ToString());
}
}
Console.Read();
}
Here it is for anyone that needs to do this:
string sysGuid = "";
try
{
ManagementObjectSearcher ms = new ManagementObjectSearcher("SELECT * FROM Win32_Volume");
foreach (ManagementObject mo in ms.Get())
{
if (mo["Label"].ToString() == "System Reserved")
{
sysGuid = mo["DeviceID"].ToString();
break;
}
}
}
catch (Exception) {}
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;
}