Internet Access Controller in C# - c#

How can I disable/enable an internet connection? Just want to disable internet connection only not LAN.
I tried this but it is not working
string[] connections = DisconnectWrapper.Connections();
for (int i = 0; i < connections.Length; i++)
{
try
{
DisconnectWrapper.CloseConnection(connections[i]);
}
catch (Exception ex)
{ }
}

You can use WMI.
Add System.Management to your referenced and try this code
SelectQuery wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionId != NULL");
ManagementObjectSearcher searchProcedure = new ManagementObjectSearcher(wmiQuery);
foreach (ManagementObject item in searchProcedure.Get())
{
if (((string)item["NetConnectionId"]) == "Local Network Connection")
{
item.InvokeMethod("Disable", null);
}
}
There is another article:Disable/Enable Network Connections Programmatically.
with WMI you can disable and enable all network connections.
Edited:
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(#"select * from Win32_NetworkAdapter"))
{
ManagementObjectCollection results = searcher.Get();
foreach (ManagementObject obj in results)
{
System.Console.WriteLine("Found adapter {0} :", obj["Caption"]);
System.Console.WriteLine("Disabling adapter ...");
object[] param = new object[0];
obj.InvokeMethod("Disable",param);
System.Console.WriteLine("Done.");
}
Console.ReadLine();
}
Be aware Some of the adapter cannot be disabled.

You can do what you need by doing a shell call to netsh.
Example:
netsh interface set interface "Target Adapter Name" enabled
netsh interface set interface "Target Adapter Name" disabled
Netsh will block so if you wait for the process you spawn to exit, you'll know it's done. It requires administrator privileges, so your process will also require it. Netsh will set its exit code to 0 on success or 1 on failure, so you can check that for feedback if needed.

Related

Telling if a remote server is up or down using C#

I was wondering if it's possible to tell if a remote server is up or down using C#? First I have a method to shut down the server:
private static void RestartSecondServer()
{
Console.WriteLine("Computer details retrieved using Windows Management Instrumentation (WMI)");
//Connect to the remote computer
ConnectionOptions co = new ConnectionOptions();
co.Username = #"***********";
co.Password = "*********";
ManagementScope ms = new ManagementScope("\\\\******\\root\\cimv2", co);
//Query remote computer across the connection
ObjectQuery oq = new System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher query1 = new ManagementObjectSearcher(ms, oq);
ManagementObjectCollection queryCollection1 = query1.Get();
foreach (ManagementObject mo in queryCollection1)
{
string[] ss = {""};
mo.InvokeMethod("Reboot", ss);
Console.WriteLine(mo.ToString());
Console.WriteLine("Reboot complete");
//Process.Start("shutdown", "/r /t 0");
}
}
Now I want to create a method to see if this remote server which is in the process of being restarted is down. I tried a generic pinging method but it was returning true/success.
Can a server be successfully pinged if it's in the process of being restarted? Is it possible to tell if the server is being restarted?

What to specify for Local ManagementScope

I am trying to connect (locally) to get a list of virtual machines and their properties. I have hacked some code I found, but my code is failing to connect so I can only assume that the connection string is wrong.
Using Server 2012, Hyper-V
private void listVirtualMachines() {
ManagementScope manScope = new ManagementScope(#"\\LOCALHOST\root\cimv2");
if (manScope.IsConnected) {
ObjectQuery queryObj = new ObjectQuery("SELECT * FROM Msvm_ComputerSystem");
// connect and set up our search
ManagementObjectSearcher vmSearcher = new ManagementObjectSearcher(manScope, queryObj);
ManagementObjectCollection vmCollection = vmSearcher.Get();
// loop through the machines
foreach (ManagementObject vm in vmCollection) {
// display VM details
LogString(vm["ElementName"].ToString());
LogString(vm["EnabledState"].ToString());
LogString(vm["Description"].ToString());
}
} else {
//WE END UP HERE EVERY TIME!
LogString("Cannot Connect to ManagementScope!");
}
} //funct
In Server 2012, Msvm_ComputerSystem is in the WMI namespace root\virtualization\v2 so the code should be:
ManagementScope manScope = new ManagementScope(#"\\.\root\virtualization\v2");
manScope.Connect();

Releasing and Renewing your DHCP-based IP Address

Using C# how can I release and renew my DHCP-based IP Address?
At the moment I am using the process method to use these DOS commands:
ipconfig /release
and
ipconfig /renew
Is there a more managed approach in C# for this?
You could use WMI, but its much simpler to just do it using System.Diagnostics.Process
Here is a WMI solution anyway:
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
//Need to determine which adapter here with some kind of if() statement
objMO.InvokeMethod("ReleaseDHCPLease", null, null);
objMO.InvokeMethod("RenewDHCPLease", null, null);
}
You can try something like this:
SelectQuery query = new SelectQuery("Win32_NetworkAdapter", "AdapterTypeID=0");
ManagementObjectSearcher search = new ManagementObjectSearcher(query);
foreach (ManagementObject result in search.Get())
{
NetworkAdapter adapter = new NetworkAdapter(result);
adapter.Disable();
}
Not that your process must have elevated privileges.
Hope it helps.

check if a process runs on a remote machine for a certain user

I have to create an executable which checks if a certain process is running for a certain user (a service account) on a remote machine, the input parameters are 3 strings, machine name, user name and process name.
I have the idea to do this using either System.Diagnostics or WMI, just wanted to double check if anybody has another idea like powershell or even a window functionality which could make the task even easier.
since we want to make sure that process is always running on a dedicated server we will configure a scheduled task to execute a small console application which does this check. Not sure if coding it in C# is the best option or am I ignoring a builtin feature of windows server? Thanks!
I'm pretty sure you can accomplish this with tasklist cmd: tasklist /S \\<server> /V > tasklist.txt. this will give you a file you can grep through.
namespace not referenced
using System.Management;
I have ended up by implementing following solution in C#
this retrieves the username without domain name of the user running processName on machineName
public static string GetProcessOwner()
{
try
{
var resultUserName = string.Empty;
ConnectionOptions opt = new ConnectionOptions();
string path = string.Format(#"\\{0}\root\cimv2", machineName);
ManagementScope scope = new ManagementScope(path, opt);
scope.Connect();
var query = new ObjectQuery(string.Format("Select * From Win32_Process Where Name = '{0}'", processName));
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
var processList = searcher.Get();
foreach (ManagementObject obj in processList)
{
string[] argList = new string[] { string.Empty, string.Empty };
int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
if (returnVal == 0)
{
// return DOMAIN\user
//return argList[1] + "\\" + argList[0];
resultUserName = argList[0];
}
}
return resultUserName;
}
catch (Exception exc)
{
Debug.WriteLine(exc.Message);
return string.Empty;
}
}
GetOwner can return empty array for remote comp, so it may not work

Get local printer list to change printer IP and default printer

How am I able do find all local printers of the machine where the program is running with a user that doesn't have admin rights. I need to remap the printer IP and set the printer as default. My idea is to use impersonation to do this but I don't know where to find the printer and if it is a good solution to use impersonation.
Thanks for any help!
I don't think you will have any luck with this. Impersonation will not work here and just throw a exception. You can try this by making a impersonation and try to open Environment.Domain it should give you a exception.
You can try something like this without impersonation:
ManagementScope mscope = new ManagementScope(#"\root\CIMV2", options);
mscope.Connect();
System.Management.ObjectQuery oQuery = new ObjectQuery("Select * from Win32_TCPIPPrinterPort");
System.Management.ManagementObjectSearcher searcher = new ManagementObjectSearcher(mscope, oQuery);
ManagementObjectCollection moCollection = searcher.Get();
foreach (ManagementObject mo in moCollection)
{
string name = mo["Name"].ToString();
if (name.Equals(this.portName))
{
System.Threading.Thread.Sleep(10000);
mo["HostAddress"] = this.printerIP;
mo.Put();
Console.WriteLine("Adjusted Printer Port to new IP address " + this.printerIP);
return true;
}
}

Categories

Resources