How to – Use 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 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") &amp;&amp; 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..


Advertisements
Advertisement

Author: Nishant Rana

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

5 thoughts on “How to – Use WebClient to call external service from CRM Online Sandboxed Plugin (HTTP POST and JSON)”

  1. HTTP requests being issued in plug-ins reviewed where Keep-Alive is not being set to false. Keep-Alive set to true in the HTTP request header can cause delays upwards of 20+ seconds that is sporadic, especially within Microsoft Dynamics 365/CRM Online.

    To set KeepAlive to false use an override implementation of the WebClient similar to…

    internal class MyWebClient : WebClient
    {
    // Overrides the GetWebRequest method and sets keep alive to false
    protected override WebRequest GetWebRequest(Uri address)
    {
    HttpWebRequest req = (HttpWebRequest)base.GetWebRequest(address);
    req.KeepAlive = false;

    return req;
    }
    }

    Liked by 1 person

  2. I have try out the sample, but then with a certificate which is embedded in the API request call, but when i do the request from inside a Plugin in CRM 365 then a security exception appair. Then same exception appair when i use an Activity too in a Workflow. I have try many scenario’s but no-one works as the Plugin and Workflows run in a sandbox instance of CRM 365.
    Do you have a solution to solve my problem?

    Like

  3. Hi Nishant ,
    I tried this with late bound crm entity object it gives the following error “The data contract type cannot be serialized in partial trust because the member ‘key’ is not public”.I registered the plugin in sandbox mode.
    How to resolve this?

    Like

    1. Hi Nishant, I’ve followed the webclient method within a plugin which is working really good. Thanks for the example above. But with Web Client, Is there any way we can find the status code of the Post call using Web Client?

      Like

Please share your thoughts

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

My Trial

It is my experience timeline.

Power⚡Thomas

Sharing my knowledge and experience about the Microsoft Power Platform.

Arpit Power Guide

a guide to powering up community

Welcome to the Blog & Website of Paul Andrew

Technical Leadership Centred Around the Microsoft Data Platform

Deriving Dynamics 365

Deriving Solutions and features on Power Platform/Dynamics 365

The CRM Ninja

Thoughts & musings from a Dynamics 365 Ninja!

D CRM Explorer

Learn about Microsoft Dynamics CRM Power Platform customization and implementation and other cool stuffs

Stroke // Jonas Rapp

I know pre-stroke. I will improve who I was.

Power Melange

Power Melange By Shalinee

Clavin's Blog

Power Automate - Power Apps - SharePoint Online - Azure - Nintex - K2 - Artificial Intelligence

Sat Sangha Salon

An Inquiry in Being

The Indoencers

The Influencers & Influences of Indian Music

Monika Halan's blog

Hand's-free money management

D365 Demystified

A closer look at Microsoft Dynamics 365.

Microsoft Mate (msftmate) - Andrew Rogers

Experienced consultant primarily focused on Microsoft Dynamics 365 and the Power Platform

Knowhere365

Specific topics by Django Lohn on the whole Microsoft365 Stack

Manmit Rahevar's Blog

One Stop Destination for Microsoft Technology Solutions

MG

Naturally Curious

Brian Illand

Power Platform and Dynamics 365

Steve Mordue MVP

A Microsoft Business Applications MVP

Subwoofer 101

Bass defines your home theater

SQLTwins by Nakul Vachhrajani

SQL Server tips and experiences dedicated to my twin daughters.

Everything D365

Discovering Azure DevOps and D365 Business Applications

Tech Wizard

Lets do IT Spells

XRM Tricks (Power Platform & Dynamics CRM )

Power Platform & Dynamics CRM

CRM TIPS BY PRM

Mail to crmtipsbyprm@gmail.com for queries and suggestions

nijos.dev

Giving back to the community what I have learned

xrm CRM Dynamics

Dynamics CRM Technical & Functional Info

Dynamics 365 Blogs - Explained in unique way

Sometimes you need to look at things from different perspective.

CRM Keeper

Dynamics 365 Customer Engagement, CRM, Microsoft CRM, Dynamics CRM

EVOLVED365

Step into the world of a Dynamics 365 Consultant

Dianamics PCF Lady

Diana & Dynamics 365 & Power Platform

%d bloggers like this: