ttajic
10/7/2015 - 3:39 PM

FetchPaged

FetchPaged

       public EntityCollection FetchPaged(string fetchXML, int fetchCount, IOrganizationService service)
        {
            EntityCollection AllRecords = new EntityCollection();

            int pageNumber = 1;
            string pagingCookie = null;

            try
            {
                while (true)
                {
                    string xml = CreateXml(fetchXML, pagingCookie, pageNumber, fetchCount);

                    RetrieveMultipleRequest fetchRequest1 = new RetrieveMultipleRequest
                    {
                        Query = new FetchExpression(xml)
                    };

                    EntityCollection fetXMLRecord = ((RetrieveMultipleResponse)service.Execute(fetchRequest1)).EntityCollection;

                    foreach (Entity ChildRecord in fetXMLRecord.Entities)
                    {
                        AllRecords.Entities.Add(ChildRecord);
                    }

                    if (fetXMLRecord.MoreRecords)
                    {
                        pageNumber = pageNumber + 1;
                        pagingCookie = fetXMLRecord.PagingCookie;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
            return AllRecords;
        }
        
        private string CreateXml(XmlDocument doc, string cookie, int page, int count)
        {
            XmlAttributeCollection attrs = doc.DocumentElement.Attributes;

            if (cookie != null)
            {
                XmlAttribute pagingAttr = doc.CreateAttribute("paging-cookie");
                pagingAttr.Value = cookie;
                attrs.Append(pagingAttr);
            }

            XmlAttribute pageAttr = doc.CreateAttribute("page");
            pageAttr.Value = System.Convert.ToString(page);
            attrs.Append(pageAttr);

            XmlAttribute countAttr = doc.CreateAttribute("count");
            countAttr.Value = System.Convert.ToString(count);
            attrs.Append(countAttr);

            StringBuilder sb = new StringBuilder(1024);
            StringWriter stringWriter = new StringWriter(sb);

            XmlTextWriter writer = new XmlTextWriter(stringWriter);
            doc.WriteTo(writer);
            writer.Close();

            return sb.ToString();
        }

        private string CreateXml(string xml, string cookie, int page, int count)
        {
            StringReader stringReader = new StringReader(xml);
            XmlTextReader reader = new XmlTextReader(stringReader);

            // Load document
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);

            return CreateXml(doc, cookie, page, count);
        }