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 ...
随机推荐
- Selenium2Lib库之操作浏览器相关的关键字实战
1.1 操作浏览器相关的关键字 Selenium2Lib提供了与浏览器交互的关键词 1.1.1 Open Browser关键字 按F5 查看Open Browser关键字的说明,如下图: Open ...
- 并发库应用之六 & 有条件阻塞Condition应用
Condition的功能类似在传统线程技术中的 Object.wait() 和 Object.natify() 的功能,传统线程技术实现的互斥只能一个线程单独干,不能说这个线程干完了通知另一个线程来干 ...
- hibernate多表查询封装实体
以前用sql实现联合查询 是非常简单的事,只需要写sql语句就可以,第一次遇到hibernate要实现多表联合查询的时候还楞了一下.最后看了下资料,才恍然大悟,hibernate实现多表联合查询跟SQ ...
- MySql 物理文件组成
1.日志文件 MySQL 各类日志文件介绍 2.数据文件 MySQL 各类数据文件介绍
- struts2中的拦截器
一 AOP思想: 面向切面编程的思想 AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术.AOP ...
- 二十一、Hadoop学记笔记————kafka的初识
这些场景的共同点就是数据由上层框架产生,需要由下层框架计算,其中间层就需要有一个消息队列传输系统 Apache flume系统,用于日志收集 Apache storm系统,用于实时数据处理 Spark ...
- Asp.Net Core 2.0 项目实战(6)Redis配置、封装帮助类RedisHelper及使用实例
本文目录 1. 摘要 2. Redis配置 3. RedisHelper 4.使用实例 5. 总结 1. 摘要 由于內存存取速度远高于磁盘读取的特性,为了程序效率提高性能,通常会把常用的不常变动的数 ...
- OAuth 2 开发人员指南(Spring security oauth2)
https://github.com/spring-projects/spring-security-oauth/blob/master/docs/oauth2.md 入门 这是支持OAuth2.0的 ...
- box-shadow 详解及示例
box-shadow [bɑks] - [ˈʃædoʊ] 英文示意: box:盒,包厢 shadow:阴影,渐变 定义: box-shadow: none | <shadow> ...
- javascript知识详解之8张思维导图
学习的道路就是要不断的总结归纳,好记性不如烂笔头,so,下面将po出8张javascript相关的思维导图. 思维导图小tips:思维导图又叫心智图,是表达发射性思维的有效的图形思维工具 ,它简单却又 ...