mylifeinaminute.com

An Active Directory Helper Class

by liquidpooled on Jul.23, 2008, under .NET, Microsoft, Visual Studio 2005, Visual Studio 2008

Updated version here.

The following is an Active Directory helper class, allowing for actions such as resetting a users’ password, or properties pertaining to a users’ account.


using System;
using System.Data;
using System.DirectoryServices;
using System.Configuration;
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;

namespace MyLifeInAMinute.Base.Utiltities
{
    public class ActiveDirectoryHelper
    {
        /// <summary>
        /// returns a string (i.e. LDAP://example.dc.local
        /// </summary>
        private string LDAPConnection
        {
            get { return System.Configuration.ConfigurationManager.AppSettings["LDAPConnection"].ToString(); }
        }

        /// <summary>
        /// returns a string contain the username for the LDAP connection (preferably admin level so we
        /// can reset passwords)
        /// </summary>
        private string LDAPAdminPassword
        {
            get { return System.Configuration.ConfigurationManager.AppSettings["LDAPAdminPass"].ToString(); }
        }

        /// <summary>
        /// returns a string containing the password for the LDAP connection
        /// </summary>
        private string LDAPAdminUserName
        {
            get { return System.Configuration.ConfigurationManager.AppSettings["LDAPAdmin"].ToString(); }
        }

        private DirectoryEntry GetDirectoryObject()
        {
            DirectoryEntry oDE;
            oDE = new DirectoryEntry(this.LDAPConnection, this.LDAPAdminUserName, this.LDAPAdminPassword, AuthenticationTypes.Secure);
            return oDE;
        }

        public SearchResultCollection GetAllUsers()
        {
            DirectoryEntry de = GetDirectoryObject();
            DirectorySearcher deSearch = new DirectorySearcher();
            deSearch.SearchRoot = de;

            deSearch.Filter = "(&(objectClass=user))";
            deSearch.SearchScope = SearchScope.Subtree;
            SearchResultCollection results = deSearch.FindAll();

            return results;
        }

        public DirectoryEntry GetUser(string propertyName, string propertyValue)
        {
            DirectoryEntry de = GetDirectoryObject();
            DirectorySearcher deSearch = new DirectorySearcher();
            deSearch.SearchRoot = de;

            deSearch.Filter = "(&(objectClass=user)(" + propertyName + "=" + propertyValue + "))";
            deSearch.SearchScope = SearchScope.Subtree;
            SearchResult results = deSearch.FindOne();

            if (!(results == null))
            {
                de = new DirectoryEntry(results.Path, this.LDAPAdminUserName, this.LDAPAdminPassword, AuthenticationTypes.Secure);
                return de;
            }
            else
            {
                return null;
            }
        }

        public void SetProperty(DirectoryEntry de, string PropertyName, string PropertyValue)
        {
            if (PropertyValue != null)
            {
                if (de.Properties.Contains(PropertyName))
                {
                    de.Properties[PropertyName][0] = PropertyValue;
                }
                else
                {
                    de.Properties[PropertyName].Add(PropertyValue);
                }
            }
        }

        public void ChangePassword(string userPath, string userName, string userCurrentPwd, string userNewPwd)
        {
            DirectoryEntry oDE;
            oDE = new DirectoryEntry(userPath, userName, userCurrentPwd, AuthenticationTypes.Secure);

            try
            {
                // Change the password.
                oDE.Invoke("ChangePassword", new object[] { userCurrentPwd, userNewPwd });
                oDE.CommitChanges();
                oDE.Close();
            }
            catch (Exception excep)
            {
                throw new Exception("Error changing password. Reason: " + excep.InnerException);
            }
        }

        public void SetPassword(string userPath, string userPassword)
        {
            DirectoryEntry usr = new DirectoryEntry();
            usr.Path = userPath;
            usr.AuthenticationType = AuthenticationTypes.Secure;
            object[] password = new object[] { userPassword };
            object ret = usr.Invoke("SetPassword", password);
            usr.CommitChanges();
            usr.Close();
        }

        public string ToADDateString(DateTime date)
        {
            string year = date.Year.ToString();
            int month = date.Month;
            int day = date.Day;
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(year);
            if (month < 10)
            {
                sb.Append("0");
            }
            sb.Append(month.ToString());
            if (day < 10)
            {
                sb.Append("0");
            }
            sb.Append(day.ToString());
            sb.Append("000000.0Z");
            return sb.ToString();
        }
    }
}

Here are a few examples:

Changing a Password


Utiltities.ActiveDirectoryHelper adHelper = new Utiltities.ActiveDirectoryHelper();

System.DirectoryServices.DirectoryEntry de = new System.DirectoryServices.DirectoryEntry();

if (txtuName.Text.Contains("@"))
	de = adHelper.GetUser("userPrincipalName", txtuName.Text);
else
	de = adHelper.GetUser("sAMAccountName", txtuName.Text);

if (de != null)
	adHelper.ChangePassword(de.Path, txtuName.Text, txtCurrentPwd.Text, txtNewPwd.Text);

Finding a User Property (in this case, sAMAccountName)


Utiltities.ActiveDirectoryHelper adHelper = new JonesDay.JDAuthorization.Utiltities.ActiveDirectoryHelper();

System.DirectoryServices.DirectoryEntry de = new System.DirectoryServices.DirectoryEntry();

if (txtuName.Text.Contains("@"))
	de = adHelper.GetUser("userPrincipalName", txtResetuName.Text);
else
	de = adHelper.GetUser("sAMAccountName", txtResetuName.Text);

string userName = string.Empty;

foreach (object value in de.Properties["sAMAccountName"])
{
	userName = Convert.ToString(value);
}
No comments for this entry yet...

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...