我是微软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执行批量操作的更多相关文章

  1. 使用JS通过Web API执行批量操作,多个操作是一个事务!

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

  2. Dynamics 365 Web Api之基于single-valued navigation property的filter查询

    本篇要讲的是dynamics 新版本中web api的一个改进功能,虽然改进的很有限,但至少是改进了. 举个例子,我们现在知道联系人的名字vic,我们想找出客户记录中主要联系人名字为vic的所有客户, ...

  3. 利用Fiddler修改请求信息通过Web API执行Dynamics 365操作(Action)实例

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

  4. 不借助工具在浏览器中通过Web API执行Dynamics 365操作(Action)实例

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

  5. Dynamics CRM Web API中的and和or组合的正确方式!

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

  6. MVC项目实践,在三层架构下实现SportsStore-09,ASP.NET MVC调用ASP.NET Web API的查询服务

    ASP.NET Web API和WCF都体现了REST软件架构风格.在REST中,把一切数据视为资源,所以也是一种面向资源的架构风格.所有的资源都可以通过URI来唯一标识,通过对资源的HTTP操作(G ...

  7. Dynamics CRM2016 Web Api之分页查询

    在dynamics crm web api还没出现前,我们是通过fetchxml来实现的,当然这种方式依旧可行,那既然web api来了我们就拥抱新的方式. web api中我们通过指定查询的条数来实 ...

  8. 延迟调用或多次调用第三方的Web API服务

    当我们调用第三方的Web API服务的时候,不一定每次都是成功的.这时候,我们可能会再多尝试几次,也有可能延迟一段时间再去尝试调用服务. Task的静态方法Delay允许我们延迟执行某个Task,此方 ...

  9. 利用Fiddler修改请求信息通过Web API执行操作(Action)实例

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

随机推荐

  1. Nginx配置实例-反向代理实现浏览器请求Nginx跳转到服务器某页面

    场景 Ubuntu Server 16.04 LTS上怎样安装下载安装Nginx并启动: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/detai ...

  2. Gradle for Android ( 构建变体 )

    链接: http://77blogs.com/?p=38 https://www.cnblogs.com/tangZH/p/10999060.html 有时候我们一个app需要有不同的版本,不同的版本 ...

  3. .NET Core 使用HMAC算法

    一. HMAC 简介 通过哈希算法,我们可以验证一段数据是否有效,方法就是对比该数据的哈希值,例如,判断用户口令是否正确,我们用保存在数据库中的password_md5对比计算md5(password ...

  4. 设计模式(含UML、设计原则、各种模式讲解链接)

    一.统一建模语言UML UML是一种开放的方法,用于说明.可视化.构建和编写一个正在开发的.面向对象的.软件密集系统的制品的开放方法 UML展现了一系列最佳工程实践,这些最佳实践在对大规模,复杂系统进 ...

  5. 如何在 Chrome中导出、导入书签和密码

    目录 书签 密码 书签 1.导出 点击浏览器右上角的三小点,选择"书签",再选择"书签管理器",进入如下页面 点击蓝色书签栏右上角的三小点,选择"导出 ...

  6. Java实现抢红包功能

    采用多线程模拟多人同时抢红包.服务端将玩家发出的红包保存在一个队列里,然后用Job定时将红包信息推送给玩家.每一批玩家的抢红包请求,其实操作的都是从队列中弹出的第一个红包元素,但当前的红包数量为空的时 ...

  7. JavaScript设计模式基础(二)

    JavaScript 设计模式基础(一) 原型模式 在以类为中心的面向对象编程语言中,类和对象的关系就像铸模和铸件的关系,对象总是从类中创建.而原型编程中,类不是必须的,对象未必从类中创建而来,可以拷 ...

  8. Spring整合JMS消息中间件

    1. 点对点模式 1.1消息生产者 (1)创建工程springjms_producer,在POM文件中引入SpringJms .activeMQ以及单元测试相关依赖 (2)在src/main/reso ...

  9. diango url的命名和反向解析

    url的命名和反向解析 静态路由 url(r'^login/', views.login,name='login'), 反向解析ht 模板 {% url 'login' %} --> '/app ...

  10. 阿里云ECS服务器部署HADOOP集群(五):Pig 安装

    本篇将在阿里云ECS服务器部署HADOOP集群(一):Hadoop完全分布式集群环境搭建的基础上搭建. 1 环境介绍 一台阿里云ECS服务器:master 操作系统:CentOS 7.3 Hadoop ...