title: Effective pagination with Active Directory searches
body: <p>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. I want to be able to indicate <code>Skip</code> and <code>Take</code> parameters and be able to retrieve the total number of records matching my search criteria in the result.</p>
  
  <p>I have tried searching with the <a href="http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.principalsearcher%28v=vs.110%29.aspx"><code>PrincipalSearcher</code></a> class:</p>
  
  <pre><code>using (var ctx = new PrincipalContext(ContextType.Domain, "FABRIKAM", "DC=fabrikam,DC=com"))
  using (var criteria = new UserPrincipal(ctx))
  {
      criteria.SamAccountName = "*foo*";
  
      using (var searcher = new PrincipalSearcher(criteria))
      {
          ((DirectorySearcher)searcher.GetUnderlyingSearcher()).SizeLimit = 3;
          var results = searcher.FindAll();
          foreach (var found in results)
          {
              Console.WriteLine(found.Name);
          }
      }
  }
  </code></pre>
  
  <p>Here I was able to limit the search results to 3 but I wasn't able to get the total number of records corresponding to my search criteria (<code>SamAccountName</code> contains <code>foo</code>) neither I was able to indicate to the searcher to skip the first 50 records for example.</p>
  
  <p>I also tried using the <a href="http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry%28v=vs.110%29.aspx"><code>System.DirectoryServices.DirectoryEntry</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.directoryservices.protocols.searchrequest%28v=vs.110%29.aspx"><code>System.DirectoryServices.Protocols.SearchRequest</code></a> but the only thing I can do is specify the page size.</p>
  
  <p>So is the only way to fetch all the results on the client and do the Skip and Count there? I really hope that there are more effective ways to achieve this directly on the domain controller.</p>