摘要: 本人微信公众号:微软动态CRM专家罗勇 ,回复295或者20190112可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!我的网站是 www.luoyong.me 。

系统作业实体(实体逻辑名称为asyncoperation),若这个实体记录数太多,会对系统造成较大压力,可以利用系统标准的【批量删除】功能(Bulk Delete)来定期删除,批量删除最频繁的密度为每天运行一次。有时候记录数暴增,可能会用到程序来删除,我这里有个例子,上代码,这个是每次获取5000条记录,每次提交500条记录进行删除。

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceModel.Description;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml; namespace DeleteAsyncOperations
{
class Program
{
static void Main(string[] args)
{
try
{
string inputKey;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
IServiceManagement<IOrganizationService> orgServiceMgr = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri(ConfigurationManager.AppSettings["orgUrl"]));
AuthenticationCredentials orgAuCredentials = new AuthenticationCredentials();
orgAuCredentials.ClientCredentials.UserName.UserName = ConfigurationManager.AppSettings["userName"];
orgAuCredentials.ClientCredentials.UserName.Password = ConfigurationManager.AppSettings["passWord"];
string needConfirm = ConfigurationManager.AppSettings["needConfirm"];
using (var orgSvc = GetProxy<IOrganizationService, OrganizationServiceProxy>(orgServiceMgr, orgAuCredentials))
{
orgSvc.Timeout = new TimeSpan(, , );
WhoAmIRequest whoReq = new WhoAmIRequest();
var whoRsp = orgSvc.Execute(whoReq) as WhoAmIResponse;
var userEntity = orgSvc.Retrieve("systemuser", whoRsp.UserId, new Microsoft.Xrm.Sdk.Query.ColumnSet("fullname"));
Console.WriteLine(string.Format("欢迎【{0}】登陆到【{1}】", userEntity.GetAttributeValue<string>("fullname"), ConfigurationManager.AppSettings["orgUrl"]));
Console.WriteLine("本程序用于删除已经成功或者取消的系统作业!");
if (needConfirm == "Y")
{
Console.WriteLine("当前处于需要确认才会继续的模式,若要继续请输入Y然后回车确认!");
inputKey = Console.ReadLine();
if (inputKey.ToUpper() == "Y")
{
UpdateContactCountryCode(orgSvc);
}
else
{
Console.WriteLine("你选择了取消运行!");
}
}
else
{
UpdateContactCountryCode(orgSvc);
}
}
Console.Write("程序运行完成,按任意键退出." + DateTime.Now.ToString());
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("程序运行出错:" + ex.Message + ex.StackTrace);
Console.ReadLine();
}
} private static void UpdateContactCountryCode(OrganizationServiceProxy orgSvc)
{
const string functionName = "删除已经成功或者取消的系统作业";
Console.WriteLine(string.Format("开始 {0} - {1}", functionName, DateTime.Now.ToString()));
try
{
var updateContactCountryCodeResult = ConfigurationManager.AppSettings["updateContactCountryCodeResult"]; string line = string.Empty;
var contactFetchxml = @"<fetch version='1.0' mapping='logical' distinct='false' no-lock='true'>
<entity name='asyncoperation'>
<attribute name='asyncoperationid' />
<filter type='and'>
<condition attribute='statuscode' operator='in'>
<value>32</value>
<value>30</value>
</condition>
</filter>
</entity>
</fetch>";
int pageNumber = ;
int fetchCount = ;
string pagingCookie = null;
orgSvc.Timeout = new TimeSpan(, , ); int j = ;
int i = ; ExecuteMultipleRequest multiReqs = new ExecuteMultipleRequest()
{
Settings = new ExecuteMultipleSettings()
{
ContinueOnError = true,
ReturnResponses = false
},
Requests = new OrganizationRequestCollection()
};
while (true)
{
string xml = CreateXml(contactFetchxml, pagingCookie, pageNumber, fetchCount);
RetrieveMultipleRequest pageRequest1 = new RetrieveMultipleRequest
{
Query = new FetchExpression(xml)
};
EntityCollection returnCollection = ((RetrieveMultipleResponse)orgSvc.Execute(pageRequest1)).EntityCollection;
int count = returnCollection.Entities.Count();
foreach (var item in returnCollection.Entities)
{
DeleteRequest req = new DeleteRequest();
req.Target = new EntityReference("asyncoperation", item.Id);
if (j <= )
{
multiReqs.Requests.Add(req);
}
else
{
multiReqs.Requests = new OrganizationRequestCollection();
multiReqs.Requests.Add(req);
j = ;
}
if (j == || i == count)
{
orgSvc.Execute(multiReqs);
}
j++;
i++; }
Console.WriteLine(string.Format("共{0}条处理完毕!{1}", pageNumber * fetchCount, DateTime.Now.ToString()));
if (returnCollection.MoreRecords)
{
pageNumber++;
pagingCookie = returnCollection.PagingCookie;
}
else
{
Console.WriteLine("最后一页");
break;
}
}
Console.WriteLine(string.Format("程序处理完成 {0}", updateContactCountryCodeResult));
}
catch (Exception ex)
{
Console.WriteLine(string.Format("运行 {0} 出现异常:{1}", functionName, ex.Message + ex.StackTrace));
}
Console.WriteLine(string.Format("结束 {0} - {1}", functionName, DateTime.Now.ToString()));
Console.WriteLine("================================================");
} private static TProxy GetProxy<TService, TProxy>(
IServiceManagement<TService> serviceManagement,
AuthenticationCredentials authCredentials)
where TService : class
where TProxy : ServiceProxy<TService>
{
Type classType = typeof(TProxy); if (serviceManagement.AuthenticationType !=
AuthenticationProviderType.ActiveDirectory)
{
AuthenticationCredentials tokenCredentials =
serviceManagement.Authenticate(authCredentials);
return (TProxy)classType
.GetConstructor(new Type[] { typeof(IServiceManagement<TService>), typeof(SecurityTokenResponse) })
.Invoke(new object[] { serviceManagement, tokenCredentials.SecurityTokenResponse });
}
return (TProxy)classType
.GetConstructor(new Type[] { typeof(IServiceManagement<TService>), typeof(ClientCredentials) })
.Invoke(new object[] { serviceManagement, authCredentials.ClientCredentials });
} public static 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 static 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();
StringWriter stringWriter = new StringWriter(sb);
XmlTextWriter writer = new XmlTextWriter(stringWriter);
doc.WriteTo(writer);
writer.Close();
return sb.ToString();
}
}
}

使用的配置文件示例:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<appSettings>
<add key="userName" value="luoyong\crmadmin" />
<add key="passWord" value="*******" />
<add key="orgUrl" value="https://demo.luoyong.me/XRMServices/2011/Organization.svc" />
</appSettings>
</configuration>

Dynamics 365使用Execute Multiple Request删除系统作业实体记录的更多相关文章

  1. Dynamics 365的系统作业实体记录增长太快怎么回事?

    摘要: 本人微信公众号:微软动态CRM专家罗勇 ,回复294或者20190111可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!我的网站是 www.luoyong.me ...

  2. Dynamics 365检查工作流、SDK插件步骤是否选中运行成功后自动删除系统作业记录

    本人微信公众号:微软动态CRM专家罗勇 ,回复298或者20190120可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!我的网站是 www.luoyong.me . 系统 ...

  3. Dynamics 365的审核日志分区删除超时报错怎么办?

    摘要: 本人微信公众号:微软动态CRM专家罗勇 ,回复296或者20190112可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!我的网站是 www.luoyong.me ...

  4. Dynamics 365中计算字段与Now进行计算实体导入报错:You can't use Now(), which is of type DateTime, with the current function.

    微软动态CRM专家罗勇 ,回复338或者20190521可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me. 计算字段是从Dynamics CRM 2015 SP1版本开始推 ...

  5. Dynamics 365中的批量删除作业执行频率可以高于每天一次吗?

    微软动态CRM专家罗勇 ,回复317或者20190314可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!我的网站是 www.luoyong.me . 我先来做一个例子,登 ...

  6. Dynamics 365 CE中AsyncOperationBase表记录太多,影响系统性能怎么办?

    微软动态CRM专家罗勇 ,回复311或者20190311可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!我的网站是 www.luoyong.me . 本文主要是根据微软官 ...

  7. Dynamics 365中使用Web API将查找字段的值设置为空值的方法。

    摘要: 本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复270或者20180424可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyon ...

  8. 自定义适用于手机和平板电脑的 Dynamics 365(二):窗体自定义项

    适用于手机的 Dynamics 365 和 适用于平板电脑的 Dynamics 365 使用窗体作为 Web 应用. 窗体在应用程序中的显示方式为移动体验进行了优化. 下图显示了从 Web 应用程序到 ...

  9. 利用Dynamics 365 Customer Engagement的标准导入功能导入附件。

    我是微软Dynamics 365 & Power Platform方面的工程师罗勇,也是2015年7月到2018年6月连续三年Dynamics CRM/Business Solutions方面 ...

随机推荐

  1. 使用cAdvisor+Influxdb+Grafana监控系统

      今天准备开始研究研究当前非常流行的Grafana+Influxdb监控系统,两者都是非常轻量级的应用但是功能却异常强大,可以说Grafana在作图显示方面真的毫不逊色与Cacti. 组件介绍 cA ...

  2. Jenkins(Docker容器内)使用宿主机的docker命令

    1.Jenkins镜像 Docker容器内的Jenkins使用容器外宿主机的Docker(即DooD,还有另外的情况就是DioD),google一下有几种说法,但是都没试成功(试过一种就是修改宿主机/ ...

  3. [Swift]LeetCode81. 搜索旋转排序数组 II | Search in Rotated Sorted Array II

    Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e. ...

  4. 执行find / -name *.sh时报错 find: 路径必须在表达式之前: start-ressvr-release.sh

    想查找一个包含4000多文件的目录下所有.sh结尾的文件 使用命令     find  ./ -name *.sh     (本身已经在要查找的目录里了) 结果报错:  解决方法一:find ./ - ...

  5. Mysql的两种“排名第几且有可能为空的记录”写法(力扣176)

    编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) . +----+--------+ | Id | Salary | +----+--------+ | 1 | 100 ...

  6. .NET Core实战项目之CMS 第五章 入门篇-Dapper的快速入门看这篇就够了

    写在前面 上篇文章我们讲了如在在实际项目开发中使用Git来进行代码的版本控制,当然介绍的都是比较常用的功能.今天我再带着大家一起熟悉下一个ORM框架Dapper,实例代码的演示编写完成后我会通过Git ...

  7. 一段奇葩Javascript代码引发的思考

    今天与一挚友加同事调试一段奇葩的javascript代码,在分析出结果后,让我萌生了写此篇文章的想法,如有不对之处望指正,也欢迎大家一起讨论.缩减后的js代码如下,你是否能准确说明他的输出值呢? fu ...

  8. JDK1.8源码(三)——java.util.HashMap

      什么是哈希表? 在讨论哈希表之前,我们先大概了解下其他数据结构在新增,查找等基础操作执行性能 数组:采用一段连续的存储单元来存储数据.对于指定下标的查找,时间复杂度为O(1):通过给定值进行查找, ...

  9. 【安卓本卓】Android系统源码篇之(一)源码获取、源码目录结构及源码阅读工具简介

    前言        古人常说,“熟读唐诗三百首,不会作诗也会吟”,说明了大量阅读诗歌名篇对学习作诗有非常大的帮助.做开发也一样,Android源码是全世界最优秀的Android工程师编写的代码,也是A ...

  10. 在越狱的iPhone/iPad上安装自开发环境

    自开发跟自编译意思一样,后者表示一个开发语言的开发能力成熟度:前者则表示一个开发平台的开发能力成熟度. iPhone跟iPad面世这么多年,一直无法摆脱"娱乐"工具的宿命.Appl ...