Skip to main content

Search Employee By Using Lightweight Directory Access Protocol (LDAP)

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, nullnullAuthenticationTypes.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, nullnullAuthenticationTypes.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----------------------------------------------------------------------");
        }
 
    }
}

Popular posts from this blog

Error : Task Scheduler - This task requires that the user account specified has Log on as batch job rights

In one of the production environment, we were running with low disk space problem because of the logs. To cleanup the old logs created a  task within the scheduler and have specified "Run whether use is logged on or not". The user account we used was the system logged on user. The task was running fine, after few months as a security policy the password expired. Since the old password expired we had to apply the new password for the task also, but this time we decided to create a new account specifically for the task scheduler with password never expire option. While setting up the new user account and password, run into the below issue: "The task required that the user account specified has log on as batch job rights" To fix the issue follow below steps: From Run type "secpol.msc /s" and enter, the local security policy snap in will open. Select "Local Policies" in MSC snap in Select "User Rights Assignment" Righ...

ISAPI & CGI Restriction configuration missing in IIS

In windows 7 by default ISAPI & CGI Restrictions are not configured. To enable ISAPI & CGI restrictions, GoTo -> Control Panel -> Programs -> Click on "Windows features on or off -> Expand Internet Information Services - >Expand World Wide Web Services ->Select CGI and ISAPI extensions and Click OK. After enabling, Check in IIS, Open your IIS and the feature will be available. What is ISAPI and CGI restrictions : ISAPI and CGI restrictions are request handlers that allow dynamic content to execute on a server. These restrictions are either CGI files (.exe) or ISAPI extensions (.dll). You can add custom ISAPI or CGI restrictions if the IIS configuration system allows this.

Implementing Parallelism With A SearchResultCollection

Implementing Parallel.ForEach with a SearchResultCollection: The below piece of code helps to check the given user is a part of the given active directory group. To implement Parallel.ForEach with a SearchResultCollection, do the casting with the SearchResult object and covert it into a list. //// Directory Searcher var directorySearcher = new DirectorySearcher(string.Format("(CN={0})", groupName)); //// Find group var searchResultCollection = directorySearcher.FindAll().Cast ().ToList(); Parallel.ForEach(searchResultCollection, searchResult => {  // enumerate members  var resultPropColl = searchResult.Properties;  Parallel.ForEach(resultPropColl["member"].Cast ().ToList(), member =>  {    var memberEntry = new DirectoryEntry("LDAP://" + member);    var userProperties = memberEntry.Properties;    if (GetUserNameFromProperties(userProperties, "sAMAccountName") == userName)    {      return true; ...