What would be an effective way to do pagination with Active Directory searches in .NET? There are many ways to search in AD but so far I couldn\'t find how to do it effectively.
Waaaay late to the party, but this is what I'm doing:
I'm using FindOne()
instead of FindAll()
and member;range=
on PropertiesToLoad
.
There's a catch on member;range
: when it's the last page, even if you pass member;range=1000-1999
(for instance), it returns member;range=1000-*
, so you have to check for the *
at the end to know if there is more data.
public void List PagedSearch()
{
var list = new List();
bool lastPage = false;
int start = 0, end = 0, step = 1000;
var rootEntry = new DirectoryEntry("LDAP://domain.com/dc=domain,dc=com", "user", "pwd");
var filter = "(&(objectCategory=person)(objectClass=user)(samAccountName=*foo*))";
using (var memberSearcher = new DirectorySearcher(rootEntry, filter, null, SearchScope.Base))
{
while (!lastPage)
{
start = end;
end = start + step - 1;
memberSearcher.PropertiesToLoad.Clear();
memberSearcher.PropertiesToLoad.Add(string.Format("member;range={0}-{1}", start, end));
var memberResult = memberSearcher.FindOne();
var membersProperty = memberResult.Properties.PropertyNames.Cast().FirstOrDefault(p => p.StartsWith("member;range="));
if (membersProperty != null)
{
lastPage = membersProperty.EndsWith("-*");
list.AddRange(memberResult.Properties[membersProperty].Cast());
end = list.Count;
}
else
{
lastPage = true;
}
}
}
return list;
}