I have written small console application to search the employee information from the directory by using Lightweight Directory Access Protocol. You can run this tool by entering the input as domain\EmployeeId or domain\FirstName LastName. The output would be employee details. The code has been written in C#.
Code:
ISearch.cs:
using System.DirectoryServices; namespace LDAP { public interface ISearch { DirectoryEntry Search(string domain, string filter); } }
SearchNumeric.cs:
using System.DirectoryServices; namespace LDAP { public class SearchNumeric : ISearch { public DirectoryEntry Search(string domain, string filter) { return SearchEmployee.GetEmpDirectoryEntry(domain, filter); } } }
SearchAlphaNumeric.cs:
using System; using System.DirectoryServices; namespace LDAP { public class SearchAlphaNumeric : ISearch { public DirectoryEntry Search(string domain, string filter) { SearchResultCollection collection = SearchEmployee.GetEmpSearchResultCollection(domain, filter); if (collection.Count > 1) throw new InvalidOperationException(); return SearchEmployee.GetEmpDirectoryEntry(domain, filter); } } }
SearchContext.cs:
using System.DirectoryServices; namespace LDAP { public class SearchContext { private ISearch iSearch; public SearchContext(ISearch search) { iSearch = search; } public DirectoryEntry ExecuteSearch(string domain, string filter) { return iSearch.Search(domain, filter); } } }
SearchEmployee.cs
using System.DirectoryServices; namespace LDAP { public class SearchEmployee { public static DirectoryEntry GetEmpDirectoryEntry(string domain, string filter) { DirectoryEntry adRoot = new DirectoryEntry("LDAP://" + domain, null, null, AuthenticationTypes.Secure); DirectorySearcher searcher = new DirectorySearcher(adRoot); searcher.SearchScope = SearchScope.Subtree; searcher.ReferralChasing = ReferralChasingOption.All; //searcher.PropertiesToLoad.AddRange(properties); searcher.Filter = filter; SearchResult result = searcher.FindOne(); DirectoryEntry directoryEntry = result.GetDirectoryEntry(); return directoryEntry; } public static SearchResultCollection GetEmpSearchResultCollection(string domain, string filter) { DirectoryEntry adRoot = new DirectoryEntry("LDAP://" + domain, null, null, AuthenticationTypes.Secure); DirectorySearcher searcher = new DirectorySearcher(adRoot); searcher.SearchScope = SearchScope.Subtree; searcher.ReferralChasing = ReferralChasingOption.All; //searcher.PropertiesToLoad.AddRange(properties); searcher.Filter = filter; SearchResultCollection collection = searcher.FindAll(); return collection; } } }
SearchResolver.cs:
using System.Text.RegularExpressions; namespace LDAP { public class SearchResolver { public static bool IsNumeric(string value) { bool match; //string pattern = "(^[-+]?\\d+(,?\\d*)*\\.?\\d*([Ee][-+]\\d*)?$)|(^[-+]?\\d?(,?\\d*)*\\.\\d+([Ee][-+]\\d*)?$)"; string pattern = "(^[0-9]*$)"; Regex regEx = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); match = regEx.Match(value).Success ? true : false; return match; } } }
SearchController.cs:
using System.Text; using System.DirectoryServices; namespace LDAP { public class SearchController { private static SearchContext _sContext; public static DirectoryEntry GetEmployeeInfo(string userDomain, string userId) { DirectoryEntry directoryEntry = null; if (SearchResolver.IsNumeric(userId)) { string filter = string.Format("(&(ObjectClass={0})(employeeId={1}))", "person", userId); _sContext = new SearchContext(new SearchNumeric()); directoryEntry = _sContext.ExecuteSearch(userDomain, filter); } else { string filter = string.Format("(&(ObjectClass={0})(anr={1}))", "person", userId); if (userId.Length == 7) { filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", userId); } _sContext = new SearchContext(new SearchAlphaNumeric()); directoryEntry = _sContext.ExecuteSearch(userDomain, filter); } return directoryEntry; } public static StringBuilder WriteEmployeeInfo(DirectoryEntry directoryEntry, StringBuilder sbWriteEmployeeInfo) { sbWriteEmployeeInfo.AppendLine(); sbWriteEmployeeInfo.AppendLine("============================================================================="); sbWriteEmployeeInfo.AppendLine("Display Name: " + directoryEntry.Properties["displayName"].Value.ToString()); sbWriteEmployeeInfo.AppendLine("First Name: " + directoryEntry.Properties["givenName"].Value.ToString()); sbWriteEmployeeInfo.AppendLine("Last Name: " + directoryEntry.Properties["sn"].Value.ToString()); sbWriteEmployeeInfo.AppendLine("Email: " + directoryEntry.Properties["mail"].Value.ToString()); sbWriteEmployeeInfo.AppendLine("EmployeeId: " + directoryEntry.Properties["employeeId"].Value.ToString()); sbWriteEmployeeInfo.AppendLine("AccountName " + directoryEntry.Properties["samaccountname"].Value.ToString()); sbWriteEmployeeInfo.AppendLine("Title: " + directoryEntry.Properties["title"].Value.ToString()); if (directoryEntry.Properties["department"].Value != null) { sbWriteEmployeeInfo.AppendLine("Department: " + directoryEntry.Properties["department"].Value.ToString()); } if (directoryEntry.Properties["co"].Value != null) { sbWriteEmployeeInfo.AppendLine("Country: " + directoryEntry.Properties["co"].Value.ToString()); } sbWriteEmployeeInfo.AppendLine("City: " + directoryEntry.Properties["l"].Value.ToString()); sbWriteEmployeeInfo.AppendLine("============================================================================="); return sbWriteEmployeeInfo; } public static StringBuilder WriteManagerInfo(DirectoryEntry directoryEntry, StringBuilder sbWriteEmployeeInfo) { sbWriteEmployeeInfo.AppendLine(); sbWriteEmployeeInfo.AppendLine("Manager Information:"); sbWriteEmployeeInfo = WriteEmployeeInfo(directoryEntry, sbWriteEmployeeInfo); return sbWriteEmployeeInfo; } public static string GetManagerId(string[] managerFirstNameInfo) { return managerFirstNameInfo[managerFirstNameInfo.Length - 1]; } public static string GetManagerDomain(string managerDomainInfo) { string[] mDomainInfo = managerDomainInfo.Split('='); return mDomainInfo[mDomainInfo.Length - 1]; } public static string GetManagerFirstName(string[] managerFirstNameInfo) { string managerFirstName = string.Empty; for (int i = 0; i < managerFirstNameInfo.Length - 1; i++) { managerFirstName += " " + managerFirstNameInfo[i]; } return managerFirstName.Trim(); } public static string GetManagerLastName(string managerLastName) { string[] managerLastNameInfo = managerLastName.Split('='); string mLastName = managerLastNameInfo[1]; mLastName = mLastName.Replace("\\", " "); return mLastName.Trim(); } } }
Program.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.DirectoryServices; namespace LDAP { class Program { private static string _userInput = string.Empty; private static string _managerId = string.Empty; private static string _managerDomain = string.Empty; private static string[] _managerFirstNameInfo; private static string[] _userInfo; private static string _userDomain = string.Empty; private static string _userId = string.Empty; static void Main(string[] args) { ConsoleKeyInfo cki; Console.TreatControlCAsInput = false; Console.CancelKeyPress += new ConsoleCancelEventHandler(myHandler); while (true) { try { if (!Validate(args)) { return; } if (args != null && args.Length == 1) { if (ValidateUserInput(args[0].ToString())) { _userInfo = args[0].ToString().Split('\\'); _userDomain = _userInfo[0]; _userId = _userInfo[1]; } args = null; } else { ToolUsage(); Console.Write("\nEnter [Domain]\\[EID OR FNLN] " ); _userInput = Console.ReadLine().Trim(); if (ValidateUserInput(_userInput)) { _userInfo = _userInput.Split('\\'); _userDomain = _userInfo[0]; _userId = _userInfo[1]; } } if (!string.IsNullOrEmpty(_userDomain) && !string.IsNullOrEmpty(_userId)) { SearchDirectory(_userDomain, _userId); } } catch (InvalidOperationException ioEx) { Console.WriteLine("----------------------------------------------------------------------\n"); Console.WriteLine("More than one " + _userInput + "'s found!\n"); Console.WriteLine("Try with EmployeeId\n"); Console.WriteLine("----------------------------------------------------------------------\n"); } catch (Exception ex) { Console.WriteLine("----------------------------------------------------------------------\n"); Console.WriteLine("Not able to find employee information. Please try again....\n"); Console.WriteLine("----------------------------------------------------------------------\n"); } Console.Write("\nPress any key to Continue, or 'X' to Quit\n"); cki = Console.ReadKey(true); if (cki.Key == ConsoleKey.X) break; } } private static void myHandler(object sender, ConsoleCancelEventArgs args) { args.Cancel = true; } private static void SearchDirectory(string userDomain, string userId) { DirectoryEntry directoryEntry = SearchController.GetEmployeeInfo(userDomain, userId); StringBuilder stringBuilder = new StringBuilder(); stringBuilder = SearchController.WriteEmployeeInfo(directoryEntry, stringBuilder); if (directoryEntry.Properties["manager"].Value != null) { string[] managerInfo = directoryEntry.Properties["manager"].Value.ToString().Split(','); if (userDomain.ToLower() == "specificdomain") { _managerFirstNameInfo = managerInfo[0].Split('='); _managerId = SearchController.GetManagerId(_managerFirstNameInfo); _managerDomain = SearchController.GetManagerDomain(managerInfo[2]); } else { _managerFirstNameInfo = managerInfo[1].Split(' '); _managerId = SearchController.GetManagerId(_managerFirstNameInfo); _managerDomain = SearchController.GetManagerDomain(managerInfo[7]); } DirectoryEntry managerDirectoryEntry = SearchController.GetEmployeeInfo(_managerDomain, _managerId); stringBuilder = SearchController.WriteManagerInfo(managerDirectoryEntry, stringBuilder); Console.WriteLine(stringBuilder.ToString()); } else { stringBuilder.AppendLine(); stringBuilder.AppendLine("Currently Manager Information not available\n"); stringBuilder.AppendLine("----------------------------------------------------------------------"); Console.WriteLine(stringBuilder.ToString()); } } private static bool Validate(string[] args) { bool validate = true; if (args != null && args.Length >= 1) { string input = args[0].ToString(); if (input == @"/?" || input.ToLower() == "-help" || input.ToLower() == @"/help") { ToolUsage(); validate = false; } } /*if (args.Length == 0) { validate = true; } else { string input = args[0].ToString(); if (input == @"/?" || input.ToLower() == "-help" || input.ToLower() == @"/help") { ToolUsage(); validate = false; } }*/ return validate; } private static bool ValidateUserInput(string userInput) { bool validate = true; if (!userInput.Contains('\\')) { Console.WriteLine("----------------------------------------------------------------------"); Console.WriteLine("\nEntered invalid input data....\n"); Console.WriteLine("----------------------------------------------------------------------"); validate = false; } return validate; } private static void ToolUsage() { Console.WriteLine("\n-------------------------- Search Employee --------------------------\n"); Console.WriteLine("Start executing the Search Employee tool....\n"); Console.WriteLine("Tool Usage : app.exe [Domain]\\[EID OR FNLN]\n" ); Console.WriteLine("Domain: Current domain of the user"); Console.WriteLine("EID: Employee Id of the user"); Console.WriteLine("FN: First Name of the user"); Console.WriteLine("LN: Last Name of the user"); Console.WriteLine("\n----------------------------------------------------------------------"); } } }