Focus on Microsoft Technologies - Tutorials, Articles, Code Samples.

Sunday, September 03, 2006

Using Active Directory In ASP.NET

Using Active Directory In ASP.NET

This article is first in the series demonstrating the use of Active Directory in ASP.NET. Of course all the demo code is written in language of choice - C#. This series will not go into discussion of Active Directory or LDAP servers. We are assuming that the readers of these articles have basic understanding of these technologies.

.NET namespace and classes utilized

  • System.DirectoryServices
  • System.DirectoryServices.DirectoryEntry
  • System.DirectoryServices.DirectorySearcher
  • System.DirectoryServices.SearchResultCollection
  • System.DirectoryServices.SearchResult
  • System.DirectoryServices.ResultPropertyCollection
  • System.DirectoryServices.PropertyValueCollection

What is this article about?

Searching an Active Directory is one of the major tasks in manipulation of various resources. When I started with ADSI programming, I used to look for right kind of filter values to use. Some time I had to go back forth and look at the Active Directory schema to find value I should be using to get the information I was looking for. For example If you want to get the information when the user account was last changed, you need to create a filter looking for whenchanged property in schema. So we decided to write a small dump utility that will display all the properties that are used to describe a user's account in Active Directory.

How To Do It

The first step in using Directory Services interfaces is to make connection with the node that you want to search for. .NET framework provides DirectoryEntry class to specify the search node. For example if you want to search for a resource in whole domain, then you need to connect to the top node of domain in Active Directory. It is very important that you specify the search location as close as possible to the nearest location where the resource could be found. Otherwise the search will take longer time. For example if You want to search for a user information, you need to specify the location as User node and not the whole domain resource tree.

string strLDAP = "LDAP://"
m_obDirEntry = new DirectoryEntry(strLDAP);
DirectorySearcher srch = new DirectorySearcher(m_obDirEntry);
srch.Filter = "(cn=foo)";

SearchResultCollection results;
results = srch.FindAll();

foreach (SearchResult result in results)
   ResultPropertyCollection propColl = result.Properties;

foreach (string strKey in propColl.PropertyNames)
  foreach (object obProp in propColl[strKey])
    this.AppendPropertyNode(obTopNode, strKey, obProp);

Post a Comment