using System;
using System.IO;
using System.Xml;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
public class FetchPagingWithCookieHelper
{
public void Retrieve(IOrganizationService service)
{
//单次查询的个数
int fetchCount = 15;
//第几页
int pageNumber = 1;
string pagingCookie = null;
int sumCount = 0;
string fetchXml = @"<fetch version=‘1.0‘ output-format=‘xml-platform‘ mapping=‘logical‘ distinct=‘false‘>
<entity name=‘new_supplyaccount‘>
<attribute name=‘new_supplyaccountid‘ />
<attribute name=‘new_name‘ />
<filter type=‘and‘>
<condition attribute=‘statecode‘ operator=‘eq‘ value=‘0‘ />
</filter>
</entity>
</fetch>";
while(true)
{
string xml = CreateXml(fetchXml, pagingCookie, pageNumber, fetchCount);
RetrieveMultipleRequest retrieveRequest = new RetrieveMultipleRequest();
retrieveRequest.Query = new FetchExpression(xml);
EntityCollection returnCollection = ((RetrieveMultipleResponse)service.Execute(retrieveRequest)).EntityCollection;
sumCount += returnCollection.Entities.Count;
foreach (var c in returnCollection.Entities)
{
DisplayEntity(c, "new_supplyaccount");
}
if (returnCollection.MoreRecords)
{
//如果还要更多记录,继续查询
pageNumber++;
}
else
{
//没有,则退出
break;
}
}
System.Console.WriteLine("sumCount: " + sumCount);
}
public string CreateXml(string xml, string cookie, int page, int count)
{
StringReader stringReader = new StringReader(xml);
XmlTextReader reader = new XmlTextReader(stringReader);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
return CreateXml(doc, cookie, page, count);
}
public 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);
System.Text.StringBuilder sb = new System.Text.StringBuilder(1024);
StringWriter stringWriter = new StringWriter(sb);
XmlTextWriter writer = new XmlTextWriter(stringWriter);
doc.WriteTo(writer);
writer.Close();
return sb.ToString();
}
private void DisplayEntity(Entity entity, string label)
{
System.Console.WriteLine("display" + label + "start_________________________________");
var keyArray = entity.Attributes.Keys;
foreach (string name in keyArray)
{
System.Console.WriteLine("attributeName: " + name + ",attributeValue: " + entity.Attributes[name]);
}
System.Console.WriteLine("display" + label + "end!_________________________________");
}
}
crm2011fetchxml分页查询