Breaking News

Monday, December 14, 2009

LDAP: How to get the list of UserIDs from active directory

LDAP: How to get the sorted list all userids that exist on active directory. See following snip:

/// 
    /// List all UserIDs(not user names) that exist on active directory
    /// 
    /// 
    public static List GetAllDomainUsersEx()
    {
        string strLdap = Common.Utility.Constants.LDAP_URL;
        DirectoryEntry objOU = new DirectoryEntry(strLdap);

        //Properties that 
        string[] loadProps = new string[] { "cn"/*Canonical name*/, 
                                            "samaccountname"/*UserID*/, 
                                            "name"/*User Name*/, 
                                            "distinguishedname" /*LDAP unique path to the user*/
                                          };

        //Create a directory searcher object
        DirectorySearcher objUserSearcher = new DirectorySearcher(objOU, "(&(objectClass=user)(objCategory=person))", loadProps);
        SearchResultCollection objResults;

        //Filter criteria.
        objUserSearcher.Filter = "(objectClass=user)";

        //Find all records
        objResults = objUserSearcher.FindAll();

        List lstUsers = new List();
        
        //Loop through
        foreach (SearchResult objResult in objResults)
        {
            string str = objResult.Properties["samaccountname"][0].ToString();
            if(!str.Contains("$")) //remove system users, thats is, users with dollar sign
            {
                lstUsers.Add(str.ToLower());
            }
        }

        return lstUsers.Sort();
    }


Usage:
Following is how you would use; or bind it with a drop down list box.
private void ReloadDomainUserList()
{
List lstUsers = new List();
lstUsers = CLDAPManager.GetAllDomainUsersEx();

ddlADUsers.DataSource = lstUsers;
ddlADUsers.DataBind();
}

No comments:

Post a Comment

Designed By Published.. Blogger Templates