home | site map | contacts
about us
consulting
client login
support
contacts
  Active Directory in C# ASP .NET Web Applications
More Articles by Primary Objects Subscribe to our C# .NET RSS feed

 
 

Active Directory is the primary user management system used by business and enterprise networks. It's basically just another kind of database, similar to MSSQL or Oracle, but with its own type of query language and protocol, which is based on LDAP.

Active Directory in C# ASP .NET Web Application

Being able to query objects in Active Directory from within a C# ASP .NET web application can be a great knowledge tool. Many businesses who are moving their desktop applications to the web are asking for their .NET web applications to contain forms-based LDAP authentication and other hooks into Active Directory to process user objects.

The DirectoryEntry Object

The fundamental starting point for a .NET application using Active Directory is to include the System.DirectoryServices library. This contains the basic Active Directory library routines used to query. Communicating with Active Directory starts out with obtaining a DirectoryEntry object. This object is your root connection into the LDAP database, from which you can query for additional folders or objects. In order to obtain the DirectoryEntry object, you will need an Active Directory server address, username, and password. The server address can be an IP address or a complete LDAP path in the form LDAP://MyCompany.com/DC=MyCompany,DC=com

Connecting to Active Directory for the DirectoryEntry Object

Below is an example function to obtain a DirectoryEntry object for a fictional Active Directory server. Note the user of AuthenticationTypes.Secure to indicate we are making a secure authenticated connection to Active Directory. If you specify a regular user login, you will be restricted in what you may access. This can be handy to enforce role policies within your .NET web application. Alternatively, by connecting with an administrative account, you can perform administrative Active Directory functions such as modifying users, creating users, deleting users, etc.

using System.DirectoryServices;

private DirectoryEntry GetDirectoryObject()
{
    DirectoryEntry oDE;
    oDE = new DirectoryEntry("LDAP://192.168.1.101", "administrator", "password", AuthenticationTypes.Secure);
    return oDE;
}

Grabbing a User from Active Directory in C# ASP .NET

Querying a User in Active Directory in C# ASP .NET Web Application

After connecting to Active Directory, you will want to query for an object, such as a user. The below code sample shows how to get a user from Active Directory based on their login name. Note that we use a specific Active Directory query language where clauses are included inside parenthesis. You can only query on certain fields. The below example uses the field "SAMAccountName", which is another word for "username" or "login" in Active Directory. Notice we also query for an objectClass of type "user". Another objectClass is of type "contact". After finding the DirectoryEntry, we create a new DirectoryEntry object pointing to the result and use our administrative login information in the connection (so that we can perform admin functions on the object).

private DirectoryEntry GetUser(string UserName)
{
    DirectoryEntry de = GetDirectoryObject();
    DirectorySearcher deSearch = new DirectorySearcher();
    deSearch.SearchRoot = de;

    deSearch.Filter = "(&(objectClass=user)(SAMAccountName=" + UserName + "))";
    deSearch.SearchScope = SearchScope.Subtree;
    SearchResult results = deSearch.FindOne();

    if (!(results == null))
    {
       de = new DirectoryEntry(results.Path, "administrator", "password", AuthenticationTypes.Secure);
       return de;
    }
    else
    {
       return null;
    }
}

Modifying a User's Properties in Active Directory in C# .NET

Modifying the property of an Active Directory object in C# .NET is fairly simple. You access the DirectoryEntry's Properties field, modify the values as needed (be sure to check for null), and finally call CommitChanges to commit and save the changes. An example is shown below, which modifies the user's Display Name property (this is the name shown as their real name in Active Directory or the Global Address List).

  DirectoryEntry de = GetUser("john.doe");
  if (de != null)
  {
  if (de.Properties["displayName"] != null && de.Properties["displayName"].Value != null)
  {
      de.Properties["displayName"].Value = "John, Doe (Nice Guy)";
      de.CommitChanges();
  }
}

Note in the above code, if you do not call de.CommitChanges(), the changes will not be saved to Active Directory. Another important note is that any changes you make will not be instantly visible in applications that query Active Directory (such as Active Directory Users and Computers in the control panel). This is because the changes need to synchronize over the servers and throughout the network. Some networks may take between 5-30 minutes for changes to be visible.

Querying Multiple Users in Active Directory with C# ASP .NET

Querying Multiple Users in Active Directory in C# ASP .NET Web Application

The above discussed querying for individual DirectoryEntry objects. However, if you wish to retrieve a list of objects, you will need to use the SearchResultCollection type combined with deSearch.FindAll instead of deSearch.FindOne.

SearchResultCollection MyUsers = GetAllUsers();
if (MyUsers != null && MyUsers.Count > 0)
{
   foreach (SearchResult m_User in MyUsers)
   {
     DirectoryEntry de = m_User.GetDirectoryEntry();
   }
}

Using Active Directory within a C# .NET Web Application can be a powerful tool for business and enterprise networks. By designing web applications to suit the enterprise world, more desktop applications can be ported to the web and empower organizations.

Feel free to contact Primary Objects if you are in need of a C# .NET Web Application dealing with Active Directory functionality.

About the Author

This article was written by Kory Becker, founder and chief developer of Primary Objects, a software and web application development company. You can contact Primary Objects regarding your software development needs at http://www.primaryobjects.com

 
 
  Post comment >
        
DateUserComment
12/26/2006K By the way, the GetAllUsers() function will look like the following:

private DirectoryEntry GetAllUsers()
{
      DirectoryEntry de = GetDirectoryObject();
      DirectorySearcher deSearch = new DirectorySearcher();
      deSearch.SearchRoot = de;

      deSearch.Filter = "(&(objectClass=user))";
      deSearch.SearchScope = SearchScope.Subtree;
      SearchResult results = deSearch.FindOne();

      if (!(results == null))
      {
         de = new DirectoryEntry(results.Path, "administrator", "password", AuthenticationTypes.Secure);
         return de;
      }
      else
      {
         return null;
      }
}


5/21/2007xyz Hi How to print all the users in the GetallUsers() Function

8/7/2007Tom Yea you could do that or you could get the AD-Advantage library (ad-advantage.com) which automates nearly every AD task to a single line of code...

8/7/2007Tom Oops... that's ad-advantage.net

8/8/2007amtez thank you friends!.. i made it!

8/31/2007falak Hello,
I appreciate the way you have worked on this website. I just
like to ask some questions regarding Active Directory in C#

This fucntion GetAllUsers()   indeed works well for finding
single user but how   can i retrieve the list by changing in the
code of this fucntion
private DirectoryEntry GetAllUsers()
{
      DirectoryEntry de = GetDirectoryObject();
      DirectorySearcher deSearch = new DirectorySearcher();
      deSearch.SearchRoot = de;

      deSearch.Filter = "(&(objectClass=user))";
      deSearch.SearchScope = SearchScope.Subtree;
      SearchResult results = deSearch.FindOne();

      if (!(results == null))
      {
         de = new DirectoryEntry(results.Path, "administrator", "password", AuthenticationTypes.Secure);
         return de;
      }
      else
      {
         return null;
      }
}
*********************

I also need its implementation in following code after we
change getallusers fucntion.Keep one thing in mind which is
that i want to get the list not a single contact


SearchResultCollection MyUsers = GetAllUsers();
if (MyUsers != null && MyUsers.Count > 0)
{
   foreach (SearchResult m_User in MyUsers)
   {
      DirectoryEntry de = m_User.GetDirectoryEntry();
   }
}


9/12/2007K The GetAllUsers() function can be defined as follows:

            static SearchResultCollection GetAllUsers()
            {
                  DirectoryEntry de = GetDirectoryObject();
                  DirectorySearcher deSearch = new DirectorySearcher();
                  deSearch.SearchRoot = de;

                  deSearch.Filter = "(&(objectClass=user))";
                  deSearch.SearchScope = SearchScope.Subtree;
                  SearchResultCollection results = deSearch.FindAll();

                  return results;
            }


12/4/2007miheich How can I get all users with not null email?

12/19/2007shri hi
whatever is mentioned is great but i want to find employee no
based on usedName he provides at the time of login.  


Profile
Learn more about Primary Objects and our goals ..  More
01/24/08
Primary Objects releases Alumni Notes Express - online alumni class notes .. More
08/10/06
Primary Objects releases PrimaryCMS Content Management System .. More
Home | About Us | Services | Client Login | Job Opportunities | Contact Us
Copyright © Primary Objects 2008