using System;
using System.DirectoryServices;// Be sure to set a reference to "System.DirectoryServices.dll"
namespace AdTest// Change namespace for your project
{
// Structures for returning user information
public struct UserInfo
{
public string LoginName;
public string FirstName;
public string LastName;
}
public struct UserInfoEx
{
public string LoginName;
public string Password;
public string FirstName;
public string LastName;
public string EmailAddress;
public string Title;
public string Company;
public string Address;
public string City;
public string State;
public string PostalCode;
public string Phone;
public string Country;
}
// Static class containing all the supported user property names
public class UserProperty
{
public static string CommonName = "cn";
public static string Password = "homePhone";
public static string UserName = "sAMAccountName";
public static string Country = "co";
public static string Company = "company";
public static string Department = "department";
public static string Description = "description";
public static string DisplayName = "displayName";
public static string FirstName = "givenName";
public static string City = "l";
public static string Email = "mail";
public static string PostalCode = "postalCode";
public static string LastName = "sn";
public static string State = "st";
public static string Address = "streetAddress";
public static string Phone = "telephoneNumber";
public static string Title = "title";
}
// Active Directory Utility Class
public class ADUtil
{
public ADUtil()
{
//
// TODO: Add constructor logic here
//
}
#region Constants
// *** SECURE CONSTANTS ***
// Reality Check: In production, these would be stored in a secure are of the registry
// or another secure location. In production, instead of "Administrator", an account
// would be created which has ONLY the privileges it needs for the AD operations
// and no more.
// Domain Settings:
const string usersLdapPath = "LDAP://MYDOMAIN.local/CN=Users, DC=MYDOMAIN, DC=local";
const string adLoginName = "MYDOMAIN//Administrator";
const string adLoginPassword = "password";
#endregion
// GetUserCN - given the CMS user string, returns a friendly name for the user
static public string GetUserCN (string username)
{
DirectoryEntry usersDE =
new DirectoryEntry (usersLdapPath, adLoginName, adLoginPassword);
DirectorySearcher ds = new DirectorySearcher (usersDE);
ds.Filter = "(sAMAccountName=" + username + ")";
ds.PropertiesToLoad.Add (UserProperty.FirstName);
ds.PropertiesToLoad.Add (UserProperty.LastName);
SearchResult r = ds.FindOne();
return (r.Properties[UserProperty.FirstName][0].ToString()
+ " "
+ r.Properties[UserProperty.Last