Using WebClient to call external service from CRM Online Sandboxed Plugin (HTTP POST and JSON)
Views (3232)
Sharing a sample code that can be used to send JSON data using POST to an external service inside CRM Online Plugin. As plugin runs in sandbox mode we cannot reference Newtonsoft’s JSON.NET library http://www.newtonsoft.com/json. The other option could be to use ILMerge, which isn’t that elegant.
Here, basically we are passing some information related to lead to an external service on Post Create of it.
using Microsoft.Xrm.Sdk;
using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
namespace MyTestPlugin
{
public class Lead
{
public string Topic { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
}
public class MyPluginClass : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
try
{
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];
using (WebClient client = new WebClient())
{
var myLead = new Lead();
myLead.Topic = entity.Attributes["subject"].ToString();
myLead.FullName = entity.Attributes["fullname"].ToString();
myLead.Email = entity.Attributes["emailaddress1"].ToString();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Lead));
MemoryStream memoryStream = new MemoryStream();
serializer.WriteObject(memoryStream, myLead);
var jsonObject = Encoding.Default.GetString(memoryStream.ToArray());
var webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
var code = "key";
var serviceUrl = "https://xyz.azurewebsites.net/api/mylead?code=" + code;
// upload the data using Post mehtod
string response = webClient.UploadString(serviceUrl, jsonObject);
}
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
}
}
}
Hope it helps..
Filed under: CRM, CRM 2013, CRM 2015, CRM 2016, CRM 2016 Update 1, Dynamics 365, Microsoft Dynamics 365, Microsoft Dynamics CRM Tagged: CRM, CRM 2011, CRM 2016, CRM 2016 Update 1, Dynamics 365, Microsoft Dynamics 365, Microsoft Dynamics CRM
This was originally posted here.

Like
Report
*This post is locked for comments