Monday, April 18, 2011

LINQ To LDAP: Dynamics!

Short post to be updated later. During my property mapping changes (added support for file time date mapping and enum mapping and cleaned up the structure to support directory modifications in the future), I was inspired in a massive way to add dynamic support for LINQ to LDAP. I'm happy to say that it works very well! You can't use expressions, but everything else works.

dynamic user = context.Query("CN=Users,CN=Employees,DC=Northwind,DC=local")
    .Select(new[]{"cn", "givenname", "sn", "telephonenumber"})
    .FilterWith("cn=Andrew Fuller")
    .FirstOrDefault();

Console.WriteLine(user.cn);
Console.WriteLine(user.givenname);
Console.WriteLine(user.sn);
Console.WriteLine(user.telephonenumber);

I added a Select extension that takes an array of strings so you still get projection support. FilterWith is the only way to query since everything else uses expressions (you can't use dynamic types in expressions). The only type support you get here is what can come back from the directory so that's string, string[], and byte[]. Also, property names will always be lower case so even though it may be givenName in the directory, use givenname to access it. That's just how DirectoryServices.Protocols rolls.