Deal with Active Directory using C#

objUser = objAD.FindOneByProperty(clsAD.ADProperties.samAccountName, accountName, true);
objAD.UpdateProperty(accountName, clsAD.ADProperties.telephoneNumber, txtWorkPhone.Text.Trim());

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;

namespace ActiveDirectoryTools
{
    class clsAD
    {
        static string LDAPPath = string.Empty;
        static string Username = string.Empty;
        static string Password = string.Empty;

        public clsAD(string ldapPath, string username, string password)
        {
            LDAPPath = ldapPath;
            Username = username;
            Password = password;
        }

        public static DirectoryEntry GetDirectoryEntry()
        {
            DirectoryEntry de = new DirectoryEntry(LDAPPath, Username, Password);
            return de;
        }

        public List<clsUser> FindAllByProperty(ADProperties property, String propertyValue)
        {
            DirectoryEntry entry = GetDirectoryEntry();
            List<clsUser> searchResults = new List<clsUser>();

            try
            {
                DirectorySearcher search = new DirectorySearcher(entry);
                SearchResultCollection resultCollection;

                LoadProperties(ref search);

                search.Filter = "(" + property + "=*" + propertyValue + "*)";
                resultCollection = search.FindAll();

                if (resultCollection != null)
                {
                    foreach (SearchResult result in resultCollection)
                    {
                        clsUser objUser = new clsUser();

                        MapToObject(result, ref objUser);

                        searchResults.Add(objUser);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }

            return searchResults;
        }

        public clsUser FindOneByProperty(ADProperties property, String propertyValue, bool findManager)
        {
            clsUser objUser = new clsUser();

            try
            {
                SearchResult result = FindOne(property, propertyValue);

                if (result != null)
                {
                    MapToObject(result, ref objUser, findManager);
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.ToUpper().Contains("LOGON FAILURE")) throw new Exception("The Password That You Entered Is Not Correct");
                else throw new Exception(ex.Message.ToString());
            }

            return objUser;
        }

        public void UpdateProperty(string accountName, ADProperties property, string propertyValue)
        {
            DirectoryEntry de = FindOne(ADProperties.samAccountName, accountName).GetDirectoryEntry();
            de.InvokeSet("" + property + "", new object[] { propertyValue });
            de.CommitChanges();
        }

        public enum ADProperties
        {
            distinguishedName,
            displayName,
            telephoneNumber,
            samAccountName,
            manager,
            title,
            department,
            mobile
        }

        private SearchResult FindOne(ADProperties property, string propertyValue)
        {
            DirectoryEntry entry = GetDirectoryEntry();
            SearchResult result;

            try
            {
                DirectorySearcher search = new DirectorySearcher(entry);

                LoadProperties(ref search);

                search.Filter = "(" + property + "=" + propertyValue + ")";
                result = search.FindOne();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }

            return result;
        }

        private void LoadProperties(ref DirectorySearcher search)
        {
            try
            {
                // load up the properties we want to expose
                search.PropertiesToLoad.Add("title");
                search.PropertiesToLoad.Add("distinguishedName");
                search.PropertiesToLoad.Add("samAccountName");
                search.PropertiesToLoad.Add("displayName");
                search.PropertiesToLoad.Add("telephoneNumber");
                search.PropertiesToLoad.Add("manager");
                search.PropertiesToLoad.Add("department");
                search.PropertiesToLoad.Add("mobile");
                search.PropertiesToLoad.Add("l");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
        }

        private void MapToObject(SearchResult result, ref clsUser objUser, bool mapManager)
        {
            try
            {
                MapToObject(result, ref objUser);
                if (result.Properties["manager"].Count > 0)
                    objUser.manager = FindOneByProperty(ADProperties.distinguishedName,
                        result.Properties["manager"][0].ToString(), false);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
        }

        private void MapToObject(SearchResult result, ref clsUser objUser)
        {
            try
            {

                if (result.Properties["title"].Count > 0)
                    objUser.Title = result.Properties["title"][0].ToString();
                if (result.Properties["distinguishedName"].Count > 0)
                    objUser.distinguishedName = result.Properties["distinguishedName"][0].ToString();
                if (result.Properties["displayName"].Count > 0)
                    objUser.displayName = result.Properties["displayname"][0].ToString();
                if (result.Properties["telephoneNumber"].Count > 0)
                    objUser.telephoneNumber = result.Properties["telephoneNumber"][0].ToString();
                if (result.Properties["samAccountName"].Count > 0)
                    objUser.samAccountName = result.Properties["samAccountName"][0].ToString();
                if (result.Properties["manager"].Count > 0)
                    objUser.manager = FindOneByProperty(ADProperties.distinguishedName,
                        result.Properties["manager"][0].ToString(), true);
                if (result.Properties["department"].Count > 0)
                    objUser.department = result.Properties["department"][0].ToString();
                if (result.Properties["mobile"].Count > 0)
                    objUser.mobilePhone = result.Properties["mobile"][0].ToString();
                if (result.Properties["l"].Count > 0)
                    objUser.city = result.Properties["l"][0].ToString();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
        }

        public void ChangePassword(string ldapPath, string distinguishedName, string OldPassword, string NewPassword)
        {
            DirectoryEntry oDE = new DirectoryEntry("LDAP://" + distinguishedName);
            // oDE.AuthenticationType = AuthenticationTypes.Secure;

            try
            {
                oDE.Invoke("ChangePassword", new object[] { OldPassword, NewPassword });
                oDE.CommitChanges();
            }
            catch (Exception ex)
            {
                try
                {
                    if (ex.InnerException.Message.ToString().ToUpper().Contains("CONSTRAINT"))
                        throw new Exception("The Password You Entered Does Not Meet The Minimum Requirements Defined By Your Network Administrator");
                    else throw new Exception(ex.Message.ToString());
                }
                catch (Exception innerEX)
                {
                    // the inner exception is null – throw the parent
                    throw new Exception(ex.Message.ToString());
                }
            }
        }
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s