how to get all devices information between 2 devices - c#

I've 2 devices My-PC and another-PC
another-PC are connected to switch which connected to main switch with-in the same LAN
My question is how to get all devices information such as (IP,MAC,Serial Number) from My-PC to another-PC

Refer to the documentation for the System.Management namespace on MSDN. All you need is in there. There are also numerous examples out there if you search for retrieving WMI information with C#. A small example:
using System;
using System.Management;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// create management class object
ManagementClass mc = new
ManagementClass("Win32_ComputerSystem");
//collection to store all management objects
ManagementObjectCollection moc = mc.GetInstances();
if (moc.Count != 0)
{
foreach (ManagementObject mo in mc.GetInstances())
{
// display general system information
Console.WriteLine("\nMachine Make: {0}", mo["Manufacturer"].ToString());
}
}
//wait for user action
Console.ReadLine();
}
}
}

Related

Get Windows service dependencies using C#

I can use PowerShell to do this fairly easily, but I am looking for a C# way to do this. With PS, I can use Get-Service to iterate over the collection and check collections in there called DependentServices and RequiredServices to get the list of the dependent and required services for a given service.
I've looked into the WMI model using the query "Select * from Win32_Service", but this returns a collection of Win32_Service objects that does not seem to have the collections I am interested in. I feel like I am missing something here. I have looked around and tried various searches, but I've not turned up a C#-centric way of doing this.
I want to query a given service and get back the collections mentioned above (DependentServices and RequiredServices). Sorry if I missed the obvious, but I really have not been able to find relevant topics.
You can use the ServiceController class:
StringBuilder sb = new System.Text.StringBuilder();
foreach (var svc in System.ServiceProcess.ServiceController.GetServices())
{
sb.AppendLine("============================");
sb.AppendLine(svc.DisplayName);
foreach (var dep in svc.DependentServices)
{
sb.AppendFormat("\t{0}", dep.DisplayName);
sb.AppendLine();
}
}
MessageBox.Show(sb.ToString());
You can use the Win32_DependentService WMI class and the Associators of sentence to retrieve the dependent services.
Try this sample
using System;
using System.Collections.Generic;
using System.Management;
using System.Text;
namespace GetWMI_Info
{
class Program
{
static void Main(string[] args)
{
try
{
string ComputerName = "localhost";
ManagementScope Scope;
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect();
ObjectQuery Query = new ObjectQuery("Associators of {Win32_Service.Name='NetMan'} Where AssocClass=Win32_DependentService ResultClass=Win32_Service");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
foreach (ManagementObject WmiObject in Searcher.Get())
{
Console.WriteLine("{0,-35} {1,-40}","Name",WmiObject["Name"]);// String
}
}
catch (Exception e)
{
Console.WriteLine(String.Format("Exception {0} Trace {1}",e.Message,e.StackTrace));
}
Console.WriteLine("Press Enter to exit");
Console.Read();
}
}
}
You can use this property -
http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.dependentservices.aspx
ServiceController sc = new ServiceController("Event Log");
ServiceController[] scServices = sc.DependentServices;
// Display the list of services dependent on the Event Log service.
if (scServices.Length == 0)
{
Console.WriteLine("There are no services dependent on {0}",
sc.ServiceName);
}
else
{
Console.WriteLine("Services dependent on {0}:",
sc.ServiceName);
foreach (ServiceController scTemp in scServices)
{
Console.WriteLine(" {0}", scTemp.DisplayName);
}
}

WMI Hardware Addresses and IRQs

Can anyone help me out trying to find a WMI method for retrieving hardware addresses and IRQs?
The classes I've looked at so far seem a bit empty for telling you what device is actually using the resource - but it must be possible if it's available under Windows' 'System Information' tool.
Ultimately I want to create an address map and an IRQ map in my C# application.
I've briefly looked at the following classes:
Win32_DeviceMemoryAddress
Win32_IRQResource
and I just this second saw another, but I haven't really looked into it:
Win32_AllocatedResource
Maybe pairing it with Win32_PnPEntity?
To get that info you must use the ASSOCIATORS OF WQL sentence to create a link between the
Win32_DeviceMemoryAddress -> Win32_PnPEntity -> Win32_IRQResource classes.
Check this sample app
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
namespace WMIIRQ
{
class Program
{
static void Main(string[] args)
{
foreach(ManagementObject Memory in new ManagementObjectSearcher(
"select * from Win32_DeviceMemoryAddress").Get())
{
Console.WriteLine("Address=" + Memory["Name"]);
// associate Memory addresses with Pnp Devices
foreach(ManagementObject Pnp in new ManagementObjectSearcher(
"ASSOCIATORS OF {Win32_DeviceMemoryAddress.StartingAddress='" + Memory["StartingAddress"] + "'} WHERE RESULTCLASS = Win32_PnPEntity").Get())
{
Console.WriteLine(" Pnp Device =" + Pnp["Caption"]);
// associate Pnp Devices with IRQ
foreach(ManagementObject IRQ in new ManagementObjectSearcher(
"ASSOCIATORS OF {Win32_PnPEntity.DeviceID='" + Pnp["PNPDeviceID"] + "'} WHERE RESULTCLASS = Win32_IRQResource").Get())
{
Console.WriteLine(" IRQ=" + IRQ["Name"]);
}
}
}
Console.ReadLine();
}
}
}

Using win32_NetworkAdapterSettings to query a specific NIC. C#

Im trying to get tcp/ip info and physical info from a NIC card. I have queries for both (from win_32 NetworkAdapter and win32_NetworkAdapterConfiguration) But i want to join them together so i can select a specific network card from a combobox and get both sets of info.
I have been told I can use win_32 NetworkAdaptersetting but Im pretty new to this stuff so I don't know how!! It must be in c#.
Here is an example:
using System;
using System.Management;
namespace WMITest
{
class Program
{
static void Main(string[] args)
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(
"Select * From Win32_NetworkAdapter");
foreach (ManagementObject adapter in searcher.Get())
{
Console.WriteLine(adapter["Name"]);
foreach(ManagementObject configuration in
adapter.GetRelated("Win32_NetworkAdapterConfiguration"))
{
Console.WriteLine(configuration["Caption"]);
}
Console.WriteLine();
}
}
}
}

Powershell Command in C#

I am trying to query the names all of the WMI classes within the root\CIMV2 namespace. Is there a way to use a powershell command to retrieve this information in C# ?
Along the lines of Keith's approach
using System;
using System.Management.Automation;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var script = #"
Get-WmiObject -list -namespace root\cimv2 | Foreach {$_.Name}
";
var powerShell = PowerShell.Create();
powerShell.AddScript(script);
foreach (var className in powerShell.Invoke())
{
Console.WriteLine(className);
}
}
}
}
I'm not sure why you mentioned PowerShell; you can do this in pure C# and WMI (the System.Management namespace, that is).
To get a list of all WMI classes, use the SELECT * FROM Meta_Class query:
using System.Management;
...
try
{
EnumerationOptions options = new EnumerationOptions();
options.ReturnImmediately = true;
options.Rewindable = false;
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\cimv2", "SELECT * FROM Meta_Class", options);
ManagementObjectCollection classes = searcher.Get();
foreach (ManagementClass cls in classes)
{
Console.WriteLine(cls.ClassPath.ClassName);
}
}
catch (ManagementException exception)
{
Console.WriteLine(exception.Message);
}
Personally I would go with Helen's approach and eliminate taking a dependency on PowerShell. That said, here's how you would code this in C# to use PowerShell to retrieve the desired info:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Management.Automation;
namespace RunspaceInvokeExp
{
class Program
{
static void Main()
{
using (var invoker = new RunspaceInvoke())
{
string command = #"Get-WmiObject -list -namespace root\cimv2" +
" | Foreach {$_.Name}";
Collection<PSObject> results = invoker.Invoke(command);
var classNames = results.Select(ps => (string)ps.BaseObject);
foreach (var name in classNames)
{
Console.WriteLine(name);
}
}
}
}
}
Just to note that there is a tool available that allows you to create, run, and save WMI scripts written in PowerShell, the PowerShell Scriptomatic tool, available for download from the Microsoft TechNet site.
Using this tool, you could explore all of the WMI classes within the root\CIMV2 or any other WMI namespace.
You'd probably want to just use the System.Management namespace like Helen answered, but you can also host powershell within your application. See http://www.codeproject.com/KB/cs/HowToRunPowerShell.aspx

Can I print a standard test page in code-behind in .NET 3.5?

Is there a way to print a standard test page in WPF from C# code if I have the name of a network printer?
Thanks!
The following is an example of using the System.Management namespace to access WMI and print a Test Page to a Printer. This relies on the Printer being connected to the Computer, I can provide code for connecting a Network printer through System.Management if you want that as well. This code should work for any version of the .Net Framework
using System;
using System.Management;
public class PrintTestPageUsingWMI
{
private String _name;
private ManagementObject _printer = null;
public PrintTestPageUsingWMI(String printerName)
{
this._name = printerName;
//Find the Win32_Printer which is a Network Printer of this name
//Declare WMI Variables
ManagementObject MgmtObject;
ManagementObjectCollection MgmtCollection;
ManagementObjectSearcher MgmtSearcher;
//Perform the search for printers and return the listing as a collection
MgmtSearcher = new ManagementObjectSearcher("Select * from Win32_Printer");
MgmtCollection = MgmtSearcher.Get();
foreach (ManagementObject objWMI in MgmtCollection)
{
if (objWMI.Item("sharename").ToString().Equals(this._name))
{
this._printer = objWMI;
}
}
if (this._printer == null)
{
throw new Exception("Selected Printer is not connected to this Computer");
}
}
public void PrintTestPage()
{
this.InvokeWMIMethod("PrintTestPage");
}
/// <summary>
/// Helper Method which Invokes WMI Methods on this Printer
/// </summary>
/// <param name="method">The name of the WMI Method to Invoke</param>
/// <remarks></remarks>
private void InvokeWMIMethod(String method) {
if (this._printer == null)
{
throw new Exception("Can't Print a Test Page on a Printer which is not connected to the Computer");
}
Object[] objTemp = new Object[0] { null };
ManagementObject objWMI;
//Invoke the WMI Method
this._printer.InvokeMethod(method, objTemp);
}
}
Alternatively you could look at the System.Printing Namespace which is supported in .Net 3.0 and higher
It should be possible using prnadmin.dll. You most probably will have to create the printer in windows first (either by code or with the user interface) if it's not already configured on the workstation.
http://support.microsoft.com/kb/321025
http://www.codeproject.com/KB/cs/PrinterAdmin.aspx?display=Print

Categories