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.
</p>
<p>using Microsoft.Xrm.Sdk;<br />
using System;<br />
using System.IO;<br />
using System.Net;<br />
using System.Runtime.Serialization.Json;<br />
using System.Text;</p>
<p>namespace MyTestPlugin<br />
{</p>
<p> public class Lead<br />
{<br />
public string Topic { get; set; }<br />
public string FullName { get; set; }<br />
public string Email { get; set; }<br />
}</p>
<p> public class MyPluginClass : IPlugin<br />
{<br />
public void Execute(IServiceProvider serviceProvider)<br />
{<br />
try<br />
{<br />
// Obtain the execution context from the service provider.<br />
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));</p>
<p> // The InputParameters collection contains all the data passed in the message request.<br />
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)<br />
{<br />
// Obtain the target entity from the input parameters.<br />
Entity entity = (Entity)context.InputParameters["Target"];</p>
<p> using (WebClient client = new WebClient())<br />
{<br />
var myLead = new Lead();<br />
myLead.Topic = entity.Attributes["subject"].ToString();<br />
myLead.FullName = entity.Attributes["fullname"].ToString();<br />
myLead.Email = entity.Attributes["emailaddress1"].ToString();</p>
<p> DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Lead));<br />
MemoryStream memoryStream = new MemoryStream();<br />
serializer.WriteObject(memoryStream, myLead);<br />
var jsonObject = Encoding.Default.GetString(memoryStream.ToArray());</p>
<p> var webClient = new WebClient();<br />
webClient.Headers[HttpRequestHeader.ContentType] = "application/json";<br />
var code = "key";<br />
var serviceUrl = "https://xyz.azurewebsites.net/api/mylead?code=" + code;</p>
<p> // upload the data using Post mehtod<br />
string response = webClient.UploadString(serviceUrl, jsonObject);<br />
}<br />
}<br />
}<br />
catch (Exception ex)<br />
{<br />
throw new InvalidPluginExecutionException(ex.Message);<br />
}<br />
}<br />
}<br />
}<br />
Hope it helps..























