Dynamics 365 CRM online 使fetchXml分页查询大于5000条记录的

学习目标:

Dynamics 365 CRM online 使fetchXml分页查询大于5000条记录的

学习内容:

1、使用Visula studio 2017,选择C# 2、 使用IOrganizationService连接CRM执行查询 3、 FetchXml简单查询语句

学习过程:

学习过程不多说,直接贴上如下代码

引如下命名空间

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Organization;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Tooling.CrmConnector;
using Microsoft.Xrm.Tooling.Connector;
using Microsoft.Xrm.Tooling.CrmConnectControl;


public class Crm_FetchXml_Pagging_Cookie
    {
        public string fetchXmlSalesdetails()
        {
            string fetchxml = @"<fetch version='1.0'  count-='true'>
                                <entity name='salesorderdetail'>
                                <attribute name='thk_doc_no' alias='doc_no' />
                                <attribute name='productnumber' alias='productid' />
                                <attribute name='createdon' alias='createdon' />
                                <filter type='and'>
                                <condition attribute='createdon' operator='ge' value='2020-11-08 08:00:00' />
                                <condition attribute='createdon' operator='lt' value='2020-11-11 08:20:59' />
                                </filter>
                                </entity></fetch>";
            return fetchxml;
        }

        public void FetchXmlByPagingCookie()
        {
            string xml = this.fetchXmlSalesdetails();
            string pagingCookie = null;
            int fetchCount = 5000;
            int pageNumber = 1;
            int recordcount = 0;
            string connectionstring = Crm_ConnectionString.GetConnectionString();            
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            CrmServiceClient conn = new CrmServiceClient(connectionstring);
            IOrganizationService _serviceProxy = (IOrganizationService)conn.OrganizationWebProxyClient != null
                                 ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;
            List<Contact_Model> retList = new List<Contact_Model>();
            while (true)
            {
                string localxml = CreateXml(xml, pagingCookie, pageNumber, fetchCount);
                RetrieveMultipleRequest fetchRequest1 = new RetrieveMultipleRequest
                {
                    Query = new FetchExpression(localxml)
                };
                EntityCollection returncollection = ((RetrieveMultipleResponse)_serviceProxy.Execute(fetchRequest1)).EntityCollection;
                foreach (var c in returncollection.Entities)
                {
                    Contact_Model list = new Contact_Model();
                    ++recordcount;
                    list.invoiceid = (string)((AliasedValue)c["doc_no"]).Value.ToString();
                    list.product_guid = (string)((AliasedValue)c["productid"]).Value.ToString();
                    list.orderdate = Convert.ToDateTime( c.FormattedValues["createdon"]);
                   // list.orderdate = ((DateTime)((AliasedValue)c["createdon"]).Value).Date;

                    retList.Add(list);
                    Console.WriteLine("recordcount = " + recordcount.ToString() + "  salesorderdetail_guid = " + list.invoiceid + " product =" + list.product_guid + " ");
                }
                if (returncollection.MoreRecords)
                {
                    Console.WriteLine("\n****************\nPage number {0}\n****************", pageNumber);                    
                    pageNumber++;                    
                    pagingCookie = returncollection.PagingCookie;
                }
                else
                {
                    break;
                }
            }
          //  Console.WriteLine(ObjectToJson(retList));
            System.Threading.Thread.Sleep(10000);

        }
        //注意引用:System.Runtime.Serialization,System.ServiceModel.Web
        // 从一个对象信息生成Json串
        public string ObjectToJson(object obj)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            MemoryStream stream = new MemoryStream();
            serializer.WriteObject(stream, obj);
            byte[] dataBytes = new byte[stream.Length];
            stream.Position = 0;
            stream.Read(dataBytes, 0, (int)stream.Length);
            return Encoding.UTF8.GetString(dataBytes);
        }

        public string ExtractNodeValue(XmlNode parentNode, string name)
        {
            XmlNode childNode = parentNode.SelectSingleNode(name);

            if (null == childNode)
            {
                return null;
            }
            return childNode.InnerText;
        }

        public string ExtractAttribute(XmlDocument doc, string name)
        {
            XmlAttributeCollection attrs = doc.DocumentElement.Attributes;
            XmlAttribute attr = (XmlAttribute)attrs.GetNamedItem(name);
            if (null == attr)
            {
                return null;
            }
            return attr.Value;
        }

        public 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);
        }

        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);

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

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

            return sb.ToString();
        }
    }

<hr style=" border:solid; width:100px; height:1px;" color=#000000 size=1">

# 学习产出:

<font color=#999AAA >能达到预期的效果,实现分页查询大于5000条记录的条件
![在这里插入图片描述](https://img-blog.csdnimg.cn/20201204092945143.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDEzNjgyMw==,size_16,color_FFFFFF,t_70)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Fei-AX&CRM

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值