I'm using the code below to look up information in active directory when a user logs on to a website. Running against a local domain it's very quick, but running over a VPN to a remote trusted domain, it's very slow (takes around 7 or 8 seconds). Running dsa.msc from the same box to the remote domain is almost as quick as running it locally.
I'm using property filtering to retrieve the minimum amount of data possible, so is there something inherently slow about System.DirectoryServices in this scenario, or does anyone have any hints on how to improve the performance?
The network connection across the VPN is fine, it's only this code that runs slowly.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using (var LDAPConnection = new DirectoryEntry("LDAP://domain/dc=domain,dc=com", "username", "password"))
{
LDAPConnection.AuthenticationType = AuthenticationTypes.Secure;
using (DirectorySearcher Searcher = new DirectorySearcher(LDAPConnection))
{
Searcher.Filter = "(&(&(objectclass=user)(objectcategory=person))sAMAccountName=username)";
Searcher.PropertiesToLoad.Add("mail");
SearchResult result = Searcher.FindOne(); //this line takes ages!
string EmailAddress = result.Properties["mail"][0].ToString();
Console.WriteLine(EmailAddress);
}
}
}
}
}