Search For Win32_Directory using the Volume Guid - c#

I am trying to check if a directory exists on a remote computer by using the Volume GUID rather than the Volume Name. Is there any way in WMI to accomplish this? I have a tried a few different approaches but my WQL syntax never seems to be correct, most likely becuase of poor character escaping. Below is one of my attempts at the problem:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ObjectQuery query = new ObjectQuery("Select * From Win32_Directory Where Name=\"" + #"\\\\?\\Volume{10b4259b-f659-11df-b8cc-806e6f6e6963}\\test" + "\"");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection coll = searcher.Get();
foreach (ManagementObject mo in coll)
{
Console.Write("found");
}
Console.Read();
}
}
}
When I execute this code, I receieve an Invalid Query exception. I have tried numerous Powershell attempts at this query and have received the same Invalid Query exception as well. Has anyone attempted this in the past or is it even possible?
Thanks,
Chris

Related

Get all connected device information

I want to get all information of connected devices as the below picture using C# (device name, location, status is required).
https://i.stack.imgur.com/8cFXs.png
Please help me with this issue.
Retrieve using WMI.
You need to install System.Management from nuget.
Computer System Hardware Classes
Here is an example of getting keyboard information.
It is unclear how Location is obtained, but it is probably determined from the DeviceID string.
using System;
using System.Management;
using System.Runtime.Versioning;
internal class Program
{
[SupportedOSPlatform("windows5.0")]
private static void Main()
{
var scope = new ManagementScope("\\\\.\\ROOT\\cimv2");
var query = new ObjectQuery("SELECT * FROM Win32_Keyboard");
using (var sercher = new ManagementObjectSearcher(scope, query))
using (var queryCollection = sercher.Get())
{
foreach (var o in queryCollection)
{
Console.WriteLine(o["Description"].ToString());
Console.WriteLine(o["Status"].ToString());
Console.WriteLine(o["DeviceID"].ToString());
o.Dispose();
}
}
}
}

Lucene.Net Query Error

I've just installed Solr/Lucene on a Windows machine simply to test its capability. I've indexed a couple hundred files and I'm able to successfully query the indexed content through the web interface. Given that the web interface isn't too user friendly I thought I'd try to create a simple application to do a full text search over the indexed content. So far I have:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Lucene.Net;
namespace solrTest
{
class Program
{
static void Main(string[] args)
{
string indexFileLocation = #"C:\solr-5.3.1\server\solr\test\data\index";
Lucene.Net.Store.Directory dir = Lucene.Net.Store.FSDirectory.Open(indexFileLocation);
Lucene.Net.Search.IndexSearcher searcher = new Lucene.Net.Search.IndexSearcher(dir);
Lucene.Net.Index.Term searchTerm = new Lucene.Net.Index.Term("ID", "1");
Lucene.Net.Search.Query query = new Lucene.Net.Search.TermQuery(searchTerm);
Lucene.Net.Search.TopDocs results = searcher.Search(query, null, 10);
foreach(Lucene.Net.Search.ScoreDoc test in results.ScoreDocs)
{
Console.WriteLine(test.ToString());
Console.ReadLine();
}
}
}
}
When running the code I receive an error stating:
An unhandled exception of type 'System.IO.IOException' occurred in Lucene.Net.dll
Additional information: read past EOF
I know I'm missing something obvious. Your help would be greatly appreciated.
Edit: I downloaded Luke.Net and received the same error.

RallyApi.Net Getting Workspaces from a Subscription Version 2.0

Following this link How to obtain a list of workspaces using Rally REST .NET
I tried the example however when I try to query against sub["Workspaces"] I get the error
RuntimeBinderException was unhandled;
The best overloaded method match for 'Rally.RestApi.RallyRestApi.Query(Rally.RestApi.Request)' has some invalid arguments
I cannot find any other ways to gather a list of workspaces from the subscription using the RallyApi dll for .Net which I obtained from the link provided.
Any help will be much appreciated.
Try to modify that code as follows:
Request wRequest = new Request(sub["Workspaces"]);
QueryResult queryResult = restApi.Query(wRequest);
Here is an entire app:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using Rally.RestApi;
using Rally.RestApi.Response;
namespace Rest_v2._0_test
{
class Program
{
static void Main(string[] args)
{
//Initialize the REST API
RallyRestApi restApi;
restApi = new RallyRestApi("user#co.com", "secret", "https://rally1.rallydev.com", "v2.0");
//get the current subscription
DynamicJsonObject sub = restApi.GetSubscription("Workspaces");
Request wRequest = new Request(sub["Workspaces"]);
//query the Workspaces collection
QueryResult queryResult = restApi.Query(wRequest);
foreach (var result in queryResult.Results)
{
var workspaceReference = result["_ref"];
var workspaceName = result["Name"];
Console.WriteLine( workspaceName + " " + workspaceReference);
}
}
}
}

How can I determine the SATA channel for a given disk?

Using DISKPART command line utility, I can get something called a "Location path" which appears to give me what I need, you can view this by using the command detail disk after selecting one of your disks in diskpart.
It appears I can get this information programatically via this class: MSFT_Disk
I am unsure about how to get an instance of this class. I have a few examples of using a ManagementObjectSearcher for WMI classes but that method is not working for me, I am also unsure of MSFT_Disk's availability in Windows 7 as the page mentions that this is for Windows 8.
Does anyone know of a good way to get SATA channel information or the "location path" of a disk?
If you want to not require Windows 8, I believe WMI is the way to go:
using System;
using System.Linq;
using System.Management;
namespace DiskScanPOC
{
class Program
{
static void Main()
{
var managementScope = new ManagementScope();
//get disk drives
var query = new ObjectQuery("select * from Win32_DiskDrive");
var searcher = new ManagementObjectSearcher(managementScope, query);
var oReturnCollection = searcher.Get();
//List all properties available, in case the below isn't what you want.
var colList = oReturnCollection.Cast<ManagementObject>().First();
foreach (var property in colList.Properties)
{
Console.WriteLine("Property: {0} = {1}", property.Name, property.Value);
}
//loop through found drives and write out info
foreach (ManagementObject oReturn in oReturnCollection)
{
Console.WriteLine("Name : " + oReturn["Name"]);
Console.WriteLine("Target Id: " + oReturn["SCSITargetId"]);
Console.WriteLine("Port: " + oReturn["SCSIPort"]);
}
Console.Read();
}
}
}
I didn't crack open my case to verify the SATA port numbers, but the above app looks like it gives reasonable results on my machine with 3 SATA hard drives.
If you want to get the location path, SetupDiGetDeviceRegistryProperty is the function you're looking for. Set the property value to SPDRP_LOCATION_INFORMATION.
I'm assuming you already know how to enumerate devices to get the DeviceInfoSet and DeviceInfoData.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management;
namespace Hard_Disk_Interface
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCheck_Click(object sender, EventArgs e)
{
WqlObjectQuery q = new WqlObjectQuery("SELECT * FROM Win32_IDEController");
ManagementObjectSearcher res = new ManagementObjectSearcher(q);
lblHDDChanels.Text = string.Empty;
foreach (ManagementObject o in res.Get())
{
string Caption = o["Caption"].ToString();
lblHDDChanels.Text += Caption + "\n\n";
if (Caption.Contains("Serial"))
{
lblInterface.Text = "S-ATA";
}
}
}
}
}
Note: First Add the reference of System.Management.dll of .net freamwork 4.0

Find out battery charge capacity in percentage using C# or .NET

I have an application that gets detailed system information, and I have been able to get the percent of charge remaining but not the percent of the battery itself.
Explanation: As time goes on, the battery slowly gets worse and worse, and some applications, like Dell Support Center on Laptops, display the status of the battery, not the status of the charge, which used to be 100% but now is 90%.
How can I get this value in C# or .NET?
Don't have a laptop to test with, but I'm guessing you could use the WMI class Win32_Battery.
It has two fields that look interesting - DesignCapacity, which tells you
Design capacity of the battery in milliwatt-hours.
and FullChargeCapacity, which has the fascinating note that
Full charge capacity of the battery in milliwatt-hours. Comparison of the value to the DesignCapacity property determines when the battery requires replacement.
So my guess is that you can use WMI to read these two values, and then calculate FullChargeCapacity/DesignCapacity to find the battery health percentage number.
EDIT
Here's a brief example of accessing WMI information using C#. I first added a reference to the System.Management assembly. Then:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
System.Management.ObjectQuery query = new ObjectQuery("Select * FROM Win32_Battery");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection collection = searcher.Get();
foreach (ManagementObject mo in collection)
{
foreach (PropertyData property in mo.Properties)
{
Console.WriteLine("Property {0}: Value is {1}", property.Name, property.Value);
}
}
}
}
}
Also, note that you are basically running a SQL-like query against WMI, so you can vary that if you want. Windows Management Instrumentation Query Language, or WQL, is what you want to search for to learn more about it.
Also take a look at ahawker's answer, it may end up being more helpful if WMI isn't properly capturing the battery data, as he notes.
It seems that you are looking for the values of FullChargeCapacity, DesignCapacity and CurrentCapacity. As someone who has solved this problem before, let me make a few comments.
The first route normally taken would be through a WMI query (Win32_Battery). However, on the test laptops I ran the WMI query (Win32_Battery) against, which included multiple manufacturers, I consistently ran into the problem of FullChargeCapacity always returning zero. Since that didn't work, I re-wrote my solution using Win32 API and was successfully able to get accurate values that way.
Hopefully, WMI will work for you. However, if you experience the same issues I did, here is a summary of the steps required for Win32API.
Use SetupDiGetClassDevs to get a device handle to the battery (GUID_DEVCLASS_BATTERY).
Use SetupDiEnumDeviceInterfaces to get the device data (SP_DEVICE_INTERFACE_DATA).
Use SetupDiGetDeviceInterfaceDetail to get the device path (SP_DEVICE_INTERFACE_DETAIL_DATA).
Use CreateFile with the device path to get handle to battery.
Use DeviceIoControl with battery handle, IOCTL_BATTERY_QUERY_TAG to retrieve battery query info (BATTERY_QUERY_INFORMATION).
Use DeviceIoControl with battery handle, IOCTL_BATTERY_QUERY_INFORMATION and marshalled structs to to retrieve battery info (BATTERY_INFORMATION).
Also see the Enumerating Battery Devices post on MSDN as I found that quite helpful.
I can post my solution if necessary but with all the native struct definitions, it ends up around 500 lines of code.
Example source code: https://gist.github.com/ahawker/9715872
No need to unnecessary complicate things. Try something like:
using System.Management;
PowerStatus pwr = SystemInformation.PowerStatus;
String strBatteryChargingStatus;
strBatteryChargingStatus = pwr.BatteryChargeStatus.ToString();
MessageBox.Show("battery charge status : " + batterystatus);
String strBatterylife;
strBatterylife = pwr.BatteryLifePercent.ToString();
MessageBox.Show("Battery life: "+batterylife);
In this way you can get all of the battery information.
You can use the System.Windows.Forms.PowerStatus class - http://msdn.microsoft.com/en-us/library/system.windows.forms.powerstatus.aspx
PowerStatus p = SystemInformation.PowerStatus;
int a = (int)(p.BatteryLifePercent * 100);
MessageBox.Show(""+a);
WMI worked for me (tested on 3 notebooks of different brands), but I had to use something like this:
new ManagementObjectSearcher(#"\\localhost\root\wmi",
"Select FullChargedCapacity From BatteryFullChargedCapacity");
// use value of resultingInstance.Properties["FullChargedCapacity"]
new ManagementObjectSearcher(#"\\localhost\root\wmi",
"Select DesignedCapacity From BatteryStaticData");
//use value of resultingInstance2.Properties["DesignedCapacity"]
BatteryChargeStatus.Text = SystemInformation.PowerStatus.BatteryChargeStatus.ToString();
BatteryFullLifetime.Text = SystemInformation.PowerStatus.BatteryFullLifetime.ToString();
BatteryLifePercent.Text = SystemInformation.PowerStatus.BatteryLifePercent.ToString();
BatteryLifeRemaining.Text = SystemInformation.PowerStatus.BatteryLifeRemaining.ToString();
PowerLineStatus.Text = SystemInformation.PowerStatus.PowerLineStatus.ToString();
If you want to perform some operation just convert these string values into the integer.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace batterie
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
showbattrie();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void showbattrie()
{
PowerStatus status = SystemInformation.PowerStatus;
textBox1.Text = status.BatteryLifePercent.ToString("P0");
}
}
}
Simple code to get Battery Level in C#
protected void batteryLevel ()
{
var filter = new IntentFilter(Intent.ActionBatteryChanged);
var battery = RegisterReceiver(null, filter);
int level = battery.GetIntExtra(BatteryManager.ExtraLevel, -1);
int scale = battery.GetIntExtra(BatteryManager.ExtraScale, -1);
double level_0_to_100 = Math.Floor (level * 100D / scale);
}

Categories

Resources