2
votes

Hi there I am trying to create a textbox that when a user types into it they get a list of users with the specific name:

Example: If I started to type Jane.Doe, and I had only typed in Ja a list would come up with users from the Active Directory who start with Ja. I need to figure out how I can get the Users to a list each time a user types. I pretty much have the ajax side done. Its just getting the list of users updated each time.

My current idea:

 [HttpPost]
    public ActionResult RemoteData(string query)
    {
        List<string> lstADUsers = new List<string>();

        using (var context = new PrincipalContext(ContextType.Domain, null, "LDAPPATH"))
        {
            using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
            {
                foreach (var result in searcher.FindAll())
                {
                    DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;

                    string usersWithName;


                    if (!String.IsNullOrEmpty((String)de.Properties["samaccountname"].Value))
                    {
                        usersWithName = de.Properties["samaccountname"].Value.ToString();



                        lstADUsers.Add(usersWithName);
                    }

                }
            }
        }

        List<string> listData = null;
        if (!string.IsNullOrEmpty(query))
        {

            listData = lstADUsers.Where(q => q.ToLower().StartsWith(query.ToLower())).ToList();

        }   

        return Json(new { Data = listData });
    }

So this allows us to get EVERY user in the Active Directory but I don't want this because the issue at hand gets that there are too many users and the search takes FOREVER to load this before it even displays the list of names. I only want to be able to take a parameter and only search for user that starts with that. How would I go about doing this?

1

1 Answers

2
votes

You need to populate the Name property of UserPrincipal with a wildcard to limit the result set:

// assume 'query' is 'Ja'
UserPrincipal user = new UserPrincipal(context);
user.Name = query + "*"; // builds 'Ja*', which finds names starting with 'Ja'
using (var searcher = new PrincipalSearcher(user))
// ...