Fred
Fred

Reputation: 2478

Active Directory - Get All Users Belonging to a Manager

I have this little problem.

I want to get all the users that has the same manager.

Currently, I have code that can do this, but the problem is that it gets ALL the users. I then loop through all the users, and match the manager. The problem with this is that this will take a bit too long when there is, let's say, 100 000 users.

My current code:

        UserPrincipal managerP = UserPrincipal.FindByIdentity(GetPrincipalContext(), IdentityType.SamAccountName, sAMManager);

        if (managerP != null)
        {
            using (UserPrincipal user = new UserPrincipal(GetPrincipalContext()))
            {
                using (PrincipalSearcher search = new PrincipalSearcher(user))
                {
                    search.QueryFilter = user;

                    foreach (UserPrincipal userP in search.FindAll())
                    {
                        if (managerP.SamAccountName.ToLower() == sAMManager.ToLower())
                        {
                            //Add 'userP' to list.
                        }
                    }
                }
            }
        }

How can I change this, so that I can get all the users belonging to a manager, instead of getting them all first?

Upvotes: 0

Views: 1108

Answers (1)

Brian Desmond
Brian Desmond

Reputation: 4503

You can do this with a simple LDAP query:

        using (DirectorySearcher searcher = new DirectorySearcher(new DirectoryEntry("LDAP://contoso.com")))
        {
            searcher.Filter = "(&(objectCategory=person)(objectClass=user)(manager=CN=John Doe,CN=Users,DC=contoso,DC=com))";

            searcher.PropertiesToLoad.AddRange(new string[] { "givenName", "sn", "sAMAccountName" });

            foreach (SearchResult item in searcher.FindAll())
            {
                Console.WriteLine(String.Format("User {0} {1} ({2}) works for John Doe", item.Properties["givenName"].ToString(), item.Properties["sn"].ToString(), item.Properties["sAMAccountName"].ToString()));
            }
        }

Upvotes: 1

Related Questions