Extended UserPrinciple Extremely Slow

时间:2017-11-08 22:01:47

标签: c#

I'm working on a program that needs to loop over 30k AD users. For the initial incarnation I used System.Management.Automation.PowerShell. This works perfect, but I didn't like the taste of executing PowerShell from within a C# all.

I then switched to using DirectoryServices.AccountManagement as a more "pure" solution. I need to get the user's Title and Manager. Due to this I had to extend UserPrinciple. However, after doing this I found it takes an extremely long time to get either Title or Manager. For my environment it's takes about 160ms to retrieve those 2 properties.

The delay seems to come when I attempt to access either the Title or Manager properties.

Examples:

Original Code - Each loop iteration takes less than 2ms:

ps.AddCommand("Get-Aduser");
ps.AddParameter("Filter", "*");
ps.AddParameter("SearchBase", dName);
string[] props = { "Name", "EmailAddress", "GivenName", "Surname", "Title", "Manager", "Enabled", "EmployeeID" };
ps.AddParameter("Properties", props);

foreach (PSObject i in ps.Invoke())
{
    Console.WriteLine(i.Properties["Title"].Value.ToString());
}

New Code - Each loop iteration takes about 165ms:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "*******", distinguishedName);

UserPrincipalsEx qbeUser = new UserPrincipalsEx(ctx);
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
PrincipalSearchResult<Principal> res = srch.FindAll();
foreach (UserPrincipalsEx i in res)
{
    Console.WriteLine(i.Title);
}

Is there something I am missing here or does it just take extra time to individually query the extended properties?

1 个答案:

答案 0 :(得分:0)

The obvious difference for me is that in the Powershell example you are specifying the properties you want before you execute the command.

In the C# version you are querying the .title property after having searched AD. This probably goes and fetches the record from AD again as that property was not loaded

Is it maybe possible for you to to tell the PrincipalSearcher object what fields you want included in the result?