通过C#代码调用Dynamics 365 Web API执行批量操作
我是微软Dynamics 365 & Power Platform方面的工程师罗勇,也是2015年7月到2018年6月连续三年Dynamics CRM/Business Solutions方面的微软最有价值专家(Microsoft MVP),欢迎关注我的微信公众号 MSFTDynamics365erLuoYong ,回复356或者20190830可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!
之前的文章 使用JS通过Web API执行批量操作,多个操作是一个事务! 讲的是JavaScript的做法,今天我实验了一阵子终于搞定了C#做法。
不多说,上代码,这个代码的用途简单,就是新建一个注释,然后将某个注释的stepid字段值设置为Y,两个操作做成一个事务:
private static async Task<string> ExecuteBatch(string ODataBaseUrl)
{
Guid batchId = Guid.NewGuid();
Guid changesetId = Guid.NewGuid();
string returnVal = string.Empty;
StringBuilder requestBody = new StringBuilder();
requestBody.Append($"--batch_{batchId}");
requestBody.Append("\n");
requestBody.Append($"Content-Type: multipart/mixed;boundary=changeset_{changesetId}");
requestBody.Append("\n");
requestBody.Append("\n");
requestBody.Append($"--changeset_{changesetId}");
requestBody.Append("\n");
requestBody.Append("Content-Type: application/http");
requestBody.Append("\n");
requestBody.Append("Content-Transfer-Encoding:binary");
requestBody.Append("\n");
requestBody.Append("Content-ID: 1");
requestBody.Append("\n");
requestBody.Append("\n");
requestBody.Append($"POST {ODataBaseUrl}annotations HTTP/1.1");
requestBody.Append("\n");
requestBody.Append("Content-Type: application/json;type=entry");
requestBody.Append("\n");
requestBody.Append("\n");
JObject jObject = new JObject(
new JProperty("subject", "克隆出来的记录"),
new JProperty("filename", "MSFTDynamics365erLuoYong.jpg"),
new JProperty("filesize", ),
new JProperty("documentbody", "/9j/4AAQSkZJRgAB2cFFABRRRQAUUUUAf//Z"
requestBody.Append("\n");
requestBody.Append($"--changeset_{changesetId}");
requestBody.Append("\n");
requestBody.Append("Content-Type: application/http");
requestBody.Append("\n");
requestBody.Append("Content-Transfer-Encoding:binary");
requestBody.Append("\n");
requestBody.Append("Content-ID: 2");
requestBody.Append("\n");
requestBody.Append("\n");
requestBody.Append($"PUT {ODataBaseUrl}annotations(4B502B89-4520-E911-B0C6-E05D5152C120)/stepid HTTP/1.1");
requestBody.Append("\n");
requestBody.Append("Content-Type: application/json;type=entry");
requestBody.Append("\n");
requestBody.Append("\n");
requestBody.Append("{\"value\":\"Y\"}");
requestBody.Append("\n");
requestBody.Append("\n");
requestBody.Append($"--changeset_{changesetId}--");
requestBody.Append("\n");
requestBody.Append("\n");
requestBody.Append($"--batch_{batchId}--");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create($"{ODataBaseUrl}$batch");
request.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["userName"], ConfigurationManager.AppSettings["passWord"]);
request.Method = "POST";
request.ContentType = $"multipart/mixed;boundary=batch_{batchId}";
request.Accept = "application/json";
request.Headers.Add("OData-MaxVersion", "4.0");
request.Headers.Add("OData-Version", "4.0");
byte[] buffer = Encoding.UTF8.GetBytes(requestBody.ToString());
request.ContentLength = buffer.Length;
using (Stream stream = await request.GetRequestStreamAsync())
{
stream.Write(buffer, , buffer.Length);
stream.Flush();
}
using (WebResponse response = await request.GetResponseAsync())
{
var webResponse = response as HttpWebResponse;
if (webResponse.StatusCode == HttpStatusCode.OK)
{
Stream Answer = response.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
returnVal = _Answer.ReadToEnd();
}
else
{
throw new Exception($"Error. {webResponse.StatusCode}");
}
}
return returnVal;
}
我的执行效果如下,我这里是执行成功HTTP STATUS CODE = 200)后显示了返回内容:

如果改成用 HttpClient 来发起请求,代码如下,个人推荐使用这种:
private static async Task<string> ExecuteBatch(string ODataBaseUrl)
{
Guid batchId = Guid.NewGuid();
Guid changesetId = Guid.NewGuid();
string returnVal = string.Empty;
StringBuilder requestBody = new StringBuilder();
requestBody.Append($"--batch_{batchId}");
requestBody.Append("\n");
requestBody.Append($"Content-Type: multipart/mixed;boundary=changeset_{changesetId}");
requestBody.Append("\n");
requestBody.Append("\n");
requestBody.Append($"--changeset_{changesetId}");
requestBody.Append("\n");
requestBody.Append("Content-Type: application/http");
requestBody.Append("\n");
requestBody.Append("Content-Transfer-Encoding:binary");
requestBody.Append("\n");
requestBody.Append("Content-ID: 1");
requestBody.Append("\n");
requestBody.Append("\n");
requestBody.Append($"POST {ODataBaseUrl}annotations HTTP/1.1");
requestBody.Append("\n");
requestBody.Append("Content-Type: application/json;type=entry");
requestBody.Append("\n");
requestBody.Append("\n");
JObject jObject = new JObject(
new JProperty("subject", "克隆出来的记录"),
new JProperty("filename", "MSFTDynamics365erLuoYong.jpg"),
new JProperty("filesize", ),
new JProperty("documentbody", "/9j/4AAQSkZJRRRQAUUUUAf//Z"),
new JProperty("isdocument", true),
new JProperty("mimetype", "image/jpeg"),
new JProperty("notetext", "罗勇测试用的"),
new JProperty("objectid_account@odata.bind", "/accounts(C543D891-9FBD-E911-B0D1-8280A40FB795)")
);
requestBody.Append(JsonConvert.SerializeObject(jObject));
requestBody.Append("\n");
requestBody.Append("\n");
requestBody.Append($"--changeset_{changesetId}");
requestBody.Append("\n");
requestBody.Append("Content-Type: application/http");
requestBody.Append("\n");
requestBody.Append("Content-Transfer-Encoding:binary");
requestBody.Append("\n");
requestBody.Append("Content-ID: 2");
requestBody.Append("\n");
requestBody.Append("\n");
requestBody.Append($"PUT {ODataBaseUrl}annotations(85412E8C-B08D-E911-B0C9-C8187530CEF1)/stepid HTTP/1.1");
requestBody.Append("\n");
requestBody.Append("Content-Type: application/json;type=entry");
requestBody.Append("\n");
requestBody.Append("\n");
requestBody.Append("{\"value\":\"Y\"}");
requestBody.Append("\n");
requestBody.Append("\n");
requestBody.Append($"--changeset_{changesetId}--");
NetworkCredential credentials = new NetworkCredential(ConfigurationManager.AppSettings["userName"], ConfigurationManager.AppSettings["passWord"]);
HttpMessageHandler messageHandler = new HttpClientHandler()
{
Credentials = credentials
};
using (HttpClient httpClient = new HttpClient(messageHandler))
{
httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
MultipartContent mainContent = new MultipartContent("mixed", $"batch_{batchId.ToString().Replace("\"","")}");
StringContent sc = new StringContent(requestBody.ToString());
sc.Headers.Clear();
sc.Headers.Add("Content-Type", $"multipart/mixed;boundary={changesetId.ToString()}");
mainContent.Add(sc);
var response = await httpClient.PostAsync($"{ODataBaseUrl}$batch", mainContent);
if (response.IsSuccessStatusCode)
{
returnVal = await response.Content.ReadAsStringAsync();
}
else
{
var errorMsg = await response.Content.ReadAsStringAsync();
throw new Exception(errorMsg);
}
return returnVal;
}
}
通过C#代码调用Dynamics 365 Web API执行批量操作的更多相关文章
- 使用JS通过Web API执行批量操作,多个操作是一个事务!
关注本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复235或者20161105可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong. ...
- Dynamics 365 Web Api之基于single-valued navigation property的filter查询
本篇要讲的是dynamics 新版本中web api的一个改进功能,虽然改进的很有限,但至少是改进了. 举个例子,我们现在知道联系人的名字vic,我们想找出客户记录中主要联系人名字为vic的所有客户, ...
- 利用Fiddler修改请求信息通过Web API执行Dynamics 365操作(Action)实例
本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复261或者20170724可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong.me ...
- 不借助工具在浏览器中通过Web API执行Dynamics 365操作(Action)实例
摘要: 本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复262或者20170727可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyon ...
- Dynamics CRM Web API中的and和or组合的正确方式!
关注本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复243或者20170111可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong. ...
- MVC项目实践,在三层架构下实现SportsStore-09,ASP.NET MVC调用ASP.NET Web API的查询服务
ASP.NET Web API和WCF都体现了REST软件架构风格.在REST中,把一切数据视为资源,所以也是一种面向资源的架构风格.所有的资源都可以通过URI来唯一标识,通过对资源的HTTP操作(G ...
- Dynamics CRM2016 Web Api之分页查询
在dynamics crm web api还没出现前,我们是通过fetchxml来实现的,当然这种方式依旧可行,那既然web api来了我们就拥抱新的方式. web api中我们通过指定查询的条数来实 ...
- 延迟调用或多次调用第三方的Web API服务
当我们调用第三方的Web API服务的时候,不一定每次都是成功的.这时候,我们可能会再多尝试几次,也有可能延迟一段时间再去尝试调用服务. Task的静态方法Delay允许我们延迟执行某个Task,此方 ...
- 利用Fiddler修改请求信息通过Web API执行操作(Action)实例
本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复261或者20170724可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong.me ...
随机推荐
- .net(C#数据库访问) Mysql,Sql server,Sqlite,Access四种数据库的连接方式
便签记录Mysql,Sql server,Sqlite,Access四种数据库的简单连接方式 //using MySql.Data.MySqlClient; #region 执行简单SQL语句,使用M ...
- Nginx配置实例-负载均衡实例:平均访问多台服务器
场景 Nginx配置实例-反向代理实例:根据访问的路径跳转到不同端口的服务中: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/10 ...
- CentOS7 下nginx与PHP的安装与配置
下载Nginx 1.在服务器上新建文件夹 /home/soft/ ; 2.cd /home/soft/ => 执行命令下载Nginx wget http://nginx.or ...
- ASP.NET Core on K8S深入学习(8)数据管理
本篇已加入<.NET Core on K8S学习实践系列文章索引>,可以点击查看更多容器化技术相关系列文章. 在Docker中我们知道,要想实现数据的持久化(所谓Docker的数据持久化即 ...
- php的swoole和rpc区别
RPC是远程过程调用(Remote Procedure Call)的缩写形式. SAP系统RPC调用的原理其实很简单,有一些类似于三层构架的C/S系统,第三方的客户程序通过接口调用SAP内部的标准或自 ...
- js实现弹出框跟随鼠标移动
又是新的一天网上冲浪,在bing的搜索页面下看到这样一个效果: 即弹出框随着鼠标的移动而移动.思路大概为: 调用onmousemove函数,将鼠标的当前位置赋予弹出框即可 //html <div ...
- 《C#并发编程经典实例》学习笔记—2.8 处理 async Task 方法的异常
异常处理一直是所有编程语言不可避免需要考虑的问题,C#的异步方法的异常处理和同步方法并无差别,同样要借助 try catch 语句捕获异常. 首先编写一个抛出异常的方法 static async Ta ...
- HeadFirst设计模式<1>
HeadFirst设计模式<1> 1 策略模式 鸭子飞行和嘎嘎叫策略 2 工厂模式 简单工厂 工厂方法 抽象工厂 简单工厂简单的pizza工厂 通过一个工厂类的方法,创建和返回对象实例 原 ...
- SSM框架之SpringMVC(6)异常处理及拦截器
SpringMVC(6)异常处理及拦截器 1.异常处理 1.1.异常处理的思路 系统中异常包括两类:预期异常和运行时异常 RuntimeException,前者通过捕获异常从而获取异常信息,后者主 ...
- axios统一接口管理及优化
之前我写了一篇文章,分享了自己的项目中对于接口管理的方法.总结下来就是:定义接口文件--withAxios导出--调用接口方法.这样实现了接口的统一管理和调用接口的语义化与简单化. 根据在项目的使用, ...