Tuesday, June 9, 2015

RetrieveMultiple - Retrieve more than 5000 records with C#

This method uses the RetrieveMultiple SDK Method and loops between all the Pages in order to avoid the 5000 records limitation.

/// <summary>
/// Method used to return more than 5000 records at the same time
/// </summary>
/// <param name="service">Organization service instance</param>
/// <param name="query">Query</param>
/// <returns>All entities that matches the query</returns>
private List < Entity > RetrieveMultiple(OrganizationServiceProxy service, QueryExpression query) {
 List < Entity > result = new List < Entity > ();
 int fetchCount = 5000;
 int pageNumber = 1;

 query.PageInfo = new PagingInfo();
 query.PageInfo.Count = fetchCount;
 query.PageInfo.PageNumber = pageNumber;
 query.PageInfo.PagingCookie = null;

 while (true) {
  EntityCollection collections = service.RetrieveMultiple(query);

  if (collections.Entities.Count > 0) {

   result.AddRange(collections.Entities);
  }

  if (collections.MoreRecords) {
   query.PageInfo.PageNumber++;
   query.PageInfo.PagingCookie = collections.PagingCookie;
  } else {
   break;
  }
 }

 return result;
}

1 comment: