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?