Simulate a network failure - c#

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);
}
}

Related

How to get registry and file exclusions from UWF using WMI query in C#

I want to get all registry exclusion and file exclusion from UWF, using the WMI.
I've already tried to invoke GetExclusions methods from UWF_RegistryFilter class but of no luck.
I am looking forward to a working sample code, thanks in advance for any help!
The difficult part is to read the out parameters from the method result. There is no appropriate documentation available on Microsoft website and it's difficult to guess how ManagementBaseObject can be utilized for reading the out parameters.
In order to reach to a solution, I tried to develop an understanding of how WMI makes use of out parameters based on other well-documented wmi samples. Please use the C# code below, I hope it helps:
public static void GetRegistryExclusions()
{
ManagementScope scope = new ManagementScope(#"root\standardcimv2\embedded");
using (ManagementClass mc = new ManagementClass(scope.Path.Path, "UWF_RegistryFilter",
null))
{
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
ManagementBaseObject[] result = (ManagementBaseObject[])mo.InvokeMethod("GetExclusions", null, null).Properties["ExcludedKeys"].Value;
if (result != null)
{
foreach (var r in result)
{
Console.WriteLine(r.GetPropertyValue("RegistryKey"));
}
}
}
}
}
Note/Request Request someone with 1500 reputation to create and link following tags so that it becomes easier for people like me to request solutions/answer questions on stackoverflow.
UWF
UWFMGR
Found Manoj's answer only after I figured it out myself from a hint on a microsoft forum, when I wanted to put my code on SO. Therefore adding keywords Unified Write Filter and UWF_Volume (does it work like this?).
I used a slightly shorter syntax to access the properties, and also return the excluded files as the OP asked. I tried to make it as robust as possible, as it seems that there are some invalid volume entries. If someone has a clue what they are, please let me know.
public static string GetFilterDetail()
{
string details = "";
string detailsCurrent = "";
string detailsNext = "";
try
{
// Get WMI provider for UWF
var scope = new ManagementScope(#"\\localhost\root\StandardCimv2\embedded");
var managementPath = scope.Path.Path;
using (ManagementClass volumeFilterClass = new ManagementClass(managementPath, "UWF_Volume", null))
{
var volumeFilters = volumeFilterClass?.GetInstances();
if (volumeFilters != null && volumeFilters.Count > 0)
{
foreach (ManagementObject volumeFilter in volumeFilters)
{
if (volumeFilter != null)
{
// Now we have access to the Volume's WMI provider class
// First check if this is a valid Volume instance, as from trial and error it seems that is not always the case.
// Some invalid/undocumented instances throw a Not Found ManagementException on the GetExclusions method.
// Some also throw a NullReferenceException on mo.GetPropertyValue("Protected"), but that covers less cases.
bool isInstanceValid = true;
try
{
volumeFilter.InvokeMethod("GetExclusions", null, null);
}
catch (ManagementException ex)
{
if (ex.Message.ToLower().Contains("not found"))
isInstanceValid = false;
else throw ex;
}
if (isInstanceValid)
{
bool currentSession = ((bool)volumeFilter.GetPropertyValue("CurrentSession"));
string driveLetter = (string)volumeFilter.GetPropertyValue("DriveLetter");
bool isProtected = ((bool)volumeFilter.GetPropertyValue("Protected"));
string detail = "Volume " + driveLetter + " is " + (isProtected ? "protected" : "not protected") + ".\n";
detail += "Excluded files:\n";
ManagementBaseObject outParams = volumeFilter.InvokeMethod("GetExclusions", null, null);
if (outParams != null)
{
var excludedItems = (ManagementBaseObject[])outParams["ExcludedFiles"];
if (excludedItems != null)
{
foreach (var excludedItem in excludedItems)
{
detail += " " + driveLetter + excludedItem["FileName"] + "\n";
}
}
else detail += " [No excluded files]\n";
}
if (currentSession)
detailsCurrent += detail;
else
detailsNext += detail;
}
}
}
}
}
using (ManagementClass registryFilterClass = new ManagementClass(managementPath, "UWF_RegistryFilter", null))
{
var registryFilters = registryFilterClass?.GetInstances();
if (registryFilters != null && registryFilters.Count > 0)
{
foreach (ManagementObject registryFilter in registryFilters)
{
if (registryFilter != null)
{
// Now we have access to the RegistryFilter's WMI provider class
bool currentSession = ((bool)registryFilter.GetPropertyValue("CurrentSession"));
string detail = "Excluded registry keys:\n";
ManagementBaseObject outParams = registryFilter.InvokeMethod("GetExclusions", null, null);
if (outParams != null)
{
var excludedItems = (ManagementBaseObject[])outParams["ExcludedKeys"];
if (excludedItems != null)
{
foreach (var excludedItem in excludedItems)
{
detail += " " + excludedItem["RegistryKey"] + "\n";
}
}
else detail += " [No excluded registry keys]\n";
}
if (currentSession)
detailsCurrent += detail;
else
detailsNext += detail;
}
}
}
}
}
catch (Exception ex)
{
details += ex.ToString();
}
details += "\nNOTE: These settings are only active if the Write Filter is Enabled\n"
+ "\nCURRENT SETTINGS:\n" + detailsCurrent
+ "\nNEXT SETTINGS: (after next reboot)\n" + detailsNext;
return details;
}
Example output:

Cannot connect Hyper-V VM Network Adapter to a Hyper-V Switch via WMI in C#

I am having quite some difficulty connecting a specific, existing network adapter to an existing switch. I can create a new network adapter and connect it to my VM through several examples posted online but cannot make that extra step. The following function finds my network adapter and executes without error, but does not otherwise make the connection. Any assistance is greatly appreciated!
**EDIT: Solved, see code below.**
Solved:
public static void ConnectInterfaceToSwitch(string VmName, string networkInterfaceName, string switchName)
{
ManagementScope scope = new ManagementScope(#"root\virtualization\v2");
ManagementObject mgtSvc = WmiUtilities.GetVirtualMachineManagementService(scope);
ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(switchName, scope);
ManagementObject virtualMachine = WmiUtilities.GetVirtualMachine(VmName, scope);
ManagementObject virtualMachineSettings = WmiUtilities.GetVirtualMachineSettings(virtualMachine);
ManagementObjectCollection portsSettings = virtualMachineSettings.GetRelated("Msvm_SyntheticEthernetPortSettingData", "Msvm_VirtualSystemSettingDataComponent", null, null, null, null, false, null);
{
foreach (ManagementObject portSettings in portsSettings)
{
if (portSettings["ElementName"].Equals(networkInterfaceName))
{
Console.WriteLine("Adapter found: " + networkInterfaceName);
ManagementObjectCollection connections = portSettings.GetRelated("Msvm_EthernetPortAllocationSettingData");
foreach (ManagementObject connection in connections)
{
connection["HostResource"] = new string[] { ethernetSwitch.Path.Path };
connection["EnabledState"] = 2; // 2 means "Enabled"
ManagementBaseObject inParams = mgtSvc.GetMethodParameters("ModifyResourceSettings");
inParams["ResourceSettings"] = new string[] { connection.GetText(TextFormat.WmiDtd20) };
ManagementBaseObject outParams = mgtSvc.InvokeMethod("ModifyResourceSettings", inParams, null);
WmiUtilities.ValidateOutput(outParams, scope);
Console.WriteLine(string.Format(CultureInfo.CurrentCulture, "Connected VM '{0}' to switch '{1}'.", VmName, switchName));
}
}
}
}
}

SoftwareLicensingProduct Which one is my

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);
}
}

Need to get name (DeviceID) of System Reserved partition

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) {}

WMI defrag method not found in C#

I'm trying to use WMI to defrag my C: Drive.
I'm running Windows 7 Pro x64.
Console.WriteLine(SMARTManager.Instance.SMARTHDD.Defrag("C:", ref ERR));
Function:
public string Defrag(string a_DriveName, ref string ERR)
{
try
{
ManagementObject classInstance =
new ManagementObject("root\\CIMV2",
String.Format("Win32_Volume.DeviceID='{0}'", a_DriveName),
null);
// Obtain in-parameters for the method
ManagementBaseObject inParams =
classInstance.GetMethodParameters("Defrag");
// Add the input parameters.
inParams["Force"] = true;
// Execute the method and obtain the return values.
ManagementBaseObject outParams =
classInstance.InvokeMethod("Defrag", inParams, null);
// List outParams
string callback = "Out parameters:\n" + "ReturnValue: " + outParams["ReturnValue"];
return callback;
}
catch (ManagementException err)
{
ERR = "An error occurred while trying to execute the WMI method: " + err.Message;
}
return null;
}
I got this code from WMI Code Creator but when I run it it returns an exeption saying "Not Found".
Has anyone else tried this?
This error is caused because you are passing a wrong object path to the ManagementObject constructor, a DeviceID looks like \\?\Volume{3a7a882b-8713-11e0-bfc8-806e6f6e6963}\, So to fix your issue you must pass a valid DeviceID or modify your code to use the Name property of the Win32_Volume class.
check this sample code which uses the Name property instead
using System;
using System.Collections.Generic;
using System.Management;
using System.Text;
namespace GetWMI_Info
{
class Program
{
public static void Defrag(string a_DriveName)
{
try
{
string ComputerName = "localhost";
ManagementScope Scope;
if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
{
ConnectionOptions Conn = new ConnectionOptions();
Conn.Username = "";
Conn.Password = "";
Conn.Authority = "ntlmdomain:DOMAIN";
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), Conn);
}
else
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect();
string WQL = String.Format("SELECT * FROM Win32_Volume Where Name='{0}'", a_DriveName);
ObjectQuery Query = new ObjectQuery(WQL);
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
foreach (ManagementObject ClassInstance in Searcher.Get())
{
ManagementBaseObject inParams = ClassInstance.GetMethodParameters("Defrag");
ManagementBaseObject outParams= ClassInstance.InvokeMethod("Defrag", inParams ,null);
Console.WriteLine("{0,-35} {1,-40}","DefragAnalysis",outParams["DefragAnalysis"]);
Console.WriteLine("{0,-35} {1,-40}","ReturnValue",outParams["ReturnValue"]);
}
}
catch (Exception e)
{
Console.WriteLine(String.Format("Exception {0} Trace {1}",e.Message,e.StackTrace));
}
}
static void Main(string[] args)
{
//the drive name must be escaped
Defrag("F:\\\\");
Console.WriteLine("Press Enter to exit");
Console.Read();
}
}

Categories

Resources