using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
public partial class ADLogin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DirectoryEntry dirEntry = GetDirectoryEntry();
Style bodyStyle = new Style();
bodyStyle.ForeColor = System.Drawing.Color.Black;
bodyStyle.BackColor = System.Drawing.Color.Wheat; //]wIC
//N˦[JثeHeader
Page.Header.StyleSheet.CreateStyleRule(bodyStyle, null, "BODY");
}
//Setting up the connection
public static DirectoryEntry GetDirectoryEntry()
{
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://OU=Domain,DC=Cathaybk,DC=com"; //AD
de.AuthenticationType = AuthenticationTypes.Secure;
return de;
}
// Translate the friendly domain name to fully qualified domain:
public static string FriendlyDomainToLdapDomain(string friendlyDomainName)
{
string ldapPath = null;
try
{
DirectoryContext objContext = new DirectoryContext(
DirectoryContextType.Domain, friendlyDomainName);
Domain objDomain = Domain.GetDomain(objContext);
ldapPath = objDomain.Name;
}
catch (DirectoryServicesCOMException e)
{
ldapPath = e.Message.ToString();
}
return ldapPath;
}
//Enumerate Domains in the Current Forest
public static ArrayList EnumerateDomains()
{
ArrayList alDomains = new ArrayList();
Forest currentForest = Forest.GetCurrentForest();
DomainCollection myDomains = currentForest.Domains;
foreach (Domain objDomain in myDomains)
{
alDomains.Add(objDomain.Name);
}
return alDomains;
}
// Enumerate Objects in an OU
//The parameter OuDn is the Organizational Unit distinguishedName such as OU=Users,dc=myDomain,dc=com
public ArrayList EnumerateOU(string OuDn)
{
ArrayList alObjects = new ArrayList();
try
{
DirectoryEntry directoryObject = new DirectoryEntry("LDAP://" + OuDn);
foreach (DirectoryEntry child in directoryObject.Children)
{
string childPath = child.Path.ToString();
alObjects.Add(childPath.Remove(0,7)); //remove the LDAP prefix from the path
child.Close();
child.Dispose();
}
directoryObject.Close();
directoryObject.Dispose();
}
catch (DirectoryServicesCOMException e)
{
Console.WriteLine("An Error Occurred: " + e.Message.ToString());
}
return alObjects;
}
//Check for the Existence of an Object
//This method does not need you to know the distinguishedName, you can concat strings or even guess a location and it will still run
// (and return false if not found).
public static bool Exists(string objectPath)
{
bool found = false;
if (DirectoryEntry.Exists("LDAP://" + objectPath))
{
found = true;
}
return found;
}
// Move an Object From One Location to Another
// It should be noted that the string newLocation should NOT include the CN= value of the object.
// The method will pull that from the objectLocation string for you. So object CN=group,OU=GROUPS,DC=contoso,DC=com is sent in as the objectLocation but the newLocation is something like: OU=NewOUParent,DC=contoso,DC=com. The method will take care of the CN=group.
public void Move(string objectLocation, string newLocation)
{
//For brevity, removed existence checks
DirectoryEntry eLocation = new DirectoryEntry("LDAP://" + objectLocation);
DirectoryEntry nLocation = new DirectoryEntry("LDAP://" + newLocation);
string newName = eLocation.Name;
eLocation.MoveTo(nLocation, newName);
nLocation.Close();
eLocation.Close();
}
// Enumerate Multi-String Attribute Values of an Object
// This method includes a recursive flag in case you want to recursively dig up properties of properites such as enumerating all the member values of a group and then getting each member group's groups all the way up the tree.
public ArrayList AttributeValuesMultiString(string attributeName,
string objectDn, ArrayList valuesCollection, bool recursive)
{
DirectoryEntry ent = new DirectoryEntry(objectDn);
PropertyValueCollection ValueCollection = ent.Properties[attributeName];
IEnumerator en = ValueCollection.GetEnumerator();
while (en.MoveNext())
{
if (en.Current != null)
{
if (!valuesCollection.Contains(en.Current.ToString()))
{
valuesCollection.Add(en.Current.ToString());
if (recursive)
{
AttributeValuesMultiString(attributeName, "LDAP://" +
en.Current.ToString(), valuesCollection, true);
}
}
}
}
ent.Close();
ent.Dispose();
return valuesCollection;
}
//Enumerate Single String Attribute Values of an Object
public string AttributeValuesSingleString(string attributeName, string objectDn)
{
string strValue;
DirectoryEntry ent = new DirectoryEntry(objectDn);
strValue = ent.Properties[attributeName].Value.ToString();
ent.Close();
ent.Dispose();
return strValue;
}
//Enumerate an Object's Properties (The Ones With Values)
public static ArrayList GetUsedAttributes(string objectDn)
{
DirectoryEntry objRootDSE = new DirectoryEntry("LDAP://" + objectDn);
ArrayList props = new ArrayList();
foreach (string strAttrName in objRootDSE.Properties.PropertyNames)
{
props.Add(strAttrName);
}
return props;
}
/*
* Get an Object DistinguishedName (ADO.NET Search) - ADVANCED
* This method is the glue that ties all the methods together since most all the methods require the consumer to provide a distinguishedName.
* Where ever you put this code, you must ensure that you also add these enumerations as well. This allows the consumer to specifiy the type of object to search for and whether they want the distinguishedName returned or the objectGUID.
*/
public enum objectClass
{
user,
group,
computer
}
public enum returnType
{
distinguishedName,
ObjectGUID
}
/* A call to this class might look like:
* myObjectReference.GetObjectDistinguishedName(objectClass.user, returnType.ObjectGUID, "john.q.public", "contoso.com")
* Collapse */
public string GetObjectDistinguishedName(objectClass objectCls,
returnType returnValue,
string objectName,
string LdapDomain)
{
string distinguishedName = string.Empty;
string connectionPrefix = "LDAP://" + LdapDomain;
DirectoryEntry entry = new DirectoryEntry(connectionPrefix);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
switch (objectCls)
{
case objectClass.user:
mySearcher.Filter = "(&(objectClass=user)(|(cn=" + objectName + ")(sAMAccountName=" + objectName + ")))";
break;
case objectClass.group:
mySearcher.Filter = "(&(objectClass=group)(|(cn=" + objectName + ")(dn=" + objectName + ")))";
break;
case objectClass.computer:
mySearcher.Filter = "(&(objectClass=computer)(|(cn=" + objectName + ")(dn=" + objectName + ")))";
break;
}
System.DirectoryServices.SearchResult result = mySearcher.FindOne();
if (result == null){
throw new NullReferenceException("unable to locate the distinguishedName for the object " +
objectName + " in the " + LdapDomain + " domain");
}
DirectoryEntry directoryObject = result.GetDirectoryEntry();
if (returnValue.Equals(returnType.distinguishedName)){
distinguishedName = "LDAP://" + directoryObject.Properties["distinguishedName"].Value;
}
if (returnValue.Equals(returnType.ObjectGUID)){
distinguishedName = directoryObject.Guid.ToString();
}
entry.Close();
entry.Dispose();
mySearcher.Dispose();
return distinguishedName;
}
// Convert distinguishedName to ObjectGUID
public string ConvertDNtoGUID(string objectDN)
{
//Removed logic to check existence first
DirectoryEntry directoryObject = new DirectoryEntry(objectDN);
return directoryObject.Guid.ToString();
}
// Convert an ObjectGUID to OctectString (the native ObjectGUID)
public static string ConvertGuidToOctectString(string objectGuid)
{
System.Guid guid = new Guid(objectGuid);
byte[] byteGuid = guid.ToByteArray();
string queryGuid = "";
foreach (byte b in byteGuid)
{
queryGuid += @"\" + b.ToString("x2");
}
return queryGuid;
}
//Publish Network Shares in Active Directory
//Example
private void init()
{
CreateShareEntry("OU=HOME,dc=cathaybk,dc=com",
"Music",
@"\\192.168.2.1\Music",
"mp3 Server Share");
Console.ReadLine();
}
//Actual Method
public void CreateShareEntry(string ldapPath,
string shareName,
string shareUncPath,
string shareDescription)
{
string oGUID = string.Empty;
string connectionPrefix = "LDAP://" + ldapPath;
DirectoryEntry directoryObject = new DirectoryEntry(connectionPrefix);
DirectoryEntry networkShare = directoryObject.Children.Add("CN=" + shareName, "volume");
networkShare.Properties["uNCName"].Value = shareUncPath;
networkShare.Properties["Description"].Value = shareDescription;
networkShare.CommitChanges();
directoryObject.Close();
networkShare.Close();
}
//Active Directory Users Tasks:
//These methods require these imports
//You must add a references in your project as well
//Add User to Group
public void AddToGroup(string userDn, string groupDn)
{
try
{
DirectoryEntry dirEntry = new DirectoryEntry("LDAP://" + groupDn);
dirEntry.Properties["member"].Add(userDn);
dirEntry.CommitChanges();
dirEntry.Close();
}
catch (System.DirectoryServices.DirectoryServicesCOMException E)
{
//doSomething with E.Message.ToString();
Console.WriteLine(E.Message);
}
}
// Remove User From Group
public void RemoveUserFromGroup(string userDn, string groupDn)
{
try
{
DirectoryEntry dirEntry = new DirectoryEntry("LDAP://" + groupDn);
dirEntry.Properties["member"].Remove(userDn);
dirEntry.CommitChanges();
dirEntry.Close();
}
catch (System.DirectoryServices.DirectoryServicesCOMException E)
{
//doSomething with E.Message.ToString();
Console.WriteLine(E.Message);
}
}
// Get User Group Memberships of the Logged In User (From ASP.NET)
public ArrayList Groups()
{
ArrayList groups = new ArrayList();
foreach (System.Security.Principal.IdentityReference group in
System.Web.HttpContext.Current.Request.LogonUserIdentity.Groups)
{
groups.Add(group.Translate(typeof(System.Security.Principal.NTAccount)).ToString());
}
return groups;
}
// Get User Group Memberships
// This method requires that you have the AttributeValuesMultiString method earlier in the article included in your class.
public ArrayList Groups(string userDn, bool recursive)
{
ArrayList groupMemberships = new ArrayList();
return AttributeValuesMultiString("memberOf", userDn,
groupMemberships, recursive);
}
//Create User Account
public string CreateUserAccount(string ldapPath, string userName, string userPassword)
{
string oGUID =string.Empty;
try
{
oGUID = string.Empty;
string connectionPrefix = "LDAP://" + ldapPath;
DirectoryEntry dirEntry = new DirectoryEntry(connectionPrefix);
DirectoryEntry newUser = dirEntry.Children.Add("CN=" + userName, "user");
newUser.Properties["samAccountName"].Value = userName;
newUser.CommitChanges();
oGUID = newUser.Guid.ToString();
newUser.Invoke("SetPassword", new object[] { userPassword });
newUser.CommitChanges();
dirEntry.Close();
newUser.Close();
}
catch (System.DirectoryServices.DirectoryServicesCOMException Ex)
{
//DoSomethingwith --> E.Message.ToString();
Console.WriteLine(Ex.Message);
}
return oGUID;
}
//Enable a User Account
public void Enable(string userDn)
{
try
{
DirectoryEntry user = new DirectoryEntry(userDn);
int val = (int)user.Properties["userAccountControl"].Value;
user.Properties["userAccountControl"].Value = val & ~0x2; //ADS_UF_NORMAL_ACCOUNT;
user.CommitChanges();
user.Close();
}
catch (System.DirectoryServices.DirectoryServicesCOMException E)
{
//DoSomethingWith --> E.Message.ToString();
Console.WriteLine(E.Message);
}
}
// Disable a User Account
public void Disable(string userDn)
{
try
{
DirectoryEntry user = new DirectoryEntry(userDn);
int val = (int)user.Properties["userAccountControl"].Value;
user.Properties["userAccountControl"].Value = val | 0x2; //ADS_UF_ACCOUNTDISABLE;
user.CommitChanges();
user.Close();
}
catch (System.DirectoryServices.DirectoryServicesCOMException E)
{
//DoSomethingWith --> E.Message.ToString();
Console.WriteLine(E.Message);
}
}
//Unlock a User Account
public void Unlock(string userDn)
{
try
{
DirectoryEntry uEntry = new DirectoryEntry(userDn);
uEntry.Properties["LockOutTime"].Value = 0; //unlock account
uEntry.Close();
}
catch (System.DirectoryServices.DirectoryServicesCOMException E)
{
//DoSomethingWith --> E.Message.ToString();
Console.WriteLine(E.Message);
}
}
//Reset a User password
public void ResetPassword(string userDn, string password)
{
DirectoryEntry uEntry = new DirectoryEntry(userDn);
uEntry.Invoke("SetPassword", new object[] { password });
uEntry.Properties["LockOutTime"].Value = 0; //unlock account
uEntry.Close();
}
}