Wednesday, 29 October 2014

Connect Remote Active Directory using C# code

Sometimes it is required to get users information from remote server’s Active Directory. You may need to fetch some Groups of Active Directory. Here are sample codes which can help you.

Get all the users from AD specific group and fetch their information using Group Principal

   private static void GroupSearch()
        {
            Console.WriteLine("Start Group Search");
            try
            {
                PrincipalContext principalctx = new PrincipalContext(ContextType.Domain, YourServer/YourDomain, YourUserName, YourPassword);
                GroupPrincipal groupprinciple = GroupPrincipal.FindByIdentity(principalctx, IdentityType.Name, GroupName);
                if (groupprinciple != null)
                {
                    foreach (Principal innerprincipal in groupprinciple.GetMembers(false))
                    {
                        try
                        {
                            Console.WriteLine(((System.DirectoryServices.AccountManagement.UserPrincipal)(innerprincipal)).GivenName);
                            Console.WriteLine(((System.DirectoryServices.AccountManagement.UserPrincipal)(innerprincipal)).Surname);
                            Console.WriteLine(innerprincipal.SamAccountName);
                            Console.WriteLine(((System.DirectoryServices.AccountManagement.UserPrincipal)(innerprincipal)).EmailAddress);
                            Console.WriteLine(((System.DirectoryServices.AccountManagement.AuthenticablePrincipal)(innerprincipal)).Enabled ?? false);

                        }
                        catch (Exception exe)
                        {
                        }
                    }
                    groupprinciple.Dispose();
                    principalctx.Dispose();
                }
            }
            catch (Exception ex)
            {
            
            }
            Console.WriteLine("End of Group Search");
        }

Achieve same using Directory Searcher object with LDAP command

  private static void LDAP()
        {
            try
            {
                string DomainPath = "LDAP://YourIP/dc=yourDomain,dc=yourDomainExtension";
               
                DirectoryEntry searchRoot = new DirectoryEntry(DomainPath, "yourUserName", "yourPassword",AuthenticationTypes.Secure);
               
                DirectorySearcher search = new DirectorySearcher(searchRoot);
                search.Filter = ((memberOf=CN=YourGroupName,OU=YourDirectoryHierarchy, dc=yourDomain,dc=yourDomainExtension))";
                search.PropertiesToLoad.Add("samaccountname");
                search.PropertiesToLoad.Add("mail");
                search.PropertiesToLoad.Add("userAccountControl");
                search.PropertiesToLoad.Add("displayname");//first name
                SearchResult result;
                SearchResultCollection resultCol = search.FindAll();
                if (resultCol != null)
                {
                    for (int counter = 0; counter < resultCol.Count; counter++)
                    {
                        string UserNameEmailString = string.Empty;
                        result = resultCol[counter];
                        if (result.Properties.Contains("displayname"))
                        {
                            Console.WriteLine((String)result.Properties["displayname"][0]);
                        }
                        if (result.Properties.Contains("samaccountname"))
                        {
                            Console.WriteLine((String)result.Properties["samaccountname"][0]);
                        }
                        if (result.Properties.Contains("mail"))
                        {
                            Console.WriteLine((String)result.Properties["mail"][0]);
                        }
                        if (result.Properties.Contains("userAccountControl"))
                        {
                            //Property check status of user
                        }
                       
                    }
                }
            }
            catch (Exception ex)
            {
          
            }

            Console.WriteLine("END Start LDAP");
        }

If you want to search all the users from root AD change bellow code from above lines:
search.Filter = "(&(objectClass=user)(objectCategory=person))";

If you want to get one user information change bellow code from above lines:
search.Filter = "(&(objectClass=user)(objectCategory=person) (sAMAccountName=yourUserName))";


Hope this sample codes help you!