Create search object which operates on LDAP connection object

        //Active Directory Connection
        public static DirectoryEntry createDirectoryEntry()
        {
            // create and return new LDAP connection with desired settings
            DirectoryEntry ldapConnection = new DirectoryEntry("@Domain Name");
            ldapConnection.Path = "LDAP://OU=People,DC=@Domain,DC=internal";
            ldapConnection.AuthenticationType = AuthenticationTypes.Secure;

            return ldapConnection;
        }

        //Retrieve Existing User - Only One User
        static public string retrieveEmployeeID(DirectoryEntry myLdapConnection, string username)
        {
            string employeeID = null;

            LoggerBlock.Log("retrieveEmployeeID AD Name : " + username);
            // create search object which operates on LDAP connection object
            // and set search object to only find the user specified
            DirectorySearcher search = new DirectorySearcher(myLdapConnection);
            search.Filter = "(samaccountname=" + username + ")";

            // create an array of properties that we would like and
            // add them to the search object
            string[] requiredProperties = new string[] { "employeeid" };

            foreach (String property in requiredProperties)
                search.PropertiesToLoad.Add(property);

            SearchResult result = search.FindOne();

            if (result != null)
            {
                foreach (String property in requiredProperties)
                {
                    foreach (Object myCollection in result.Properties[property])
                    {
                        employeeID = myCollection.ToString();
                    }
                }

                if (employeeID != null)
                    LoggerBlock.Log("retrieve Employee ID  : " + employeeID);
            }
            else
            {
                employeeID = null;
            }

            return employeeID;
        }
    }

Comments