Jon Harding
Jon Harding

Reputation: 4946

Retrieve name of user from Active Directory

I am admittedly very new to AD. I have a dropdown list that I have bound with a list of members within our organization. My end goal is to find their manager name, but I'm starting with baby steps.

I've done enough searching to get the right result. I'm having a problem getting the right data (verified by using breakpoints etc) out of the result

private void cmbUserList_SelectedIndexChanged(object sender, EventArgs e)
{
    var userName = cmbUserList.SelectedValue.ToString();
    DirectorySearcher search = new DirectorySearcher();

    search.Filter = String.Format("(cn={0})", userName);
    search.PropertiesToLoad.Add("givenName");

    SearchResult result = search.FindOne();

    if (result != null)
    {
        // For now I'm trying to just retrieve their name
        lblManagerName.Text = result.GetDirectoryEntry().Name;
    }
}

EDIT: I'm using .net version 4.0

Could someone point me towards retrieving the correct name, and then maybe even a link or resources to pull the manager name?

Upvotes: 2

Views: 3298

Answers (3)

Zilog
Zilog

Reputation: 476

to find name and/or manager name:

if (sResult != null)
{
    string userName = sResult.Properties["name"][0].ToString();
    string managerDN = sResult.Properties["manager"][0].ToString();

    DirectoryEntry man =  new DirectoryEntry("LDAP://server_name/"+managerDN);
    string managerName = man.Properties["name"][0].ToString();

}

server_name can be just domain component of FQDN i.e yourcompany.com, that way it will find catalog server on its own via DNS.

Edit:

I also recomend Active Directory Explorer from Sysinternals. It is great tool for exploring and understanding structure of AD

Upvotes: 0

Uzzy
Uzzy

Reputation: 550

helper class and enum

public enum ActiveDirectoryObjectClass
{
    Computer,
    User,
    Domain,
    Group,
}

public static class ActiveDirectorySearcher
{
    public static string  GetCurrentDomainName()
    {
        string result;
        using (Domain domain = Domain.GetCurrentDomain())
        {
            result = domain.Name;
        }

        return result;
    }

    public static IEnumerable<T> Select<T>(
        ActiveDirectoryObjectClass activeDirectoryObjectClass,
        Func<DirectoryEntry, ActiveDirectoryObjectClass, bool> condition,
        Func<DirectoryEntry, T> selector
        )
    {
        List<T> list = new List<T>();
        using (Domain domain = Domain.GetCurrentDomain())
        using (DirectoryEntry root = domain.GetDirectoryEntry())
        {
            string filter = string.Format("(objectClass={0})", activeDirectoryObjectClass);
            using (DirectorySearcher searcher = new DirectorySearcher(filter))
            {
                searcher.SearchRoot = root;
                searcher.SearchScope = SearchScope.Subtree;
                using (SearchResultCollection result = searcher.FindAll())
                {
                    foreach (SearchResult item in result)
                    {
                        using (DirectoryEntry entry = item.GetDirectoryEntry())
                        {
                            if (condition(entry, activeDirectoryObjectClass))
                            {
                                list.Add(selector(entry));
                            }
                        }
                    }
                }
            }

        }
        return list;
    }
}

how to use

    public IEnumerable<User> GetUsers()
    {
        return ActiveDirectorySearcher.Select(
            ActiveDirectoryObjectClass.User,
            (entry, adObjectClass) => string.Compare(entry.SchemaClassName, adObjectClass.ToString(), StringComparison.InvariantCultureIgnoreCase) == 0,
            _ => new User
                     {
                         Name = _.Name.Substring(3),
                         Domain = ActiveDirectorySearcher.GetCurrentDomainName(),
                     });
    }

Note: User in sample - custom class with properties Name, Domain, etc.

Upvotes: 0

Sergey
Sergey

Reputation: 2343

I think the problem with your code is you are using "(cn={0})", userName. You need to pass fully qualified name like

CN=Doe,John,OU=Users,OU=Headquarters,DC=company,DC=net

If you only have login ID, then the code below should work

DirectorySearcher directorySearcher = new DirectorySearcher("LDAP://RootDSE");
directorySearcher.Filter = "sAMAccountName=" + acctName;
directorySearcher.PropertiesToLoad.Add("manager");
SearchResult searchResult = directorySearcher.FindOne();
if (searchResult != null)
DirectoryEntry user = searchResult.GetDirectoryEntry();

Note that acctName is Windows login ID. If you want to play with AD and check out vearious properties and how they are stored, try dsquery and dsget command line tools. The command below will return a user record based on login id and will display contents of the manager field:

dsquery user domainroot -samid "loginid" | dsget user -samid -mgr

Upvotes: 2

Related Questions