Link to home
Start Free TrialLog in
Avatar of ZaDrizzle
ZaDrizzle

asked on

Limiting the number of results returned in an Active Directory query using PrincipalSearcher

I have a username textbox on my page. I've created an autocomplete feature which queries Active Directory for all users where the username contains the text in the textbox. Because this is an autocomplete feature, I want to limit the number of results returned to optimize performance. The only methods I see available are FindOne() and FindAll(). Is there a way to get the first 'n' records matching the criteria of the query?

My code currently breaks out of the loop after reading 'n' records but the FindAll() method still returns all matching records causing a performance hit.

[WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string[] GetUsernames(string partialUsername, int maxResults, string serverName)
        {
            List<string> userNames = new List<string>();
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, serverName);
                
                UserPrincipal userPrincipal = new UserPrincipal(principalContext);
                userPrincipal.Name = "*" + partialUsername + "*";
                PrincipalSearcher principalSearcher = new PrincipalSearcher(userPrincipal);
                                
                PrincipalSearchResult<Principal> results = principalSearcher.FindAll();
                foreach (var result in results)
                {
                    if (!string.IsNullOrEmpty(result.Name))
                    {

                            userNames.Add(result.Name);
                      
                            if (userNames.Count >= maxResults)
                                    break;
                    }
                }
            });
            userNames.Sort();
            return userNames.ToArray();
        }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Rainer Jeschor
Rainer Jeschor
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ZaDrizzle
ZaDrizzle

ASKER

Thanks Rainer!