Jan 4, 2017

Calling third party Web service from Dynamics CRM online plug-in

Just thought of sharing this important code snippet. Please have a closer look at Binding Configuration part which is the essence of the exercise.

public class PostUpdateTransaction : IPlugin
{
  public void Execute(IServiceProvider serviceProvider)
  {
    IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
    IOrganizationService service = (IOrganizationService)serviceFactory.CreateOrganizationService(context.UserId);
    ITracingService tracer = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

    if (context.Depth > 1)
    {
        return;
    }

    try
    {
        BasicHttpBinding myBinding = new BasicHttpBinding();
        myBinding.Name = "BasicHttpBinding_Service";
        myBinding.Security.Mode = BasicHttpSecurityMode.Transport;
        myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
        myBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
        myBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;

        EndpointAddress endPointAddress = new EndpointAddress(@"https://XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.asmx");
        ClassLibrary1.XXXXX.XXXClient serviceClient = new ClassLibrary1.XXXXX.XXXClient(myBinding, endPointAddress);
        string xmlRequest = @"XXX";

        string result = serviceClient.<Method>(xmlRequest);
        XmlDocument resultXML = new XmlDocument();
        resultXML.LoadXml(result);

     }
     catch (Exception ex)
     {
        throw new InvalidPluginExecutionException(ex.Message);
     }
     finally
     {

     }
  }
}

No comments:

Post a Comment