Share

This is another one of those “out of necessity” scenarios.  I’m currently building an Active Directory-aware application that impliments an Active Directory helper class I wrote to provide methods for working with AD.  A lot of my work was based on this article.  One of the methods I added to my class I decided to share here because I was unable to find a similar solution through Googling.

So the problem I had was, I needed to be able to get the category of an object in AD.  To do this in C#, we first have to import the AD namespaces:

using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;

Then we create an object category enumeration to define what categories to support:

public enum ObjectCategory
{
   User,
   Group,
   Computer,
   Unknown
}

And now we define the method:

public ObjectCategory GetObjectCategory(string ObjectName, string FQDN)
{
   string sDistinguishedName = string.Empty;
   string sConnectPrefix = "LDAP://" + FQDN;
   DirectoryEntry entry = new DirectoryEntry(sConnectPrefix);
   DirectorySearcher mySearcher = new DirectorySearcher(entry);
   string[] sSearches = new string[] {"(&(objectClass=user)(objectCategory=person)(|(cn=" + ObjectName + ")(sAMAccountName=" + ObjectName + ")))"
                                    , "(&(objectClass=group)(objectCategory=group)(|(cn=" + ObjectName + ")(dn=" + ObjectName + ")))"
                                    , "(&(objectClass=computer)(objectCategory=computer)(|(cn=" + ObjectName + ")(dn=" + ObjectName + ")))"};
    foreach (string s in sSearches)
    {
        mySearcher.Filter = s;
        SearchResult result = mySearcher.FindOne();
        if (result == null)
        {
           continue;
        }
        else
        {
           if (s.Contains("objectCategory=person"))
           {
              return ObjectClass.User;
           }
           if (s.Contains("objectCategory=group"))
           {
              return ObjectClass.Group;
           }
           if (s.Contains("objectCategory=computer"))
           {
              return ObjectClass.Computer;
           }
        }
     }
   return ObjectClass.Unknown;
}

Now we can use this like so:

if (GetObjectCategory("John Doe", "Fabrikam.com") == ObjectCategory.User)
{
   Console.WriteLine("John Doe is a User!");
}
else
{
   Console.WriteLine("John Doe is NOT a User!!");
}

I will eventually release a class library project (VS2008/.NET Framework 2.0) which contains my entire helper class and custom exceptions after I complete the application I’m currently working (this could be a lil while).

Happy coding!