Click here to Skip to main content
Click here to Skip to main content

Active Directory Objects and C#

, 28 Jun 2010
Rate this:
Please Sign up or sign in to vote.
If you are wondering how to access an Active Directory Objects using C#, please look at the attached code as a reference.

Update : If you want a newer version which is using .Net 3.5 System.DirectoryServices.AccountManagement I had created a new version here  

If you are wondering how to access an Active Directory Objects using C#, please look at the attached code as a reference. The code reference is nearly complete in terms of functionalities you need to Create, View and Update necessary User Information in the Active Directory.

The code is divided into several regions but here are the 5 key regions with their methods explained:

Validate Methods

  • Login - This method will verify if the User Account exists by matching both the Username and Password as well as checking if the Account is Active.
  • IsAccountActive - This will perform a logical operation on the iUserAccountControl values to see if the user Account is Enabled or Disabled.
  • IsUserValid - This method will attempt to log in a User based on the Username and Password to ensure that they have been set up within the Active Directory. This is the basic UserName and Password check.

Search Methods

  • GetUser - This will return a DirectoryEntry Object if the User exists
  • GetUserDataSet - This will take a Username and Query the AD for the User. When found, it will transform the results from the Property Collection into a Dataset.

User Account Methods

  • SetUserPassword - This method will set the User's Password
  • EnableUserAccount - This method will enable a User Account
  • ExpireUserPassword - This method will force expire a Users Password
  • DisableUserAccount - This method will disable the User Account
  • MoveUserAccount - Moves a User Account to a new OU path
  • IsAccountLocked - This method checks whether an Account is Locked
  • UnlockUserAccount - This method will unlock a User Account
  • IsUserExpired - This method checks whether an Account is Expired
  • CreateNewUser - This method will create a new User Directory Object
  • DeleteUser - This method will delete an AD User based on Username.

Group Methods

  • CreateNewGroup - This method will create a New Active Directory Group
  • AddUserToGroup - This method will add a User to a group
  • RemoveUserFromGroup - This method will remove a User from a group
  • IsUserGroupMember - This method will Validate whether the User is a member of a Group
  • GetUserGroups - This method will return an ArrayList of a User Group Memberships

Helper Methods

  • GetProperty - This will retrieve the Specified Property Value from the Directory Entry Object
  • GetProperty_Array - This will retrieve the Specified Property Value if it's an Array Type from the Directory Entry object
  • GetProperty_Byte - This will retrieve the Specified Property Value if it's a Byte Type from the Directory Entry object
  • SetProperty - This will set the Property of the Directory Entry Object
  • ClearProperty - This method will clear the Property Values
using System;
using System.Collections;
using System.Text;
using System.DirectoryServices;
using System.Data;
using System.Configuration;

namespace ADExchangeLib
{
 public class ADMethods : IDisposable
 {
 DirectoryEntry oDE = null;
 DirectoryEntry oDEC = null;
 DirectorySearcher oDS = null;
 SearchResultCollection oResults = null;
 DataSet oDs = null;
 DataSet oDsUser = null;
 DataTable oTb = null;
 DataRow oRwUser = null;
 DataRow oRwResult = null;
 DataRow oNewCustomersRow = null;

 #region Private Variables

 private string sADPath = "";
 private string sADPathPrefix = "";
 private string sADUser = "";
 private string sADPassword = "";
 private string sADServer = "";
 private string sCharactersToTrim = "";

 #endregion

 #region Enumerations

 public enum ADAccountOptions
 {
 UF_TEMP_DUPLICATE_ACCOUNT = 0x0100,
 UF_NORMAL_ACCOUNT = 0x0200,
 UF_INTERDOMAIN_TRUST_ACCOUNT = 0x0800,
 UF_WORKSTATION_TRUST_ACCOUNT = 0x1000,
 UF_SERVER_TRUST_ACCOUNT = 0x2000,
 UF_DONT_EXPIRE_PASSWD = 0x10000,
 UF_SCRIPT = 0x0001,
 UF_ACCOUNTDISABLE = 0x0002,
 UF_HOMEDIR_REQUIRED = 0x0008,
 UF_LOCKOUT = 0x0010,
 UF_PASSWD_NOTREQD = 0x0020,
 UF_PASSWD_CANT_CHANGE = 0x0040,
 UF_ACCOUNT_LOCKOUT = 0X0010,
 UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0X0080,
 UF_EXPIRE_USER_PASSWORD = 0x800000,
 }
 public enum GroupType : uint
 {
 UniversalGroup = 0x08,
 DomainLocalGroup = 0x04,
 GlobalGroup = 0x02,
 SecurityGroup = 0x80000000
 }

 public enum LoginResult
 {
 LOGIN_OK = 0,
 LOGIN_USER_DOESNT_EXIST,
 LOGIN_USER_ACCOUNT_INACTIVE
 }

 #endregion

 #region Methods

 public ADMethods()
 {
 sADPath = ConfigurationSettings.AppSettings["sADPath"].ToString();
 sADUser = ConfigurationSettings.AppSettings["sADUser"].ToString();
 sADPassword = ConfigurationSettings.AppSettings["sADPassword"].ToString();
 sADServer = ConfigurationSettings.AppSettings["sADServer"].ToString();
 }
 //Implement IDisposable.
 public void Dispose()
 {
 Dispose(true);
 GC.SuppressFinalize(this);
 }

 protected virtual void Dispose(bool bDisposing)
 {
 if (bDisposing)
 {

 }
 // Free your own state.
 // Set large fields to null.

 sADPath = null;
 sADUser = null;
 sADPassword = null;
 sADServer = null;
 sCharactersToTrim = null;

 oDE = null;
 oDEC = null;
 oDS = null;
 oResults = null;
 oDs = null;
 oDsUser = null;
 oTb = null;
 oRwUser = null;
 oRwResult = null;
 oNewCustomersRow = null;
 }

 //Use C# Destructor Syntax for Finalization Code.
 ~ADMethods()
 {
 //Simply call Dispose(false).
 Dispose(false);
 }

 #region Validate Methods

 /// <span class="code-SummaryComment"><summary>
</span> /// This Method will verify if the User Account Exists
 /// By Matching both the Username and Password as well as
 /// checking if the Account is Active.
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sUserName">Username to Validate</param>
</span> /// <span class="code-SummaryComment"><param name="sPassword">Password of the Username to Validate</param>
</span> /// <span class="code-SummaryComment"><returns></returns>
</span> public ADMethods.LoginResult Login(string sUserName, string sPassword)
 {
 //Check if the Logon exists Based on the Username and Password
 if (IsUserValid(sUserName, sPassword))
 {
 oDE = GetUser(sUserName);
 if (oDE != null)
 {
 //Check the Account Status
 int iUserAccountControl = Convert.ToInt32(oDE.Properties["userAccountControl"][0]);
 oDE.Close();

 //If the Disabled Item does not Exist then the Account is Active
 if (!IsAccountActive(iUserAccountControl))
 {
 return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;
 }
 else
 {
 return LoginResult.LOGIN_OK;
 }

 }
 else
 {
 return LoginResult.LOGIN_USER_DOESNT_EXIST;
 }
 }
 else
 {
 return LoginResult.LOGIN_USER_DOESNT_EXIST;
 }
 }

 /// <span class="code-SummaryComment"><summary>
</span> /// This will perform a logical operation on the iUserAccountControl values
 /// to see if the user Account is Enabled or Disabled.
 /// The Flag for Determining if the Account is active is a Bitwise value (Decimal = 2)
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="iUserAccountControl"></param>
</span> /// <span class="code-SummaryComment"><returns></returns>
</span> public bool IsAccountActive(int iUserAccountControl)
 {
 int iUserAccountControl_Disabled = Convert.ToInt32(ADAccountOptions.UF_ACCOUNTDISABLE);
 int iFlagExists = iUserAccountControl & iUserAccountControl_Disabled;

 //If a Match is Found, then the Disabled Flag Exists within the Control Flags
 if (iFlagExists >

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Raymund Macaalay
Technical Lead
New Zealand New Zealand
http://nz.linkedin.com/in/macaalay
http://macaalay.com/
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
QuestionC++ Pinmembermacupryk17-Jan-12 5:03 
GeneralAdding users from one domain to another PinmemberMichael J. Collins9-Sep-10 3:40 
GeneralRe: Adding users from one domain to another PinmemberRaymund Macaalay9-Sep-10 10:24 
GeneralRe: Adding users from one domain to another PinmemberRaymund Macaalay9-Sep-10 10:27 
GeneralRe: Adding users from one domain to another PinmemberMichael J. Collins9-Sep-10 10:29 
GeneralRe: Adding users from one domain to another PinmemberRaymund Macaalay9-Sep-10 13:21 
GeneralAuthenticating ADAM / AD LDS users Pinmemberswndev30-May-10 21:10 
GeneralRe: Authenticating ADAM / AD LDS users PinmemberRaymund Macaalay31-May-10 10:49 
Generalimpressive PinmemberMDL=>Moshu28-Mar-10 5:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 29 Jun 2010
Article Copyright 2010 by Raymund Macaalay
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid