Dynamics 365 CE的插件/自定义工作流活动中调用Web API示例代码
微软动态CRM专家罗勇 ,回复325或者20190428可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!
现在Web API越来越流行,有时候为了程序更加健壮,需要在插件/自定义工作流活动中调用Web API,请求数据内容和返回数据内容都是JSON格式,我这里准备了一些代码示例,方便以后参考,也欢迎各位读者提供建议,我的C#水平有限,望各位不吝赐教。
插件代码示例:
using System;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using System.Net.Http;
using System.Threading.Tasks; namespace Plugins
{
public class PreAccountCreate : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
tracingService.Trace("Enter PreAccountCreate on {0}", DateTime.Now.ToString());
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity currentEntity = (Entity)context.InputParameters["Target"];
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
try
{
string requestJson = string.Empty;
var request = new GetTeamMembersRequest()
{
TeamName = "Thomas Luo",
WordConnector = ";"
};
var serializer = new DataContractJsonSerializer(typeof(GetTeamMembersRequest));
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, request);
requestJson = Encoding.UTF8.GetString(ms.ToArray());
}
tracingService.Trace("HTTP POST REQUEST BODY = {0}", requestJson);
var responseContent = PostApiAsync(requestJson).Result;
tracingService.Trace("HTTP POST RESPONSE CONTENT = {0}", responseContent);
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(responseContent)))
{
DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(GetTeamMembersResponse));
GetTeamMembersResponse repsonse = (GetTeamMembersResponse)deseralizer.ReadObject(ms);
//这里就是调用返回内容
//throw new InvalidPluginExecutionException(repsonse.UserEmailAddrs + repsonse.UserFullName + repsonse.UserIds);
}
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("An error occurred in PreAccountCreate.", ex);
}
catch (Exception ex)
{
tracingService.Trace("PreAccountCreate unexpected exception: {0}", ex.Message);
throw;
}
}
tracingService.Trace("Leave PreAccountCreate on {0}", DateTime.Now.ToString());
} private async Task<string> PostApiAsync(string requestJson)
{
string returnVal = string.Empty;
using (var client = new HttpClient())
{
var content = new StringContent(requestJson, Encoding.UTF8, "application/json");
var response = client.PostAsync(@"https://thomaswebapi.azurewebsites.net/api/CustomerEngagement", content).Result;
if (response.IsSuccessStatusCode)
{
returnVal = await response.Content.ReadAsStringAsync();
}
else
{
throw new InvalidPluginExecutionException(response.Content.ReadAsStringAsync().Result);
}
}
return returnVal;
}
} public class GetTeamMembersRequest
{
public string TeamName { get; set; } public string WordConnector { get; set; }
} public class GetTeamMembersResponse
{
public string UserIds { get; set; } public string UserEmailAddrs { get; set; } public string UserFullName { get; set; } public string ResultCode { get; set; } public string ResultDesc { get; set; }
}
}
自定义工作流活动代码示例:
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using System;
using System.Activities;
using System.IO;
using System.Net.Http;
using System.Runtime.Serialization.Json;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks; namespace Flows
{
public class InvokeWebApi : CodeActivity
{
protected override void Execute(CodeActivityContext executionContext)
{
ITracingService tracingService = executionContext.GetExtension<ITracingService>();
tracingService.Trace("Enter InvokeWebApi on {0}", DateTime.Now.ToString());
IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
IOrganizationService orgService = serviceFactory.CreateOrganizationService(context.UserId);
try
{
string requestJson = string.Empty;
var request = new GetTeamMembersRequest()
{
TeamName = "Thomas Luo",
WordConnector = ";"
};
var serializer = new DataContractJsonSerializer(typeof(GetTeamMembersRequest));
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, request);
requestJson = Encoding.UTF8.GetString(ms.ToArray());
}
tracingService.Trace("HTTP POST REQUEST BODY = {0}", requestJson);
var responseContent = PostApiAsync(requestJson).Result;
tracingService.Trace("HTTP POST RESPONSE CONTENT = {0}", responseContent);
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(responseContent)))
{
DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(GetTeamMembersResponse));
GetTeamMembersResponse repsonse = (GetTeamMembersResponse)deseralizer.ReadObject(ms);
//这里就是调用返回内容
//throw new InvalidPluginExecutionException(repsonse.UserEmailAddrs + repsonse.UserFullName + repsonse.UserIds);
}
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("An error occurred in InvokeWebApi.", ex);
}
catch (Exception ex)
{
tracingService.Trace("InvokeWebApi unexpected exception: {0}", ex.Message);
throw;
}
tracingService.Trace("Leave InvokeWebApi on {0}", DateTime.Now.ToString());
} private async Task<string> PostApiAsync(string requestJson)
{
string returnVal = string.Empty;
using (var client = new HttpClient())
{
var content = new StringContent(requestJson, Encoding.UTF8, "application/json");
var response = client.PostAsync(@"https://thomaswebapi.azurewebsites.net/api/CustomerEngagement", content).Result;
if (response.IsSuccessStatusCode)
{
returnVal = await response.Content.ReadAsStringAsync();
}
else
{
throw new InvalidPluginExecutionException(response.Content.ReadAsStringAsync().Result);
}
}
return returnVal;
}
} public class GetTeamMembersRequest
{
public string TeamName { get; set; } public string WordConnector { get; set; }
} public class GetTeamMembersResponse
{
public string UserIds { get; set; } public string UserEmailAddrs { get; set; } public string UserFullName { get; set; } public string ResultCode { get; set; } public string ResultDesc { get; set; }
}
}
当然若你使用HTTP GET,参考下面的示例:
private async Task<string> GetApiAsync(string OrderNumber)
{
string returnVal = string.Empty;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync(string.Format("https://thomaswebapi.azurewebsites.net/api/Order?OrderNo={0}",OrderNumber)).Result;
if (response.IsSuccessStatusCode)
{
returnVal = await response.Content.ReadAsStringAsync();
}
else
{
throw new InvalidPluginExecutionException(response.Content.ReadAsStringAsync().Result);
}
}
return returnVal;
}
Dynamics 365 CE的插件/自定义工作流活动中调用Web API示例代码的更多相关文章
- 利用Fiddler模拟通过Dynamics 365的OAuth 2 Client Credentials认证后调用Web API
微软动态CRM专家罗勇 ,回复337或者20190521可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me. 配置Dynamics 365 & PowerApps 支 ...
- Dynamics 365中自定义工作流活动获取的上下文分析及注意事项
关注本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复244或者20170306可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong. ...
- Dynamics 365中自定义工作流活动更新了输入输出参数后获取的方法
关注本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复245或者20170309可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong. ...
- Dynamics CRM模拟OAuth请求获得Token后在外部调用Web API
关注本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复233或者20161104可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong. ...
- Dynamics 365 CE将自定义工作流活动程序集注册到磁盘并引用其他类库
我是微软Dynamics 365 & Power Platform方面的工程师罗勇,也是2015年7月到2018年6月连续三年Dynamics CRM/Business Solutions方面 ...
- 自定义工作流活动报错:您无法登陆系统。原因可能是您的用户记录或您所属的业务部门在Microsoft Dynamics 365中已被禁用。
本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复265或者20170926可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong.me ...
- 自定义工作流活动运行产生System.Security.SecurityException
摘要: 微软动态CRM专家罗勇 ,回复305或者20190224可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!我的网站是 www.luoyong.me . 最近碰到一个 ...
- Dynamics 365 CE Update消息PostOperation阶段Image的尝试
我是微软Dynamics 365 & Power Platform方面的工程师罗勇,也是2015年7月到2018年6月连续三年Dynamics CRM/Business Solutions方面 ...
- 使用Dynamics 365 CE Web API查询数据加点料及选项集字段常用查询
微软动态CRM专家罗勇 ,回复336或者20190516可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me. 紧接上文:配置Postman通过OAuth 2 implicit ...
随机推荐
- python_code list_2
>>> import math>>> math.sin(0.5)0.479425538604203>>> >>> import ...
- Tiny4412之外部中断
一:外部中断 在之前我们学习按键驱动的时候,我们检测按键有没有按下是通过轮循的方式(也就是我们说的死循环),这样虽然可以检测实现按键,但太浪费系统资源了,不论我们按键中断有没有发生,cpu都要一直进行 ...
- 关于mui 中popover与下拉刷新冲突问题
最近用mui做app混合式开发时,作为一个后端开发,高前端确实有点吃了,期间遇到的问题肯定也不少.这两天app做更新,为了装逼,将更新的提示搞得好看些,用到了mui中的popover,结果把自己整死了 ...
- linxu安装SNMP
http://wiki.jiankongbao.com/doku.php/%E6%96%87%E6%A1%A3:%E5%AE%89%E5%85%A8%E6%8C%87%E5%BC%95#linux_s ...
- &
在 xml 中,不能直接使用 '&' 表示 '&',要转译为 '&' (转译序列个字符不能有空格,区分大小写,以';'结束,不要丢了分号哦 ; amp;不是" ...
- Python爬虫-pyspider框架的使用
pyspider 是一个用python实现的功能强大的网络爬虫系统,能在浏览器界面上进行脚本的编写,功能的调度和爬取结果的实时查看,后端使用常用的数据库进行爬取结果的存储,还能定时设置任务与任务优 ...
- Java 读书笔记 (十四) Java 方法
finalize() 方法 finalize() 用来清除回收对象. //为什么要回收内存?怎样写可以避免内存过多占用?什么时候需要手动回收内存? protected void finalize() ...
- spring boot 搭建web项目常见五种返回形式
在web项目中一般常见的五种返回形式: 返回页面,使用模板引擎,spring boot推荐使用thymeleaf,类似的还有freemarker等. 返回字符串(json),一般用于完全的前后端分离开 ...
- 利用异或求(整数数组中,有2K+1个数,其中有2k个相同,找出不相同的那个数)
转自https://blog.csdn.net/renjie_998003/article/details/50738025 java的位运算符中有一个叫异或的运算符,用符号(^)表示,其运算规则是: ...
- 用Axure进行原型设计
用Axure进行原型设计 看这个视频 http://www.iqiyi.com/playlist409963402.html