Using WebClient to call external service from CRM Online Sandboxed Plugin (HTTP POST and JSON)

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 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)
 // 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 = "" + code;

 // upload the data using Post mehtod
 string response = webClient.UploadString(serviceUrl, jsonObject);
 catch (Exception ex)
 throw new InvalidPluginExecutionException(ex.Message);

Hope it helps..

Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

Share your thoughts

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s