ActiveDirectoryQuery Class

This page is a Draft. Its content is not complete and might contain errors.

This page is part of the Class Library Pages collection.
Click the icon to see the index.

Example of Searching ActiveDirectory

private void SearchForGivenName()
{
    string nameSought = uxNameSoughtTextBox.Text.Trim();

    if (nameSought.Length >= 3)
    {
        DirectorySearcher search = new DirectorySearcher();
        string root = search.SearchRoot.Path;
        DirectoryEntry entry = new DirectoryEntry(root);
        string[] word = nameSought.Split( new char[] {' '} );
        int wordCount = word.GetUpperBound(0) + 1;

        string filter = "(& ";
        filter += "(objectClass=user)";
        //filter += "(telephoneNumber=*)";
        filter += "(givenName=*)";
        filter += "(sn=*)";

        if (wordCount == 1)
        {
            filter += "(| ";
            filter += "(givenName=" + word[0] + "*)";
            filter += "(sn=" + word[0] + "*)";
            filter += ")";
        }
        else
        {
            filter += "(givenName=" + word[0] + "*)";
            filter += "(sn=" + word[1] + "*)";
        }
        filter += ")";

        search.Filter = filter; 
        search.SearchScope = SearchScope.Subtree;
        search.PropertiesToLoad.Add("cn");
        search.PropertiesToLoad.Add("sn");
        search.PropertiesToLoad.Add("givenName");
        search.PropertiesToLoad.Add("mail");
        search.PropertiesToLoad.Add("samaccountname");
        search.PropertyNamesOnly = true;
        search.Sort.Direction = SortDirection.Ascending;
        search.Sort.PropertyName = "sn";
        SearchResultCollection results = search.FindAll();
        if (results.Count == 1)
        {
            System.DirectoryServices.PropertyCollection c = results[0].GetDirectoryEntry().Properties;
            uxNameLabel.Text = ToString(c["cn"].Value); 
            uxPhoneNumberLabel.Text = ToString(c["telephoneNumber"].Value);
            uxEmailAddressLabel.Text = ToString(c["mail"].Value);
            uxSearchResultsBindingSource.DataSource = null;
        }
        else
        {
            uxNameLabel.Text = "";
            uxPhoneNumberLabel.Text = "";
            uxEmailAddressLabel.Text = "";
            int imax = Math.Min(10, results.Count) - 1;
            SearchResultsDataSet.SearchResultsDataTable t = new SearchResultsDataSet.SearchResultsDataTable();

            for (int i = 0; i <= imax; i++)
            {
                System.DirectoryServices.PropertyCollection c = results[i].GetDirectoryEntry().Properties;
                SearchResultsDataSet.SearchResultsRow row = t.NewSearchResultsRow();
                row.Name = ToString(c["sn"].Value) + ", " + ToString(c["givenName"].Value);
                row.EmailAddress = ToString(c["mail"].Value);
                row.PhoneNumber = ToString(c["telephoneNumber"].Value);
                row.UserId = ToString(c["samaccountname"].Value);
                t.Rows.Add(row);
            }
            uxSearchResultsBindingSource.DataSource = null;
            uxSearchResultsBindingSource.DataSource = t;
        }

        search.Dispose();
    }
}

Source Code

VB.NET

TODO

C#

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;

namespace PeopleFinder
{
    public enum ActiveDirectoryProperty {FullName, LastName, PhoneNumber, FirstName, 
        EmailAddress, LoginId}

    public class ActiveDirectoryQuery
    {
        private static Dictionary<ActiveDirectoryProperty, string> _properties = 
            new Dictionary<ActiveDirectoryProperty, string>();

        static ActiveDirectoryQuery()
        {
            _properties.Add(ActiveDirectoryProperty.FullName,"cn");
            _properties.Add(ActiveDirectoryProperty.LastName, "sn");
            _properties.Add(ActiveDirectoryProperty.PhoneNumber, "telephoneNumber");
            _properties.Add(ActiveDirectoryProperty.FirstName, "givenName");
            _properties.Add(ActiveDirectoryProperty.EmailAddress, "mail");
            _properties.Add(ActiveDirectoryProperty.LoginId, "samaccountname");
        }

        public ActiveDirectoryDataSet.UsersDataTable Search(Dictionary<ActiveDirectoryProperty, string> 
            conditions)
        {
            //- Build Filter ----------------------------------------------------------------------
            string filter = "(& ";
            filter += "(objectClass=user)";

            foreach (ActiveDirectoryProperty item in conditions.Keys)
            {
                filter += "(";
                filter += _properties[item];
                filter += "=";
                filter += conditions[item];
                filter += ")";
            }

            filter += ")";

            //- Build Search Object ---------------------------------------------------------------
            DirectorySearcher search = new DirectorySearcher();
            search.Filter = filter;
            search.SearchScope = SearchScope.Subtree;

            foreach (ActiveDirectoryProperty p in _properties.Keys)
            {
                search.PropertiesToLoad.Add(_properties[p]);
            }
            search.PropertyNamesOnly = true;
            search.Sort.Direction = SortDirection.Ascending;
            search.Sort.PropertyName = "sn";
            SearchResultCollection searchResults = search.FindAll();

            //- Build Result Set ------------------------------------------------------------------
            ActiveDirectoryDataSet.UsersDataTable result = new ActiveDirectoryDataSet.UsersDataTable();
            if (searchResults.Count > 0)
            {
                foreach (SearchResult searchResult in searchResults)
                {
                    PropertyCollection c = searchResult.GetDirectoryEntry().Properties;
                    ActiveDirectoryDataSet.UsersRow usersRow = result.NewUsersRow();

                    usersRow.LastName = GetProperty(c, ActiveDirectoryProperty.LastName);
                    usersRow.PhoneNumber = GetProperty(c, ActiveDirectoryProperty.PhoneNumber);
                    usersRow.FirstName = GetProperty(c, ActiveDirectoryProperty.FirstName);
                    usersRow.EmailAddress = GetProperty(c, ActiveDirectoryProperty.EmailAddress);
                    usersRow.LoginId = GetProperty(c, ActiveDirectoryProperty.LoginId);
                    usersRow.FullNameFl = usersRow.FirstName + " " + usersRow.LastName;
                    usersRow.FullNameLf = usersRow.LastName + ", " + usersRow.FirstName;

                    result.Rows.Add(usersRow);
                }
            }


            //- Clean Up --------------------------------------------------------------------------
            return result;
        }

        //- Helper Functions ----------------------------------------------------------------------
        private static string GetProperty(PropertyCollection c, ActiveDirectoryProperty p)
        {
            string result = "";
            PropertyValueCollection pvc = c[_properties[p]];

            if (pvc != null && pvc.Value != null)
                result = pvc.Value.ToString();

            return result;
        }
    }
}