I've found multiple online tutorials for establishing WMI connections to remote machines using c#. These tutorials describe a process like the following:
ConnectionOptions cOpts = new ConnectionOptions();
ManagementObjectCollection moCollection;
ManagementObjectSearcher moSearcher;
ManagementScope mScope;
ObjectQuery oQuery;
mScope = new ManagementScope(String.Format("\\\\{0}\\{1}", host.hostname, "ROOT\\CIMV2"), cOpts);
oQuery = new ObjectQuery("Select * from Win32_OperatingSystem");
moSearcher = new ManagementObjectSearcher(mScope, oQuery);
moCollection = moSearcher.Get();
The happy path cases - connecting to a local host, or connecting to a remote host with proper credentials - work fine. I'm working on a project where we need to support the case when the currently logged in account does not have access to the remote host we're attempting to connect to. That is, we need to catch this case, bring the bad credentials to the attention of the user, and prompt them to supply credentials again.
When I specify credentials in my ConnectionOptions object that do not have context on the remote machine, my call to moSearcher.Get() hangs (seemingly) indefinitely. Similarly, a call to the Connect() function in ManagementScope hangs in the same manner.
We have similar logic in place to perform the equivalent WMI commands in c++, and I can report that those return almost immediately if improper credentials are supplied. An appropriate "access is denied" message is returned. The hosts I'm using for test purposes right now are the same ones we use when testing our existing c++ logic, so I have no reason to believe that WMI is incorrectly configured in our environment.
I've searched for timeout issues surrounding WMI connections in c#. I've explored the Timeout property of ConnectionOptions and moSearcher.Options. I've also looked at the ReturnImmediately property of the EnumerationOptions object that can be associated with ManagementObjectSearcher instance. These options did not have the desired effect for me.
I suppose I could perform these WMI commands in a separate thread, and surround the thread with monitoring code that kills it if it hasn't returned in a reasonable amount of time. That seems like a fair amount of work that would be pushed to all consumers of the c# WMI routines, and I'm hoping there's an easier way. Plus, I'm not sure that killing an outstanding thread this way properly cleans up the WMI connection.
Pinging the remote host doesn't do me any good, because knowing the host is up and running does not tell me if the credentials I have are appropriate (and if the c# WMI calls will hang). Is there another way to validate the credentials against a remote host?
It's always possible that there's an obvious flag or API I'm missing, because I would think others have run into this problem. Any information/assistance would be appreciated. Thanks for reading this lengthy post.
I don't know what all your special functions are, but here's a little routine to help you troubleshoot that should be able to wrap your routine in a thread and give it 5 seconds to execute:
void Fake() {
bool ok = false;
ConnectionOptions cOpts = new ConnectionOptions();
ManagementObjectCollection moCollection;
ManagementObjectSearcher moSearcher;
ManagementScope mScope;
ObjectQuery oQuery;
if (cOpts != null) {
mScope = new ManagementScope(String.Format("\\\\{0}\\{1}", host.hostname, "ROOT\\CIMV2"), cOpts);
if (mScope != null) {
oQuery = new ObjectQuery("Select * from Win32_OperatingSystem");
if (oQuery != null) {
moSearcher = new ManagementObjectSearcher(mScope, oQuery);
if (moSearcher != null) {
ManualResetEvent mre = new ManualResetEvent(false);
Thread thread1 = new Thread(() => {
moCollection = moSearcher.Get();
mre.Set();
};
thread1.Start();
ok = mre.WaitOne(5000); // wait 5 seconds
} else {
Console.WriteLine("ManagementObjectSearcher failed");
}
} else {
Console.WriteLine("ObjectQuery failed");
}
} else {
Console.WriteLine("ManagementScope failed");
}
} else {
Console.WriteLine("ConnectionOptions failed");
}
}
Hope that helps or gives you some ideas.
I took jp's suggestion to surround the WMI API calls in a separate thread that could be killed if they exceeded a timeout. When testing, the separate thread threw an exception of type System.UnauthorizedAccessException. I removed the threading logic and added a catch statement to handle this exception type. Sure enough, the exception is caught almost immediately following the call to ManagementObjectSearcher.Get().
try
{
moCollection = moSearcher.Get();
}
catch (System.UnauthorizedAccessException)
{
return Program.ERROR_FUNCTION_FAILED;
}
catch (System.Runtime.InteropServices.COMException)
{
MessageBox.Show("Error, caught COMException.");
return Program.ERROR_FUNCTION_FAILED;
}
(Note that the System.Runtime.InteropServices.COMException catch statement already existed in my code)
I don't know why this exception isn't thrown (or at least is not brought to the user's attention through the VS 2010 IDE) when executed as part of the parent thread. In any event, this is exactly what I was looking for, and is consistent with the behavior of the WMI connection routines in c++.
Related
I've seen several similar questions on Google, but nothing exactly matches what I'm trying to do. I'm making a lag-reducing program (for a game) that basically lowers the user's MTU when a certain process is open, and restores it when the process is closed. However, MTU is a network-adapter specific setting, and some users have multiple connected network adapters. To this end, I thought it'd be nice to have the program also detect which adapter is being used by the game, and only change the MTU on that adapter.
The game will only use one adapter at a time.
I can't hardcode in end-server-IP addresses because they change fairly frequently. It seems to be there must be a way to determine which adapter the other process is using without knowing the end IP address, but I can't seem to find it.
EDIT:
Thanks to Cicada and Remco, I've solved the problem.
I used the ManagedIPHelper class that Remco linked to (ManagedIpHelper) and Cicada's comments led me to this article (Identifying active network interface)
Combining those with some (Nasty, horribly unoptimized) LINQ, I got this code snippet, which takes the process name and returns the Network Interface it's using, or null if it can't find one.
private NetworkInterface getAdapterUsedByProcess(string pName)
{
Process[] candidates = Process.GetProcessesByName(pName);
if (candidates.Length == 0)
throw new Exception("Cannot find any running processes with the name " + pName + ".exe");
IPAddress localAddr = null;
using (Process p = candidates[0])
{
TcpTable table = ManagedIpHelper.GetExtendedTcpTable(true);
foreach (TcpRow r in table)
if (r.ProcessId == p.Id)
{
localAddr = r.LocalEndPoint.Address;
break;
}
}
if (localAddr == null)
throw new Exception("No routing information for " + pName + ".exe found.");
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceProperties ipProps = nic.GetIPProperties();
if (ipProps.UnicastAddresses.Any(new Func<UnicastIPAddressInformation, bool>((u) => { return u.Address.ToString() == localAddr.ToString(); })))
return nic;
}
return null;
}
Testing confirms this works perfectly! Many thanks, guys!
Side notes to anyone using this snippet:
You'll need the ManagedIpHelper classes.
Your app may need to request elevation, depending on the situation.
Multiple running processes (think Chrome) will return an undefined result. If you're going to use this code with a multpile-process-candiate situation, I highly recommend you change using (Process p = candidates[0]) to a more specific filter, ie based on PID.
You may also want to impliment new exception types, so you can, for example, catch "No routing info" more cleanly, the reason being that this error is often fixed by simply waiting a bit (to let the target process open a connection) and then retrying.
in addition to Cicada, this must help you:
It is a C# wrapper around some c/c++ code, which gets you the list of all open connections with associated PID ( Process Id ).
http://www.timvw.be/2007/09/09/build-your-own-netstatexe-with-c/
I do believe this is the only way to go, determine the process(id) based on executable path/name and try to find the current connection of that process.
I'm using WMI for monitoring all our servers through a small C# service, which creates a bunch of ManagementScopes (one per server it should monitor) and periodically polls for CPU load etc.
However every once in a while it starts throwing COMExceptions, with the message "The RPC server is unavailable". Now that's fair enough if it was true, however I can manully connect to the server just fine, and if I create a new ManagementScope to the same server, I can reconnect without problems!
There's a problem with this approach though: It leaks memory :-(
ManagementScope has no Close, Dispose or similar cleanup function, and leaks memory when just garbage collected. This is, according to all my google searches, a problem with the underlying WMI components, and as such not a .Net issue.
So I figure my best approach is to solve the COMException issue, and just staying with the original ManagementScope - however if I manually call Connect on the scope after the COMException, it does return true (as in "Yes I've got a connection), but at first attempt at getting data from it, it throws another COMException.
I've tried quite a few things, but I simply cannot figure out why this happens :-(
The code is quite large, therefore I haven't pasted it here (and it's split into a lot of classes)
But basically I create a scope, and then call the following methods:
public ManagementObject GetSingleObject(string query)
{
using (var searcher = CreateSearcher(query))
{
try
{
using (var collection = searcher.Get())
{
return collection
.Cast<ManagementObject>()
.FirstOrDefault();
}
}
catch
{
return null;
}
}
}
private ManagementObjectSearcher CreateSearcher(string query)
{
return new ManagementObjectSearcher(_scope, new ObjectQuery(query), _options);
}
If you need more code, let me know :-)
I'm using WMI, I need to get some information, but when class is not available due to insufficient permissions, everything hangs up for a few (~5) seconds. Even setting low timeout doesn't work (not to mention that it would be stupid solution).
Problem isn't insufficient permissions, problem is "hang up".
Is there any way to check if current process has privileges to read information from some class to prevent "hang up" and "access denied" exception?
ConnectionOptions co = new ConnectionOptions();
co.Impersonation = ImpersonationLevel.Impersonate;
co.Authentication = AuthenticationLevel.Packet;
co.Timeout = new TimeSpan(0, 0, 1); // 1 second, but still hangs for ~5
co.EnablePrivileges = false; // false or true, doesn't matter
ManagementPath mp = new ManagementPath();
mp.NamespacePath = #"root\CIMV2\Security\MicrosoftTpm";
mp.Server = "";
ManagementScope ms = new ManagementScope(mp, co);
ms.Connect(); // Hangs for ~5 seconds and throws "access denied"
What you need to do is run the operation on a background thread. It may still take five seconds (or more) but your application will remain responsive instead of hanging. Try something like this:
Task.Factory.StartNew(() =>
{
// Your permission checking code here.....
}).ContinueWith((t) =>
{
// Inform user of permissions status.
});
If you aren't using a version of the framework that supports 'Task' try a BackgroundWorker instead. These are common ways to keep long running processes from hanging your app.
I am developing a window application in Microsoft visual C # 2008 express edition.I get a run time error wen i run the application.
string[] diskArray;
string driveNumber;
string driveLetter;
**searcher1 = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDiskToPartition");**
foreach (ManagementObject dm in searcher1.Get())
{
diskArray = null;
driveLetter = getValueInQuotes(dm["Dependent"].ToString());
diskArray = getValueInQuotes(dm["Antecedent"].ToString()).Split(',');
driveNumber = diskArray[0].Remove(0, 6).Trim();
if(driveLetter==this._driveLetter)
{
/* This is where we get the drive serial */
ManagementObjectSearcher disks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
foreach (ManagementObject disk in disks.Get())
{
if (disk["Name"].ToString() == ("\\\\.\\PHYSICALDRIVE" + driveNumber) & disk["InterfaceType"].ToString() == "USB") {
this._serialNumber = parseSerialFromDeviceID(disk["PNPDeviceID"].ToString());
(in the highlighted line)
Context 0x3c74b38 is disconnected. No proxy will be used to service the request on the COM component. This may cause corruption or data loss. To avoid this problem, please ensure that all contexts/apartments stay alive until the application is completely done with the RuntimeCallableWrappers that represent COM components that live inside them.
Likely, you can find in the inner exceptions another one, e.g.
COMException: The application called an interface that was marshalled for a different thread.
That means you have to call your methods in another thread. Likely if you review the call stack you'll find an event handler what calls this code. Just use Invoke/BeginInvoke method to call your code. See example below:
if (this.InvokeRequired) // in some cases this condition will not work
{
this.BeginInvoke(new MethodInvoker(delegate() { this.Your_Method(); }));
return;
}
I got similar error when a USB device has been disconnected. But in my case I got it in autogenerated WMI wrap class which I called in LibUsbDotNet event handler.
I'm building what could be called the DAL for a new app. Unfortunately, network connectivity to the database is a real problem.
I'd like to be able to temporarily block network access within the scope of my test so that I can ensure my DAL behaves as expected under those circumstances.
UPDATE: There are many manual ways to disable the network, but it sure would be nice if I could enable/disable within the test itself.
For the time being, I'm just "disabling" the network by setting a bogus static IP as follows:
using System.Management;
class NetworkController
{
public static void Disable()
{
SetIP("192.168.0.4", "255.255.255.0");
}
public static void Enable()
{
SetDHCP();
}
private static void SetIP(string ip_address, string subnet_mask)
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC) {
if ((bool)objMO("IPEnabled")) {
try {
ManagementBaseObject setIP = default(ManagementBaseObject);
ManagementBaseObject newIP = objMO.GetMethodParameters("EnableStatic");
newIP("IPAddress") = new string[] { ip_address };
newIP("SubnetMask") = new string[] { subnet_mask };
setIP = objMO.InvokeMethod("EnableStatic", newIP, null);
}
catch (Exception generatedExceptionName) {
throw;
}
}
}
}
private static void SetDHCP()
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc) {
// Make sure this is a IP enabled device. Not something like memory card or VM Ware
if ((bool)mo("IPEnabled")) {
ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
newDNS("DNSServerSearchOrder") = null;
ManagementBaseObject enableDHCP = mo.InvokeMethod("EnableDHCP", null, null);
ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
}
}
}
Write a wrapper to the network class connectivity class you're using (e.g. WebClient) with an on-off switch :)
Either that, or block your application in the firewall.
Try blocking the connection with a firewall midway through the session maybe?
I like the wrapper idea as well, but thats kind of abstracting the problem and you prolly might not get exact real world behavior. Also, inserting the wrapper layer and then removing it may be more trouble than its worth.
Edit: Run a script that turns the Network adapter on/off randomly or at set intervals?
If you are trying a complete network outage for your application unplugging the network cable will work. Sometimes you might have a data access layer with multiple data sources (on different machines) in which case you can simulate an exception in your tests with a Mock Framework like Rhino Mocks. Here is some pseudo-code that you may have in your test
void TestUserDBFailure()
{
// ***** THIS IS PSEUDO-CODE *******
//setting up the stage - retrieval of the user info create an exception
Expect.Call(_userRepository.GetUser(null))
.IgnoreArguments()
.Return(new Exception());
// Call that uses the getuser function, see how it reacts
User selectedUser = _dataLoader.GetUserData("testuser", "password");
}
Probably not helpful for simulating "real" network issues, but you could just point your DB connection string to a non-existent machine while within the scope of your test.
Depends on what particular network problem you wish to simulate. For most folks, it's as simple as "server unreachable", in which case you'd just try to connect to a non existent server. Be careful, though, because you want something that is routable but does not answer. Trying to connect to dkjdsjk.com will fail immediately (DNS lookup), but trying to connect to www.google.com:1433 will (probably) time out due to a firewall - which is how your app will behave when your DB server is down.
Try Toxiproxi, it can simulate network outage.
They have REST API and even .NET Client API to change the network simulation programatically (from your test code)
https://github.com/shopify/toxiproxy
Look for a WAN simulator that will allow you to restrict bandwidth (and cut it off completely) I always find it interesting to see how the user experience changes when my apps are run in a bandwidth restricted environment. Look here for some information.
There is a tool you can use for simulating High Latency and Low Bandwidth in Testing of Database Applications as explained in this blog entry.
Just found an alternative that allows to directly close TCP connections:
http://lamahashim.blogspot.ch/2010/03/disabling-network-using-c.html
It is based on Windows IP Helper API (uses DllImport):
http://msdn.microsoft.com/en-us/library/windows/desktop/aa366073(v=vs.85).aspx
Use mock objects to create configurable, destructible versions of the real thing--in this case, the database.