Paging in FetchXml

By | December 22, 2017

Was working on the code that needed paging with FetchXml.. There is a good example on MSDN:

https://msdn.microsoft.com/en-us/library/gg328046.aspx

But, in case you don’t want to mess with XmlDocument (not that it’s really that messy), you can easily do the same using simple string Replace – there is an example below. The only tricky part is that a few characters in the paging cookie have to be decoded before you can put it into the FetchXml, but that’s about it:

        public EntityCollection RetrieveContacts(IOrganizationService service, int page, string pagingCookie)
        {
            if (pagingCookie != null && pagingCookie != "")
                pagingCookie = pagingCookie.Replace("\"", "'").Replace(">", "&gt;").Replace("<", "&lt;");
            string fetchXml =
                    @"<fetch version=""1.0""
                          count=""25""
                          page=""{0}""
                          paging-cookie=""{1}""
                          returntotalrecordcount=""true""
                          output-format=""xml-platform""
                          mapping=""logical""
                          distinct=""false"">
                        <entity name=""contact"">
                          <attribute name=""contactid"" />
                        </entity>
                    </fetch>";
            fetchXml = string.Format(fetchXml, page, pagingCookie);
            var qe = new FetchExpression(fetchXml);
            var result = service.RetrieveMultiple(qe);
            return result;
        }

                int pageNumber = 1;
                 string pagingCookie = “”;
                 EntityCollection result = null;
                 do
                 {
                     result = RetrieveContacts(service, pageNumber, pagingCookie);
                     foreach (var e in result.Entities)
                     {
                         …
                     }
                     pagingCookie = result.PagingCookie;
                     pageNumber++;
                 } while (result.MoreRecords);






Leave a Reply

Your email address will not be published. Required fields are marked *