Sunday, February 6, 2011

LINQ to LDAP: Attributes, Where?

I think one of the hardest things for me in working with LDAP is finding out what is actually in the directory. A Google search can help with identifying predefined attributes, but what about custom ones? Each directory is going to be different and different organizations are going to track different things. I wanted to make this discovery process easier.

I created an extension method called ListAttributes that does what it's name suggests. I'll use LINQPad to show how much I like this feature. You can download it here for free.


First thing you'll want to do is Launch the application and switch the language to "C# Program"


Right click and then select "Query Properties"


You should now see this screen. From here you should click on "Add" to add System.DirectoryServices.Protocols and "Browse" to add LinqToLdap.dll from where you have it on your machine.


It should look like this when you're done.


Next click the "Additional Namespace Imports" tab and type in System.DirectoryServices.Protocols and LinqToLdap.

After you hit OK, you can then type in some C# code and execute it. I'm going to use Andrew Fuller from the Northwind database that I used to populate my directory.

void Main()
{
 using (LdapConnection connection = new LdapConnection("localhost"))
 {
  var example = new { Cn = "" };
  using (var context = new DirectoryContext(connection))
  {
   context.Query(example, "CN=Employees,DC=Northwind,DC=local")
    .Where(u => u.Cn == "Andrew Fuller")
    .ListAttributes()
    .Dump();
  }
 }
}

That Dump() method is a special extension method that is part of LINQPad. It will format the results auto-magically for you which is why I like it so much. Here's what I get when I execute the query:


Now this won't just dump everything. It will only list populated attributes. It's not perfect, but it will give you a pretty good idea what is and isn't tracked about directory objects and what their data types are. LINQPad is even doing some color coding for you to show you what's a byte[]. Awesome!

No comments:

Post a Comment