Today we going to develop one project who will make something in the Active Directory.
Wikipédia (http://en.wikipedia.org/wiki/Active_Directory)
Basically we going to develop this methods:
- Disable an existing user from AD;
- Update an user from AD;
- Remove all the groups which user belongs;
- Move user to the group: "Blockeds";
But, We need to develop some methods to get the principal context from AD:
- GetUser: get the user from AD
- GetGroup: get the groups of an user from AD
- GetPrincipalContext: get the principal context from AD
- GetDirectoryEntry: set the directory for connect to AD
So let's go to the code... :)
Note: I will not develop the project for complete, I will just to show the methods.
You can use and adapt on your project.
Note2:
- USERNAME = Login
DISPLAYNAME = Full Name
Firstly, we need to reference the project
Picture 1 - Referencing your project
The code: AD.cs
using System.Collections.Generic;
using System.Data.SqlClient;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.DirectoryServices.AccountManagement;
public class ActiveDirectory
// TODO: Add constructor logic here
private string sDomain = ""; //add your domain here
private string sDefaultOU = "OU=Test Users,OU=Test,DC=test,DC=com";
private string sServiceUser = @"ServiceUser";
private string sServicePassword = "ServicePassword";
string UserDisplayName = ObterUserDisplayName (string UserName);
UpdateUserFromAD(string Username, string Fullname, string Department,
string Email, string Manager);
DisableUserFromAD(string UserName);
string groups = GetUserGroupsFromAD(string UserName);
RemoveGroupsUserAD(string groups, string userName);
MoveUserFromAnotherGroup(string UserName);
/// Method to get the userDisplayName from AD
/// <param name="Matricula">The UserName</param>
/// <returns>The UserDisplayName </returns>
public string ObterUserDisplayName(string Username)
SqlCommand cmd = new SqlCommand();
StringBuilder sb = new StringBuilder();
SqlConnection conn = new SqlConnection(""); //put here your connection string
string UserDisplayName = string.Empty;
sb.AppendLine("DECLARE @Sql VARCHAR(1000)");
sb.AppendLine("DECLARE @UserDisplayName varchar(30)");
sb.AppendLine("CREATE TABLE #tmp (UserDisplayName varchar(30))");
sb.AppendLine("set @Sql =");
sb.AppendLine("insert into #tmp");
sb.AppendLine("select displayName");
sb.AppendLine("from openquery");
sb.AppendLine("displayName,");
sb.AppendLine("''''LDAP://dc=,dc=,dc=,dc=''''"); //put here your domain
sb.AppendLine("objectCategory = ''''Person'''' AND");
sb.AppendLine("objectClass = ''''user'''' AND");
sb.AppendLine("sAMAccountName = '''''+@Username+'''''");
sb.AppendLine("EXEC(@Sql)");
sb.AppendLine("SELECT @UserDisplayName=displayName FROM #tmp");
sb.AppendLine("DROP TABLE #tmp");
cmd.Parameters.Add(new SqlParameter("@Username", Username));
cmd.CommandText = sb.ToString();
cmd.CommandType = CommandType.Text;
UserDisplayName = cmd.ExecuteScalar() == null ? null :
cmd.ExecuteScalar().ToString();
/// Method to update an existing user from AD
/// <param name="Username">The UserName</param>
/// <param name="Fullname">The new user Full Name</param>
/// <param name="Department">The new department that the user works</param>
/// <param name="Email">The new email</param>
/// <param name="Manager">The new manager</param>
public void UpdateUserFromAD(string Username, string Fullname,
string Department, string Email, string Manager)
DirectoryEntry de = GetDirectoryEntry();
DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = ("(&(objectclass=user)(objectcategory=person)(displayname=" +
userDisplayName + "))");
ds.SearchScope = SearchScope.Subtree;
SearchResult results = ds.FindOne();
DirectoryEntry updateEntry = results.GetDirectoryEntry();
updateEntry.Properties["department"].Value = Department;
updateEntry.Properties["manager"].Value = Manager;
updateEntry.Properties["mail"].Value = Email;
updateEntry.Properties["displayName"].Value = FullName;
updateEntry.CommitChanges();
/// Disable an existing user from AD
/// <param name="userName">The userName</param>
public void DesabilitaUsuarioAD(string userName)
UserPrincipal Usuario = GetUser(userName);
/// Method to get all the user groups
/// <param name="userName">UserName</param>
/// <returns>all the user groups</returns>
public string GetGroupsFromAD(string userName)
DirectorySearcher search = new DirectorySearcher();
search.Filter = string.Format("(cn={0}", userName);
search.PropertiesToLoad.Add("memberOf");
StringBuilder listaGrupo = new StringBuilder();
SearchResult resultado = search.FindOne();
int numeroDeGrupos = resultado.Properties["memberOf"].Count;
for (int i = 0; i < numeroDeGrupos; i++)
listaGrupo.Append((string)resultado.Properties["memberOf"][i]);
return listaGrupo.ToString();
/// Method to remove all the groups which user belongs
/// <param name="gruposUser">Groups wich user belongs</param>
/// <param name="userName">UserName from AD</param>
public void RemoveGroupsUserAD(string gruposUser, string userName)
string[] groups = gruposUser.Split('|');
UserPrincipal Usuario = GetUser(userName);
for (int i = 0; i < groups.Length; i++)
GroupPrincipal GrupoUsuario = GetGroup(groups[i]);
if (Usuario != null && GrupoUsuario != null && groups[i] != "Domain Users")
GrupoUsuario.Members.Remove(Usuario);
/// Move user to the group "Blockeds"
/// <param name="userName">UserName</param>
public void MoverUsuarioGrupoBloqueados(string userName)
string grupoUserTarget = "Blockeds";
UserPrincipal UsuarioPrincipal = GetUser(userName);
GroupPrincipal GrupoPrincipal = GetGroup(grupoUserTarget);
if (UsuarioPrincipal != null && GrupoPrincipal != null)
GrupoPrincipal.Members.Add(UsuarioPrincipal);
/// Gets a certain group on Active Directory
/// <param name="GroupName"> The group to get</param>
/// <returns>Returns the GroupPrincipal Object</returns>
public GroupPrincipal GetGroup(string GroupName)
PrincipalContext oPrincipalContext = GetPrincipalContext();
GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, GroupName);
/// Get the DirectoryEntry Object
/// <returns>The DirectoryEntry Object</returns>
public static DirectoryEntry GetDirectoryEntry()
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://OU=,DC=,DC=, DC=, DC="; //put your domain here
de.AuthenticationType = AuthenticationTypes.Secure;
/// Get the UserPrincipal Object if the User Exists
/// <param name="UserName">UserName of the user</param>
/// <returns>The UserPrincipal Object</returns>
public UserPrincipal GetUser(string UserName)
PrincipalContext oPrincipalContext = GetPrincipalContext();
UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, UserName);
See you guys in the next post.
Thanks!