Query multiple object classes from AD using LDAP Query
Rate this post

Recently I had to make a query to the Active Directory to get the list of users and contacts. To achieve this, I used the LDAP query. See the following function:

 ///<summary>
/// Queries the Active Directory using LDAP
///</summary>
///<param name="entry">Directory entry</param>
///<param name="search">Directory searcher with properties to load and filters</param>
///<returns>A dictionary with ObjectGuid as the key</returns>
public static Dictionary<string, SearchResult> QueryLDAP(DirectoryEntry entry, DirectorySearcher search)
{
    entry.AuthenticationType = AuthenticationTypes.SecureSocketsLayer;
    entry.Path = ConfigurationManager.AppSettings["LDAP.URL"].ToString();
    entry.Username = ConfigurationManager.AppSettings["LDAP.Username"].ToString();
    entry.Password = ConfigurationManager.AppSettings["LDAP.Password"].ToString();
    /// Load any attributes you want to retrieve
    search.SearchRoot = entry;
    search.PropertiesToLoad.Add("name");
    search.PropertiesToLoad.Add("telephonenumber");
    search.PropertiesToLoad.Add("mobile");
    search.PropertiesToLoad.Add("mail");
    search.PropertiesToLoad.Add("title");
    search.PropertiesToLoad.Add("department");
    search.PropertiesToLoad.Add("objectguid");
    search.PropertiesToLoad.Add("sn");
    search.PropertiesToLoad.Add("userAccountControl");
    search.PropertiesToLoad.Add("userPrincipalName");
    search.PropertiesToLoad.Add("msexchhidefromaddresslists");
    search.PropertiesToLoad.Add("samaccountname");
    search.Filter = "(|(ObjectClass=user)(ObjectClass=contact))";
    search.SearchScope = SearchScope.Subtree;
    SearchResultCollection result = search.FindAll();
    Dictionary<string, SearchResult> dicResult = new
    Dictionary<string, SearchResult>();
    foreach (SearchResult profile in result)
    {
       if (profile.Properties["objectGUID"] != null && profile.Properties["objectGUID"].Count > 0)
         {
           Guid guid = new Guid((Byte[])profile.Properties["objectGUID"][0]);
           dicResult.Add(guid.ToString(), profile);
         }
     }
     result.Dispose();
     entry.Close();
     entry.Dispose();
    return dicResult;

}

What this function does is, it queries the Active Directory and returns all profiles (set by filter) in a dictionary object. Notice the search filter set to return all objects class of user AND contact. The settings would come from a config file as below. Replace the tags with your settings:

<appSettings>
<!--LDAP settings-->
<add key="LDAP.URL" value="LDAP://OU=<OU_NAME>,DC=<DC_NAME>,DC=com" />
<add key="LDAP.Username" value="<SERVICE_ACCOUNT_USERNAME>" />
<add key="LDAP.Password" value="<SERVICE_ACCOUNT_PWD>" />
</appSettings>

So to use it, we will do:

using (DirectoryEntry entry = new DirectoryEntry())
using (DirectorySearcher search = new DirectorySearcher())
{
      //extract all AD profiles
      sbLog.AppendLine("Preparing to query LDAP...");
      Dictionary<string, SearchResult> AD_Results = QueryLDAP(entry, search);
      foreach (SearchResult ADProfile in AD_Results)
       {
         string email = ADProfile.GetDirectoryEntry().Properties["mail"].Value.ToString();
         //etc
       }
}

You can now loop through the dictionary to get each profile. 🙂


Category:
Application Development and Integration, SharePoint
Tags:
, , , ,

Leave a Reply

  Subscribe  
Notify of
nitin swarup
Guest
nitin swarup

Looks like a great article , but its missing information on prerequisites for someone like me to run a script like this successfully . So if you can add some of the information like . 1. What LDAP URL needs to be used in here ” entry.Path = ConfigurationManager.AppSettings[“LDAP.URL”].ToString();” 2. What language has been used to write this and In which tool. 3. May be more comments for us to know where we have to modify the Script. if you can point to more content to read and learn how can we write more scripts like this . I really… Read more »

Follow Us!

Kloud Solutions Blog - Follow Us!