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.
Here the code of the Active Directory data contract and Interface for the operation contracts:
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
- {
-
- 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:
- 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)
- {
-
- }
- 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)
- {
-
- }
- 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 = 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.