AXForum  
Вернуться   AXForum > Microsoft Dynamics CRM > Dynamics CRM: Blogs
CRM
Забыли пароль?
Зарегистрироваться Правила Справка Пользователи Сообщения за день Поиск

 
 
Опции темы Поиск в этой теме Опции просмотра
Старый 18.01.2016, 11:11   #1  
Blog bot is offline
Blog bot
Участник
 
25,475 / 846 (79) +++++++
Регистрация: 28.10.2006
Microsoft Dynamics CRM Team Blog: Sending WebHooks with Microsoft Dynamics CRM
Источник: http://blogs.msdn.com/b/crm/archive/...amics-crm.aspx
==============

Applies to: CRM Online 2016 Update, CRM 2016, and CRM Online 2015 Update 1.

Microsoft Dynamics CRM has a robust customization framework for tailoring how it works to any business need. Here, we will show how to use workflows and custom workflow activities to send WebHooks from CRM to an external web service.

About WebHooks

WebHooks is a lightweight HTTP pattern for connecting Web APIs and services with a publish/subscribe model. WebHook senders notify receivers about events by making requests to receiver endpoints with some information about the events. Microsoft ASP.NET provides a preview project for working with WebHooks, which is also available on GitHub.

Architecture overview


To send a WebHook, we need to know the events that will trigger it, the receiver to which it will be sent, and data about the event. Each of these is readily available in CRM workflows.

CRM workflows have a set of workflow triggers that align well with the common events that we may wish to send: create, set state, assign, update, and delete. We will leverage these events to kick off the process of sending a WebHook.

The business entity that triggered the event is available both to the workflow and to custom code that is run from the workflow. As we will see below, both workflows and custom workflow activities can perform additional processing before sending a WebHook, which enables scenarios like filtering when a WebHook should be sent based on privilege or the value of a field.

Custom workflow activity

The core of a WebHook is a HTTP POST request made by the sender to an endpoint in the receiver. This is implemented using a custom workflow activity that creates a JSON object for the event data and posts it to a designated receiver endpoint. We’ll use the custom workflow activity template from the Developer Toolkit for Microsoft Dynamics CRM to create the activity. For more information about how to install the Developer Toolkit, see Install or uninstall the Developer Toolkit.

The URL of the receiver endpoint is provided using an input argument that is configured when the custom workflow activity is added as a workflow step. We can also provide additional input arguments to the workflow. In this example, a shared secret used to validate the origin of a WebHook is configured using another input argument.

using System.Activities;
using Microsoft.Xrm.Sdk.Workflow;


namespace Microsoft.Xrm.Samples.WebHooks
{
public class SendWebHook : WorkFlowActivityBase
{
[Input("WebHook receiver URI")]
public InArgument ReceiverURL { get; set; }


[Input("WebHook receiver secret")]
public InArgument ReceiverSecret { get; set; }
public override void ExecuteCRMWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext crmWorkflowContext)
{
// ...
}
}
}


Since this class is a custom workflow activity, we can use all of the features that are available to workflow activities, including the CRM organization service, plugin tracing service, managed-type serialization using data contracts, and HTTP(S) connections. For more information on what you can do inside a custom workflow activity, see Custom workflow activities (workflow assemblies) and Plug-in isolation, trusts, and statistics.

When the custom workflow activity is completed, it can be compiled into an assembly and registered with CRM using the Plugin Registration Tool. For information on using the Plug-in Registration Tool to register a custom workflow activity assembly, which is similar to registering a plug-in assembly, refer to the CRM SDK topic Register a plug-in using the plug-in registration tool. For more information on registering a custom workflow assembly see Register and use a custom workflow activity assembly.


Sending WebHooks with workflows

To set up CRM to use the custom workflow activity to send a WebHook, we’ll leverage the event pipeline and workflow triggers. We’ll define a workflow that triggers for our basic scenario (in this example, when creating an account). In the CRM application, choose Settings > Processes > New to create a new workflow process.




Inside the workflow editor, we should see that the custom workflow activity is available as an option for a workflow step. Add it to the workflow and configure the activity properties with the URL of the WebHook receiver, and the other required input arguments.









The URL of the WebHook receiver should be in the format https:///api/webhooks/incoming/dynamicscrm. In this example, the host name is “sampledynamicscrmwebhookreceiver.azurewebsites.net”. Here we have neglected to enforce that the WebHook receiver use HTTPS. It is recommended that you use HTTPS for your business application for enhanced security. We have also provided a shared secret that identifies CRM to the WebHook receiver. You should provide your own application secret for your business application. As always, use high-entropy values such as a SHA256 hash or similar, which you can get from FreeFormatter Online Tools For Developers. You can also set your application secret through the Azure Portal instead of hard-coding it in the Web.config file.

You can add more steps to the workflow to customize the way the WebHook will be sent. For example, you can add a condition step so that the WebHook will only be triggered if the account’s primary contact has an email address at a particular domain.

Once you’re satisfied with your workflow, save it. We’ll activate the workflow later, once the receiver is set up. Now, let’s build a simple receiver to observe the WebHooks.

Receiving WebHooks in your web application

Add the NuGet package for the ASP.NET WebHooks receivers for CRM to your web project in Visual Studio using the NuGet package manager, or by typing Install-Package Microsoft.AspNet.WebHooks.Receivers.DynamicsCRM -Pre into the package manager console. This example uses a Web API project created from the default Visual Studio ASP.NET project template. Remember that ASP.NET WebHooks is a preview package, so you must select Include Prerelease in the NuGet package manager window to install it.





Alternatively, you can clone the ASP.NET WebHooks project from GitHub, check out the dev branch, and build the NuGet package from source.

Create a handler that will respond to the WebHooks, following the instructions in the introduction to Microsoft ASP.NET WebHooks:

using System.Threading.Tasks;
using Microsoft.AspNet.WebHooks;


public sealed class SampleDynamicsCrmWebHookHandler : WebHookHandler
{
public override Task ExecuteAsync(string receiver, WebHookHandlerContext context)
{
// Get the event data.
JObject data = context.GetDataOrDefault();
// ...
return Task.FromResult(true);
}
}


Then add the following line to the end of Register() in WebApiConfig.cs to have ASP.NET WebHooks configure routes in your web application for handling WebHooks:

// Web API routes
config.MapHttpAttributeRoutes();
// ...
config.InitializeReceiveDynamicsCrmWebHooks();


Finally, add the secret that you provided to the custom workflow activity in your application settings. Use a high-entropy value such as SHA256 or similar. You can define the secret in your Web.config or in the Azure Portal.





When you rebuild and publish your web application, WebApiConfig will initialize the WebHook routes in your web application during startup and register the WebHook receiver and handler with the ASP.NET WebHooks framework. When a WebHook is received, the ASP.NET WebHooks framework will dispatch the event to your handler for processing.

Try it out

The source for the custom workflow activity for CRM that we’ve developed above is available here.

For this section, let’s suppose that you are publishing your WebHook receiver in your web application to an Azure website.

Add the CRM WebHook receiver to your web application project, as shown above, and rebuild it. Then publish it to your website from Visual Studio by selecting the web application project in Solution Explorer and choosing Build > Publish […].



Make sure the publish configuration is set to Debug so that you can attach the debugger to your web application.



Once your web application is published, open the Server Explorer pane in Visual Studio and navigate to your web application under Azure > App Service. Right-click on the web application’s entry and choose Attach Debugger, then set a breakpoint in the WebHook handler.



Now go back into the CRM application and activate your workflow. Next, create and save a new account in CRM. After a few seconds, the breakpoint in the WebHookHandler subclass in your web application should be hit, showing the data from the new account. This means that the event was successfully sent to the web application.






We look forward to seeing what you’ll do with WebHooks and Microsoft Dynamics CRM.

Cheers,

Andrew Shen




Источник: http://blogs.msdn.com/b/crm/archive/...amics-crm.aspx
__________________
Расскажите о новых и интересных блогах по Microsoft Dynamics, напишите личное сообщение администратору.
 

Похожие темы
Тема Автор Раздел Ответов Посл. сообщение
crminthefield: Podcast and Overview: Microsoft Dynamics CRM 2011 Update Rollup 16 Blog bot Dynamics CRM: Blogs 0 23.01.2014 03:15
Microsoft Dynamics CRM Team Blog: December Updates for CRM Customer Center, Implementation Guide and Software Development Kit (SDK) Blog bot Dynamics CRM: Blogs 0 19.12.2013 03:14
Microsoft Dynamics CRM Team Blog: Fast, Efficient Growth for Project Management Solution - Case Studies Blog bot Dynamics CRM: Blogs 0 01.02.2012 03:18
Microsoft Dynamics CRM Team Blog: Update Rollup 5 for Microsoft Dynamics CRM 2011 Blog bot Dynamics CRM: Blogs 2 27.10.2011 17:11
Microsoft Dynamics CRM Team Blog: List Web Part for Microsoft Dynamics CRM 4.0 Deployment Scenarios Blog bot Dynamics CRM: Blogs 0 30.01.2009 22:05

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход

Рейтинг@Mail.ru
Часовой пояс GMT +3, время: 13:36.
Powered by vBulletin® v3.8.5. Перевод: zCarot
Контактная информация, Реклама.