




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.
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
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
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 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.
Joe was moderately successful in his career, but as he got older
he was increasingly hampered by incredible headaches. After being
referred from one specialist to another, he finally came across a
doctor who solved the problem.
"The good news is I can cure your headaches. The bad news is that
it will require castration. You have a very rare condition which
causes your testicles to press up against the base of your spine.
The pressure creates one hell of a headache. The only way to
relieve the pressure is to remove the testicles."
Joe was shocked and depressed. He wondered if he had anything to
live for. He couldn't concentrate long enough to answer, but
decided he had no choice but to go under the knife.
When he left the hospital following the surgery, he felt like he
was missing an important part of himself. Just the same, as he
walked down the street, he realized that he felt like a different
person. He could make a new beginning and live a new life.
He walked past a men's clothing store and thought, "That's what I
need: A new suit." He entered the shop and told the salesman,
"I'd like a new suit."
The salesman eyed him briefly and said, "Let's see . . .Size 44
tall."
Joe laughed, "That's right, how did you know?"
"It's my job," the salesman replied. Joe tried on the suit. It
fit perfectly. As Joe admired himself in the mirror, the salesman
asked,
"How about a new shirt?"
Joe thought for a moment and then said, "Sure."
The salesman eyed Joe and said, "Let's see . . . 34 sleeve and .
. .16-and-a-half neck."
Joe was surprised, "That's right, how did you know?"
"It's my job."
Joe tried on the shirt, and it fit perfectly. As Joe adjusted the
collar in the mirror, the salesman asked,
"How about new shoes?"
Joe was on a roll and said, "Sure."
The salesman eyed Joe's feet and said, "Let's see . . .9-and-a-
half . . .wide.
Joe was astonished, "That's right, how did you know?"
"It's my job."
Joe tried on the shoes and they fit perfectly. Joe walked
comfortably around the shop and the salesman asked,
"How about a new hat?"
Without hesitating, Joe said, "Sure."
The salesman eyed Joe's head and said, "Let's see . . .7 and
5/8."
Joe was incredulous, "That's right, how did you know?"
"It's my job." The hat fit perfectly. Joe was feeling great, when
the salesman asked,
"How about some new underwear?"
Joe thought for a second and said, "Sure."
The salesman stepped back, eyed Joe's waist and said, "Let's see
. . .Size 36."
Joe laughed, "No, I've worn size 34 since I was 18 years old."
The salesman shook his head, "No. You can't wear a size 34. "It
would press your testicles up against the base of your spine and
give you one hell of a headache."