Okay, I don't know how many of you know this, but at work, we're in a domain evironment. One of the tools I'm working on, is a management tool. The program requires that I read a number of objects from a specific organiational unit (OU) in active directory (AD).
If you don't know much about Active Directory, know this. Active Directory is a database of objects, which can contains a property collection. What's the value of the property collection? A property collection. What makes it worse, some objects have certain properties, others don't. And sometimes, objects of the same type have different properties. Confusing, huh?
Well, to alleviate all the headaches, I decided to write a class which will navigate AD. I wanted to have a collection for each type of object. (Right now I am only concerning myself with User, Computer, and Group.) Each object would provide strongly typed wrappers for common properties. To detect the type of object I found in Active Directory, I used the objectClass property. Unfortunately, I found that this won't work.
The objectClass property is indexed. Which means I can use it in my filter clause and filter based on that. However, I wanted everything. So, I tried to manually inspect the objectClass property, and I found that a Computer has many objectClasses, such as User, Person, Computer, and top. (All objects have top.)
The solution is objectCategory. objectCategory contains the Distinguished Name for the schema object that the object inherits. The schema is a class heirarchy which contains mandatory, and optional fields for each type of object. Every single object in Active Directory inherits one of these classes. The distinguished name for the schema class looks something like this:
"CN=Computer,CN=Schema,CN=Configuration,DC=corp,DC=mydomain,DC=com"
We can't always count on that schema using that format, so we must programatically find the schema object programatically. First, we must obtain a DirectoryContext object, like so:
Domain domain = Domain.GetCurrentDomain();
Forest forest = domain.Forest;
m_DirectoryContext = new DirectoryContext(DirectoryContextType.Forest, forest.Name);
This DirectoryContext object allows us to perform a ton of tasks on the entire Directory. To get the schema object, use the following code:
ActiveDirectorySchemaClass cls = ActiveDirectorySchemaClass.FindByName(m_DirectoryContext, "Computer");
DirectoryEntry de = cls.GetDirectoryEntry();
m_SchemaComputerName = (string)de.Properties["distinguishedname"][0];
Notice in the first line, "Computer". This can be substituted with "User", "Group", etc.
Now, you have the Distinguished Name of the Schema class. Compare that with the objectCategory you found on your object, and you should have a match.
0 comments:
Post a Comment