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

Tagged as

Go to top

Everything in Active Directory via C#.NET 3.5 (Using System.DirectoryServices.AccountManagement)

, 27 Jun 2010
Rate this:
Please Sign up or sign in to vote.
Everything in Active Directory via C#.NET 3.5 (Using System.DirectoryServices.AccountManagement)

Before .NET, managing Active Directory objects was a bit lengthy and you needed a good knowledge on the principal store to have your head around on what you want to do. We usually use the System.DirectoryServices namespace, but with .NET 3.5 they introduced System.DirectoryServices.AccountManagement which manages directory objects independent of the System.DirectoryServices namespace.

So what are the advantages of using this if I already have a library created for the whole AD methods that System.DirectoryServices exposed? Because everything is really simple in terms of managing a user, computer or group principal and performing queries on the stores are much faster, thanks to the Fast Concurrent Bind (FSB) feature which caches the connection which decreases the number of ports used in the process.

I remember I had posted a while back Active Directory Objects and C# which is basically everything regarding AD Methods in terms of Users and Group management and if you see the codebase, it is a bit lengthy and you need a bit of understanding on setting and getting hex values which is why I enumerated it. Now I had rewritten it using the System.DirectoryServices.AccountManagement namespace, functionalities remain the same but it's easier to understand and there are fewer lines.

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

Validate Methods

  • ValidateCredentials – This method will validate the users' credentials
  • IsUserExpired – Checks if the User Account has expired
  • IsUserExisiting – Checks if user exists on AD
  • IsAccountLocked – Checks if user account is locked

Search Methods

  • GetUser – This will return a UserPrincipal Object if the User exists

User Account Methods

  • SetUserPassword – This method will set the Users Password
  • EnableUserAccount – This method will Enable a User Account
  • DisableUserAccount – This method will Disable the User Account
  • ExpireUserPassword – This method will Force Expire a Users Password
  • UnlockUserAccount – This method will unlock a User Account
  • 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

  • GetPrincipalContext – Gets the base principal context

using System;
using System.Collections;
using System.Text;
using System.DirectoryServices.AccountManagement;
using System.Data;
using System.Configuration;

public class ADMethodsAccountManagement
{
 #region Variables

 private string sDomain = "test.com";
 private string sDefaultOU = "OU=Test Users,OU=Test,DC=test,DC=com";
 private string sDefaultRootOU = "DC=test,DC=com";
 private string sServiceUser = @"ServiceUser";
 private string sServicePassword = "ServicePassword";

 #endregion
 #region Validate Methods

 /// <span class="code-SummaryComment"><summary>
</span> /// Validates the username and password of a given user
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sUserName">The username to validate</param>
</span> /// <span class="code-SummaryComment"><param name="sPassword">The password of the username to validate</param>
</span> /// <span class="code-SummaryComment"><returns>Returns True of user is valid</returns>
</span> public bool ValidateCredentials(string sUserName, string sPassword)
 {
 PrincipalContext oPrincipalContext = GetPrincipalContext();
 return oPrincipalContext.ValidateCredentials(sUserName, sPassword);
 }

 /// <span class="code-SummaryComment"><summary>
</span> /// Checks if the User Account is Expired
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sUserName">The username to check</param>
</span> /// <span class="code-SummaryComment"><returns>Returns true if Expired</returns>
</span> public bool IsUserExpired(string sUserName)
 {
 UserPrincipal oUserPrincipal = GetUser(sUserName);
 if (oUserPrincipal.AccountExpirationDate != null)
 {
 return false;
 }
 else
 {
 return true;
 }
 }

 /// <span class="code-SummaryComment"><summary>
</span> /// Checks if user exists on AD
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sUserName">The username to check</param>
</span> /// <span class="code-SummaryComment"><returns>Returns true if username Exists</returns>
</span> public bool IsUserExisiting(string sUserName)
 {
 if (GetUser(sUserName) == null)
 {
 return false;
 }
 else
 {
 return true;
 }
 }

 /// <span class="code-SummaryComment"><summary>
</span> /// Checks if user account is locked
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sUserName">The username to check</param>
</span> /// <span class="code-SummaryComment"><returns>Returns true of Account is locked</returns>
</span> public bool IsAccountLocked(string sUserName)
 {
 UserPrincipal oUserPrincipal = GetUser(sUserName);
 return oUserPrincipal.IsAccountLockedOut();
 }
 #endregion

 #region Search Methods

 /// <span class="code-SummaryComment"><summary>
</span> /// Gets a certain user on Active Directory
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sUserName">The username to get</param>
</span> /// <span class="code-SummaryComment"><returns>Returns the UserPrincipal Object</returns>
</span> public UserPrincipal GetUser(string sUserName)
 {
 PrincipalContext oPrincipalContext = GetPrincipalContext();

 UserPrincipal oUserPrincipal = 
	UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
 return oUserPrincipal;
 }

 /// <span class="code-SummaryComment"><summary>
</span> /// Gets a certain group on Active Directory
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sGroupName">The group to get</param>
</span> /// <span class="code-SummaryComment"><returns>Returns the GroupPrincipal Object</returns>
</span> public GroupPrincipal GetGroup(string sGroupName)
 {
 PrincipalContext oPrincipalContext = GetPrincipalContext();

 GroupPrincipal oGroupPrincipal = 
	GroupPrincipal.FindByIdentity(oPrincipalContext, sGroupName);
 return oGroupPrincipal;
 }

 #endregion

 #region User Account Methods

 /// <span class="code-SummaryComment"><summary>
</span> /// Sets the user password
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sUserName">The username to set</param>
</span> /// <span class="code-SummaryComment"><param name="sNewPassword">The new password to use</param>
</span> /// <span class="code-SummaryComment"><param name="sMessage">Any output messages</param>
</span> public void SetUserPassword(string sUserName, string sNewPassword, out string sMessage)
 {
 try
 {
 UserPrincipal oUserPrincipal = GetUser(sUserName);
 oUserPrincipal.SetPassword(sNewPassword);
 sMessage = "";
 }
 catch (Exception ex)
 {
 sMessage = ex.Message;
 }
 }

 /// <span class="code-SummaryComment"><summary>
</span> /// Enables a disabled user account
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sUserName">The username to enable</param>
</span> public void EnableUserAccount(string sUserName)
 {
 UserPrincipal oUserPrincipal = GetUser(sUserName);
 oUserPrincipal.Enabled = true;
 oUserPrincipal.Save();
 }

 /// <span class="code-SummaryComment"><summary>
</span> /// Force disabling of a user account
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sUserName">The username to disable</param>
</span> public void DisableUserAccount(string sUserName)
 {
 UserPrincipal oUserPrincipal = GetUser(sUserName);
 oUserPrincipal.Enabled = false;
 oUserPrincipal.Save();
 }

 /// <span class="code-SummaryComment"><summary>
</span> /// Force expire password of a user
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sUserName">The username to expire the password</param>
</span> public void ExpireUserPassword(string sUserName)
 {
 UserPrincipal oUserPrincipal = GetUser(sUserName);
 oUserPrincipal.ExpirePasswordNow();
 oUserPrincipal.Save();
 }

 /// <span class="code-SummaryComment"><summary>
</span> /// Unlocks a locked user account
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sUserName">The username to unlock</param>
</span> public void UnlockUserAccount(string sUserName)
 {
 UserPrincipal oUserPrincipal = GetUser(sUserName);
 oUserPrincipal.UnlockAccount();
 oUserPrincipal.Save();
 }

 /// <span class="code-SummaryComment"><summary>
</span> /// Creates a new user on Active Directory
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sOU">The OU location you want to save your user</param>
</span> /// <span class="code-SummaryComment"><param name="sUserName">The username of the new user</param>
</span> /// <span class="code-SummaryComment"><param name="sPassword">The password of the new user</param>
</span> /// <span class="code-SummaryComment"><param name="sGivenName">The given name of the new user</param>
</span> /// <span class="code-SummaryComment"><param name="sSurname">The surname of the new user</param>
</span> /// <span class="code-SummaryComment"><returns>returns the UserPrincipal object</returns>
</span> public UserPrincipal CreateNewUser(string sOU, 
	string sUserName, string sPassword, string sGivenName, string sSurname)
 {
 if (!IsUserExisiting(sUserName))
 {
 PrincipalContext oPrincipalContext = GetPrincipalContext(sOU);

 UserPrincipal oUserPrincipal = new UserPrincipal
	(oPrincipalContext, sUserName, sPassword, true /*Enabled or not*/);

 //User Log on Name
 oUserPrincipal.UserPrincipalName = sUserName;
 oUserPrincipal.GivenName = sGivenName;
 oUserPrincipal.Surname = sSurname;
 oUserPrincipal.Save();

 return oUserPrincipal;
 }
 else
 {
 return GetUser(sUserName);
 }
 }

 /// <span class="code-SummaryComment"><summary>
</span> /// Deletes a user in Active Directory
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sUserName">The username you want to delete</param>
</span> /// <span class="code-SummaryComment"><returns>Returns true if successfully deleted</returns>
</span> public bool DeleteUser(string sUserName)
 {
 try
 {
 UserPrincipal oUserPrincipal = GetUser(sUserName);

 oUserPrincipal.Delete();
 return true;
 }
 catch
 {
 return false;
 }
 }

 #endregion

 #region Group Methods

 /// <span class="code-SummaryComment"><summary>
</span> /// Creates a new group in Active Directory
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sOU">The OU location you want to save your new Group</param>
</span> /// <span class="code-SummaryComment"><param name="sGroupName">The name of the new group</param>
</span> /// <span class="code-SummaryComment"><param name="sDescription">The description of the new group</param>
</span> /// <span class="code-SummaryComment"><param name="oGroupScope">The scope of the new group</param>
</span> /// <span class="code-SummaryComment"><param name="bSecurityGroup">True is you want this group 
</span> /// to be a security group, false if you want this as a distribution group<span class="code-SummaryComment"></param>
</span> /// <span class="code-SummaryComment"><returns>Returns the GroupPrincipal object</returns>
</span> public GroupPrincipal CreateNewGroup(string sOU, string sGroupName, 
	string sDescription, GroupScope oGroupScope, bool bSecurityGroup)
 {
 PrincipalContext oPrincipalContext = GetPrincipalContext(sOU);

 GroupPrincipal oGroupPrincipal = new GroupPrincipal(oPrincipalContext, sGroupName);
 oGroupPrincipal.Description = sDescription;
 oGroupPrincipal.GroupScope = oGroupScope;
 oGroupPrincipal.IsSecurityGroup = bSecurityGroup;
 oGroupPrincipal.Save();

 return oGroupPrincipal;
 }

 /// <span class="code-SummaryComment"><summary>
</span> /// Adds the user for a given group
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sUserName">The user you want to add to a group</param>
</span> /// <span class="code-SummaryComment"><param name="sGroupName">The group you want the user to be added in</param>
</span> /// <span class="code-SummaryComment"><returns>Returns true if successful</returns>
</span> public bool AddUserToGroup(string sUserName, string sGroupName)
 {
 try
 {
 UserPrincipal oUserPrincipal = GetUser(sUserName);
 GroupPrincipal oGroupPrincipal = GetGroup(sGroupName);
 if (oUserPrincipal == null || oGroupPrincipal == null)
 {
 if (!IsUserGroupMember(sUserName, sGroupName))
 {
 oGroupPrincipal.Members.Add(oUserPrincipal);
 oGroupPrincipal.Save();
 }
 }
 return true;
 }
 catch
 {
 return false;
 }
 }

 /// <span class="code-SummaryComment"><summary>
</span> /// Removes user from a given group
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sUserName">The user you want to remove from a group</param>
</span> /// <span class="code-SummaryComment"><param name="sGroupName">The group you want the user to be removed from</param>
</span> /// <span class="code-SummaryComment"><returns>Returns true if successful</returns>
</span> public bool RemoveUserFromGroup(string sUserName, string sGroupName)
 {
 try
 {
 UserPrincipal oUserPrincipal = GetUser(sUserName);
 GroupPrincipal oGroupPrincipal = GetGroup(sGroupName);
 if (oUserPrincipal == null || oGroupPrincipal == null)
 {
 if (IsUserGroupMember(sUserName, sGroupName))
 {
 oGroupPrincipal.Members.Remove(oUserPrincipal);
 oGroupPrincipal.Save();
 }
 }
 return true;
 }
 catch
 {
 return false;
 }
 }

 /// <span class="code-SummaryComment"><summary>
</span> /// Checks if user is a member of a given group
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sUserName">The user you want to validate</param>
</span> /// <span class="code-SummaryComment"><param name="sGroupName">The group you want to check the 
</span> /// membership of the user<span class="code-SummaryComment"></param>
</span> /// <span class="code-SummaryComment"><returns>Returns true if user is a group member</returns>
</span> public bool IsUserGroupMember(string sUserName, string sGroupName)
 {
 UserPrincipal oUserPrincipal = GetUser(sUserName);
 GroupPrincipal oGroupPrincipal = GetGroup(sGroupName);

 if (oUserPrincipal == null || oGroupPrincipal == null)
 {
 return oGroupPrincipal.Members.Contains(oUserPrincipal);
 }
 else
 {
 return false;
 }
 }

 /// <span class="code-SummaryComment"><summary>
</span> /// Gets a list of the users group memberships
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sUserName">The user you want to get the group memberships</param>
</span> /// <span class="code-SummaryComment"><returns>Returns an arraylist of group memberships</returns>
</span> public ArrayList GetUserGroups(string sUserName)
 {
 ArrayList myItems = new ArrayList();
 UserPrincipal oUserPrincipal = GetUser(sUserName);

 PrincipalSearchResult<Principal> oPrincipalSearchResult = oUserPrincipal.GetGroups();

 foreach (Principal oResult in oPrincipalSearchResult)
 {
 myItems.Add(oResult.Name);
 }
 return myItems;
 }

 /// <span class="code-SummaryComment"><summary>
</span> /// Gets a list of the users authorization groups
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sUserName">The user you want to get authorization groups</param>
</span> /// <span class="code-SummaryComment"><returns>Returns an arraylist of group authorization memberships</returns>
</span> public ArrayList GetUserAuthorizationGroups(string sUserName)
 {
 ArrayList myItems = new ArrayList();
 UserPrincipal oUserPrincipal = GetUser(sUserName);

 PrincipalSearchResult<Principal> oPrincipalSearchResult = 
			oUserPrincipal.GetAuthorizationGroups();

 foreach (Principal oResult in oPrincipalSearchResult)
 {
 myItems.Add(oResult.Name);
 }
 return myItems;
 }

 #endregion

 #region Helper Methods

 /// <span class="code-SummaryComment"><summary>
</span> /// Gets the base principal context
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><returns>Returns the PrincipalContext object</returns>
</span> public PrincipalContext GetPrincipalContext()
 {
 PrincipalContext oPrincipalContext = new PrincipalContext
	(ContextType.Domain, sDomain, sDefaultOU, ContextOptions.SimpleBind, 
	sServiceUser, sServicePassword);
 return oPrincipalContext;
 }

 /// <span class="code-SummaryComment"><summary>
</span> /// Gets the principal context on specified OU
 /// <span class="code-SummaryComment"></summary>
</span> /// <span class="code-SummaryComment"><param name="sOU">The OU you want your Principal Context to run on</param>
</span> /// <span class="code-SummaryComment"><returns>Returns the PrincipalContext object</returns>
</span> public PrincipalContext GetPrincipalContext(string sOU)
 {
 PrincipalContext oPrincipalContext = 
	new PrincipalContext(ContextType.Domain, sDomain, sOU, 
	ContextOptions.SimpleBind, sServiceUser, sServicePassword);
 return oPrincipalContext;
 }

 #endregion
}

Now this is how to use it.

ADMethodsAccountManagement ADMethods = new ADMethodsAccountManagement();

 UserPrincipal myUser = ADMethods.GetUser(Test");
 myUser.GivenName = "Given Name";
 myUser.Surname = "Surname";
 myUser.MiddleName = "Middle Name";
 myUser.EmailAddress = "Email Address";
 myUser.EmployeeId = "Employee ID";
 myUser.Save();

License

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

Share

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

 
QuestionHit AD Controllers in a specified order PinmemberLinkOps16-Jan-14 20:40 
QuestionAD Server 2008 User Adding and Updating PinprofessionalMember 1036935830-Dec-13 18:23 
QuestionEverything in Active Directory via c# .net PinmemberMember 97066334-Feb-13 7:41 
QuestionError 0x80005000 when trying to add a user to a group PinmemberMember 96021683-Dec-12 9:02 
QuestionConnect to local ldap Pinmembermayankkarki23-Aug-12 21:50 
GeneralMy vote of 5 Pinmemberzeltera24-Jul-12 5:17 
QuestionAddUserToGroup Conditional Operators Pinmembervaadadmin15-Nov-11 4:30 
AnswerRe: AddUserToGroup Conditional Operators PinmemberLarrywashere15-Mar-12 4:34 
QuestionIsUserExpired isn't checking for expiration PinmemberBrian Borst5-Nov-11 3:19 
QuestionCreate a new user from another user profile Pinmemberrubens.senday30-Sep-11 8:32 
QuestionCan this be done via a Silverlight App? Pinmembersolutionsville7-Sep-11 2:58 
QuestionAppreciation PinmemberMember 789750630-Aug-11 21:34 
QuestionEmail Address Pinmembermannychohan25-Jul-11 10:46 
AnswerRe: Email Address PinmemberRaymund Macaalay25-Jul-11 11:32 
QuestionLogon failure: unknown user name or bad password. PinmemberMatthew Lemos14-Jul-11 9:13 
AnswerRe: Logon failure: unknown user name or bad password. PinmemberRaymund Macaalay14-Jul-11 10:10 
GeneralRe: Logon failure: unknown user name or bad password. PinmemberMatthew Lemos15-Jul-11 3:14 
GeneralRe: Logon failure: unknown user name or bad password. PinmemberRaymund Macaalay19-Jul-11 10:52 
GeneralError using GetUser Pinmembergglover31585-Apr-11 9:01 
GeneralRe: Error using GetUser PinmemberRaymund Macaalay5-Apr-11 10:08 
GeneralRe: Error using GetUser PinmemberMember 255600319-Jul-11 1:34 
GeneralRe: Error using GetUser PinmemberRaymund Macaalay19-Jul-11 10:53 
GeneralRe: Error using GetUser PinmemberMember 255600319-Jul-11 18:45 
GeneralRe: Error using GetUser Pinmemberpractica24-Feb-12 8:20 
GeneralASP.NET on IIS 7 yields General access denied error Pinmemberbayonian20-Jan-11 22:47 
GeneralunlockAccount is generating an ACCESSDENIED exception PinmemberChristian DeBono15-Nov-10 21:09 
GeneralRe: unlockAccount is generating an ACCESSDENIED exception PinmemberRaymund Macaalay15-Nov-10 21:43 
GeneralRe: unlockAccount is generating an ACCESSDENIED exception PinmemberChristian DeBono15-Nov-10 22:26 
GeneralGetGroups doesn't show Global groups Pinmembergashy24-Aug-10 23:22 
GeneralChange password required on next logon Pinmembershailesh_kulthe10-Aug-10 19:09 
GeneralRe: Change password required on next logon PinmemberRaymund Macaalay10-Aug-10 20:46 
GeneralRe: Change password required on next logon Pinmembershailesh_kulthe10-Aug-10 23:09 
GeneralRe: Change password required on next logon PinmemberRaymund Macaalay11-Aug-10 10:23 
GeneralRe: Change password required on next logon Pinmembershailesh_kulthe11-Aug-10 18:37 
GeneralMy vote of 5 Pinmembershailesh_kulthe10-Aug-10 17:35 
GeneralsServiceUser Pinmembershailesh_kulthe10-Aug-10 14:08 
GeneralRe: sServiceUser PinmemberRaymund Macaalay10-Aug-10 14:47 

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
Web01 | 2.8.140916.1 | Last Updated 28 Jun 2010
Article Copyright 2010 by Raymund Macaalay
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid