sábado, 10 de março de 2012

How to manipulate the Active Directory using C# (Framework 4.0)

Good morning guys.

Today we going to develop one project who will make something in the Active Directory.

AD
Active Directory (AD) is a directory service created by Microsoft for Windows domain networks. It is included in most Windows Server operating systems. Server computers on which Active Directory is running are called domain controllers.
Active Directory serves as a central location for network administration and security. It is responsible for authenticating and authorizing all users and computers within a network of Windows domain type, assigning and enforcing security policies for all computers in a network and installing or updating software on network computers.
 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;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.DirectoryServices.AccountManagement;
using System.IO;

namespace ADProject
{
    public class ActiveDirectory
    {
        public 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";
             
        public void AD
        {                   
              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);
        }
             
        /// <summary>
        /// Method to get the userDisplayName from AD
        /// </summary>
        /// <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;

            cmd.Connection = conn;
            conn.Open();

            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("'");
            sb.AppendLine("insert into #tmp");
            sb.AppendLine("select displayName");
            sb.AppendLine("from  openquery");
            sb.AppendLine("(");
            sb.AppendLine("ADSI,");
            sb.AppendLine("''");
            sb.AppendLine("select");
            sb.AppendLine("displayName,");
            sb.AppendLine("from");
            sb.AppendLine("''''LDAP://dc=,dc=,dc=,dc=''''"); //put here your domain
            sb.AppendLine("where");
            sb.AppendLine("objectCategory = ''''Person'''' AND");
            sb.AppendLine("objectClass = ''''user'''' AND");
            sb.AppendLine("sAMAccountName = '''''+@Username+'''''");
            sb.AppendLine("''");
            sb.AppendLine(")");
            sb.AppendLine("'");
            sb.AppendLine("EXEC(@Sql)");
            sb.AppendLine("SELECT @UserDisplayName=displayName FROM #tmp");
            sb.AppendLine("DROP TABLE #tmp");

            try
            {
                cmd.Parameters.Add(new SqlParameter("@Username", Username));
                cmd.CommandText = sb.ToString();
                cmd.CommandType = CommandType.Text;

                UserDisplayName = cmd.ExecuteScalar() == null ? null :             
                cmd.ExecuteScalar().ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
                cmd.Dispose();
            }
            return UserDisplayName;
        }
             
         /// <summary>
         /// Method to update an existing user from AD
        /// </summary>
        /// <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();
            de.Username = Username;

            DirectorySearcher ds = new DirectorySearcher(de);
            ds.Filter = ("(&(objectclass=user)(objectcategory=person)(displayname=" +  
                         userDisplayName + "))");
            ds.SearchScope = SearchScope.Subtree;
            SearchResult results = ds.FindOne();

            if (results != null)
            {
                try
                {
                    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();
                    updateEntry.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
             
        /// <summary>
        /// Disable an existing user from AD
        /// </summary>
        /// <param name="userName">The userName</param>
        public void DesabilitaUsuarioAD(string userName)
        {
            UserPrincipal Usuario = GetUser(userName);
            Usuario.Enabled = false;
            Usuario.Save();
        }
             
        /// <summary>
        /// Method to get all the user groups
        /// </summary>
        /// <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();

            if (resultado != null)
            {
                int numeroDeGrupos = resultado.Properties["memberOf"].Count;

                for (int i = 0; i < numeroDeGrupos; i++)
                {
                    listaGrupo.Append((string)resultado.Properties["memberOf"][i]);
                    listaGrupo.Append("|");
                }
            }
            listaGrupo.Length -= 1;
            return listaGrupo.ToString();
        }

        /// <summary>
        /// Method to remove all the groups which user belongs
        /// </summary>
        /// <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);
                    GrupoUsuario.Save();
                }
            }
        }
             
        /// <summary>
        /// Move user to the group "Blockeds"
        /// </summary>
        /// <param name="userName">UserName</param>
        public void MoverUsuarioGrupoBloqueados(string userName)
        {
            string grupoUserTarget = "Blockeds";
            try
            {
                UserPrincipal UsuarioPrincipal = GetUser(userName);
                GroupPrincipal GrupoPrincipal = GetGroup(grupoUserTarget);
                if (UsuarioPrincipal != null && GrupoPrincipal != null)
                {
                    GrupoPrincipal.Members.Add(UsuarioPrincipal);
                    GrupoPrincipal.Save();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
             
        /// <summary>
        /// Gets a certain group on Active Directory
        /// </summary>
        /// <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);
            return oGroupPrincipal;
        }
             
        /// <summary>
        /// Get the DirectoryEntry Object
        /// </summary>
        /// <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;
            return de;
        }
             
              /// <summary>
        /// Get the UserPrincipal Object if the User Exists
        /// </summary>
        /// <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);
            return oUserPrincipal;
        }
       }
}

See you guys in the next post.
Thanks!

2 comentários:

  1. Simple but useful article... it's the best way to start coding with this powerful tool...

    Congratulations

    ResponderExcluir