Trying to add a hostname to a domain group, and I'm getting the exception There is a naming violation.
I've seen several accepted answers covering this exact thing and as far as I know my syntax is correct.
try
{
DirectoryEntry de = new DirectoryEntry("LDAP://aa.bbbbb.com/CN=Group,OU=Application,OU=Groups,OU=US,DC=aa,DC=bbbbb,DC=com");
string hostname = "CN=" + SystemInformation.ComputerName;
DirectoryEntry add = de.Children.Add(hostname, "Computer");
add.CommitChanges();
}
catch (Exception ex)
{
MessageBox.Show("Group join failed" + Environment.NewLine + Environment.NewLine + ex.ToString());
}
Any help would be greatly appreciated.
I figured out what the problem was - I needed to pass the Distinguished Name, rather than just the hostname... that should have been obvious, if I had actually read the MSDN doc... Also, de.Children.Add() may be a valid method to accomplish this (it was an accepted answer on SE, for .Net 3.5 IIRC), but I used de.Properties["member"].Add() to accomplish it.
Updated source code for any Googlers out there:
private void DoStuff(object sender, EventArgs e)
{
using (Process addgroup = new Process())
{
string hostname = Environment.MachineName;
AddMemberToGroup("LDAP://aa.bbbbb.com/CN=Group,OU=Application,OU=Group,OU=US,DC=aa,DC=bbbbb,DC=com", hostname);
}
}
private void AddMemberToGroup(string ldapString, string host)
{
try
{
DirectoryEntry de = new DirectoryEntry(ldapString);
string distHost = GetDistinguishedName(host);
if (!String.IsNullOrEmpty(distHost))
{
de.Properties["member"].Add(distHost);
de.CommitChanges();
}
else
{
MessageBox.Show("Distinguished Host Name returned NULL");
}
}
catch(Exception ex)
{
MessageBox.Show("Group join failed" + Environment.NewLine + Environment.NewLine + ex.ToString());
}
}
private string GetDistinguishedName(string compName)
{
try
{
PrincipalContext pContext = new PrincipalContext(ContextType.Domain);
ComputerPrincipal compPrincipal = ComputerPrincipal.FindByIdentity(pContext, compName);
return compPrincipal.DistinguishedName;
}
catch (Exception ex)
{
MessageBox.Show("Failed to get the Distinguished Hostname from Active Directory" + Environment.NewLine + Environment.NewLine + ex.ToString());
return null;
}
}
Related
My code try to check is the PostgreSQL server running and accessible by given credentials for given database. Use the Npgsql NuGet. If all the data, also IP, Port, User, Pass and Database are correct, the code returns true.
Here is a code:
public Boolean InsertInToPGSQL()
{
var pg_con_string = "Server=" + sqlinsertserver + ";" + "Port=" + sqlinsertport + ";" + "Database=" + sqlinsertdatabase + ";" + "User ID=" + sqlinsertusername + ";" + "Password=" + sqlinsertpassword + ";";
var pg_connetion = new NpgsqlConnection(pg_con_string);
try
{
if (pg_connetion != null)
{
pg_connetion.Open();
pg_connetion.Close();
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
The problem is if i write an IP address where is no server running, or bad port, or wrong user/pass, database, i receive always on:
pg_connetion.Open();
An error:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
The problem is that a catch (Exception) don't catch this error and returns simple false.
I don't need to deal with type of errors, like wrong credential or IP / port, just need to have true on successful connection to the PostgreSQL server and false for any other case.
How to deal with this error?
To get exception details you need to do catch(Exception ex) and within catch block you can do ex.InnerException or ex.Message to find the exception details. In your case, the connection object is null because of incorrect parameters. I would do a null check on connection object before connection.open() which would avoid object ref not set to instance. Hope that should suffice your need. Change your code to following and send me the ex.Message and ex.InnerException values.
public static class Application
{
public static void Main()
{
if (InsertInToPGSQL())
Console.WriteLine("Connection successful");
else
Console.WriteLine("Connection failed");
Console.ReadLine();
}
public static Boolean InsertInToPGSQL()
{
var pg_con_string = "";
var pg_connetion = new NpgsqlConnection(pg_con_string);
try
{
if (pg_connetion != null)
{
pg_connetion.Open();
pg_connetion.Close();
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
return false;
}
}
}
``
Maybe late, but for those like me who felt on this thread it can be usefull.
I faced the same issue until i update the NpSql nuget package. I was on 4.0.3, and update to 4.1.10. Finaly it fixed the problem.
I want to create a service for Wifi Direct. If I try to add Reference, I don't see core->windows option in VS2013. I have updated the winSDK.
How do I add the Windows.Devices.WifiDirect api ?
you can use
public sealed class WiFiDirectDevice : IDisposable
this is a sample code to handle connections
Windows.Devices.WiFiDirect.WiFiDirectDevice wfdDevice;
private async System.Threading.Tasks.Task<String> Connect(string deviceId)
{
string result = "";
try
{
// No device Id specified.
if (String.IsNullOrEmpty(deviceId)) { return "Please specify a Wi- Fi Direct device Id."; }
// Connect to the selected Wi-Fi Direct device.
wfdDevice = await Windows.Devices.WiFiDirect.WiFiDirectDevice.FromIdAsync(deviceId);
if (wfdDevice == null)
{
result = "Connection to " + deviceId + " failed.";
}
// Register for connection status change notification.
wfdDevice.ConnectionStatusChanged += new TypedEventHandler<Windows.Devices.WiFiDirect.WiFiDirectDevice, object>(OnConnectionChanged);
// Get the EndpointPair information.
var EndpointPairCollection = wfdDevice.GetConnectionEndpointPairs();
if (EndpointPairCollection.Count > 0)
{
var endpointPair = EndpointPairCollection[0];
result = "Local IP address " + endpointPair.LocalHostName.ToString() +
" connected to remote IP address " + endpointPair.RemoteHostName.ToString();
}
else
{
result = "Connection to " + deviceId + " failed.";
}
}
catch (Exception err)
{
// Handle error.
result = "Error occurred: " + err.Message;
}
return result;
}
private void OnConnectionChanged(object sender, object arg)
{
Windows.Devices.WiFiDirect.WiFiDirectConnectionStatus status =
(Windows.Devices.WiFiDirect.WiFiDirectConnectionStatus)arg;
if (status == Windows.Devices.WiFiDirect.WiFiDirectConnectionStatus.Connected)
{
// Connection successful.
}
else
{
// Disconnected.
Disconnect();
}
}
private void Disconnect()
{
if (wfdDevice != null)
{
wfdDevice.Dispose();
}
}
I am trying to add some logging functionality to a service, however I want it to create a new log, copy the old log into the new one and delete the original.
Sudo for ClearLog: if log1 full create log2, delete contents of log1
Please see code below, currently the ClearLog function is not doing what I want.
Can anyone see what I'm doing wrong?
public static void WriteLog(string txt)
{
string fp = _AppPath + #"\Logging";
try
{
File.AppendAllText(fp + #"\Log1.txt", txt);
}
catch (IOException iex)
{
Debug.Print("Error writing log" + iex.ToString());
}
}
private static void ClearLog()
{
string fp = _AppPath + #"\Logging";
try
{
if (!File.Exists(fp + #"\Log1.txt"))
{
WriteErrorLog("");
}
else
{
File.AppendAllText(fp + #"\Log1.txt", fp + #"\Log2.txt");
File.Delete(fp + #"\Log1.txt");
WriteLog("");
}
}
catch (Exception ex)
{
WriteLog("Clear log failed " + ex.ToString());
}
}
Try creating a public static field of the file path, as you're opening the same file twice it seems.
IE: public static string logfp = _AppPath + #"\Logging";
Then rename everything in those two functions logfp.
Improved example (can use paths in both or declared throughout)
private static void ClearLog()
{
string logfp = _AppPath + #"\Logging";
try
{
if (File.Exists(logfp + #"\Log2.txt"))
{
File.Delete(logfp + #"\Log2.txt");
if (File.Exists(logfp + #"\Log1.txt"))
{
File.Copy(logfp + #"\Log1.txt", logfp + #"\Log2.txt");
File.Delete(logfp + #"\Log1.txt");
}
else
{
File.AppendAllText(logfp + #"\Log1.txt", "New Log created: " + DateTime.Now.ToString());//showing you when it was created
}
}
else
{
File.Copy(logfp + #"\Log1.txt", logfp + #"\Log2.txt");
File.Delete(logfp + #"\Log1.txt");
}
}
catch (Exception ex)
{
WriteErrorLog("Clear log failed " + ex.ToString());
}
}
what's a better way of doing the below try catch? Currently I have each WMI field in its own try catch statement.
I do not want to put the whole class into a massive try catch as I have issues with fields not displaying anything back (tried this and does not work well for what I am doing).
I have about 25 other WMI fields that I need to put in and am wondering if there is a simpler way of doing this?
private void cmbHdd_SelectedIndexChanged(object sender, EventArgs e)
ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE Model = '" + cmbHdd.SelectedItem + "'");
foreach (ManagementObject moDisk in mosDisks.Get())
{
try
{
lblSystemName.Text = "SystemName: " + moDisk["systemname"];
}
catch (Exception)
{
lblSystemName.Text = "SystemName: WMI Error"; ;
}
try
{
lblType.Text = "Type: " + moDisk["MediaType"].ToString();
}
catch (Exception)
{
lblType.Text = "Type: WMI Error";
}
}
You could use a helper method:
private static string GetMOValue(ManagementObject mo, string name)
{
try
{
object result = mo[name];
return result == null ? "" : result.ToString();
}
catch(Exception)
{
return "WMI Error";
}
}
...
lblSystemName.Text = GetMOValue(moDisk, "systemname");
lblType.Text = GetMOValue(moDisk, "MediaType");
Note you should probably catch a more specific exception (not sure what exceptions can be thrown by the ManagementObject indexer).
I think erro occur when there is no data avaialbe for the given column in datatable
if (moDisk.Columns.Contains("systemname"))
{
lblSystemName.Text = "SystemName: " + moDisk["systemname"];
}
else
{
lblSystemName.Text = "SystemName: WMI Error";
}
Note : not sure this is datatable or not but you can code like this instead of catching exception for each value ... with the help of if ..else you can code this easily
I feel that using these many try catch is not good. If i were u i would have done in following method..if try catch really needed.
private void cmbHdd_SelectedIndexChanged(object sender, EventArgs e)
ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE Model = '" + cmbHdd.SelectedItem + "'");
string current= string.Empty;
foreach (ManagementObject moDisk in mosDisks.Get())
{
try
{
current = "SystemName";
lblSystemName.Text = "SystemName: " + moDisk["systemname"];
current = "MediaType";
lblType.Text = "Type: " + moDisk["MediaType"].ToString();
}
catch(Exception)
{
//print "error in" + current;
}
}
I am trying to Configure my IIS programmatically following the steps on this
msdn guide
the only difference i made was switching to winforms instead of console..
and variables instead of function parameters.
however the code throws an exception when i try to set the singleproperty value...
here is my code..
string metabasePath = "IIS://localhost/W3SVC/1234", propertyName = "ServerBindings";
object newValue = " :8080:";
try
{
DirectoryEntry path = new DirectoryEntry(metabasePath);
//when i try to retrieve the old value,it returns a null
PropertyValueCollection propValues = path.Properties[propertyName];
MessageBox.Show("7");
//the code throws an exception after messagebox,
//kinda old school debuging
path.Properties[propertyName][0] = newValue;
path.CommitChanges();
lblerror.Text = "Done";
}
catch (Exception ex)
{
if ("HRESULT 0x80005006" == ex.Message)
lblerror.Text = " Property does not exist at ";
else
lblerror.Text = "Failed in SetSingleProperty "+ ex.Message.ToString();
}
The following 'helper' methods (SetServerBinding and RemoveServerBinding) should be of use:
static void Main(string[] args)
{
using(DirectoryEntry site = new DirectoryEntry("IIS://Localhost/W3SVC/1234"))
{
SetServerBinding(":8080:", site);
RemoveServerBinding(":8080:", site);
RemoveServerBinding("172.16.4.99:8087:somesite.com", site);
SetServerBinding("172.16.4.99:8087:somesite.com", site);
}
}
public static void SetServerBinding(string binding, DirectoryEntry site)
{
if(site.Properties["ServerBindings"].Contains(binding))
{
site.Properties["ServerBindings"].Remove(binding);
return;
}
site.Properties["ServerBindings"].Add(binding);
site.CommitChanges();
}
public static void RemoveServerBinding(string binding, DirectoryEntry site)
{
if (site.Properties["ServerBindings"].Contains(binding))
{
site.Properties["ServerBindings"].Remove(binding);
}
site.CommitChanges();
}