Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Dynamics 365 general forum

Plug-In Calling WebService with WebClient

(0) ShareShare
ReportReport
Posted on by

Hi all,

my solution is composed from a custom plug-in and a custom webservice.

The plugin (Async PostOperation) use WebClient class to call an external webService without authentication. This si the code:

localContext.Trace(json);

try
{
    localContext.Trace("Sleep at {0}", DateTime.Now.ToLongTimeString());
    Thread.Sleep(30000);
    localContext.Trace("Wakeup at {0}", DateTime.Now.ToLongTimeString());
    //var permission = new WebPermission(PermissionState.Unrestricted);
    //permission.Demand();
    localContext.Trace("Send to Wrapper");
    using (var wc = new WebClient())
    {
        wc.Headers.Add(HttpRequestHeader.Accept, "application/json");
        wc.Headers.Add(HttpRequestHeader.ContentType, "application/json");
        wc.UploadStringCompleted += wc_UploadStringCompleted;
        string wrapperResponse = string.Empty;
        try
        {
            var uri = new Uri(HttpUrl);
            localContext.Trace(string.Concat("Send to:", uri.ToString()));
            localContext.Trace(string.Concat("Protocol: ", System.Net.ServicePointManager.SecurityProtocol.ToString()));
wc.UploadStringAsync(new Uri(HttpUrl), json); //wrapperResponse = wc.UploadString(new Uri(HttpUrl), json); //_localContext.Trace(string.Concat("Wrapper response: ", wrapperResponse)); } catch (Exception ex) { throw ex; } finally { wc.UploadStringCompleted -= wc_UploadStringCompleted; } } } catch (WebException exception) { string str = string.Empty; if (exception.Response != null) { using (StreamReader reader = new StreamReader(exception.Response.GetResponseStream())) { str = reader.ReadToEnd(); } exception.Response.Close(); } var msg = string.Empty; if (exception.Status == WebExceptionStatus.Timeout) { msg = "The timeout elapsed while attempting to issue the request."; localContext.Trace(msg); throw new InvalidPluginExecutionException(msg, exception); } msg = String.Format(CultureInfo.InvariantCulture, "A Web exception occurred while attempting to issue the request\nException message: {0}\nResponse: {1}\n", exception.Message, str); localContext.Trace(msg); throw new InvalidPluginExecutionException(msg, exception); } catch (Exception ex) { localContext.Trace("Generic Exception"); localContext.Trace(ex.Message); throw new InvalidPluginExecutionException("Generic Exception", ex); } finally { localContext.Trace("Communication to Wrapper finished"); }

I've already deployed my solution on Dynamics 365 Version 1612 (8.2.3.114) and it's working fine.

Now Dynamics has been updated to new version Version 1710 (9.1.0.646) and plugin no longer work.

It's do not release any error, but the webservice is not called.

This is the trace log of plugin:

Entered PostDistributeCampaignActivity.Execute()
Plugin Invoked from 40.85.85.245
Plugin has started
Check which is the status reason:
The status reason code is 6
Get CampaignActivity
Get ChannelType
Check ChannelType
Create body object
Serialize body object
{"ActivityId":"c41bd0db-72f8-e811-a966-000d3ab496c3","FlowType":3}
Sleep at 9:48:23 AM
Wakeup at 9:48:53 AM
Send to Wrapper
Send to:myserver/.../PUBLISH_DISTRIBUTED
Protocol: Ssl3, Tls, Tls11, Tls12
Communication to Wrapper finished
Exiting PostDistributeCampaignActivity.Execute()



So, in production environment, old version of dynamics still exists, and plugin is still working, but in test environment dynamics has besn updated to the new versione and plugin seems to work, but no call comes to webservice.

Any idea?

  • Community Member Profile Picture
    on at
    RE: Plug-In Calling WebService with WebClient

    I've also tried a WebHook; the system job was filed with thi error:

    Plugin Trace:
    
    [Microsoft.Crm.ServiceBus: Microsoft.Crm.ServiceBus.WebhookPlugin]
    [af507f2a-2ff9-e811-a969-000d3ab49476: Distribute Campaign Activity WebHook]
    
    
    
    Error Message:
    
    Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: The webhook call failed during http post. Please check the exception for more details.Detail: 
    <OrganizationServiceFault xmlns:i="www.w3.org/.../XMLSchema-instance" xmlns="schemas.microsoft.com/.../Contracts">
      <ActivityId>a04d707f-c496-41b5-b648-beb92aab9c6c</ActivityId>
      <ErrorCode>-2147155451</ErrorCode>
      <ErrorDetails xmlns:d2p1="schemas.datacontract.org/.../System.Collections.Generic" />
      <Message>The webhook call failed during http post. Please check the exception for more details.</Message>
      <Timestamp>2018-12-06T14:31:05.2167038Z</Timestamp>
      <ExceptionRetriable>false</ExceptionRetriable>
      <ExceptionSource i:nil="true" />
      <InnerFault>
        <ActivityId>a04d707f-c496-41b5-b648-beb92aab9c6c</ActivityId>
        <ErrorCode>-2147220970</ErrorCode>
        <ErrorDetails xmlns:d3p1="schemas.datacontract.org/.../System.Collections.Generic" />
        <Message>Unhandled Exception: System.Net.WebException: Unable to connect to the remote server
       at System.Net.HttpWebRequest.GetRequestStream(TransportContext&amp; context)
       at System.Net.HttpWebRequest.GetRequestStream()
       at Microsoft.Crm.ServiceBus.WebhookClient.PrepareFullHttpRequest(HttpWebRequest baseHttpRequest, WebhookHttpRequestConfig httpConfig, String jsonPayload)
       at Microsoft.Crm.ServiceBus.WebhookClient.&lt;SendAsync&gt;d__20.MoveNext()
    Inner Exception: System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond xxx.xxx.xxx.xxx:80
       at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
       at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket&amp; socket, IPAddress&amp; address, ConnectSocketState state, IAsyncResult asyncResult, Exception&amp; exception)
    </Message>
        <Timestamp>2018-12-06T14:31:05.2167038Z</Timestamp>
        <ExceptionRetriable>false</ExceptionRetriable>
        <ExceptionSource i:nil="true" />
        <InnerFault i:nil="true" />
        <OriginalException i:nil="true" />
        <TraceText i:nil="true" />
      </InnerFault>
      <OriginalException i:nil="true" />
      <TraceText>
    [Microsoft.Crm.ServiceBus: Microsoft.Crm.ServiceBus.WebhookPlugin]
    [af507f2a-2ff9-e811-a969-000d3ab49476: Distribute Campaign Activity WebHook]
    
    </TraceText>
    </OrganizationServiceFault>
    
    
  • Community Member Profile Picture
    on at
    RE: Plug-In Calling WebService with WebClient

    I've tried to delete and rebuild Plugin, with the same step and same post-image. Now I've this error:

    Plugin Trace:
    
    [CRM.Plugin.HU: CRM.Plugin.HU.PostDistributeCampaignActivity]
    [93f62d2f-63f9-e811-a969-000d3ab49476: CRM.Plugin.HU.PostDistributeCampaignActivity: Update of campaignactivity]
    
    
    
    Error Message:
    
    Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
       at System.ComponentModel.Win32Exception.GetObjectData(SerializationInfo info, StreamingContext context)
       at System.Runtime.Serialization.ObjectCloneHelper.GetObjectData(Object serObj, String& typeName, String& assemName, String[]& fieldNames, Object[]& fieldValues)
    
    
       at Microsoft.Crm.Sandbox.SandboxAppDomainHelper.Execute(IOrganizationServiceFactory organizationServiceFactory, Dictionary`2 sandboxServices, String pluginTypeName, String pluginConfiguration, String pluginSecureConfig, IPluginExecutionContext requestContext, Boolean enablePluginStackTrace, Boolean chaosFailAppDomain)
       at Microsoft.Crm.Sandbox.SandboxWorker.Execute(SandboxCallInfo callInfo, SandboxPluginExecutionContext requestContext, Guid pluginAssemblyId, Int32 sourceHash, String assemblyName, Guid pluginTypeId, String pluginTypeName, String pluginConfiguration, String pluginSecureConfig, SandboxRequestCounter& workerCounter, Boolean returnTraceInfo)
    The action that failed was:
    Demand
    The type of the first permission that failed was:
    System.Security.Permissions.SecurityPermission
    The first permission that failed was:
    <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
    version="1"
    Flags="SerializationFormatter"/>
    
    The demand was for:
    <PermissionSet class="System.Security.PermissionSet"
    version="1">
    <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
    version="1"
    Flags="SerializationFormatter"/>
    </PermissionSet>
    
    The granted set of the failing assembly was:
    <PermissionSet class="System.Security.PermissionSet"
    version="1">
    <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
    version="1"
    Flags="Execution"/>
    <IPermission class="System.Net.WebPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
    version="1">
    <ConnectAccess>
    <URI uri="^http[s]?://(?!((localhost[:/])|(\[.*\])|([0-9]+[:/])|(0x[0-9a-f]+[:/])|(((([0-9]+)|(0x[0-9A-F]+))\.){3}(([0-9]+)|(0x[0-9A-F]+))[:/]))).+"/>
    </ConnectAccess>
    </IPermission>
    </PermissionSet>
    
    The assembly or AppDomain that failed was:
    mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #39CB4260Detail: 
    <OrganizationServiceFault xmlns:i="www.w3.org/.../XMLSchema-instance" xmlns="schemas.microsoft.com/.../Contracts">
      <ActivityId>e9205edf-e66b-45f7-b98b-34acdcbd8f59</ActivityId>
      <ErrorCode>-2147220970</ErrorCode>
      <ErrorDetails xmlns:d2p1="schemas.datacontract.org/.../System.Collections.Generic" />
      <Message>System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
       at System.ComponentModel.Win32Exception.GetObjectData(SerializationInfo info, StreamingContext context)
       at System.Runtime.Serialization.ObjectCloneHelper.GetObjectData(Object serObj, String&amp; typeName, String&amp; assemName, String[]&amp; fieldNames, Object[]&amp; fieldValues)
    
    
       at Microsoft.Crm.Sandbox.SandboxAppDomainHelper.Execute(IOrganizationServiceFactory organizationServiceFactory, Dictionary`2 sandboxServices, String pluginTypeName, String pluginConfiguration, String pluginSecureConfig, IPluginExecutionContext requestContext, Boolean enablePluginStackTrace, Boolean chaosFailAppDomain)
       at Microsoft.Crm.Sandbox.SandboxWorker.Execute(SandboxCallInfo callInfo, SandboxPluginExecutionContext requestContext, Guid pluginAssemblyId, Int32 sourceHash, String assemblyName, Guid pluginTypeId, String pluginTypeName, String pluginConfiguration, String pluginSecureConfig, SandboxRequestCounter&amp; workerCounter, Boolean returnTraceInfo)
    The action that failed was:
    Demand
    The type of the first permission that failed was:
    System.Security.Permissions.SecurityPermission
    The first permission that failed was:
    &lt;IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
    version="1"
    Flags="SerializationFormatter"/&gt;
    
    The demand was for:
    &lt;PermissionSet class="System.Security.PermissionSet"
    version="1"&gt;
    &lt;IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
    version="1"
    Flags="SerializationFormatter"/&gt;
    &lt;/PermissionSet&gt;
    
    The granted set of the failing assembly was:
    &lt;PermissionSet class="System.Security.PermissionSet"
    version="1"&gt;
    &lt;IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
    version="1"
    Flags="Execution"/&gt;
    &lt;IPermission class="System.Net.WebPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
    version="1"&gt;
    &lt;ConnectAccess&gt;
    &lt;URI uri="^http[s]?://(?!((localhost[:/])|(\[.*\])|([0-9]+[:/])|(0x[0-9a-f]+[:/])|(((([0-9]+)|(0x[0-9A-F]+))\.){3}(([0-9]+)|(0x[0-9A-F]+))[:/]))).+"/&gt;
    &lt;/ConnectAccess&gt;
    &lt;/IPermission&gt;
    &lt;/PermissionSet&gt;
    
    The assembly or AppDomain that failed was:
    mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #39CB4260</Message>
      <Timestamp>2018-12-06T14:31:37.7538529Z</Timestamp>
      <ExceptionRetriable>false</ExceptionRetriable>
      <ExceptionSource>PluginExecution</ExceptionSource>
      <InnerFault i:nil="true" />
      <OriginalException>System.Security.SecurityException
       at System.ComponentModel.Win32Exception.GetObjectData(SerializationInfo info, StreamingContext context)
       at System.Runtime.Serialization.ObjectCloneHelper.GetObjectData(Object serObj, String&amp; typeName, String&amp; assemName, String[]&amp; fieldNames, Object[]&amp; fieldValues)
    
    
       at Microsoft.Crm.Sandbox.SandboxAppDomainHelper.Execute(IOrganizationServiceFactory organizationServiceFactory, Dictionary`2 sandboxServices, String pluginTypeName, String pluginConfiguration, String pluginSecureConfig, IPluginExecutionContext requestContext, Boolean enablePluginStackTrace, Boolean chaosFailAppDomain)
       at Microsoft.Crm.Sandbox.SandboxWorker.Execute(SandboxCallInfo callInfo, SandboxPluginExecutionContext requestContext, Guid pluginAssemblyId, Int32 sourceHash, String assemblyName, Guid pluginTypeId, String pluginTypeName, String pluginConfiguration, String pluginSecureConfig, SandboxRequestCounter&amp; workerCounter, Boolean returnTraceInfo)</OriginalException>
      <TraceText>
    [CRM.Plugin.HU: CRM.Plugin.HU.PostDistributeCampaignActivity]
    [93f62d2f-63f9-e811-a969-000d3ab49476: CRM.Plugin.HU.PostDistributeCampaignActivity: Update of campaignactivity]
    
    </TraceText>
    </OrganizationServiceFault>
    
    
  • Community Member Profile Picture
    on at
    RE: Plug-In Calling WebService with WebClient

    Hi @Andrew Butenko, I use standard port 80, and the service has not authentication

    Hi @LeoAlt, the communication starts from server and goes to client, your note for communication limitation concerns the opposit.

    Anyway, I will follow the advice for WebHooks, it's seems good.

    Thanks for all

  • LeoAlt Profile Picture
    16,331 Moderator on at
    RE: Plug-In Calling WebService with WebClient

    Hi Glucolo,

    According to "What's new for developers in D365 v9" ,we know that Microsoft has limited the API requeset.

    WeChat-Screenshot_5F00_20181206104708.png

    You could also try WebHooks suggested by Microsoft to interact with external webService.

    WeChat-Screenshot_5F00_20181206104708.png

    Hope it helps.

    Best Regards

    Leo

  • a33ik Profile Picture
    84,331 Most Valuable Professional on at
    RE: Plug-In Calling WebService with WebClient

    Hello,

    Do you use 80/443 port or some custom?

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

November Spotlight Star - Khushbu Rajvi

Congratulations to a top community star!

Forum Structure Changes Coming on 11/8!

In our never-ending quest to help the Dynamics 365 Community members get answers faster …

Dynamics 365 Community Platform update – Oct 28

Welcome to the next edition of the Community Platform Update. This is a status …

Leaderboard > Dynamics 365 general forum

Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans