Get WMI properties - c#

I am quite novice in c# but unfortunately have to discover usb ports VIDs and PIDs.
ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0");
ManagementObjectSearcher comPortSearcher = new ManagementObjectSearcher(connectionScope, objectQuery);
using (comPortSearcher)
{
string caption = null;
foreach (ManagementObject obj in comPortSearcher.Get())
{
if (obj != null)
{
object captionObj = obj["Caption"];
// Rest of code
}
}
}
I actually can't understand whre this key "Caption" comes from. How can I know what else keys are hidden in this object? It is very unclear for me.
How can I get the list of other of such a "Keys"

This code accesses by WMI different properties. Specifically Win32_PnPEntity class represents the properties of a Plug and Play device.
See more on MSDN about Win32_PnPEntity class and it's properties:
[Dynamic, Provider("CIMWin32"), UUID("{FE28FD98-C875-11d2-B352-00104BC97924}"), AMENDMENT]
class Win32_PnPEntity : CIM_LogicalDevice
{
uint16 Availability;
string Caption;
string ClassGuid;
string CompatibleID[];
uint32 ConfigManagerErrorCode;
/* Rest of properties... */
};
The ManagementObjectSearcher is one way to retrieve information of a WMI Class

Related

WMI PrinterStatus always 0

I want to check if the printer has a paper or not, for this I use WMI to pick up the printer and use PrinterStatus, the problem is that it always returns 0 ("Unknow"), and I don't understand the reason, my code is as follows:
public int ImpresoraStatus()
{
var printerQuery = new ManagementObjectSearcher("SELECT * from Win32_Printer WHERE Name = \"KPOS_80 Printer\"");
foreach (var printer in printerQuery.Get())
{
int status = (int)printer["PrinterStatus"];
return status;
}
return 404;
}
Any improvements or something I'm missing?
It is a known issue AFAIK. You probably need to try printing something first and then check the status.
See: Not Able to Monitor Printers' States and Statuses

LibVLCSharp how to get list of webcams

VLC GUI shows the list of available webcams, like v4l2:///dev/video0 and v4l2:///dev/video1, I am wondering is there a way to get a list of available webcams? what about their default resolution?
I tried this but md.MediaList is empty.
var mds = libVlc.MediaDiscoverers(MediaDiscovererCategory.Devices);
if (mds.Any(x => x.LongName == "Video capture"))
{
var devices = mds.First(x => x.LongName == "Video capture");
var md = new MediaDiscoverer(libVlc, devices.Name);
foreach (var media1 in md.MediaList)
{
// Nothing ...
}
}
Your MediaDiscoverer is empty because you never call md.Start().
For more info, I found this really helpful: /LibVLCSharp/MediaDiscoverer.cs
That being said, I had no success using MediaDiscoverer to look for webcams myself.
If you don't insist on using LibVLC, you can list all camera devices without any third party software: How can I get a list of camera devices from my PC C#
from Francesco Bonizzi:
public static List<string> GetAllConnectedCameras()
{
var cameraNames = new List<string>();
using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE (PNPClass = 'Image' OR PNPClass = 'Camera')"))
{
foreach (var device in searcher.Get())
{
cameraNames.Add(device["Caption"].ToString());
}
}
return cameraNames;
}

C# - Get COM Ports with their friendly name using WMI

I'm developing a C# solution and I want to get the COM Ports, the description and the friendlyName (if they are bluetooth).
After investigating a bit, I've found that I can get the COM Ports using WMI/CIMV2/Win32_PnPEntity by searching the Name and Description values.
To find the friendly name I need to search on Win32_PnPSignedDriver and take the value of FriendlyName
Is there a way to match them to get a list like this?
COM56 - Bluetooth device - MyBTHDeviceName1
COM76 - Bluetooth device - MyBTHDeviceName2
COM5 - Serial device -
I attach the code that I have right now to get the first two fields.
// Method to retrieve the list of all COM ports.
public static List<PortInfo> FindComPorts()
{
List<PortInfo> portList = new List<PortInfo>();
ConnectionOptions options = PrepareOptions();
ManagementScope scope = PrepareScope(Environment.MachineName, options, #"\root\CIMV2");
// Prepare the query and searcher objects.
ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0");
ManagementObjectSearcher portSearcher = new ManagementObjectSearcher(scope, objectQuery);
using (portSearcher)
{
string caption = null;
// Invoke the searcher and search through each management object for a COM port.
foreach (ManagementObject currentObject in portSearcher.Get())
{
if (currentObject != null)
{
object currentObjectCaption = currentObject["Caption"];
if (currentObjectCaption != null)
{
caption = currentObjectCaption.ToString();
if (caption.Contains("(COM"))
{
PortInfo portInfo = new PortInfo();
portInfo.Name = caption.Substring(caption.LastIndexOf("(COM")).Replace("(", string.Empty).Replace(")", string.Empty);
portInfo.Description = caption;
portList.Add(portInfo);
}
}
}
}
}
return portList;
}
Thanks by advance.
The "friendly name" you are looking for is only suitable when COM Ports are virtual (as I assume they are on your example). I think that you can just get the information you need looking for the name property on Win32_PnPEntity class. There is no need to search for aditional information on COM ports as you will get all information already on Win32_PnPEntity class.
You can also try using ORMi and using strong typed objects for that.

How to add permission entries to visual svn server in C# [duplicate]

This question already has answers here:
SVN Rights Management Tool using Windows Authentication method
(2 answers)
Closed 7 years ago.
I have looked at this question and got it working to create a repo and add permissions for a user using the WMI interface. The issue I am running into now is this: if I am trying to update a repo I created and add another user to the repo, it clears out the current use (deletes it entirely from the repo) and just adds the one person.
So, I need to figure out how to do two things:
Add a user to an existing repo
Remove a user from an existing repo
I think once I have that I will be able to figure out the rest of my interactions. I referred to the wof file and found these entries that I believe I need to implement:
class VisualSVN_Repository
[provider("VisualSVNWMIProvider"), dynamic]
class VisualSVN_Repository
{
[Description ("Repository name"), key]
string Name;
...
[implemented] void GetSecurity([in] string Path,
[out] VisualSVN_PermissionEntry Permissions[]);
[implemented] void SetSecurity([in] string Path,
[in] VisualSVN_PermissionEntry Permissions[],
[in] boolean ResetChildren = false);
}
I am implementing set security like so:
static public void UpdatePermissions(string sid, string repository, AccessLevel level, bool isAdmin = false)
{
ManagementClass repoClass = new ManagementClass("root\\VisualSVN", "VisualSVN_Repository", null);
ManagementObject repoObject = repoClass.CreateInstance();
repoObject.SetPropertyValue("Name", repository);
ManagementBaseObject inParams =
repoClass.GetMethodParameters("SetSecurity");
inParams["Path"] = "/";
inParams["Permissions"] = new object[] { permObject };
ManagementBaseObject outParams =
repoObject.InvokeMethod("SetSecurity", inParams, null);
}
This works, but like I said, only for one user. It seems like it cleans out anything in there and just adds the one user object.
The other method I think I need to interact with is "GetSecurity" which looks like it returns an array of VisualSVN_PermissionEntry
VisualSVN_PermissionEntry
class VisualSVN_PermissionEntry
{
VisualSVN_Account Account;
uint32 AccessLevel;
};
So this one has an AccessLevel property and VisualSVN_Account object
VisualSVN_Account (I am using Windows auth, so I would need to use that one)
[provider("VisualSVNWMIProvider"), dynamic, abstract]
class VisualSVN_Account
{
};
class VisualSVN_WindowsAccount : VisualSVN_Account
{
[key] string SID;
};
So here is where I am lost. I assume I need to call "GetSecurity" and then iterate through those results and add them to an object array of the input parameters for "SetSecurity". I can't seem to get that to work. Some psuedo-code I have played with but am getting various errors (object reference errors mostly):
ManagementBaseObject inSecParams=
repoClass.GetMethodParameters("GetSecurity");
inSecParams["Path"] = "/";
ManagementBaseObject existingPerms =
repoObject.InvokeMethod("GetSecurity");
//now I need to loop through the array existingPerms and add them to an array of VisualSVN_PermissionEntry object.
--or--
//can I take this result and just add the users I need to add to it somehow.
I got this awhile ago from someone at visualSVN, figured I should paste the working solution in!
Here is the whole class file that handles creation, and repository rights assignments:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.IO;
using System.Management;
public static class SVNManager
{
public enum AccessLevel : uint
{
NoAccess = 0, ReadOnly, ReadWrite
}
private static ManagementObject GetRepositoryObject(string name)
{
return new ManagementObject("root\\VisualSVN", string.Format("VisualSVN_Repository.Name='{0}'", name), null);
}
private static ManagementObject GetPermissionObject(string sid, AccessLevel accessLevel)
{
var accountClass = new ManagementClass("root\\VisualSVN",
"VisualSVN_WindowsAccount", null);
var entryClass = new ManagementClass("root\\VisualSVN",
"VisualSVN_PermissionEntry", null);
var account = accountClass.CreateInstance();
account["SID"] = sid;
var entry = entryClass.CreateInstance();
entry["AccessLevel"] = accessLevel;
entry["Account"] = account;
return entry;
}
private static IDictionary<string, AccessLevel> GetPermissions(string repositoryName, string path)
{
var repository = GetRepositoryObject(repositoryName);
var inParameters = repository.GetMethodParameters("GetSecurity");
inParameters["Path"] = path;
var outParameters = repository.InvokeMethod("GetSecurity", inParameters, null);
var permissions = new Dictionary<string, AccessLevel>();
foreach (var p in (ManagementBaseObject[])outParameters["Permissions"])
{
// NOTE: This will fail if VisualSVN Server is configured to use Subversion
// authentication. In that case you'd probably want to check if the account
// is a VisualSVN_WindowsAccount or a VisualSVN_SubversionAccount instance
// and tweak the property name accordingly.
var account = (ManagementBaseObject)p["Account"];
var sid = (string)account["SID"];
var accessLevel = (AccessLevel)p["AccessLevel"];
permissions[sid] = accessLevel;
}
return permissions;
}
private static void SetPermissions(string repositoryName, string path, IDictionary<string, AccessLevel> permissions)
{
var repository = GetRepositoryObject(repositoryName);
var inParameters = repository.GetMethodParameters("SetSecurity");
inParameters["Path"] = path;
var permissionObjects = permissions.Select(p => GetPermissionObject(p.Key, p.Value));
inParameters["Permissions"] = permissionObjects.ToArray();
repository.InvokeMethod("SetSecurity", inParameters, null);
}
/// <summary>
/// Will execute the commands needed to create a repository on the SVN server
/// </summary>
/// <param name="r">Object with the repository name.</param>
/// <returns>True if creation was successful, False if there was a failure.</returns>
static public bool CreateRepository(repository r)
{
ManagementClass repoClass = new ManagementClass("root\\VisualSVN", "VisualSVN_Repository", null);
// Obtain in-parameters for the method
ManagementBaseObject inParams = repoClass.GetMethodParameters("Create");
// Add the input parameters.
inParams["Name"] = r.name;
// Execute the method and obtain the return values.
ManagementBaseObject outParams =
repoClass.InvokeMethod("Create", inParams, null);
return true;
}
}
I think that was all the relevant code. If you see anything missing let me know and I can double check the project (it's been a month, I forgot most of this)

Cannot get system identifier in WPF

I programming in WPF C# and trying to get the ProcessorID (or other system identifier). I have read through MSDN - System.Management Namespace. I add the namespace, but it does not provide ManagementBaseObject Class.
using System.Management;
/* code */
System.Management.(there is no ManagementBaseObject)
Is System.Management only used in WinForms, and not WPF?
The following code will give you the processor id, given that you have added a reference to System.Management:
public static string GetProcessorID()
{
var processorID = "";
var query = "SELECT ProcessorId FROM Win32_Processor";
var oManagementObjectSearcher = new ManagementObjectSearcher(query);
foreach (var oManagementObject in oManagementObjectSearcher.Get())
{
processorID = (string)oManagementObject["ProcessorId"];
break;
}
return processorID;
}
You need to add a reference to System.Management.dll
(Per the "Assembly" in the documentation for that class)
There are some existing types with the System.Management namespace within System.Core, this is why you are seeing some types.
For ManagementBaseObject, however, you will also need to add a reference to System.Management.dll to your project.
The code of Dirk might return a null object.
Please correct it in this way:
public static string GetProcessorID()
{
string cpuid = "";
ManagementObjectSearcher mbs = new ManagementObjectSearcher("Select ProcessorID From Win32_processor");
foreach (ManagementObject mo in mbs.Get())
{
var processorId = mo["ProcessorID"];
if (processorId != null)
{
cpuid = processorId.ToString();
break;
}
}
return cpuid;
}

Categories