Thursday, March 31, 2011

Get All AD Groups using LDAP in C#

Issue: LDAP Query not pulling all the Active Directory Groups (including subgroups) available in the given domain.

Solution:
To retrieve a set of results that is larger than 1000 items, you must set SizeLimit to its default value (zero) and set PageSize to a value that is less than or equal to 1000.

Concept Source: Click here


public static DataTable GetAllActiveDirectoryGroups(string ldapServer, string ldapUserName, string ldapPassWord)
        {
            DataTable dt = new DataTable();
            DataRow dr;
 
 
            DirectoryEntry de = new DirectoryEntry(ldapServer);
            de.Username = ldapUserName;
            de.Password = ldapPassWord;
            DirectorySearcher deSearch = new DirectorySearcher(de.Path);
            
            SearchResultCollection results;
            dt.Columns.Add("GroupName");
            try
            {
                deSearch.Filter = ("(&(objectCategory=group))");
                deSearch.SearchScope = SearchScope.Subtree;
                //deSearch.SizeLimit = 10000;
                deSearch.PageSize = 1000;
                results = deSearch.FindAll();
 
                foreach (SearchResult result in results)
                {
                    dr = dt.NewRow();
                    dr["GroupName"] = result.Properties["cn"][0].ToString();
                    dt.Rows.Add(dr);
                }
                de.Close();
 
 
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (deSearch != null)
                {
                    deSearch.Dispose();
                }
                if (de != null)
                {
                    de.Dispose();
                }
            }
            
            return dt;
 
        }
 
 
Code can be downloaded here: Download

2 comments:

  1. Shrinivas,

    I am trying to get all the users from AD based on the query.
    Example
    i want to display all the user's name start from pet*
    How can we query this ? Pls help

    ReplyDelete

Access to XMLHttpRequest at 'from origin has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. .net core angular

Issue: The angular application was getting error from API that the origin has been blocked by CORS policy. Solution: Make sure that the...