Welcome to Steve Saxon's Downtime Sign in | Join | Help in Search
  Home Forums Photos Downloads

Querying Active Directory using LINQ

Last post 10-22-2006, 6:20 PM by xmlguy. 0 replies.
Sort Posts: Previous Next
  •  10-22-2006, 6:20 PM 49

    Geeked [8-|] Querying Active Directory using LINQ

    At Desert Code Camp in Tempe AZ on October 28th I will be giving a talk on how to write an extender that lets you query Active Directory using LINQ.

    At that time I will post the code here for folks that would like to try it out for themselves.

    Here are examples of queries written using my LINQ extender:

    // find the names of all people in AD whose last name is Smith or first name is John
    var
    q = from e in AD.Users
    where e.LastName == "Smith" || e.FirstName == "John" select e.Name;

    This query ends up querying Active Directory with this filter:

    (&(objectCategory=user)(objectClass=person)(|(sn=Smith)(givenName=John)))

    For comparison, the traditional System.DirectoryServices API equivalent of this query is:

    List<string> q = new List<string>();

    using(DirectorySearch searcher = new DirectorySearcher())
    {
        searcher.Filter = "(&(objectCategory=user)(objectClass=person)" +
                          "(|(sn=Smith)(givenName=John)))";

        foreach(SearchResult result in searcher.FindAll())
        {
            q.Add(result.Properties["name"][0].Value);
        }
    }

    As you can see, the LINQ based query is much easier to read! 

    You can also do membership-based queries such as this one:

    // get the name and email of everyone in the group called Western Region
    var
    q = from e in AD.Groups.Single(g => g.Name == "Western Region").GetMembers()
       
    select new { e.Name, e.Email };

    Before anyone asks, my example does not currently support making changes back to the repository.

    Filed under: ,
View as RSS news feed in XML
Powered by Community Server, by Telligent Systems