I want to read the username and NickName of any users on my local network from server's active directory. How can I do it? Thanks alot.
public void getUser()
{
DirectoryServices.SearchResult myResult;
string filterString = string.Empty;
string EntryString = "LDAP:// <Your AD Domain here>";
DirectoryServices.DirectorySearcher myDirectorySearcher = new DirectoryServices.DirectorySearcher(new DirectoryServices.DirectoryEntry(EntryString, "Username", "Password"));
string tempStr;
string[] splStr = new string[3];
filterString = "(sAMAccountName=" + Username + ")";
myDirectorySearcher.Filter = filterString;
myDirectorySearcher.PropertiesToLoad.Add("cn");
myResult = myDirectorySearcher.FindOne();
splStr = Regex.Split(myResult.Properties("cn").Item(0).ToString, " ");
tempStr = splStr(1).ToString + " " + splStr(0).ToString;
Label1.Text = "Hello " + tempStr;
}
Related
I'm trying to create an AD using with C# and have been getting this error every time
System.DirectoryServices.DirectoryServicesCOMException: 'The specified directory service attribute or value does not exist.
I can't seem to figure out why I'm getting this
private void ccNewHire_Button_Click(object sender, EventArgs e)
{
new Thread(() =>
{
String Password = passwordLabel.Text;
String First = newHireFirstName_TextBox.Text;
String Last = newHireLastName_TextBox.Text;
String Cnname = newHireFirstName_TextBox.Text + " " + newHireLastName_TextBox.Text;
String Username = newHireFirstName_TextBox.Text + "." + newHireLastName_TextBox.Text;
String Ldap = PathtoOURedacted;
DirectoryEntry newUser = new DirectoryEntry("LDAP://PathtoOURedacted");
DirectoryEntry childEntry = newUser.Children.Add("CN=" + Cnname, "user");
newUser.Properties["sAMAccountName"].Value = Username;
newUser.Properties["givenName"].Value = First; // first name
newUser.Properties["sn"].Value = Last; // surname = last name
newUser.Properties["displayName"].Value = Cnname;
newUser.Properties["password"].Value = Password;
newUser.Properties["userAccountControl"].Value = 512;
newUser.CommitChanges();
}).Start();
}
This is your problem:
DirectoryEntry newUser = new DirectoryEntry("LDAP://PathtoOURedacted");
DirectoryEntry childEntry = newUser.Children.Add("CN=" + Cnname, "user");
You're calling the variable newUser, but you're setting it to the OU. So you end up changing the attributes on the OU, not on the actual new user object. Just rename those variables:
DirectoryEntry ou = new DirectoryEntry("LDAP://PathtoOURedacted");
DirectoryEntry newUser = ou.Children.Add("CN=" + Cnname, "user");
Also, this won't work:
newUser.Properties["password"].Value = Password;
The password attribute is unicodePwd, but it has to be set in a very specific way, which the documentation describes. In C#, that looks like this:
newUser.Properties["unicodePwd"].Value = Encoding.Unicode.GetBytes($"\"{Password}\"");
While performing queries against Active Directory Domain Services using one of the .NETs’ reference/namespace i.e., System.DirectoryServices, we are unable to create AD account containing numeric(s) in Display Name or Email Address. It’s a 2 step process, creating the mailbox and then updating all the other attributes. While creating the mailbox we are not getting any error, however while updating the attributes to the same mailbox we are getting an custom error as mailbox / sAMAccountName doesn’t exist.
We are using the same DC throughout the code. Moreover, the code is working fine if the proposing display name and email address doesn’t have numeric(s). Since the Exchange 2016 servers have been upgraded to CU8, we are facing this issue.
We are using the .NET code instead of Exchange to avoid manual intervention. It’s integrated with other systems to auto generate the mail boxes and AD accounts.
It’s a 2 step process because we can’t pass all the other attributes to the New-Mailbox cmdlet. Once the mailbox gets created, we are updating it with the other attributes.
In Event Viewer, the object was created, modified & finally deleted. The deletion is happening automatically which is exceptional.
Code Snippet
//Creating mailbox
DirectorySearcher dSearchUPN = new DirectorySearcher(deCon);
dSearchUPN.Filter = "(UserPrincipalName=" + strUserPrincipalName + ")";
SearchResult sResultUPN = dSearchUPN.FindOne();
if (sResultUPN == null)
{
//Open it
runspace.Open();
using (PowerShell powershell = PowerShell.Create())
{
powershell.Runspace = runspace;
powershell.AddCommand("New-Mailbox");
powershell.AddParameter("Name", strName);
powershell.AddParameter("UserPrincipalName", strUserPrincipalName);
powershell.AddParameter("Alias", strAlias);
powershell.AddParameter("PrimarySmtpAddress", strPrimarySmtpAddress);
powershell.AddParameter("OrganizationalUnit", strOrganizationalUnit);
powershell.AddParameter("Database", strDatabase);
powershell.AddParameter("SamAccountName", strSamAccountName);
powershell.AddParameter("Password", strPassword);
powershell.AddParameter("ResetPasswordOnNextLogon", true);
powershell.AddParameter("DomainController", "ABCDWXYZADC2.corp.cyient.com");
powershell.Invoke();
}
//Logic for Display Name & Email Address for duplicate First Name & Last Name
int i = 1;
while (!string.IsNullOrEmpty(searchEmailAddress(strPrimarySmtpAddress)))
{
i = i + 1;
strName = dr["firstName"].ToString().Replace(".", "") + " " + dr["lastName"].ToString().Replace(".", "") + " " + dr["workerID"].ToString();
strPrimarySmtpAddress = dr["firstName"].ToString().Replace(" ", "").Replace(".", "") + "." + dr["lastName"].ToString().Replace(" ", "").Replace(".", "") + i.ToString() + strSMTPDomain;
}
//Updating mailbox
DirectorySearcher dSearch;
dSearch = new DirectorySearcher(deCon);
//Filtering AccountName with Database Domain
dSearch.Filter = "(sAMAccountName=" + strSamAccountName + ")";
SearchResult sResult = dSearch.FindOne();
if (sResult != null) //Check if the Account is available
{
DirectoryEntry deToUpdate = sResult.GetDirectoryEntry();
if (!string.IsNullOrEmpty(strEmployeeNumber))
{
deToUpdate.Properties["employeeNumber"].Value = strEmployeeNumber;
strToDisplay = strToDisplay + "\r\nEmployee Number: " + strEmployeeNumber;
}
if (!string.IsNullOrEmpty(strEmployeeType))
{
deToUpdate.Properties["employeeType"].Value = strEmployeeType;
strToDisplay = strToDisplay + "\r\nEmployee Type: " + strEmployeeType;
}
if (!string.IsNullOrEmpty(strGivenName))
{
deToUpdate.Properties["givenName"].Value = strGivenName;
strToDisplay = strToDisplay + "\r\nFirst Name: " + strGivenName;
}
if (!string.IsNullOrEmpty(strSurName))
{
deToUpdate.Properties["sn"].Value = strSurName;
strToDisplay = strToDisplay + "\r\nLast Name:" + strSurName;
}
if (!string.IsNullOrEmpty(strTitle))
{
deToUpdate.Properties["title"].Value = strTitle;
strToDisplay = strToDisplay + "\r\nTitle: " + strTitle;
}
if (!string.IsNullOrEmpty(strCompany))
{
deToUpdate.Properties["company"].Value = strCompany;
strToDisplay = strToDisplay + "\r\nCompany: " + strCompany;
}
if (!string.IsNullOrEmpty(strDepartment))
{
deToUpdate.Properties["department"].Value = strDepartment;
strToDisplay = strToDisplay + "\r\nDepartment: " + strDepartment;
}
if (!string.IsNullOrEmpty(strBUDesc))
{
deToUpdate.Properties["physicalDeliveryOfficeName"].Value = strBUDesc;
strToDisplay = strToDisplay + "\r\nBusiness Unit: " + strBUDesc;
}
if (!string.IsNullOrEmpty(strStreetAddress))
{
deToUpdate.Properties["streetAddress"].Value = strStreetAddress;
strToDisplay = strToDisplay + "\r\nAddress: " + strStreetAddress;
}
if (!string.IsNullOrEmpty(strLocation))
{
deToUpdate.Properties["l"].Value = strLocation;
strToDisplay = strToDisplay + "\r\nCity: " + strLocation;
}
if (!string.IsNullOrEmpty(strState))
{
deToUpdate.Properties["st"].Value = strState;
strToDisplay = strToDisplay + "\r\nState:" + strState;
}
if (!string.IsNullOrEmpty(strPostalCode))
{
deToUpdate.Properties["postalCode"].Value = strPostalCode;
strToDisplay = strToDisplay + "\r\nZip Code: " + strPostalCode;
}
if (!string.IsNullOrEmpty(strCountry))
{
deToUpdate.Properties["c"].Value = strCountry;
strToDisplay = strToDisplay + "\r\nCountry/Region:" + strCountry + "";
}
if (!string.IsNullOrEmpty(strExpiryDate))
{
DateTime dtExpiryDate = Convert.ToDateTime(strExpiryDate).AddDays(1);
deToUpdate.Properties["accountExpires"].Value = Convert.ToString((Int64)dtExpiryDate.ToFileTime());
strToDisplay = strToDisplay + "\r\nExpiry Date:" + strExpiryDate + "";
}
if (!string.IsNullOrEmpty(strExtensionAttribute1))
deToUpdate.Properties["extensionAttribute1"].Value = strExtensionAttribute1; //Update Company Code
if (!string.IsNullOrEmpty(strExtensionAttribute2))
deToUpdate.Properties["extensionAttribute2"].Value = strExtensionAttribute2; //Update Location Code
if (!string.IsNullOrEmpty(strExtensionAttribute3))
deToUpdate.Properties["extensionAttribute3"].Value = strExtensionAttribute3; //Update Job Title Code
if (!string.IsNullOrEmpty(strExtensionAttribute4))
deToUpdate.Properties["extensionAttribute4"].Value = strExtensionAttribute4; //Update Management Level Code
if (!string.IsNullOrEmpty(strExtensionAttribute8))
deToUpdate.Properties["extensionAttribute8"].Value = strExtensionAttribute8; //Update Sup Org Code
if (!string.IsNullOrEmpty(strExtensionAttribute10))
deToUpdate.Properties["extensionAttribute10"].Value = strExtensionAttribute10; //Update Department Code
if (!string.IsNullOrEmpty(strExtensionAttribute13))
deToUpdate.Properties["extensionAttribute13"].Value = strExtensionAttribute13; //Update Sup Org
}
catch (Exception exObj)
{
WriteToErrorLog("Error while updating Manager details.\n", " Emp AD ID: " + strAlias + "; Manager ID: " + strManager, "Application Exception");
WriteToErrorLog("Error while updating Manager (" + strManager + ") details of the Employee (" + strAlias + ").\n", "Message: " + exObj.Message + ";\n Method Name: " + exObj.TargetSite, "Application Exception");
}
}
deToUpdate.CommitChanges();
WriteToLog("Account updation succeeded...", "AD Attributes: " + strToDisplay);
}
else
{
WriteToLog("Account creation/updation failed...", "AD Attributes: " + strToDisplay);
strStatusCode = "0";
strStatusDesc = "Account Creation failed.";
}
how to post currency code as United States dollar and India. By default it uses IND.
[HttpPost]
public void Plans(UserRegistreModel model)
{
string firstName = model.FirstName;
string middleName = model.MiddleName;
string lastName = model.LastName;
string amount = Convert.ToString(model.Amount);
string Noofemp = model.NoOfEmployees;
string productInfo = "HRMS";
string email = model.Email;
string phone = model.Contact;
string FirmName = model.FirmName;
//string surl = form["txtsurl"].ToString();
//string furl = form["txtfurl"].ToString();
RemotePost myremotepost = new RemotePost();
string key = "";
string salt = "";
//posting all the parameters required for integration.
myremotepost.Url = "https://secure.payu.in/_payment";
myremotepost.Add("key", "");
string txnid = Generatetxnid();
myremotepost.Add("txnid", txnid);
myremotepost.Add("amount", amount);
myremotepost.Add("productinfo", productInfo);
myremotepost.Add("firstname", firstName);
myremotepost.Add("phone", phone);
myremotepost.Add("email", email);
//UserRegistreModel register = new UserRegistreModel();
TempData["model"] = model;
myremotepost.Add("surl", "");
myremotepost.Add("furl", "");
string hashString = key + "|" + txnid + "|" + amount + "|" + productInfo + "|" + firstName + "|" + email + "|||||||||||" + salt;
string hash = Generatehash512(hashString);
myremotepost.Add("hash", hash);
myremotepost.Post();
}
You can do things like this
myremotepost.Add("currency", "INR");
It will set the currency INR for current request.
When I upload file to my website I loss the session, and the user should login again?
This my code
if (FileUploadControl.HasFile) {
string filename = Path.GetFileName(FileUploadControl.FileName);
string newFileName = Path.Combine(Path.GetDirectoryName(filename),
string.Concat(words[0], DateTime.Now.ToString("_yyyy_MM_dd_HH_mm_ss"),
Path.GetExtension(filename)));
Session["login"] = us.Email;
Session["Id"] = us.Id;
string location = usDetail.FolderLink.Trim();
FileUploadControl.SaveAs(Server.MapPath(location) + newFileName);
lblResult.Text = "the file" + newFileName + " has uploaded";
var dateAndTime = DateTime.UtcNow;
var date = dateAndTime.Date;
var fp = new FileUpoads(usDetail.Id, DropDownList2.SelectedValue.ToString().Trim(),
location + newFileName, date);
string f = ConnectionClass.FileUplud(fp);
lblResult.Text = f;
}
string strName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; // "MW\\dalem"
string domainName = strName.Split('\\')[0];
using(var pc = new PrincipalContext(ContextType.Domain, domainName))
{
using (var user = new UserPrincipal(pc, Admin-Username, Admin-Pass, true))
{
fullname = fname + " " + lname;
user.SamAccountName = username;
user.SetPassword(password);
user.GivenName = fname;
user.Surname = lname;
user.DisplayName = fullname;
user.Save();
}
}
I'm trying to add the user to active directory, I get the error saying
"Access is Denied"
at the user.Save(); line. I don't understand why since I have full admin rights. This is my third or 5th approach at trying to add a user to the active directory.
You might achieve this by saving the database context:
string strName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; // "MW\\dalem"
string domainName = strName.Split('\\')[0];
using(var pc = new PrincipalContext(ContextType.Domain, domainName))
{
using (var user = new UserPrincipal(pc, Admin-Username, Admin-Pass, true))
{
fullname = fname + " " + lname;
user.SamAccountName = username;
user.SetPassword(password);
user.GivenName = fname;
user.Surname = lname;
user.DisplayName = fullname;
userPrincipal.Add(user);
}
pc.SaveChanges();
}