The majority of Active Directory and ADAM attributes have simple conversions to .NET data types, with strings being the most popular. We can generally just cast any data type from the System.Object returned by the collection class back to its corresponding actual runtime type:
//given a DirectoryEntry entry and a SearchResult result //we access the single-valued attribute cn which at runtime //will be a simple string string name = (string) entry.Properties["name"].Value; //or name = (string) result.Properties["name"][0];
In Visual Basic .NET, the preceding code would look something like this:
Dim cn As String cn = DirectCast(entry.Properties("cn").Value, String) cn = DirectCast(result.Properties("cn")(0), String)
Note that we can also use CType in Visual Basic .NET. The only problem is that CType will happily try a coercive conversion if the direct conversion does not work, so we need to be careful. Since DirectCast will not do this, we generally recommend using it when we just want to cast.
The other basic conversions are very similar:
DateTime createDate = (DateTime) entry.Properties["whenCreated"].Value; int userAccountControl = (int) entry.Properties["userAccountControl"].Value; bool isSystemOnly = (bool) entry.Properties["systemOnly"].Value;
As demonstrated, the actual type conversion is straightforward. We will most likely want to check if the value can be null or multivalued before blindly using the Value property or directly accessing the array by index. (We omitted this here.)
Part I: Fundamentals
Introduction to LDAP and Active Directory
Introduction to .NET Directory Services Programming
Binding and CRUD Operations with DirectoryEntry
Searching with the DirectorySearcher
Advanced LDAP Searches
Reading and Writing LDAP Attributes
Active Directory and ADAM Schema
Security in Directory Services Programming
Introduction to the ActiveDirectory Namespace
Part II: Practical Applications
User Management
Group Management
Authentication
Part III: Appendixes
Appendix A. Three Approaches to COM Interop with ADSI
Appendix B. LDAP Tools for Programmers
Appendix C. Troubleshooting and Help
Index