Introduction

This article describes how to use .NET framework to manage resources under Windows Active Directory Services. Microsoft provides ADSI (Active Directory Services Interface) which can interact with many providers including IIS (Internet Information Services), LDAP (Lightweight Directory Access Protocol), WinNT and NDS (Novell Netware Directory Service).Since my aim is to demonstrate the usage of .NET DirectoryService classes I am restricting the demo project to querying some commonly used resources (computers, users and printers) in the domain where the user's machine is, at the same time demonstrating the power of Active Directory services and the ease with which Active Directory objects can be retrieved.

I have also used LDAP in this demo since I thought that it will be useful to know this protocol as it is a platform independent protocol.

There are different ways to query the Active Directory Services in a C# program

using the ADSI through COM Interop. For this, in the Visual Studio C# project go to "Add References..." and select the COM tab and select Active DS Type Library from the list. Add using ActiveDs; statement to the top of your file or use fully qualified class names to access ADSI functions.

Using the Active Directory Services OleDB Provider (ADsDSOObject). This approach is mostly useful to add Active Directory as a linked server in SQL Server. This subject is out of scope for the present article, I will discuss how to query Active Directory using the ADS OleDB provider in a different article.

Using the classes provided under .NET System.DirectoryServices namespace. To access these classes add System.DirectoryServices.dll to the references. This article demonstrates this approach.

.NET System.DirectoryServices namespace

The System.DirectoryServices namespaces provides two important classes DirectoryEntry and DirectorySearcher to work with the Active Directory. The DirectoryEntry class represents a resource in the Active Directory and the DirectorySearcher class is used to query the Active Directory. The other classes under this namespace are for .NET security and collection classes to support the above said main classes.You have to add System.DirectoryServices to your references by selecting System.DirectoryServices.dll from .NET tab in the Add Reference dialog box.

LDAP format filter strings

The DirectorySearcher class uses a search root which is a server where the search begins and a LDAP filter string (which is analogous to where clause in SQL) to query the Active Directory resources. LDAP format filter strings are similar to LISP. A condition is enclosed by parenthesis and an operator precedes 2 conditions. Eg. (& (A)(B)) The statement is equivalent to saying A and B. Remember the parenthesis. Another example (| (& (A)(B) ) (C) ) should be interpreted as (A and B) or (C).

The OLAP conditional statements are formed by using Active Directory attributes like name, objectCategory, objectClass, printerName, ListedName etc. For eg. to query for a list of printers the condition would be (objectCategory=printQueue) where objectCategory is an attribute and printQueue is the value expected to be assigned to a printer resource in Active Directory. Similary to query for all printers which start with a character 'G' the LDAP query would be (& (objectCategory=printQueue) (name=G*) ) In the above filter observe that the values do not have quotes (' or ") around them.

Using the code

The demo project demonstrates how to query the Active Directory Services and fetch different objects. The LDAP queries and the usage of .NET classes used are confined to QueryObjectsByNETClasses() and GetFilterString() methods.

The following code in QueryObjectsByNETClasses() method creates a DirectorySearcher object and sets properties on the searcher depending on the user preferences given in the main form. The description of different properties is in the comments in the code. Only "name" is added to the PropertiesToLoad property of DirectorySearcher class to save time as we are only interested in retrieving name and objectClass for the list of objects returned.

DirectorySearcher ds = new DirectorySearcher();
ds.SearchRoot = new DirectoryEntry("");
// start searching from local domain
ds.Filter = GetFilterString();
// get the LDAP filter string based on selections on the form
ds.PropertyNamesOnly = true;
// this will get names of only those
// properties to which a value is set
ds.PropertiesToLoad.Add("name");
// (PageSize) Maximum number of objects
// the server will return per page
// in a paged search. Default is 0, i.e. no paged search
if (ObjsPerPage.Text.Length > 0)
ds.PageSize = Int32.Parse(ObjsPerPage.Text);
// (ServerPageTimeLimit) the amount of time the server
// should observe to search a page of results
// default is -1, i.e. search indefinitely
if (PageTimeLimit.Text.Length > 0)
ds.ServerPageTimeLimit = new TimeSpan((long)(Decimal.Parse(
PageTimeLimit.Text) * TimeSpan.TicksPerSecond));
// (SizeLimit) maximum number of objects the server
// returns in a search
// default is 0 - interpreted as server
// set default limit of 1000 entries
if (ObjsToFetch.Text.Length > 0)
ds.SizeLimit = Int32.Parse(ObjsToFetch.Text);
// (ServerTimeLimit) amount of time that the server
// should observe in a search
// default is -1 interpreted as server default limit of 120 seconds
if (TotalTimeLimit.Text.Length > 0)
ds.ServerTimeLimit = new TimeSpan((long)(Decimal.Parse(
TotalTimeLimit.Text) * TimeSpan.TicksPerSecond));
// (SearchScope) option to search one level or complete subtree
// default is Subtree, so set this option only if oneLevel is selected
if (searchOptionCB.SelectedIndex == 1)
ds.SearchScope = SearchScope.OneLevel;
// (CacheResults) property by default is true
ds.CacheResults = CacheResultsCB.Checked;
ds.ReferralChasing = ReferralChasingOption.None;
if (SortResultsCB.Checked)
ds.Sort = new SortOption("name", SortDirection.Ascending);

The FormFilter() and GetFilterString() functions are used to form the LDAP query strings (see the explaination for the format of these strings in the LDAP format filter strings section above). Mainly observe the placement of & and | operators before the lists. For a complete set of attributes on which the queries can be formed for different objects refer to the Active Directory Schema under MSDN here.

Important Points and Notes

Use objectCategory attribute instead of objectClass where ever possible. Active Directory documentation mentions two things related to this issue :

objectClass attribute can have multiple values. This can be a problem especially if you are retriving objectClass. You can end up with multiple values !

objectCategory is an indexed attribute in Active Directory. So using objectCategory speeds up queries.

The second point is more important because all the examples given in MSDN use objectClass, whereas using objectCategory will speed up queries !

If the list queried is too large then there is a possibility of a timeout. So don't be surprised if your query does not return the complete list. A point to be noted is that you cannot set a value to ServerTimeLimit larger than the default value of 120 seconds ! So if you are looking for all objects and your directory is too large it is better to query number of times by changing your LDAP filter string incrementally (for eg. a*, b* ..) and combining the results.

Try to use PropertiesToLoad and PropertyNamesOnly properties of DirectorySearcher if you know what properties you are trying to retrieve. If PropertyNamesOnly is set to true, the query will fetch the names of only those properties for which a value is set. Giving names of properties to be loaded to PropertiesToLoad will reduce the fetch time. By default PropertiesToLoad is set to an empty StringCollection to fetch all the properties, and PropertyNamesOnly is set to false to retrieve all properties' names even if a value is not set. For eg. in my demo I have given "name" property to be loaded and set PropertyNamesOnly to true. Please note that even if not specified objectClass and objectCategory propertied are automatically loaded whenever an object is fetched.

By default all the results of a Active Directory fetch are cached. Set the CacheResults property of DirectorySearcher to false to refresh the object cache on the local computer.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

First, I was very happy to find this project. It got me up and running with LDAP very quickly. Many thanks to the author.

But after some modifications so I optionally fetch only certain properties via the DirectorySearcher.PropertiesToLoad property, I realized that LDAP was still returning all of the properties for each directory entry, not just the ones I wanted.

After much tearing out of hair and Googling, I found this very helpful article:

Basically, I think the program presented in this Code Project article has a design fault, or maybe two of them.

1. The idea of doing an LDAP search should be that the results returned by the DirectorySearcher.FindAll() function should contain all the data you need without any further LDAP access, at least for a simple application like this. But this program uses the SearchResult.GetDirectoryEntry() function on each returned object. This invokes LDAP all over again, once for each directory entry, and obtains all of the properties for each directory entry, even if you have explicitly used DirectorySearcher.PropertiesToLoad to avoid that.

2. This program contains this statement and comment:

ds.PropertyNamesOnly = true; // this will get names of only those properties to which a value is set

This is very confusing - it took me a long time to figure out what the DirectorySearcher.PropertyNamesOnly property really does, mostly because Microsoft's explanation is really, really poor and confusing.

So what I'm trying to say is that for a simple application where you use LDAP to get some data from Active Directory (or a Domino Server - it's almost the same), you should not use DirectorySearcher.PropertyNamesOnly and you should not have to use SearchResult.GetDirectoryEntry(). See the other article for details of how to process the data returned by DirectorySearcher.FindAll().

Could you come up with a version for Visual Studio 08 please? I get the error "Application has generated an exception that could not be handled. Process id=0xbd4 (3028), Thread id=0x7d4 (2004)." I think itmight be cos I dont have the older versions of Visual Studio. You think so?

I am using following code in VB its working fine with administrtor user loging but i change login from another user which have no administrative rights is return exception regrading unauthorized I change different authontication type but its not working anyone help me regarding this because I want to create user without given rights to user.

' Set the password.
Dim result As Object = newUser.Invoke("SetPassword", password)

newUser.CommitChanges()

' Add user to the group "Members"
Dim grp As DirectoryEntry = dirEntry.Children.Find("Dars Operator")
If (Not grp Is Nothing) Then
grp.Invoke("Add", New Object() {newUser.Path.ToString()})
End If
End Sub

Actually you can. Just using the pagesize and then using a while loop with getnextrow until you get the NO_MORE_DATA error. I'm not clear on this. There are more examples in the net I was trying to find one I read a while back about this.

If the identity the code is running under already has permisson to get to AD then the username/password is not required. Another reason to enter them is if you want to impersonate a constant user. And configuration files are good for not hard coding these things, just remember to encrypt if you dont trust anyone.

Hi,
I am querying AD from Mono. The query and code works fine in Windows. When I attempt it in mono it just fails with "Operations Error" on this line: This is the first attempt to access AD in the code.

if (!DirectoryEntry.Exists("LDAP://mach.domain.net/")). The address is valid, the machine can be pinged from the linux box.

Hi,
Your codes are really nice:
My requirement is:
I have got LDAP 5.1 there in Solaris 8 environment. And I need to access from Windows 2000/xp environment.
Will these codes will be able to solve my problems.

? Can I access LDAP of Solaris environment from my Windows environment.

I followed the sample code for connecting to AD specifying the Directory enty path but got an error in the beginning which said that the server is not operatable.The next time i tried i got an exception saying that a referral was sent by the server.The next time i checked the path and got an errorwhich said logon failed bcoz of in valid user name or cos of bad password.
the code snippet for the same is given below kindly review it and help me in this regard.

HI,
From the sample code it is now clear to me how to browse the objects in a domain, however, I have problems getting the list of all the available domains. Can someone please enlighten me? I guess it's something trivial, that I am overlooking...

One ore question though: It only works for me if I run the query under an admin account. Is there a way to do the query as an ordinary user? I guess it is possible, just like at the login screen of Windows...

That segment of code only lists the domain that the user is logged into, not any of the child domains in the forest. I really need some c# code that will enumerate all the domains (including all the child domains) in a forest (without having to know any details about the forest).

It would be great if you could help me out with this, as I don't have a deep understanding of Active Directory and LDAP.

I'm trying to make an ASPX page to display on our intranet "iNet" Application, which would display several links to Sales Reports. For this, what I need to do is to Search and Query the Active Directory, on one of our servers to retain User Information (Sales Group, in this case), and run a Query against it so that all the users of the "Sales" Directory can see the links to the Reports on the iNet page on their respective machines.

I don't want anyone else (besides the Sales people) to see these links on the iNet Application on their machines (which means I'll be making the links invisible to everyone else in the Active Directory Structure).

I did come across the DirectorySearcher Class on MSDN (Topic: Intro to Active Directory Objects), but am not sure how to use it for this purpose. Just so you know, we use VB for writing the code.