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 in 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: http://msdn.microsoft.com/en-us/library/ms733127.aspx B) Add the OperationContract: http://msdn.microsoft.com/en-us/library/system.servicemodel.operationcontractattribute.aspx Here the code of the Active Directory data contract and Interface for the operation contracts: using System;using System.Collections.Generic;using System.Linq;using System.Runtime.Serialization;using System.ServiceModel;using System.Text;using System.Data;using System.DirectoryServices;using System.Configuration;namespace ActiveDirectoryManager{ // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config. [ServiceContract] public interface IActiveDirectory { [OperationContract] string GetData(int value); [OperationContract] CompositeType GetDataUsingDataContract(CompositeType composite); // TODO: Add your service operations here //DirectoryEntry directoryEntry; //[OperationContract] // void ActiveDirectoryHelper(); //[OperationContract] // void ActiveDirectoryHelper(string path, string userName, string password); /// <summary> /// Gets user infromation by user ID /// </summary> /// <param name="UserName"> User Name to search with</param> /// <returns>User Information Object</returns> [OperationContract] ActiveUser GetUserInfo(string UserName); /// <summary> /// Gets user infromation by user DistinguishName /// </summary> /// <param name="DistinguishName">User Distinguish Name to search with</param> /// <returns>User Information Object</returns> [OperationContract] ActiveUser GetUserInfoByDistinguishName(string DistinguishName); /// <summary> /// Gets all users from active directory /// </summary> /// <returns>User Information Collection</returns> [OperationContract] List<ActiveUser> GetAllUsers(); /// <summary> /// Gets all users from active directory /// </summary> /// <returns>User Information Dataset</returns> [OperationContract] DataSet GetAllUsersDataSet(); /// <summary> /// Gets all users' Display Name and ID from active directory /// </summary> /// <returns>User Information Dataset</returns> [OperationContract] DataSet GetAllUsersDataSetMinAttributes(); [OperationContract] DataTable PrepareUsersDataTable(); } // Use a data contract as illustrated in the sample below to add composite types to service operations. [DataContract] public class CompositeType { bool boolValue = true; string stringValue = "Hello "; [DataMember] public bool BoolValue { get { return boolValue; } set { boolValue = value; } } [DataMember] public string StringValue { get { return stringValue; } set { stringValue = value; } } } /// <summary> /// Carries user information object /// </summary> [DataContract] [Serializable()] public class ActiveUser : IComparable<ActiveUser> { private String _displayName; [DataMember] public String DisplayName { get { return _displayName; } set { _displayName = value; } } private String _email; [DataMember] public String Email { get { return _email; } set { _email = value; } } private String _manager; [DataMember] public String Manager { get { return _manager; } set { _manager = value; } } private String _department; [DataMember] public String Department { get { return _department; } set { _department = value; } } private String _distinguishedName; [DataMember] public String DistinguishedName { get { return _distinguishedName; } set { _distinguishedName = value; } } private String _title; [DataMember] public String Title { get { return _title; } set { _title = value; } } private String _branch; [DataMember] public String Branch { get { return _branch; } set { _branch = value; } } private String _managerDistingName; [DataMember] public String ManagerDistingName { get { return _managerDistingName; } set { _managerDistingName = value; } } private String _sAMAccountName; [DataMember] public String SAMAccountName { get { return ConfigurationManager.AppSettings["DomianName"] + _sAMAccountName; } set { _sAMAccountName = value; } } private bool _isManager; [DataMember] public bool IsManager { get { return _isManager; } set { _isManager = value; } } private String _firstName; [DataMember] public String FirstName { get { return _firstName; } set { _firstName = value; } } private String _company; [DataMember] public String Company { get { return _company; } set { _company = value; } } private String _description; [DataMember] public String Description { get { return _description; } set { _description = value; } } #region IComparable<UserInfo> Members public int CompareTo(ActiveUser other) { return DisplayName.CompareTo(other.DisplayName); } #endregion }} C) Implement the active directory service code: 1- Add active directory information (DomainName , UserName and password) in an appseting in webconfig file <appSettings> <add key="DomianName" value="#######"/> <add key="Domain" value="#######"/> <add key="ADUserName" value="#######"/> <add key="ADPassword" value="#######"/></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. using System;using System.Collections.Generic;using System.Linq;using System.Runtime.Serialization;using System.ServiceModel;using System.Text;using System.DirectoryServices;using System.Data;using System.Configuration;namespace ActiveDirectoryManager{ // 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. public class ActiveDirectory : IActiveDirectory { #region IActiveDirectory Members DirectoryEntry directoryEntry; public ActiveDirectory() { directoryEntry = new DirectoryEntry(System.Configuration.ConfigurationSettings.AppSettings["Domain"]); directoryEntry.Username = ConfigurationSettings.AppSettings["ADUserName"]; directoryEntry.Password = ConfigurationSettings.AppSettings["ADPassword"]; } public ActiveDirectory(string path, string userName, string password) { new DirectoryEntry(path); directoryEntry.Path = path; directoryEntry.Username = userName; directoryEntry.Password = password; } public ActiveUser GetUserInfo(string UserName) { UserName = UserName.Substring(UserName.IndexOf("file://%22%29%20+%201/) + 1); DirectorySearcher Searcher = new DirectorySearcher(directoryEntry); Searcher.CacheResults = true; Searcher.SearchScope = SearchScope.Subtree; Searcher.Filter = "(&(objectCategory=Person)(|samaccountname=" + UserName + "))"; Searcher.PropertiesToLoad.Add("DisplayName"); Searcher.PropertiesToLoad.Add("department"); Searcher.PropertiesToLoad.Add("DistinguishedName"); Searcher.PropertiesToLoad.Add("Title"); Searcher.PropertiesToLoad.Add("manager"); Searcher.PropertiesToLoad.Add("mail"); Searcher.PropertiesToLoad.Add("physicalDeliveryOfficeName"); Searcher.PropertiesToLoad.Add("DirectReports"); Searcher.PropertiesToLoad.Add("GivenName"); Searcher.PropertiesToLoad.Add("Company"); Searcher.PropertiesToLoad.Add("Description"); Searcher.PropertiesToLoad.Add("SAMAccountName"); SearchResult result; result = Searcher.FindOne(); ActiveUser puser = new ActiveUser(); try { puser.DisplayName = result.Properties["Displayname"][0].ToString(); if (result.Properties["Department"] != null && result.Properties["Department"].Count > 0) puser.Department = result.Properties["Department"][0].ToString(); else puser.Department = ""; if (result.Properties["GivenName"] != null && result.Properties["GivenName"].Count > 0) puser.FirstName = result.Properties["GivenName"][0].ToString(); else puser.FirstName = ""; if (result.Properties["mail"] != null && result.Properties["mail"].Count > 0) puser.Email = result.Properties["mail"][0].ToString(); else puser.Email = ""; if (result.Properties["Description"] != null && result.Properties["Description"].Count > 0) puser.Description = result.Properties["Description"][0].ToString(); else puser.Description = ""; if (result.Properties["Company"] != null && result.Properties["Company"].Count > 0) puser.Company = result.Properties["Company"][0].ToString(); else puser.Company = ""; if (result.Properties["DistinguishedName"] != null && result.Properties["DistinguishedName"].Count > 0) puser.DistinguishedName = result.Properties["DistinguishedName"][0].ToString(); else puser.DistinguishedName = ""; if (result.Properties["Title"] != null && result.Properties["Title"].Count > 0) puser.Title = result.Properties["Title"][0].ToString(); else puser.Title = ""; if (result.Properties["physicalDeliveryOfficeName"] != null && result.Properties["physicalDeliveryOfficeName"].Count > 0) puser.Branch = result.Properties["physicalDeliveryOfficeName"][0].ToString(); else puser.Branch = ""; if (result.Properties["SAMAccountName"] != null && result.Properties["SAMAccountName"].Count > 0) puser.SAMAccountName = result.Properties["SAMAccountName"][0].ToString(); else puser.SAMAccountName = ""; if (result.Properties["manager"] != null && result.Properties["manager"].Count > 0) { puser.ManagerDistingName = result.Properties["Manager"][0].ToString(); String pManager; pManager = result.Properties["manager"][0].ToString(); String[] tmpMan = pManager.Split(','); pManager = tmpMan[0].ToString(); puser.Manager = pManager.Substring(3, pManager.Length - 3); } else { puser.ManagerDistingName = ""; puser.Manager = ""; } if (result.Properties["DirectReports"] != null && result.Properties["DirectReports"].Count > 0) puser.IsManager = true; else puser.IsManager = false; } catch (Exception ex) { // Logger.WriteLog(ex.Message + " " + ex.StackTrace, "ActiveDirectoryManager --- GetUserInfo"); } return puser; } public ActiveUser GetUserInfoByDistinguishName(string DistinguishName) { DirectorySearcher Searcher = new DirectorySearcher(directoryEntry); Searcher.CacheResults = true; Searcher.SearchScope = SearchScope.Subtree; Searcher.Filter = "(&(objectCategory=Person)(|DistinguishedName=" + DistinguishName + "))"; Searcher.PropertiesToLoad.Add("DisplayName"); Searcher.PropertiesToLoad.Add("department"); Searcher.PropertiesToLoad.Add("DistinguishedName"); Searcher.PropertiesToLoad.Add("Title"); Searcher.PropertiesToLoad.Add("manager"); Searcher.PropertiesToLoad.Add("mail"); Searcher.PropertiesToLoad.Add("physicalDeliveryOfficeName"); Searcher.PropertiesToLoad.Add("DirectReports"); Searcher.PropertiesToLoad.Add("GivenName"); Searcher.PropertiesToLoad.Add("Company"); Searcher.PropertiesToLoad.Add("Description"); Searcher.PropertiesToLoad.Add("SAMAccountName"); SearchResult result; result = Searcher.FindOne(); ActiveUser puser = new ActiveUser(); try { puser.DisplayName = result.Properties["Displayname"][0].ToString(); if (result.Properties["Department"] != null && result.Properties["Department"].Count > 0) puser.Department = result.Properties["Department"][0].ToString(); else puser.Department = ""; if (result.Properties["GivenName"] != null && result.Properties["GivenName"].Count > 0) puser.FirstName = result.Properties["GivenName"][0].ToString(); else puser.FirstName = ""; if (result.Properties["mail"] != null && result.Properties["mail"].Count > 0) puser.Email = result.Properties["mail"][0].ToString(); else puser.Email = ""; if (result.Properties["Description"] != null && result.Properties["Description"].Count > 0) puser.Description = result.Properties["Description"][0].ToString(); else puser.Description = ""; if (result.Properties["Company"] != null && result.Properties["Company"].Count > 0) puser.Company = result.Properties["Company"][0].ToString(); else puser.Company = ""; if (result.Properties["DistinguishedName"] != null && result.Properties["DistinguishedName"].Count > 0) puser.DistinguishedName = result.Properties["DistinguishedName"][0].ToString(); else puser.DistinguishedName = ""; if (result.Properties["Title"] != null && result.Properties["Title"].Count > 0) puser.Title = result.Properties["Title"][0].ToString(); else puser.Title = ""; if (result.Properties["physicalDeliveryOfficeName"] != null && result.Properties["physicalDeliveryOfficeName"].Count > 0) puser.Branch = result.Properties["physicalDeliveryOfficeName"][0].ToString(); else puser.Branch = ""; if (result.Properties["SAMAccountName"] != null && result.Properties["SAMAccountName"].Count > 0) puser.SAMAccountName = result.Properties["SAMAccountName"][0].ToString(); else puser.SAMAccountName = ""; if (result.Properties["manager"] != null && result.Properties["manager"].Count > 0) { puser.ManagerDistingName = result.Properties["Manager"][0].ToString(); String pManager; pManager = result.Properties["manager"][0].ToString(); String[] tmpMan = pManager.Split(','); pManager = tmpMan[0].ToString(); puser.Manager = pManager.Substring(3, pManager.Length - 3); } else { puser.ManagerDistingName = ""; puser.Manager = ""; } if (result.Properties["DirectReports"] != null && result.Properties["DirectReports"].Count > 0) puser.IsManager = true; else puser.IsManager = false; } catch (Exception ex) { // Logger.WriteLog(ex.Message + " " + ex.StackTrace, "ActiveDirectoryManager --- GetUserInfo"); } return puser; } public List<ActiveUser> GetAllUsers() { DirectorySearcher Searcher = new DirectorySearcher(directoryEntry); Searcher.CacheResults = true; Searcher.SearchScope = SearchScope.Subtree; Searcher.Filter = "(&(objectCategory=user)(company=*))"; Searcher.PropertiesToLoad.Add("SAMAccountName"); Searcher.PropertiesToLoad.Add("DisplayName"); Searcher.PropertiesToLoad.Add("department"); Searcher.PropertiesToLoad.Add("DistinguishedName"); Searcher.PropertiesToLoad.Add("Title"); Searcher.PropertiesToLoad.Add("manager"); Searcher.PropertiesToLoad.Add("mail"); Searcher.PropertiesToLoad.Add("physicalDeliveryOfficeName"); Searcher.PropertiesToLoad.Add("DirectReports"); Searcher.PropertiesToLoad.Add("GivenName"); Searcher.PropertiesToLoad.Add("Company"); Searcher.PropertiesToLoad.Add("Description"); SearchResultCollection results; results = Searcher.FindAll(); List<ActiveUser> userCol = new List<ActiveUser>(); ActiveUser puser; foreach (SearchResult result in results) { puser = new ActiveUser(); if (result.Properties["Displayname"] != null && result.Properties["Displayname"].Count > 0) puser.DisplayName = result.Properties["Displayname"][0].ToString(); else puser.DisplayName = ""; if (result.Properties["Department"] != null && result.Properties["Department"].Count > 0) puser.Department = result.Properties["Department"][0].ToString(); else puser.Department = ""; if (result.Properties["GivenName"] != null && result.Properties["GivenName"].Count > 0) puser.FirstName = result.Properties["GivenName"][0].ToString(); else puser.FirstName = ""; if (result.Properties["mail"] != null && result.Properties["mail"].Count > 0) puser.Email = result.Properties["mail"][0].ToString(); else puser.Email = ""; if (result.Properties["Description"] != null && result.Properties["Description"].Count > 0) puser.Description = result.Properties["Description"][0].ToString(); else puser.Description = ""; if (result.Properties["Company"] != null && result.Properties["Company"].Count > 0) puser.Company = result.Properties["Company"][0].ToString(); else puser.Company = ""; if (result.Properties["DistinguishedName"] != null && result.Properties["DistinguishedName"].Count > 0) puser.DistinguishedName = result.Properties["DistinguishedName"][0].ToString(); else puser.DistinguishedName = ""; if (result.Properties["Title"] != null && result.Properties["Title"].Count > 0) puser.Title = result.Properties["Title"][0].ToString(); else puser.Title = ""; if (result.Properties["physicalDeliveryOfficeName"] != null && result.Properties["physicalDeliveryOfficeName"].Count > 0) puser.Branch = result.Properties["physicalDeliveryOfficeName"][0].ToString(); else puser.Branch = ""; if (result.Properties["SAMAccountName"] != null && result.Properties["SAMAccountName"].Count > 0) puser.SAMAccountName = result.Properties["SAMAccountName"][0].ToString(); else puser.SAMAccountName = ""; if (result.Properties["manager"] != null && result.Properties["manager"].Count > 0) { puser.ManagerDistingName = result.Properties["Manager"][0].ToString(); String pManager; pManager = result.Properties["manager"][0].ToString(); String[] tmpMan = pManager.Split(','); pManager = tmpMan[0].ToString(); puser.Manager = pManager.Substring(3, pManager.Length - 3); } else { puser.ManagerDistingName = ""; puser.Manager = ""; } if (result.Properties["DirectReports"] != null && result.Properties["DirectReports"].Count > 0) puser.IsManager = true; else puser.IsManager = false; userCol.Add(puser); } userCol.Sort(); return userCol; } public System.Data.DataSet GetAllUsersDataSet() { DirectorySearcher Searcher = new DirectorySearcher(directoryEntry); DataSet dsUsers = new DataSet(); DataTable dtUser = PrepareUsersDataTable(); Searcher.CacheResults = true; Searcher.SearchScope = SearchScope.Subtree; Searcher.Sort.PropertyName = "DisplayName"; Searcher.Filter = "(&(objectCategory=user)(company=*))"; Searcher.PropertiesToLoad.Add("DisplayName"); Searcher.PropertiesToLoad.Add("department"); Searcher.PropertiesToLoad.Add("DistinguishedName"); Searcher.PropertiesToLoad.Add("Title"); Searcher.PropertiesToLoad.Add("manager"); Searcher.PropertiesToLoad.Add("mail"); Searcher.PropertiesToLoad.Add("physicalDeliveryOfficeName"); Searcher.PropertiesToLoad.Add("DirectReports"); Searcher.PropertiesToLoad.Add("GivenName"); Searcher.PropertiesToLoad.Add("Company"); Searcher.PropertiesToLoad.Add("Description"); //Searcher.Sort.PropertyName = "DisplayName"; Searcher.Sort = new SortOption("DisplayName", SortDirection.Ascending); SearchResultCollection results; results = Searcher.FindAll(); DataRow userRow; foreach (SearchResult result in results) { userRow = dtUser.NewRow(); if (result.Properties["Displayname"] != null && result.Properties["Displayname"].Count > 0) userRow["Displayname"] = result.Properties["Displayname"][0].ToString(); else userRow["Displayname"] = ""; if (result.Properties["Department"] != null && result.Properties["Department"].Count > 0) userRow["Department"] = result.Properties["Department"][0].ToString(); else userRow["Department"] = ""; if (result.Properties["GivenName"] != null && result.Properties["GivenName"].Count > 0) userRow["FirstName"] = result.Properties["GivenName"][0].ToString(); else userRow["FirstName"] = ""; if (result.Properties["mail"] != null && result.Properties["mail"].Count > 0) userRow["Email"] = result.Properties["mail"][0].ToString(); else userRow["Email"] = ""; if (result.Properties["Description"] != null && result.Properties["Description"].Count > 0) userRow["Description"] = result.Properties["Description"][0].ToString(); else userRow["Description"] = ""; if (result.Properties["Company"] != null && result.Properties["Company"].Count > 0) userRow["Company"] = result.Properties["Company"][0].ToString(); else userRow["Company"] = ""; if (result.Properties["DistinguishedName"] != null && result.Properties["DistinguishedName"].Count > 0) userRow["DistinguishedName"] = result.Properties["DistinguishedName"][0].ToString(); else userRow["DistinguishedName"] = ""; if (result.Properties["Title"] != null && result.Properties["Title"].Count > 0) userRow["Title"] = result.Properties["Title"][0].ToString(); else userRow["Title"] = ""; if (result.Properties["physicalDeliveryOfficeName"] != null && result.Properties["physicalDeliveryOfficeName"].Count > 0) userRow["Branch"] = result.Properties["physicalDeliveryOfficeName"][0].ToString(); else userRow["Branch"] = ""; if (result.Properties["manager"] != null && result.Properties["manager"].Count > 0) { userRow["ManagerDistingName"] = result.Properties["Manager"][0].ToString(); String pManager; pManager = result.Properties["manager"][0].ToString(); String[] tmpMan = pManager.Split(','); pManager = tmpMan[0].ToString(); userRow["Manager"] = pManager.Substring(3, pManager.Length - 3); } else { userRow["ManagerDistingName"] = ""; userRow["Manager"] = ""; } if (result.Properties["DirectReports"] != null && result.Properties["DirectReports"].Count > 0) userRow["IsManager"] = true; else userRow["IsManager"] = false; dtUser.Rows.Add(userRow); } dsUsers.Tables.Add(dtUser); return dsUsers; } public System.Data.DataSet GetAllUsersDataSetMinAttributes() { DirectorySearcher Searcher = new DirectorySearcher(directoryEntry); DataSet dsUsers = new DataSet(); DataTable dtUser = new DataTable(); dtUser.Columns.Add("Displayname"); dtUser.Columns.Add("UserID"); Searcher.CacheResults = true; Searcher.SearchScope = SearchScope.Subtree; Searcher.Filter = "(&(objectCategory=user)(company=*))"; Searcher.PropertiesToLoad.Add("DisplayName"); Searcher.PropertiesToLoad.Add("SAMAccountName"); Searcher.Sort = new SortOption("DisplayName", SortDirection.Ascending); SearchResultCollection results; results = Searcher.FindAll(); DataRow userRow; foreach (SearchResult result in results) { userRow = dtUser.NewRow(); if (result.Properties["Displayname"] != null && result.Properties["Displayname"].Count > 0) userRow["Displayname"] = result.Properties["Displayname"][0].ToString(); else userRow["Displayname"] = ""; if (result.Properties["SAMAccountName"] != null && result.Properties["SAMAccountName"].Count > 0) userRow["UserID"] = ConfigurationManager.AppSettings["DomianName"] + result.Properties["SAMAccountName"][0].ToString(); else userRow["UserID"] = ""; dtUser.Rows.Add(userRow); } dsUsers.Tables.Add(dtUser); return dsUsers; } public System.Data.DataTable PrepareUsersDataTable() { DataTable userDT = new DataTable(); userDT.Columns.Add("Displayname"); userDT.Columns.Add("Department"); userDT.Columns.Add("FirstName"); userDT.Columns.Add("Description"); userDT.Columns.Add("Email"); userDT.Columns.Add("Company"); userDT.Columns.Add("DistinguishedName"); userDT.Columns.Add("Title"); userDT.Columns.Add("Branch"); userDT.Columns.Add("ManagerDistingName"); userDT.Columns.Add("Manager"); userDT.Columns.Add("IsManager"); return userDT; } #endregion }} 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: protected void Page_Load(object sender, EventArgs e){ ActiveDirectoryRef.ActiveDirectoryClient adClient = new ActiveDirectoryClient(); var activeusersVar = from activeUser in adClient.GetAllUsers() where activeUser.Branch == "Maadi 1" select activeUser; List<ActiveUser> activeUserList = activeusersVar.ToList<ActiveUser>(); foreach (ActiveUser ac in activeUserList) { Response.Write(ac.DisplayName +"<br/>"; }} Please check the full service code.
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: