微软动态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示例代码的更多相关文章

  1. 利用Fiddler模拟通过Dynamics 365的OAuth 2 Client Credentials认证后调用Web API

    微软动态CRM专家罗勇 ,回复337或者20190521可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me. 配置Dynamics 365 & PowerApps 支 ...

  2. Dynamics 365中自定义工作流活动获取的上下文分析及注意事项

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

  3. Dynamics 365中自定义工作流活动更新了输入输出参数后获取的方法

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

  4. Dynamics CRM模拟OAuth请求获得Token后在外部调用Web API

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

  5. Dynamics 365 CE将自定义工作流活动程序集注册到磁盘并引用其他类库

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

  6. 自定义工作流活动报错:您无法登陆系统。原因可能是您的用户记录或您所属的业务部门在Microsoft Dynamics 365中已被禁用。

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

  7. 自定义工作流活动运行产生System.Security.SecurityException

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

  8. Dynamics 365 CE Update消息PostOperation阶段Image的尝试

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

  9. 使用Dynamics 365 CE Web API查询数据加点料及选项集字段常用查询

    微软动态CRM专家罗勇 ,回复336或者20190516可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me. 紧接上文:配置Postman通过OAuth 2 implicit ...

随机推荐

  1. Pat1071: Speech Patterns

    1071. Speech Patterns (25) 时间限制 300 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 HOU, Qiming Peo ...

  2. 基于Mybatis的Dao层的开发

    基于Mybatis的Dao层开发 SqlSessionFactoryBuilder用于创建SqlSessionFacoty,SqlSessionFacoty一旦创建完成就不需要SqlSessionFa ...

  3. SSM-SpringMVC-33:SpringMVC中拦截器Interceptor讲解

     ------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 拦截器Interceptor: 对处理方法进行双向的拦截,可以对其做日志记录等 我选择的是实现Handler ...

  4. SwaggerUI--SosoApi

    1.SwaggerUI是什么? Swagger UI是一款RESTFUL接口的文档在线自动生成+功能测试功能软件. Swagger-UI 的官方地址:http://swagger.io/ Github ...

  5. jmeter 监听器聚合报告说明:

    Label:表示定义HTTP请求名称 Samples:表示这次测试中一共发出了多少个请求. Average:平均响应时长---默认情况下是单个Request的平均响应时长,当使用了Transactio ...

  6. tkinter中menu菜单控件(十二)

    menu菜单控件 import tkinter wuya = tkinter.Tk() wuya.title("wuya") wuya.geometry("300x200 ...

  7. MYSQL的空间查询

    http://blog.sina.com.cn/s/blog_a48af8c001018q1p.html 本文将向各位介绍如何使用MySql5.x中的空间数据库,并展示一下它高效的性能(前提是正确使用 ...

  8. 大话RabbitMQ 基础入门

    ----------写在前面---------- 近些年微服务越来越火,让我也忍不住想去一窥微服务究竟,讲到微服务,就离不开分布式,而分布式,也离不开消息队列,在消息队列中,RabbitMQ可以说是比 ...

  9. 如何添加“在这里打开PowerShell”到Windows中的上下文菜单

    It was only a matter of time, right? Due to my recent infatuation passionate love affair with PowerS ...

  10. FTP连接池

    我们项目使用的是 Apache的(commons-net-3.2.jar) FTPClient,但是系统偶尔会有异常,趁着刚解决完,总结一下. 日志中提示是类似 java.lang.Exception ...