Skip to main content
Dynamics 365 general forum
Suggested answer

Sending SOAP request with CRM data to external Application on CRM Online using CRM Plugin

editSubscribe (0) ShareShare
ReportReport
Posted on by 1,290

Hello All,

So I have created the plugin which triggers and picks up the data in CRM and then it creates a SOAP request which will then send the SOAP request to external URL using Plugin.

The instance of my CRM is online so i can only register this plugin in Sandbox Isolation mode\

I tried this plugin with HttpWebrequest  and when I trigger the plugin it gives me an error saying "The Remote name cannot be resolved 'servername"."

Then i rewrote the plugin using HttpClient and when i trigger the plugin it gives me error while debugging saying "System.Security.SecurityException
  HResult=0x8013150A
  Message=Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."

I am hardstuck on this and would really appreciate any suggestion or help on this.

Attachments
  • Durgesh Profile Picture
    Durgesh 1,290 on at
    RE: Sending SOAP request with CRM data to external Application on CRM Online using CRM Plugin

    Guido,

    I really appreciate your help with this.

    Thank you,

    Durgesh

  • Guido Preite Profile Picture
    Guido Preite 53,919 Super User on at
    RE: Sending SOAP request with CRM data to external Application on CRM Online using CRM Plugin

    if the CRM is online and the integration from CRM to Mule is still working it means that this mule endpoint is public, period.

  • Durgesh Profile Picture
    Durgesh 1,290 on at
    RE: Sending SOAP request with CRM data to external Application on CRM Online using CRM Plugin

    Hey Guido,

    We had an implementation few years back where we are sending some CRM data to Mule using a mule endpoint which was not public. And to this date its still working. And i cant figure out how, if you can also suggest me what else i can check then itll be very appreciated.

    I am trying to replicate the above action but yeah i am still not able to send the request.

    Also does the version of .Net Framework matters? Because the old implementation we did was developed in 4.5.2

    And this new implementation i am working is on 4.6.2 version.

    Thank you,

    Durgesh

  • Guido Preite Profile Picture
    Guido Preite 53,919 Super User on at
    RE: Sending SOAP request with CRM data to external Application on CRM Online using CRM Plugin

    for Online instances the server url must be reachable from public

  • Durgesh Profile Picture
    Durgesh 1,290 on at
    RE: Sending SOAP request with CRM data to external Application on CRM Online using CRM Plugin

    Guido,

    Its reachable within organization network but i don't think this is a public url. Is there any alternative or i can try something?

    Thank you,

    Durgesh

  • Guido Preite Profile Picture
    Guido Preite 53,919 Super User on at
    RE: Sending SOAP request with CRM data to external Application on CRM Online using CRM Plugin

    ask I asked before:

    are you sure the server is public and reachable?

    because in your code you have this line

     var url = "oswdev11/.../WorkflowService.asmx";

    that looks as a local/private endpoint to me

  • Durgesh Profile Picture
    Durgesh 1,290 on at
    RE: Sending SOAP request with CRM data to external Application on CRM Online using CRM Plugin

    Hey Leah,

    Appreciate you responding but my CRM instance is Online. And when i register the plugin i cannot change the Isolation mode from Sandbox to None. :(

    Thank you,

    Durgesh

  • Leah Ju Profile Picture
    Leah Ju Microsoft Employee on at
    RE: Sending SOAP request with CRM data to external Application on CRM Online using CRM Plugin

    Hi Durgesh,

    As per the limitation you cannot debug the plugin using external DLL in sandbox isolation because code run under partial trust when executing under sandbox isolation. I would suggest to debug the plugin into full trust i.e. by selecting "None" in isolation when debugging the plugin.

    You can also refer to the following link:

       

    The issue is that a sandboxed plugin in CRM online cannot access webservices unless they use basic or anonymous authentication.

    You will have to create a proxy webservice in Azure or somewhere else that then calls the other instance of CRM.

  • Durgesh Profile Picture
    Durgesh 1,290 on at
    RE: Sending SOAP request with CRM data to external Application on CRM Online using CRM Plugin

    Hey Guido!  I really appreciate your response below is the code i am using:

    Please note i have tried using HttpWebrequest and also HttpClient

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using System.Threading.Tasks;

    using System.ServiceModel;

    using Microsoft.Xrm.Sdk;

    using System.Net.Http;

    using System.Net;

    using Microsoft.Xrm.Sdk.Query;

    using System.ServiceModel.Description;

    using Microsoft.Xrm.Sdk.Client;

    using Microsoft.Crm.Sdk.Messages;

    using System.Xml;

    using System.Net.Http.Headers;

    using System.IO;

    using System.Xml.Linq;

    namespace IBC.Plugins.InfocusIntegration

    {

       public class AHAIntakeToInfocus : IPlugin

       {

           //public static readonly HttpClient httpClient = new HttpClient();

           public void Execute(IServiceProvider serviceProvider)

           {

               //// Obtain the execution context from the service provider.

               IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

               // Get a reference to the Organization service.

               IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

               IOrganizationService service = factory.CreateOrganizationService(context.UserId);

               // System service can access config and other entities even if calling user do not have sufficient privileges

               IOrganizationService systemService = factory.CreateOrganizationService(null);

               // Initialize plugin trace service

               ITracingService trace = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

               //throw new InvalidPluginExecutionException("PreExecute");

               try

               {

                    if (context.InputParameters != null && context.Depth <= 2)

                   {

                       Entity ahaintakeEntity = (Entity)context.InputParameters["Target"];

                       Entity postIntakeSelection = (Entity)context.PostEntityImages["Image"];

                       var ahaintakestatus = ahaintakeEntity.GetAttributeValue<OptionSetValue>("statuscode").Value;

                       //HttpClient client = new HttpClient();

                       if (ahaintakestatus == 863180000)

                       {

                           string ahaintakeid = ahaintakeEntity.GetAttributeValue<Guid>("intakeid").ToString().ToUpper();

                           string ahaintakename = postIntakeSelection.GetAttributeValue<string>("name");

                           string brokername = postIntakeSelection.GetAttributeValue<EntityReference>("ibc_brokercontact").Name;

                           trace.Trace("Line 44: " + intakename);

                           trace.Trace("Line 45: " + intakeid);

                           trace.Trace("Line 46: " + brokername);

                           var url = "oswdev11/.../WorkflowService.asmx";

                           trace.Trace("Line 51:" +url);

                           //var _action = "tempuri.org/CallWorkflow";

                           //trace.Trace("Line 53:" + _action);

                           //XmlDocument soapEnvelopeDocument = new XmlDocument();

                           string xmlSOAP = "<soapenv:Envelope xmlns:soapenv='www.w3.org/.../><soapenv:Body><ns1:CallWorkflow xmlns:ns1='tempuri.org/'><ns1:stringXml>" +

                                       "<![CDATA[" +

                                       "<ibc_intake1 xmlns:stepwise='http://schemas.stepwise.optum.com/Portal/2.0' stepwise:UserId='********' stepwise:Password='********' stepwise:RequestInputProcessor='Int_SF_AHA_NB_RequestInputProcessor' stepwise:EnableProfiler='false' stepwise:EnableTrace='false'>" +

                                       "<Broker>"+brokername+@"</Broker>" +

                                       "<BrokerId>"+intakeid+@"</BrokerId>" +

                                       "<ibc_name>"+intakename+@"</ibc_name>" +

                                       "</ibc_intake1>" +

                                       "]]>" +

                                       "</ns1:stringXml></ns1:CallWorkflow></soapenv:Body></soapenv:Envelope>";

                           HttpResponseMessage result = PostSOAPRequestAsync(url, xmlSOAP,systemService, trace);

                           trace.Trace("Line 65:" + result);

                           //soapEnvelopeDocument.LoadXml(xmlSOAP);

                           //trace.Trace("Line 65:" + xmlSOAP);

                           //System.Net.WebRequest.DefaultWebProxy.Credentials = System.Net.CredentialCache.DefaultCredentials;

                           //HttpWebRequest webRequest = (HttpWebRequest)CreateWebRequest(url, _action);

                           //webRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;

                           //webRequest.Timeout = System.Threading.Timeout.Infinite;

                           //webRequest.KeepAlive = false;

                           //trace.Trace("Line 67: " + webRequest);

                           //InsertSoapEnvelopeIntoWebRequest(soapEnvelopeDocument, webRequest);

                           //IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);

                           //asyncResult.AsyncWaitHandle.WaitOne();

                           //string soapResult = string.Empty;

                           //using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))

                           //{

                           //    using (var stream = webResponse.GetResponseStream())

                           //    {

                           //        using (var sr = new StreamReader(stream))

                           //        {

                           //            soapResult = sr.ReadToEnd();

                           //            //trace.Trace("Line 62:" + content);

                           //            //throw new InvalidPluginExecutionException(content);

                           //        }

                           //    }

                           //}

                       }

                       // get the response from the completed web request.

                   }

               }

               catch (Exception ex)

               {

                   throw new InvalidPluginExecutionException(ex.Message, ex);

               }

           }

           internal static HttpResponseMessage PostSOAPRequestAsync(string url, string text, IOrganizationService systemService, ITracingService trace)

                   {

               try

               {

                   using (var httpClient = new HttpClient())

                   {

                       var request = new StringContent(text, Encoding.UTF8, "text/xml");

                       trace.Trace("Line 121 " + request.ReadAsStringAsync().Result);

                       //request.Headers.Add("SOAPAction", _action);

                       //var authenticationString = $"{ClientID}:{Secret}";

                       //var byteArray = Convert.ToBase64String(System.Text.ASCIIEncoding.UTF8.GetBytes(authenticationString));

                       //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", byteArray);

                       //request.Content = content;

                       //request.Method = HttpMethod.Post;

                       //request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml; charset=utf-8");

                       var response = httpClient.PostAsync(url, request).Result;

                       return response;

                   }

               }

               catch (Exception ex)

               {

                   throw new InvalidPluginExecutionException(ex.Message);

               }

           }

           private static HttpWebRequest CreateWebRequest(string url, string action)

           {

               HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

               //var ClientID = "******";

               //var Secret = "******";

               //var byteArray = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(ClientID + ":" + Secret));

               webRequest.Headers.Add("SOAPAction", action);

               webRequest.ContentType = "text/xml";

               webRequest.Accept = "text/xml";

               webRequest.Method = "POST";

               //webRequest.Headers.Add("Authorization", "Basic " + byteArray);

               return webRequest;

           }

           private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)

           {

               using (Stream stream = webRequest.GetRequestStream())

               {

                   soapEnvelopeXml.Save(stream);

               }

           }

       }

    }

  • Suggested answer
    Bipin D365 Profile Picture
    Bipin D365 28,934 Super User on at
    RE: Sending SOAP request with CRM data to external Application on CRM Online using CRM Plugin

    Hi,

    Can you compare code with the sample code provided by Microsoft

    github.com/.../WebAccessPlugin

    Also, try adding traces in your code and run directly from UI without profiling the step to see if it works

Helpful resources

Quick Links

New Blog Features Released!

Check out the new community blog features for viewers and authors…

Setting Up Knowledge Sources for Copilot…

Look at how configuring a comprehensive knowledge base is crucial…

Demystifying Copilot with Georg Glantschnig…

Industry experts answer burning questions directly from our amazing Community…

Leaderboard

#1
Andre Arnaud de Calavon Profile Picture

Andre Arnaud de Cal... 283,126 Super User

#2
Martin Dráb Profile Picture

Martin Dráb 222,646 Super User

#3
nmaenpaa Profile Picture

nmaenpaa 101,138

Featured topics

Product updates

Dynamics 365 release plans