Andre's Blog

Personal blog of Andre Perusse

Working with Active Directory in .NET 3.5

Many projects that I’ve worked on over the years have required some kind of interface with Active Directory. Back in the good ol’ ASP days, there was ADSI (Active Directory Services Interface), and .NET uses the System.DirectoryServices namespace to essentially wrap ADSI with managed code. It’s been a long time since I worked directly with ADSI, but working with AD up to and including the .NET Framework 2.0 was never a very straight-forward task.

Take for example the classic requirement of simply obtaining the current user’s full name from AD. Say you have a web site that uses either IIS/NTFS to protect pages using ACLs, or uses ASP.NET Forms Authentication with an AD Provider. Obtaining the user’s login name is relatively easy, using the Page’s User object:

string loginName = User.Identity.Name;

But getting the user’s full name from AD requires several lines of code involving DirectorySearcher and SearchResult objects:

string firstName = null;

string lastName = null;

 

DirectoryEntry entry = new DirectoryEntry();

DirectorySearcher searcher = new DirectorySearcher(entry);

searcher.PropertiesToLoad.Add("givenName");

searcher.PropertiesToLoad.Add("sn");

searcher.Filter = "(&(objectCategory=person)(samAccountName=jsmith))";

SearchResult result = searcher.FindOne();

if (result.Properties["givenName"].Count > 0) firstName = result.Properties["givenName"][0].ToString();

if (result.Properties["sn"].Count > 0) lastName = result.Properties["sn"][0].ToString();

Ick. Thankfully, .NET 3.5 has added the System.DirectoryServices.AccountManagement namespace which abstracts most of this code and makes it super-easy to deal with AD Principals in a strongly-typed manner:

PrincipalContext pc = new PrincipalContext(ContextType.Domain);

UserPrincipal user = UserPrincipal.FindByIdentity(pc, "jsmith");

string firstName = user.GivenName;

string lastName = user.Surname;

Gotta love progress!  :-)

Comments (3) -

  • Doug Dekker

    8/24/2010 4:02:58 PM |

    Here is a way to get a list of all users:

            PrincipalContext pc = new PrincipalContext(ContextType.Domain);
            System.Collections.ArrayList UserNames = new System.Collections.ArrayList();
            UserPrincipal up = new UserPrincipal(pc);
            PrincipalSearcher ps = new PrincipalSearcher(up);
            PrincipalSearchResult results = ps.FindAll();
            foreach (UserPrincipal ur in results)
            {
                UserNames.Add(ur.Name);
            }

  • Madhusmita

    12/20/2010 12:58:56 AM |

    Thanks for sharing, Useful one.

  • John Nichols

    12/15/2011 4:48:49 PM |

    I love this blog

Loading