Create domain in windows Dns using C # [duplicate] - c#

I need some sample code to create/delete zone and A record in microsoft DNS server by C#

You have to use WMI to invoke the DNSProvider.
This to add a record:
public void AddARecord(string hostName, string zone, string iPAddress, string dnsServerName)
{
ManagementScope scope =
new ManagementScope(#"\\" + dnsServerName + "\\root\\MicrosoftDNS");
scope.Connect();
ManagementClass cmiClass =
new ManagementClass(scope,
new ManagementPath("MicrosoftDNS_AType"),
null);
ManagementBaseObject inParams =
cmiClass.GetMethodParameters("CreateInstanceFromPropertyData");
inParams["DnsServerName"] = this.ServerName;
inParams["ContainerName"] = zone;
inParams["OwnerName"] = hostName + "." + zone;
inParams["IPAddress"] = iPAddress;
cmiClass.InvokeMethod("CreateInstanceFromPropertyData", inParams, null);
}
You can reference the WMI reference and extend this as you need using the methods and classes
http://msdn.microsoft.com/en-us/library/ms682123(v=vs.85).aspx

Microsoft exposes it as a POX service, so you could just push XML over the wire to it, using the System.Net stuff & your user credentials.
http://technet.microsoft.com/en-us/library/dd278634.aspx

I agreed with Taylor but in my case i have got 2 different error with above code
1- Generic Error
2- Not Found error
Below code has solved this problems
private ManagementPath UpdateARecord(string strDNSZone, string strHostName, string strIPAddress)
{
ManagementScope mgmtScope = new ManagementScope(#"\\.\Root\MicrosoftDNS");
ManagementClass mgmtClass = null;
ManagementBaseObject mgmtParams = null;
ManagementObjectSearcher mgmtSearch = null;
ManagementObjectCollection mgmtDNSRecords = null;
string strQuery;
strQuery = string.Format("SELECT * FROM MicrosoftDNS_AType WHERE OwnerName = '{0}.{1}'", strHostName, strDNSZone);
mgmtScope.Connect();
mgmtSearch = new ManagementObjectSearcher(mgmtScope, new ObjectQuery(strQuery));
mgmtDNSRecords = mgmtSearch.Get();
//// Multiple A records with the same record name, but different IPv4 addresses, skip.
//if (mgmtDNSRecords.Count > 1)
//{
// // Take appropriate action here.
//}
//// Existing A record found, update record.
//else
if (mgmtDNSRecords.Count == 1)
{
ManagementObject mo = new ManagementObject();
foreach (ManagementObject mgmtDNSRecord in mgmtDNSRecords)
{
if (mgmtDNSRecord["RecordData"].ToString() != strIPAddress)
{
mgmtParams = mgmtDNSRecord.GetMethodParameters("Modify");
mgmtParams["IPAddress"] = strIPAddress;
mgmtDNSRecord.InvokeMethod("Modify", mgmtParams, null);
}
mo = mgmtDNSRecord;
break;
}
return new ManagementPath(mo["RR"].ToString());
}
// A record does not exist, create new record.
else
{
mgmtClass = new ManagementClass(mgmtScope, new ManagementPath("MicrosoftDNS_AType"), null);
mgmtParams = mgmtClass.GetMethodParameters("CreateInstanceFromPropertyData");
mgmtParams["DnsServerName"] = Environment.MachineName;
mgmtParams["ContainerName"] = strDNSZone;
mgmtParams["OwnerName"] = strDNSZone;// string.Format("{0}.{1}", strHostName.ToLower(), strDNSZone);
mgmtParams["IPAddress"] = strIPAddress;
var outParams = mgmtClass.InvokeMethod("CreateInstanceFromPropertyData", mgmtParams, null);
if ((outParams.Properties["RR"] != null))
{
return new ManagementPath(outParams["RR"].ToString());
}
}
return null;
}

Related

WMI does not return expected service, ServiceController identifies OK

I'm trying to identify if a certain service on a remote PC is running or not and identify its start up type.
Using ServiceController I can successfully see the expected service on the remote machine but when switching to use WMI to drill deeper this service no longer appears.
Heres my code:
public static void Main()
{
var ctl = ServiceController.GetServices("[Name]");
List<string> namelist = new List<string>();
foreach (var x in ctl)
{
if (x.DisplayName == "NHS Card Checker")
{
Console.WriteLine(string.Format("NHS Card checker found on MPC - Status: {0}", x.Status));
ConnectionOptions options = new ConnectionOptions();
options.Impersonation = System.Management.ImpersonationLevel.Impersonate;
ManagementScope scope = new ManagementScope(#"[Name]\root\cimv2");
scope.Connect();
string wmiQuery = string.Format("Select * from Win32_Service", x.DisplayName);
ManagementObjectSearcher wmi = new ManagementObjectSearcher(wmiQuery);
ManagementObjectCollection coll = wmi.Get();
foreach (var service in coll)
{
Console.WriteLine(string.Format("{0} - {1}", service["Name"].ToString(), service["StartMode"].ToString()) );
}
}
}
Console.ReadKey();
}
Looks good for the most part. I would lead the scope with "\\" before your machine name. Also, if you are just looking for one specific service, add a WHERE clause to your query.
public static void Main()
{
string MachineName = "[Name]";
var ctl = ServiceController.GetServices(MachineName);
List<string> namelist = new List<string>();
foreach (var x in ctl)
{
if (x.DisplayName == "NHS Card Checker")
{
Console.WriteLine(string.Format("NHS Card checker found on MPC - Status: {0}", x.Status));
ConnectionOptions options = new ConnectionOptions();
options.Impersonation = System.Management.ImpersonationLevel.Impersonate;
ManagementScope scope = new ManagementScope(String.Format(#"\\{0}\root\cimv2", MachineName));
scope.Connect();
string wmiQuery = string.Format("Select * from Win32_Service WHERE DisplayName='{0}'" , x.DisplayName);
ManagementObjectSearcher wmi = new ManagementObjectSearcher(wmiQuery);
ManagementObjectCollection coll = wmi.Get();
foreach (var service in coll)
{
Console.WriteLine(string.Format("{0} - {1}", service["Name"].ToString(), service["StartMode"].ToString()));
}
}
}
Console.ReadKey();
}
or maybe simplify it to only use WMI like...
string MachineName = "[Name]";
string TargetService = "NHS Card Checker";
{
ConnectionOptions options = new ConnectionOptions();
options.Impersonation = System.Management.ImpersonationLevel.Impersonate;
ManagementScope scope = new ManagementScope(String.Format(#"\\{0}\root\cimv2", MachineName));
scope.Connect();
string wmiQuery = String.Format("Select * from Win32_Service WHERE DisplayName='{0}'", TargetService);
ManagementObjectSearcher wmi = new ManagementObjectSearcher(wmiQuery);
ManagementObjectCollection coll = wmi.Get();
if (coll.Count > 0)
{
foreach (var service in coll)
{
Console.WriteLine(string.Format("NHS Card checker found on MPC - Status: {0}", service["Status"].ToString()));
Console.WriteLine(string.Format("{0} - {1}", service["Name"].ToString(), service["StartMode"].ToString()));
}
}
else
{
Console.WriteLine(string.Format("{0} Service was not found", TargetService));
}
}
}
Also, in newer implementations of C# you can use an easier variance of string interpolation. Instead of...
string.format("{0} is your value", VariableName");
you can use
$"{VariableName} is your value";

Invocation of Win32_Service UserControlService not working

I'm using WMI to install/start/stop etc. services on a remote machine. This is working nicely, only the invocation of the UserControlService seems to be a problem.
I know that it would also be possible to impersonate a user and then use the ServiceController class, but as I've already got all other methods I would rather keep the WMI code and get my method to send service control requests working.
Following code:
public static string SendServiceControlRequest(string remoteHost, string serviceName, string username,
string password, int request)
{
ConnectionOptions theConnection = new ConnectionOptions();
theConnection.Username = username;
theConnection.Password = password;
ManagementScope theScope = new ManagementScope(string.Format("\\\\{0}\\root\\cimv2", remoteHost), theConnection);
using (ManagementObject theClass = new ManagementObject(theScope, new ManagementPath("Win32_Service"),
new ObjectGetOptions())) // causes an ArgumentOutOfRangeException (Parametername: path)
{
using (ManagementBaseObject inParams = theClass.GetMethodParameters("UserControlService"))
{
inParams["ControlCode"] = (Byte)request;
ManagementBaseObject outParams = theClass.InvokeMethod("UserControlService", inParams, null);
return outParams["ReturnValue"].ToString();
}
}
}
Throws a System.Management.ManagementException complaining about invalid parameters (with request of 150, which should work). The exception is thrown on theClass.InvokeMethod I'm not sure why this happen, I'm getting the description of the method from:
http://msdn.microsoft.com/en-us/library/aa393952(v=vs.85).aspx
Edit: Working version with the corrections by Hans Passant:
public static bool SendServiceControlRequest(string remoteHost, string serviceName, string username,
string password, int request)
{
ConnectionOptions theConnection = new ConnectionOptions();
theConnection.Username = username;
theConnection.Password = password;
ManagementScope theScope = new ManagementScope(string.Format("\\\\{0}\\root\\cimv2", remoteHost),
theConnection);
string servicePath = string.Format("Win32_Service.Name='{0}'", serviceName);
ManagementPath path = new ManagementPath(servicePath);
using (ManagementObject theClass = new ManagementObject(theScope, path,
new ObjectGetOptions()))
{
using (ManagementBaseObject inParams = theClass.GetMethodParameters("UserControlService"))
{
inParams["ControlCode"] = (Byte)request;
ManagementBaseObject outParams = theClass.InvokeMethod("UserControlService", inParams, null);
return outParams["ReturnValue"].ToString() == "0";
}
}
}
Yes, there's a bug in your code. You correctly added a serviceName argument to your method but you forgot to actually use it. That's important, you really do have to be specific about what particular service you send this control code to.
Make it look like this instead:
var path = string.Format("Win32_Service.Name='{0}'", serviceName);
var thePath = new ManagementPath(path);
var theClass = new ManagementObject(theScope, thePath, null);
// etc...
Instead of
inParams["ControlCode"] = (Byte)request;
try
inParams.SetPropertyValue("ControlCode", (Byte)request);
EDIT
Untested, but this seems to be what you might be looking for:
Instead of
using (ManagementBaseObject inParams = theClass.GetMethodParameters("UserControlService"))
{
inParams["ControlCode"] = (Byte)request;
ManagementBaseObject outParams = theClass.InvokeMethod("UserControlService", inParams, null);
return outParams["ReturnValue"].ToString();
}
Try utilizing the ManagementClass instances (from http://social.msdn.microsoft.com/Forums/vstudio/en-US/1dbe4995-ce73-4f01-8d9a-6cf1650bce8a/wmi-c-managementclassinvokemethod-failure):
foreach (var instance in theClass.GetInstances())
{
using (ManagementBaseObject inParams = instance.GetMethodParameters("UserControlService"))
{
inParams["ControlCode"] = (Byte)request;
ManagementBaseObject outParams = instance.InvokeMethod("UserControlService", inParams, null);
return outParams["ReturnValue"].ToString();
}
}

how to get logged on users with their status on remote machine

I'm looking for a way to get the users that are logged in on a remote machine. I would love to know if they are logged on localy or remotely, but most of all I MUST know their status.
I saw some answers on the net that are written in VB, but I need it in c#.
the solution given in markdmak answer here is looking like a good start, but it's in VB and it looks for remote sessions only.
I have this piece of code, which can be a start, but I would like to couple the LogonId to a username and to see its status:
string fqdn = ""; // set!!!
ConnectionOptions options = new ConnectionOptions();
options.EnablePrivileges = true;
// To connect to the remote computer using a different account, specify these values:
// these are needed in dev environment
options.Username = ConfigurationManager.AppSettings["KerberosImpersonationUser"];
options.Password = ConfigurationManager.AppSettings["KerberosImpersonationPassword"];
options.Authority = "ntlmdomain:" + ConfigurationManager.AppSettings["KerberosImpersonationDomain"];
ManagementScope scope = new ManagementScope("\\\\" + fqdn + "\\root\\CIMV2", options);
try
{
scope.Connect();
}
catch (Exception ex)
{
if (ex.Message.StartsWith("The RPC server is unavailable"))
{
// The Remote Procedure Call server is unavailable
// cannot check for logged on users
return false;
}
else
{
throw ex;
}
}
SelectQuery query = new SelectQuery("Select * from Win32_LogonSession");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection results = searcher.Get();
bool returnVal = false;
foreach (ManagementObject os in results)
{
try
{
if (os.GetPropertyValue("LogonId").ToString() != null && os.GetPropertyValue("LogonId").ToString() != "")
{
returnVal = true;
}
}
catch (NullReferenceException)
{
continue;
}
}
return returnVal;
}
What I really need and can't find, is a way of getting ALL users on a remote machine AND their status, meaning: Active, Disconnected, Logged-off, etc.
You can use the Win32_LogonSession WMI class filtering for the LogonType property with the value 2 (Interactive)
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 = "remote-machine";
ManagementScope Scope;
if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
{
ConnectionOptions Conn = new ConnectionOptions();
Conn.Username = "username";
Conn.Password = "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();
ObjectQuery Query = new ObjectQuery("SELECT LogonId FROM Win32_LogonSession Where LogonType=2");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
foreach (ManagementObject WmiObject in Searcher.Get())
{
Console.WriteLine("{0,-35} {1,-40}", "LogonId", WmiObject["LogonId"]);// String
ObjectQuery LQuery = new ObjectQuery("Associators of {Win32_LogonSession.LogonId=" + WmiObject["LogonId"] + "} Where AssocClass=Win32_LoggedOnUser Role=Dependent");
ManagementObjectSearcher LSearcher = new ManagementObjectSearcher(Scope, LQuery);
foreach (ManagementObject LWmiObject in LSearcher.Get())
{
Console.WriteLine("{0,-35} {1,-40}", "Name", LWmiObject["Name"]);
}
}
}
catch (Exception e)
{
Console.WriteLine(String.Format("Exception {0} Trace {1}", e.Message, e.StackTrace));
}
Console.WriteLine("Press Enter to exit");
Console.Read();
}
}
}
#RRUZ got me started but the Associators query did not work on remote machine with a lot of Win32_LoggedOnUser objects (don't know why). No results were returned.
I also needed remote Desktop sessions so I used LogonType "10" sessions and my ConnectionOptions were differents
I replaced the Associators query with WmiObject.GetRelationships("Win32_LoggedOnUser") and the speed increases by a lot and results were there.
private void btnUnleash_Click(object sender, EventArgs e)
{
string serverName = "serverName";
foreach (var user in GetLoggedUser(serverName))
{
dataGridView1.Rows.Add(serverName, user);
}
}
private List<string> GetLoggedUser(string machineName)
{
List<string> users = new List<string>();
try
{
var scope = GetManagementScope(machineName);
scope.Connect();
var Query = new SelectQuery("SELECT LogonId FROM Win32_LogonSession Where LogonType=10");
var Searcher = new ManagementObjectSearcher(scope, Query);
var regName = new Regex(#"(?<=Name="").*(?="")");
foreach (ManagementObject WmiObject in Searcher.Get())
{
foreach (ManagementObject LWmiObject in WmiObject.GetRelationships("Win32_LoggedOnUser"))
{
users.Add(regName.Match(LWmiObject["Antecedent"].ToString()).Value);
}
}
}
catch (Exception ex)
{
users.Add(ex.Message);
}
return users;
}
private static ManagementScope GetManagementScope(string machineName)
{
ManagementScope Scope;
if (machineName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", "."), GetConnectionOptions());
else
{
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", machineName), GetConnectionOptions());
}
return Scope;
}
private static ConnectionOptions GetConnectionOptions()
{
var connection = new ConnectionOptions
{
EnablePrivileges = true,
Authentication = AuthenticationLevel.PacketPrivacy,
Impersonation = ImpersonationLevel.Impersonate,
};
return connection;
}

Change remote IP address programmatically using WMI

I am writing an application to change the IP addresses of local and remote machines using WMI. This code successfully changes the gateway and DNS of the remote machine and the same code (in a different class and minus the management scope part) changes all of the data (the two IPs, gateway, DNS) locally. The problem is it doesn't change the remote IP address. Please can someone advise as I have looked everywhere for this answer?
I have tested on windows 7 and xp with no firewalls and with .net 4 installed on remote machines
class remoteIPChange
{
public string setTillIP(string IPAddress1, string IPAddress2, string SubnetMask, string Gateway)
{
ConnectionOptions connection = new ConnectionOptions();
connection.Username = "username";
connection.Password = "password";
connection.Authority = "ntlmdomain:DOMAIN";
ManagementScope scope = new ManagementScope(
"\\\\"+IPAddress1+"\\root\\CIMV2", connection);
scope.Connect();
ObjectGetOptions o = new ObjectGetOptions();
ManagementPath p = new ManagementPath("Win32_NetworkAdapterConfiguration");
ManagementClass objMC = new ManagementClass(scope,p,o);
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if (!(bool)objMO["IPEnabled"])
continue;
try
{
ManagementBaseObject objNewIP = null;
ManagementBaseObject objSetIP = null;
ManagementBaseObject objNewGate = null;
ManagementBaseObject objNewDNS = null;
objNewIP = objMO.GetMethodParameters("EnableStatic");
objNewGate = objMO.GetMethodParameters("SetGateways");
objNewDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder");
//Set DefaultGateway
objNewGate["DefaultIPGateway"] = new string[] { Gateway };
objNewGate["GatewayCostMetric"] = new int[] { 1 };
//Set IPAddress and Subnet Mask
objNewIP["IPAddress"] = new string[] { IPAddress1, IPAddress2 };
objNewIP["SubnetMask"] = new string[] { SubnetMask, SubnetMask };
//Set DNS servers
objNewDNS["DNSServerSearchOrder"] = new string[] {Gateway };
//Invoke all changes
objSetIP = objMO.InvokeMethod("EnableStatic", objNewIP, null);
objSetIP = objMO.InvokeMethod("SetGateways", objNewGate, null);
objSetIP = objMO.InvokeMethod("SetDNSServerSearchOrder", objNewDNS, null);
return ("Updated IPAddress to " + IPAddress + ", \nSubnetMask to " + SubnetMask + " \nand Default Gateway to " + Gateway + "!");
}
catch (Exception ex)
{
return ("Unable to Set IP : " + ex.Message);
}
}
return "code has not run";
}
}
I would check the ReturnValue from the invokemethod on EnableStatic. I am pretty sure passing in a null for your subnet is your problem. Provide a valid array of subnets that match your ip addresses instead of that null.

Manage DNS server by C# code

I need some sample code to create/delete zone and A record in microsoft DNS server by C#
You have to use WMI to invoke the DNSProvider.
This to add a record:
public void AddARecord(string hostName, string zone, string iPAddress, string dnsServerName)
{
ManagementScope scope =
new ManagementScope(#"\\" + dnsServerName + "\\root\\MicrosoftDNS");
scope.Connect();
ManagementClass cmiClass =
new ManagementClass(scope,
new ManagementPath("MicrosoftDNS_AType"),
null);
ManagementBaseObject inParams =
cmiClass.GetMethodParameters("CreateInstanceFromPropertyData");
inParams["DnsServerName"] = this.ServerName;
inParams["ContainerName"] = zone;
inParams["OwnerName"] = hostName + "." + zone;
inParams["IPAddress"] = iPAddress;
cmiClass.InvokeMethod("CreateInstanceFromPropertyData", inParams, null);
}
You can reference the WMI reference and extend this as you need using the methods and classes
http://msdn.microsoft.com/en-us/library/ms682123(v=vs.85).aspx
Microsoft exposes it as a POX service, so you could just push XML over the wire to it, using the System.Net stuff & your user credentials.
http://technet.microsoft.com/en-us/library/dd278634.aspx
I agreed with Taylor but in my case i have got 2 different error with above code
1- Generic Error
2- Not Found error
Below code has solved this problems
private ManagementPath UpdateARecord(string strDNSZone, string strHostName, string strIPAddress)
{
ManagementScope mgmtScope = new ManagementScope(#"\\.\Root\MicrosoftDNS");
ManagementClass mgmtClass = null;
ManagementBaseObject mgmtParams = null;
ManagementObjectSearcher mgmtSearch = null;
ManagementObjectCollection mgmtDNSRecords = null;
string strQuery;
strQuery = string.Format("SELECT * FROM MicrosoftDNS_AType WHERE OwnerName = '{0}.{1}'", strHostName, strDNSZone);
mgmtScope.Connect();
mgmtSearch = new ManagementObjectSearcher(mgmtScope, new ObjectQuery(strQuery));
mgmtDNSRecords = mgmtSearch.Get();
//// Multiple A records with the same record name, but different IPv4 addresses, skip.
//if (mgmtDNSRecords.Count > 1)
//{
// // Take appropriate action here.
//}
//// Existing A record found, update record.
//else
if (mgmtDNSRecords.Count == 1)
{
ManagementObject mo = new ManagementObject();
foreach (ManagementObject mgmtDNSRecord in mgmtDNSRecords)
{
if (mgmtDNSRecord["RecordData"].ToString() != strIPAddress)
{
mgmtParams = mgmtDNSRecord.GetMethodParameters("Modify");
mgmtParams["IPAddress"] = strIPAddress;
mgmtDNSRecord.InvokeMethod("Modify", mgmtParams, null);
}
mo = mgmtDNSRecord;
break;
}
return new ManagementPath(mo["RR"].ToString());
}
// A record does not exist, create new record.
else
{
mgmtClass = new ManagementClass(mgmtScope, new ManagementPath("MicrosoftDNS_AType"), null);
mgmtParams = mgmtClass.GetMethodParameters("CreateInstanceFromPropertyData");
mgmtParams["DnsServerName"] = Environment.MachineName;
mgmtParams["ContainerName"] = strDNSZone;
mgmtParams["OwnerName"] = strDNSZone;// string.Format("{0}.{1}", strHostName.ToLower(), strDNSZone);
mgmtParams["IPAddress"] = strIPAddress;
var outParams = mgmtClass.InvokeMethod("CreateInstanceFromPropertyData", mgmtParams, null);
if ((outParams.Properties["RR"] != null))
{
return new ManagementPath(outParams["RR"].ToString());
}
}
return null;
}

Categories

Resources