Retrieve more than 5000 records in MS CRM using fetch XML

When you use retrieve multiple to retrieve records from any entity, the maximum no of records returned by retrieve multiple is 5000. But there will be scenario we have to retrieve more than 5000, in those scenarios we should use paging as shown below.

private string RetrieveMoreThan500Records()
{
            EntityCollection caseCollection = new EntityCollection();
            try
            {
                var moreRecords = false;
                int page = 1;
                var cookie = string.Empty;
                string fetchXML = RetrieveCaseFetchXML();
                do
                {
                    var caseFetchXML = string.Format(fetchXML, cookie);
                    var collection = service.RetrieveMultiple(new FetchExpression(caseFetchXML));
 
                    if (collection.Entities.Count >= 0)
                    {
                        caseCollection.Entities.AddRange(collection.Entities);
                    }
 
                    moreRecords = collection.MoreRecords;
                    if (moreRecords)
                    {
                        page++;
                        cookie = string.Format("paging-cookie='{0}' page='{1}'", System.Security.SecurityElement.Escape(collection.PagingCookie), page);
                    }
                } while (moreRecords);
            }
            catch (Exception ex)
            {
            }

}

private string RetrieveCaseFetchXML()
{
            return @"<fetch {0} version='1.0' output-format='xml-platform'   mapping='logical' distinct='false'>
                      <entity name='incident'>
                        <attribute name='ticketnumber' />
                        <attribute name='incidentid' />
                        <order attribute='createdon' descending='false' />
                       </entity>
                    </fetch>";
}

No comments:

Post a Comment

Featured Post

Improving MS CRM Performance

Performance on MS CRM is always a crucial thing and we may follow different ways to achieve the performance thing. Below is the one more a...