Creating Active Directory Service using WCF

In this article, I'll try to give you a full demonstration of and the steps required to create a WCF application that operates all the active directory functions

In this article I'll try to give you a full demonstration of and the steps required to create a WCF application that operates all the active directory functions; this will help us to avoid creating active directory helper for every solution in our farm, especially if we are working on an internal development team. Also, I'll try to show how to create a service contract and its operation and data contract in WCF.
 
1- Create a WCF project. 
 
Add a new C# WCF Service Application and choose it's name and location. It will create public interface IService1 (Change it to IActiveDirectory) decorated with the ServiceContract Attribute. This interface contains only the signatures of the Active Directory methods decorated with OperationContract. 
 
A) Add the service datacontract. Reference: Using Data Contracts
 
B) Add the OperationContract. Reference: OperationContractAttribute Class
 
Here the code of the Active Directory data contract and Interface for the operation contracts: 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.Text;  
  7. using System.Data;  
  8. using System.DirectoryServices;  
  9. using System.Configuration;  
  10.   
  11. namespace ActiveDirectoryManager  
  12. {  
  13.     // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.  
  14.     [ServiceContract]  
  15.     public interface IActiveDirectory  
  16.     {  
  17.         [OperationContract]  
  18.         string GetData(int value);  
  19.         [OperationContract]  
  20.         CompositeType GetDataUsingDataContract(CompositeType composite);  
  21.         // TODO: Add your service operations here  
  22.         //DirectoryEntry directoryEntry;  
  23.         //[OperationContract]  
  24.         // void ActiveDirectoryHelper();  
  25.         //[OperationContract]  
  26.         // void ActiveDirectoryHelper(string path, string userName, string password);  
  27.         /// <summary>  
  28.         /// Gets user infromation by user ID  
  29.         /// </summary>  
  30.         /// <param name="UserName"> User Name to search with</param>  
  31.         /// <returns>User Information Object</returns>  
  32.         [OperationContract]  
  33.          ActiveUser GetUserInfo(string UserName);  
  34.         /// <summary>  
  35.         /// Gets user infromation by user DistinguishName  
  36.         /// </summary>  
  37.         /// <param name="DistinguishName">User Distinguish Name to search with</param>  
  38.         /// <returns>User Information Object</returns>  
  39.         [OperationContract]  
  40.          ActiveUser GetUserInfoByDistinguishName(string DistinguishName);  
  41.         /// <summary>  
  42.         /// Gets all users from active directory  
  43.         /// </summary>  
  44.         /// <returns>User Information Collection</returns>  
  45.         [OperationContract]  
  46.          List<ActiveUser> GetAllUsers();  
  47.         /// <summary>  
  48.         /// Gets all users from active directory  
  49.         /// </summary>  
  50.         /// <returns>User Information Dataset</returns>  
  51.         [OperationContract]  
  52.          DataSet GetAllUsersDataSet();  
  53.         /// <summary>  
  54.         /// Gets all users' Display Name and ID  from active directory  
  55.         /// </summary>  
  56.         /// <returns>User Information Dataset</returns>  
  57.         [OperationContract]  
  58.          DataSet GetAllUsersDataSetMinAttributes();  
  59.         [OperationContract]  
  60.          DataTable PrepareUsersDataTable();  
  61.     }  
  62.     // Use a data contract as illustrated in the sample below to add composite types to service operations.  
  63.     [DataContract]  
  64.     public class CompositeType  
  65.     {  
  66.         bool boolValue = true;  
  67.         string stringValue = "Hello ";  
  68.         [DataMember]  
  69.         public bool BoolValue  
  70.         {  
  71.             get { return boolValue; }  
  72.             set { boolValue = value; }  
  73.         }  
  74.         [DataMember]  
  75.         public string StringValue  
  76.         {  
  77.             get { return stringValue; }  
  78.             set { stringValue = value; }  
  79.         }  
  80.     }  
  81.     /// <summary>  
  82.     /// Carries user information object  
  83.     /// </summary>  
  84.     [DataContract]  
  85.     [Serializable()]  
  86.     public class ActiveUser : IComparable<ActiveUser>  
  87.     {  
  88.         private String _displayName;  
  89.         [DataMember]  
  90.         public String DisplayName  
  91.         {  
  92.             get { return _displayName; }  
  93.             set { _displayName = value; }  
  94.         }  
  95.         private String _email;  
  96.         [DataMember]  
  97.         public String Email  
  98.         {  
  99.             get { return _email; }  
  100.             set { _email = value; }  
  101.         }  
  102.         private String _manager;  
  103.         [DataMember]  
  104.         public String Manager  
  105.         {  
  106.             get { return _manager; }  
  107.             set { _manager = value; }  
  108.         }  
  109.         private String _department;  
  110.         [DataMember]  
  111.         public String Department  
  112.         {  
  113.             get { return _department; }  
  114.             set { _department = value; }  
  115.         }  
  116.         private String _distinguishedName;  
  117.         [DataMember]  
  118.         public String DistinguishedName  
  119.         {  
  120.             get { return _distinguishedName; }  
  121.             set { _distinguishedName = value; }  
  122.         }  
  123.         private String _title;  
  124.         [DataMember]  
  125.         public String Title  
  126.         {  
  127.             get { return _title; }  
  128.             set { _title = value; }  
  129.         }  
  130.         private String _branch;  
  131.         [DataMember]  
  132.         public String Branch  
  133.         {  
  134.             get { return _branch; }  
  135.             set { _branch = value; }  
  136.         }  
  137.         private String _managerDistingName;  
  138.         [DataMember]  
  139.         public String ManagerDistingName  
  140.         {  
  141.             get { return _managerDistingName; }  
  142.             set { _managerDistingName = value; }  
  143.         }  
  144.         private String _sAMAccountName;  
  145.         [DataMember]  
  146.         public String SAMAccountName  
  147.         {  
  148.             get { return ConfigurationManager.AppSettings["DomianName"] + _sAMAccountName; }  
  149.             set { _sAMAccountName = value; }  
  150.         }  
  151.         private bool _isManager;  
  152.         [DataMember]  
  153.         public bool IsManager  
  154.         {  
  155.             get { return _isManager; }  
  156.             set { _isManager = value; }  
  157.         }  
  158.         private String _firstName;  
  159.         [DataMember]  
  160.         public String FirstName  
  161.         {  
  162.             get { return _firstName; }  
  163.             set { _firstName = value; }  
  164.         }  
  165.         private String _company;  
  166.         [DataMember]  
  167.         public String Company  
  168.         {  
  169.             get { return _company; }  
  170.             set { _company = value; }  
  171.         }  
  172.         private String _description;  
  173.         [DataMember]  
  174.         public String Description  
  175.         {  
  176.             get { return _description; }  
  177.             set { _description = value; }  
  178.         }  
  179.         #region IComparable<UserInfo> Members  
  180.         public int CompareTo(ActiveUser other)  
  181.         {  
  182.             return DisplayName.CompareTo(other.DisplayName);  
  183.         }  
  184.         #endregion  
  185.     }  
  186. }   
C) Implement the active directory service code:
 
1. Add active directory information (DomainName , UserName and password) in an appseting in webconfig file
  1. <appSettings>  
  2.        <add key="DomianName" value="#######"/>  
  3.        <add key="Domain" value="#######"/>  
  4.        <add key="ADUserName" value="#######"/>  
  5.        <add key="ADPassword" value="#######"/>  
  6. </appSettings> 
2. Implement the IActiveDirectory and write the Active Directory operation
 
Here the code of the Active Directory Function contain method to get all active directory user in a list and also method to return it into a dataSet with some methods to get the user information and user Hierarchy.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.Text;  
  7. using System.DirectoryServices;  
  8. using System.Data;  
  9. using System.Configuration;  
  10. namespace ActiveDirectoryManager  
  11. {  
  12.     // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config and in the associated .svc file.  
  13.     public class ActiveDirectory : IActiveDirectory  
  14.     {  
  15.         #region IActiveDirectory Members  
  16.         DirectoryEntry directoryEntry;   
  17.         public  ActiveDirectory()  
  18.         {  
  19.             directoryEntry = new DirectoryEntry(System.Configuration.ConfigurationSettings.AppSettings["Domain"]);  
  20.             directoryEntry.Username = ConfigurationSettings.AppSettings["ADUserName"];  
  21.             directoryEntry.Password = ConfigurationSettings.AppSettings["ADPassword"];  
  22.         }  
  23.         public  ActiveDirectory(string path, string userName, string password)  
  24.         {  
  25.             new DirectoryEntry(path);  
  26.             directoryEntry.Path = path;  
  27.             directoryEntry.Username = userName;  
  28.             directoryEntry.Password = password;  
  29.         }  
  30.         public ActiveUser GetUserInfo(string UserName)  
  31.         {  
  32.             UserName = UserName.Substring(UserName.IndexOf("file://%22%29%20+%201/) + 1);  
  33.             DirectorySearcher Searcher = new DirectorySearcher(directoryEntry);  
  34.             Searcher.CacheResults = true;  
  35.             Searcher.SearchScope = SearchScope.Subtree;  
  36.             Searcher.Filter = "(&(objectCategory=Person)(|samaccountname=" + UserName + "))";  
  37.             Searcher.PropertiesToLoad.Add("DisplayName");  
  38.             Searcher.PropertiesToLoad.Add("department");  
  39.             Searcher.PropertiesToLoad.Add("DistinguishedName");  
  40.             Searcher.PropertiesToLoad.Add("Title");  
  41.             Searcher.PropertiesToLoad.Add("manager");  
  42.             Searcher.PropertiesToLoad.Add("mail");  
  43.             Searcher.PropertiesToLoad.Add("physicalDeliveryOfficeName");  
  44.             Searcher.PropertiesToLoad.Add("DirectReports");  
  45.             Searcher.PropertiesToLoad.Add("GivenName");  
  46.             Searcher.PropertiesToLoad.Add("Company");  
  47.             Searcher.PropertiesToLoad.Add("Description");  
  48.             Searcher.PropertiesToLoad.Add("SAMAccountName");  
  49.             SearchResult result;  
  50.             result = Searcher.FindOne();  
  51.             ActiveUser puser = new ActiveUser();  
  52.             try  
  53.             {  
  54.                 puser.DisplayName = result.Properties["Displayname"][0].ToString();  
  55.                 if (result.Properties["Department"] != null && result.Properties["Department"].Count > 0)  
  56.                     puser.Department = result.Properties["Department"][0].ToString();  
  57.                 else  
  58.                     puser.Department = "";  
  59.                 if (result.Properties["GivenName"] != null && result.Properties["GivenName"].Count > 0)  
  60.                     puser.FirstName = result.Properties["GivenName"][0].ToString();  
  61.                 else  
  62.                     puser.FirstName = "";  
  63.                 if (result.Properties["mail"] != null && result.Properties["mail"].Count > 0)  
  64.                     puser.Email = result.Properties["mail"][0].ToString();  
  65.                 else  
  66.                     puser.Email = "";  
  67.                 if (result.Properties["Description"] != null && result.Properties["Description"].Count > 0)  
  68.                     puser.Description = result.Properties["Description"][0].ToString();  
  69.                 else  
  70.                     puser.Description = "";  
  71.                 if (result.Properties["Company"] != null && result.Properties["Company"].Count > 0)  
  72.                     puser.Company = result.Properties["Company"][0].ToString();  
  73.                 else  
  74.                     puser.Company = "";  
  75.                 if (result.Properties["DistinguishedName"] != null && result.Properties["DistinguishedName"].Count > 0)  
  76.                     puser.DistinguishedName = result.Properties["DistinguishedName"][0].ToString();  
  77.                 else  
  78.                     puser.DistinguishedName = "";  
  79.                 if (result.Properties["Title"] != null && result.Properties["Title"].Count > 0)  
  80.                     puser.Title = result.Properties["Title"][0].ToString();  
  81.                 else  
  82.                     puser.Title = "";  
  83.                 if (result.Properties["physicalDeliveryOfficeName"] != null && result.Properties["physicalDeliveryOfficeName"].Count > 0)  
  84.                     puser.Branch = result.Properties["physicalDeliveryOfficeName"][0].ToString();  
  85.                 else  
  86.                     puser.Branch = "";  
  87.                 if (result.Properties["SAMAccountName"] != null && result.Properties["SAMAccountName"].Count > 0)  
  88.                     puser.SAMAccountName = result.Properties["SAMAccountName"][0].ToString();  
  89.                 else  
  90.                     puser.SAMAccountName = "";  
  91.                 if (result.Properties["manager"] != null && result.Properties["manager"].Count > 0)  
  92.                 {  
  93.                     puser.ManagerDistingName = result.Properties["Manager"][0].ToString();  
  94.                     String pManager;  
  95.                     pManager = result.Properties["manager"][0].ToString();  
  96.                     String[] tmpMan = pManager.Split(',');  
  97.                     pManager = tmpMan[0].ToString();  
  98.                     puser.Manager = pManager.Substring(3, pManager.Length - 3);  
  99.                 }  
  100.                 else  
  101.                 {  
  102.                     puser.ManagerDistingName = "";  
  103.                     puser.Manager = "";  
  104.                 }  
  105.                 if (result.Properties["DirectReports"] != null && result.Properties["DirectReports"].Count > 0)  
  106.                     puser.IsManager = true;  
  107.                 else  
  108.                     puser.IsManager = false;  
  109.             }  
  110.             catch (Exception ex)  
  111.             {  
  112.               //  Logger.WriteLog(ex.Message + " " + ex.StackTrace, "ActiveDirectoryManager --- GetUserInfo");  
  113.             }  
  114.             return puser;  
  115.         }  
  116.         public ActiveUser GetUserInfoByDistinguishName(string DistinguishName)  
  117.         {  
  118.             DirectorySearcher Searcher = new DirectorySearcher(directoryEntry);  
  119.             Searcher.CacheResults = true;  
  120.             Searcher.SearchScope = SearchScope.Subtree;  
  121.             Searcher.Filter = "(&(objectCategory=Person)(|DistinguishedName=" + DistinguishName + "))";  
  122.             Searcher.PropertiesToLoad.Add("DisplayName");  
  123.             Searcher.PropertiesToLoad.Add("department");  
  124.             Searcher.PropertiesToLoad.Add("DistinguishedName");  
  125.             Searcher.PropertiesToLoad.Add("Title");  
  126.             Searcher.PropertiesToLoad.Add("manager");  
  127.             Searcher.PropertiesToLoad.Add("mail");  
  128.             Searcher.PropertiesToLoad.Add("physicalDeliveryOfficeName");  
  129.             Searcher.PropertiesToLoad.Add("DirectReports");  
  130.             Searcher.PropertiesToLoad.Add("GivenName");  
  131.             Searcher.PropertiesToLoad.Add("Company");  
  132.             Searcher.PropertiesToLoad.Add("Description");  
  133.             Searcher.PropertiesToLoad.Add("SAMAccountName");  
  134.             SearchResult result;  
  135.             result = Searcher.FindOne();  
  136.             ActiveUser puser = new ActiveUser();  
  137.             try  
  138.             {  
  139.                 puser.DisplayName = result.Properties["Displayname"][0].ToString();  
  140.                 if (result.Properties["Department"] != null && result.Properties["Department"].Count > 0)  
  141.                     puser.Department = result.Properties["Department"][0].ToString();  
  142.                 else  
  143.                     puser.Department = "";  
  144.                 if (result.Properties["GivenName"] != null && result.Properties["GivenName"].Count > 0)  
  145.                     puser.FirstName = result.Properties["GivenName"][0].ToString();  
  146.                 else  
  147.                     puser.FirstName = "";  
  148.                 if (result.Properties["mail"] != null && result.Properties["mail"].Count > 0)  
  149.                     puser.Email = result.Properties["mail"][0].ToString();  
  150.                 else  
  151.                     puser.Email = "";  
  152.                 if (result.Properties["Description"] != null && result.Properties["Description"].Count > 0)  
  153.                     puser.Description = result.Properties["Description"][0].ToString();  
  154.                 else  
  155.                     puser.Description = "";  
  156.                 if (result.Properties["Company"] != null && result.Properties["Company"].Count > 0)  
  157.                     puser.Company = result.Properties["Company"][0].ToString();  
  158.                 else  
  159.                     puser.Company = "";  
  160.                 if (result.Properties["DistinguishedName"] != null && result.Properties["DistinguishedName"].Count > 0)  
  161.                     puser.DistinguishedName = result.Properties["DistinguishedName"][0].ToString();  
  162.                 else  
  163.                     puser.DistinguishedName = "";  
  164.                 if (result.Properties["Title"] != null && result.Properties["Title"].Count > 0)  
  165.                     puser.Title = result.Properties["Title"][0].ToString();  
  166.                 else  
  167.                     puser.Title = "";  
  168.                 if (result.Properties["physicalDeliveryOfficeName"] != null && result.Properties["physicalDeliveryOfficeName"].Count > 0)  
  169.                     puser.Branch = result.Properties["physicalDeliveryOfficeName"][0].ToString();  
  170.                 else  
  171.                     puser.Branch = "";  
  172.                 if (result.Properties["SAMAccountName"] != null && result.Properties["SAMAccountName"].Count > 0)  
  173.                     puser.SAMAccountName = result.Properties["SAMAccountName"][0].ToString();  
  174.                 else  
  175.                     puser.SAMAccountName = "";  
  176.                 if (result.Properties["manager"] != null && result.Properties["manager"].Count > 0)  
  177.                 {  
  178.                     puser.ManagerDistingName = result.Properties["Manager"][0].ToString();  
  179.                     String pManager;  
  180.                     pManager = result.Properties["manager"][0].ToString();  
  181.                     String[] tmpMan = pManager.Split(',');  
  182.                     pManager = tmpMan[0].ToString();  
  183.                     puser.Manager = pManager.Substring(3, pManager.Length - 3);  
  184.                 }  
  185.                 else  
  186.                 {  
  187.                     puser.ManagerDistingName = "";  
  188.                     puser.Manager = "";  
  189.                 }  
  190.                 if (result.Properties["DirectReports"] != null && result.Properties["DirectReports"].Count > 0)  
  191.                     puser.IsManager = true;  
  192.                 else  
  193.                     puser.IsManager = false;  
  194.             }  
  195.             catch (Exception ex)  
  196.             {  
  197.                // Logger.WriteLog(ex.Message + " " + ex.StackTrace, "ActiveDirectoryManager --- GetUserInfo");  
  198.             }  
  199.             return puser;  
  200.         }  
  201.         public List<ActiveUser> GetAllUsers()  
  202.         {  
  203.             DirectorySearcher Searcher = new DirectorySearcher(directoryEntry);  
  204.             Searcher.CacheResults = true;  
  205.             Searcher.SearchScope = SearchScope.Subtree;  
  206.             Searcher.Filter = "(&(objectCategory=user)(company=*))";  
  207.             Searcher.PropertiesToLoad.Add("SAMAccountName");  
  208.             Searcher.PropertiesToLoad.Add("DisplayName");  
  209.             Searcher.PropertiesToLoad.Add("department");  
  210.             Searcher.PropertiesToLoad.Add("DistinguishedName");  
  211.             Searcher.PropertiesToLoad.Add("Title");  
  212.             Searcher.PropertiesToLoad.Add("manager");  
  213.             Searcher.PropertiesToLoad.Add("mail");  
  214.             Searcher.PropertiesToLoad.Add("physicalDeliveryOfficeName");  
  215.             Searcher.PropertiesToLoad.Add("DirectReports");  
  216.             Searcher.PropertiesToLoad.Add("GivenName");  
  217.             Searcher.PropertiesToLoad.Add("Company");  
  218.             Searcher.PropertiesToLoad.Add("Description");  
  219.             SearchResultCollection results;  
  220.             results = Searcher.FindAll();  
  221.             List<ActiveUser> userCol = new List<ActiveUser>();  
  222.             ActiveUser puser;  
  223.             foreach (SearchResult result in results)  
  224.             {  
  225.                 puser = new ActiveUser();  
  226.                 if (result.Properties["Displayname"] != null && result.Properties["Displayname"].Count > 0)  
  227.                     puser.DisplayName = result.Properties["Displayname"][0].ToString();  
  228.                 else  
  229.                     puser.DisplayName = "";  
  230.                 if (result.Properties["Department"] != null && result.Properties["Department"].Count > 0)  
  231.                     puser.Department = result.Properties["Department"][0].ToString();  
  232.                 else  
  233.                     puser.Department = "";  
  234.                 if (result.Properties["GivenName"] != null && result.Properties["GivenName"].Count > 0)  
  235.                     puser.FirstName = result.Properties["GivenName"][0].ToString();  
  236.                 else  
  237.                     puser.FirstName = "";  
  238.                 if (result.Properties["mail"] != null && result.Properties["mail"].Count > 0)  
  239.                     puser.Email = result.Properties["mail"][0].ToString();  
  240.                 else  
  241.                     puser.Email = "";  
  242.                 if (result.Properties["Description"] != null && result.Properties["Description"].Count > 0)  
  243.                     puser.Description = result.Properties["Description"][0].ToString();  
  244.                 else  
  245.                     puser.Description = "";  
  246.                 if (result.Properties["Company"] != null && result.Properties["Company"].Count > 0)  
  247.                     puser.Company = result.Properties["Company"][0].ToString();  
  248.                 else  
  249.                     puser.Company = "";  
  250.                 if (result.Properties["DistinguishedName"] != null && result.Properties["DistinguishedName"].Count > 0)  
  251.                     puser.DistinguishedName = result.Properties["DistinguishedName"][0].ToString();  
  252.                 else  
  253.                     puser.DistinguishedName = "";  
  254.                 if (result.Properties["Title"] != null && result.Properties["Title"].Count > 0)  
  255.                     puser.Title = result.Properties["Title"][0].ToString();  
  256.                 else  
  257.                     puser.Title = "";  
  258.                 if (result.Properties["physicalDeliveryOfficeName"] != null && result.Properties["physicalDeliveryOfficeName"].Count > 0)  
  259.                     puser.Branch = result.Properties["physicalDeliveryOfficeName"][0].ToString();  
  260.                 else  
  261.                     puser.Branch = "";  
  262.                 if (result.Properties["SAMAccountName"] != null && result.Properties["SAMAccountName"].Count > 0)  
  263.                     puser.SAMAccountName = result.Properties["SAMAccountName"][0].ToString();  
  264.                 else  
  265.                     puser.SAMAccountName = "";  
  266.                 if (result.Properties["manager"] != null && result.Properties["manager"].Count > 0)  
  267.                 {  
  268.                     puser.ManagerDistingName = result.Properties["Manager"][0].ToString();  
  269.                     String pManager;  
  270.                     pManager = result.Properties["manager"][0].ToString();  
  271.                     String[] tmpMan = pManager.Split(',');  
  272.                     pManager = tmpMan[0].ToString();  
  273.                     puser.Manager = pManager.Substring(3, pManager.Length - 3);  
  274.                 }  
  275.                 else  
  276.                 {  
  277.                     puser.ManagerDistingName = "";  
  278.                     puser.Manager = "";  
  279.                 }  
  280.                 if (result.Properties["DirectReports"] != null && result.Properties["DirectReports"].Count > 0)  
  281.                     puser.IsManager = true;  
  282.                 else  
  283.                     puser.IsManager = false;  
  284.                 userCol.Add(puser);  
  285.             }  
  286.             userCol.Sort();  
  287.             return userCol;  
  288.         }  
  289.         public System.Data.DataSet GetAllUsersDataSet()  
  290.         {  
  291.             DirectorySearcher Searcher = new DirectorySearcher(directoryEntry);  
  292.             DataSet dsUsers = new DataSet();  
  293.             DataTable dtUser = PrepareUsersDataTable();  
  294.             Searcher.CacheResults = true;  
  295.             Searcher.SearchScope = SearchScope.Subtree;  
  296.             Searcher.Sort.PropertyName = "DisplayName";  
  297.             Searcher.Filter = "(&(objectCategory=user)(company=*))";  
  298.             Searcher.PropertiesToLoad.Add("DisplayName");  
  299.             Searcher.PropertiesToLoad.Add("department");  
  300.             Searcher.PropertiesToLoad.Add("DistinguishedName");  
  301.             Searcher.PropertiesToLoad.Add("Title");  
  302.             Searcher.PropertiesToLoad.Add("manager");  
  303.             Searcher.PropertiesToLoad.Add("mail");  
  304.             Searcher.PropertiesToLoad.Add("physicalDeliveryOfficeName");  
  305.             Searcher.PropertiesToLoad.Add("DirectReports");  
  306.             Searcher.PropertiesToLoad.Add("GivenName");  
  307.             Searcher.PropertiesToLoad.Add("Company");  
  308.             Searcher.PropertiesToLoad.Add("Description");  
  309.             //Searcher.Sort.PropertyName = "DisplayName";  
  310.             Searcher.Sort = new SortOption("DisplayName", SortDirection.Ascending);  
  311.             SearchResultCollection results;  
  312.             results = Searcher.FindAll();  
  313.             DataRow userRow;  
  314.             foreach (SearchResult result in results)  
  315.             {  
  316.                 userRow = dtUser.NewRow();  
  317.                 if (result.Properties["Displayname"] != null && result.Properties["Displayname"].Count > 0)  
  318.                     userRow["Displayname"] = result.Properties["Displayname"][0].ToString();  
  319.                 else  
  320.                     userRow["Displayname"] = "";  
  321.                 if (result.Properties["Department"] != null && result.Properties["Department"].Count > 0)  
  322.                     userRow["Department"] = result.Properties["Department"][0].ToString();  
  323.                 else  
  324.                     userRow["Department"] = "";  
  325.                 if (result.Properties["GivenName"] != null && result.Properties["GivenName"].Count > 0)  
  326.                     userRow["FirstName"] = result.Properties["GivenName"][0].ToString();  
  327.                 else  
  328.                     userRow["FirstName"] = "";  
  329.                 if (result.Properties["mail"] != null && result.Properties["mail"].Count > 0)  
  330.                     userRow["Email"] = result.Properties["mail"][0].ToString();  
  331.                 else  
  332.                     userRow["Email"] = "";  
  333.                 if (result.Properties["Description"] != null && result.Properties["Description"].Count > 0)  
  334.                     userRow["Description"] = result.Properties["Description"][0].ToString();  
  335.                 else  
  336.                     userRow["Description"] = "";  
  337.                 if (result.Properties["Company"] != null && result.Properties["Company"].Count > 0)  
  338.                     userRow["Company"] = result.Properties["Company"][0].ToString();  
  339.                 else  
  340.                     userRow["Company"] = "";  
  341.                 if (result.Properties["DistinguishedName"] != null && result.Properties["DistinguishedName"].Count > 0)  
  342.                     userRow["DistinguishedName"] = result.Properties["DistinguishedName"][0].ToString();  
  343.                 else  
  344.                     userRow["DistinguishedName"] = "";  
  345.                 if (result.Properties["Title"] != null && result.Properties["Title"].Count > 0)  
  346.                     userRow["Title"] = result.Properties["Title"][0].ToString();  
  347.                 else  
  348.                     userRow["Title"] = "";  
  349.                 if (result.Properties["physicalDeliveryOfficeName"] != null && result.Properties["physicalDeliveryOfficeName"].Count > 0)  
  350.                     userRow["Branch"] = result.Properties["physicalDeliveryOfficeName"][0].ToString();  
  351.                 else  
  352.                     userRow["Branch"] = "";  
  353.                 if (result.Properties["manager"] != null && result.Properties["manager"].Count > 0)  
  354.                 {  
  355.                     userRow["ManagerDistingName"] = result.Properties["Manager"][0].ToString();  
  356.                     String pManager;  
  357.                     pManager = result.Properties["manager"][0].ToString();  
  358.                     String[] tmpMan = pManager.Split(',');  
  359.                     pManager = tmpMan[0].ToString();  
  360.                     userRow["Manager"] = pManager.Substring(3, pManager.Length - 3);  
  361.                 }  
  362.                 else  
  363.                 {  
  364.                     userRow["ManagerDistingName"] = "";  
  365.                     userRow["Manager"] = "";  
  366.                 }  
  367.                 if (result.Properties["DirectReports"] != null && result.Properties["DirectReports"].Count > 0)  
  368.                     userRow["IsManager"] = true;  
  369.                 else  
  370.                     userRow["IsManager"] = false;  
  371.                 dtUser.Rows.Add(userRow);  
  372.             }  
  373.             dsUsers.Tables.Add(dtUser);  
  374.             return dsUsers;  
  375.         }  
  376.         public System.Data.DataSet GetAllUsersDataSetMinAttributes()  
  377.         {  
  378.             DirectorySearcher Searcher = new DirectorySearcher(directoryEntry);  
  379.             DataSet dsUsers = new DataSet();  
  380.             DataTable dtUser = new DataTable();  
  381.             dtUser.Columns.Add("Displayname");  
  382.             dtUser.Columns.Add("UserID");  
  383.             Searcher.CacheResults = true;  
  384.             Searcher.SearchScope = SearchScope.Subtree;  
  385.             Searcher.Filter = "(&(objectCategory=user)(company=*))";  
  386.             Searcher.PropertiesToLoad.Add("DisplayName");  
  387.             Searcher.PropertiesToLoad.Add("SAMAccountName");  
  388.             Searcher.Sort = new SortOption("DisplayName", SortDirection.Ascending);  
  389.             SearchResultCollection results;  
  390.             results = Searcher.FindAll();  
  391.             DataRow userRow;  
  392.             foreach (SearchResult result in results)  
  393.             {  
  394.                 userRow = dtUser.NewRow();  
  395.                 if (result.Properties["Displayname"] != null && result.Properties["Displayname"].Count > 0)  
  396.                     userRow["Displayname"] = result.Properties["Displayname"][0].ToString();  
  397.                 else  
  398.                     userRow["Displayname"] = "";  
  399.                 if (result.Properties["SAMAccountName"] != null && result.Properties["SAMAccountName"].Count > 0)  
  400.                     userRow["UserID"] = ConfigurationManager.AppSettings["DomianName"] + result.Properties["SAMAccountName"][0].ToString();  
  401.                 else  
  402.                     userRow["UserID"] = "";  
  403.                 dtUser.Rows.Add(userRow);  
  404.             }  
  405.             dsUsers.Tables.Add(dtUser);  
  406.             return dsUsers;  
  407.         }  
  408.         public System.Data.DataTable PrepareUsersDataTable()  
  409.         {  
  410.             DataTable userDT = new DataTable();  
  411.             userDT.Columns.Add("Displayname");  
  412.             userDT.Columns.Add("Department");  
  413.             userDT.Columns.Add("FirstName");  
  414.             userDT.Columns.Add("Description");  
  415.             userDT.Columns.Add("Email");  
  416.             userDT.Columns.Add("Company");  
  417.             userDT.Columns.Add("DistinguishedName");  
  418.             userDT.Columns.Add("Title");  
  419.             userDT.Columns.Add("Branch");  
  420.             userDT.Columns.Add("ManagerDistingName");  
  421.             userDT.Columns.Add("Manager");  
  422.             userDT.Columns.Add("IsManager");  
  423.             return userDT;  
  424.         }  
  425.         #endregion  
  426.     }  
  427. }   
3. Consume the Active Directory Service in your application:
Choose add service reference and create a web test application and try with me to access your, I have created an aspx page to test my service and in its code behind I wrote these lines: 
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     ActiveDirectoryRef.ActiveDirectoryClient adClient = new ActiveDirectoryClient();  
  4.     var activeusersVar = from activeUser in adClient.GetAllUsers()  
  5.                          where activeUser.Branch == "Maadi 1"  
  6.                          select activeUser;  
  7.     List<ActiveUser> activeUserList = activeusersVar.ToList<ActiveUser>();  
  8.     foreach (ActiveUser  ac in activeUserList)  
  9.     {  
  10.         Response.Write(ac.DisplayName +"<br/>";   
  11.     }  
  12. } 
Please check the full service code.