0

I have this JsonResult that searches all users in active directory and adds specific ones to a list. However the searching through is taking sometime as there are a lot of employees.

Here is the jsonresult:

public JsonResult Search(string term)
{
    List<string> lstADUsers = new List<string>();       
    if (!string.IsNullOrEmpty(term))
    {
        using (var context = new PrincipalContext(ContextType.Domain, null, "LDAP"))
        {   
            UserPrincipal user = new UserPrincipal(context);
            using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
            {                  
                foreach (var result in searcher.FindAll().Where(m => m.SamAccountName.StartsWith(term, StringComparison.OrdinalIgnoreCase)))
                {
                    DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;                     
                    string usersWithName;
                    if (!String.IsNullOrEmpty((String)de.Properties["samaccountname"].Value) && !String.IsNullOrEmpty((String)de.Properties["sn"].Value) && !String.IsNullOrEmpty((String)de.Properties["givenName"].Value))
                    {
                        usersWithName = de.Properties["samaccountname"].Value.ToString();
                        lstADUsers.Add(usersWithName);
                    }
                }
            }
        }
    }

    return Json(lstADUsers, JsonRequestBehavior.AllowGet);
}

Right now it searches through until it finds something that starts with what the user typed:

If I'm looking for Jane.Doe and I typed; Ja, it shows me a list of all users in the active directory who start with Ja. It would be fine the way it runs now if there weren't over 10000 employees. You can tell searching can take a few seconds to get all users to a list.

Is there anything you can see that looks like it could be optimized?

tereško
  • 58,060
  • 25
  • 98
  • 150
Manny Sran
  • 173
  • 4
  • 18
  • 2
    Why not cache all on first run, then only grab from the list where it matches? Seems that would be much more efficient than querying it over and over. – Dispersia Jan 28 '16 at 20:44
  • 1
    For performance checks it is always recommended to determine the hot spots with a profiler. Visual Studio has a really good performance and memory profiler on board. – Benjamin Abt Jan 28 '16 at 22:41

1 Answers1

2

According to FindAll executes actual call (which I believe takes most of the time) and only after that you apply your filters.

Better solution would be to apply your filters before calling FindAll method to reduce amount of returned data. You achieve that using QueryFilter property. You can find usage examples in this thread.

Community
  • 1
  • 1
serhiyb
  • 4,753
  • 2
  • 15
  • 24