How to Program against Active Directory
Many times in our projects specially for big companies we have to code for Active directory. As these days security is a main concern specially in a company domain. People think active directory structure is very difficult, But its very easy if you know some basics of it
With the release of .NET 3.5 Microsoft included a new namespace: System.DirectoryServices.AccountManagement
Classes in this namespace considerably reduce the effort required to find/manipulate objects in our directory.
Prior to this namespace being available you could use GMIADAdmin to provide simplified access to AD but with this new namespace you have more power and flexibility.
Here are some samples of using the new Microsoft Active Directory classes. These samples assume that you are referencing System.DirectoryServices.dll & System.DirectoryServices.AccountManagement.dll
using System.DirectoryServices.AccountManagement;
public string GetUserEmail(string domain, string account)
{
using (var context = new PrincipalContext(ContextType.Domain, domain))
{
using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, account))
{
return user.EmailAddress;
}
}
}
public IEnumerable
{
using (var context = new PrincipalContext(ContextType.Domain, domain))
{
using (var group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, groupName))
{
return group.Members.Select(m => m.SamAccountName).ToList();
}
}
}
*Note that context objects and principals are disposable so you will need to manage that, if you are going to be accessing the directory multiple times you may want to consider wrapping some of this functionality or caching your context objects - just make sure you retain a way to properly dispose of them. All of the proper validation code was omitted for brevity.
The default connection options for the context (not shown) are to seal & sign meaning that the network traffic will be encrypted and signed so that the receiving end can verify it was not tampered with. You should always use this option when possible and only override this when absolutely necessary.