Welcome to Office Zealot Sign in | Join | Help

Web Service to Query Active Directory Attributes

Been on a coding kick lately... My colleagues and I are working on some custom SharePoint workflows and one of them requires obtaining some user data from Active Directory.  A great way to handle this is through the use of a web service.  Once implemented, this is something that can be repurposed, whether through other workflows or InfoPath forms or custom applications.  The code snippet below is a method that accepts an AD attribute (example: ‘co’ is Country) and returns the value for the current user.  Good stuff!

 

    [WebMethod]

    public string GetADProperty(string attribute)

    {

        try

        {

            string UserName = System.Environment.UserName;

            string Domain = "LDAP://" + System.Environment.UserDomainName;

            string Admin = ConfigurationManager.AppSettings["username"];

            string Password = ConfigurationManager.AppSettings["password"];

 

            //query AD and filter on current user's logon name

            DirectoryEntry root = new DirectoryEntry(Domain, Admin, Password);

            DirectorySearcher ds = new DirectorySearcher(root);

            ds.Filter = "(sAMAccountName=" + UserName + ")";

            ds.PropertiesToLoad.Add(attribute);

            SearchResult result = ds.FindOne();

 

            //if a match is found, return the requested property

            if (result == null)

            {

                return "ERROR: Can't find user '" + UserName + "' in Active Directory.";

            }

            else

            {

                return result.Properties[attribute][0].ToString();

            }

        }

        catch (Exception e)

        {

            return "ERROR: " + e.Message.ToString();

        }

    }

 

Published Monday, June 02, 2008 3:55 AM by Mauro

Comments

Friday, January 02, 2009 12:15 PM by jaxkookie

# re: Web Service to Query Active Directory Attributes

This trick is something I have been trying to figure out for some time. How do you utilize this piece of code? how are you getting the infor to the workflow?

thanks

Anonymous comments are disabled