› Dynamics 365, Enterprise › How to call a Web Service from Plugin in Dynamics CRM

How to call a Web Service from Plugin in Dynamics CRM

 Krishna Bhanushali   Leave a comment

Introduction:

In this blog, we will have a look on how a web service can be call from Plugin in Dynamics CRM.

Steps to be followed:

1)     Create an entity “Product Configuration” which consists of 2 fields

  • Key – Name of the Web Service
  • Value – Web Service URL

The basic purpose of this entity is to store the Web Service URL so that we don’t hard code the values in the code.

Web Service URL-

Where WorkOrder -> Controller Name and CreateWorkOrder -> Function Name

2)     Call the below function to call the Web Service. Retrieve Product Configuration function basically retrieves the record from CRM.

private void CallWebService(IPluginExecutionContext context, ITracingService tracer, IOrganizationService service)
        {
            string licenseResposeJSON = string.Empty;
            ////// Retrieve Product Configuration details: URL 
            tracer.Trace("Retrieve Product Configuration details: URL");
            string value = string.Empty;
            value = this.RetrieveProductConfiguration(service);
            tracer.Trace("Downloading the target URI from Product Configuration: " + value);
            if (value != string.Empty)
            {
                try
                {
                    using (WebClientEx client = new WebClientEx())
                    {
                        tracer.Trace("Call Web Service");

                        client.Timeout = 60000;
                        client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
                        licenseResposeJSON = client.UploadString(value.ToString(), "1");
                    }
                    tracer.Trace(licenseResposeJSON);
                   context.OutputParameters["WebServieCall"] = licenseResposeJSON;
                    tracer.Trace("Output Parameter is set: " + licenseResposeJSON);
                }
                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();
                    }

                    if (exception.Status == WebExceptionStatus.Timeout)
                    {
                        throw new InvalidPluginExecutionException(
                            "The timeout elapsed while attempting to issue the request.", exception);
                    }

                    throw new InvalidPluginExecutionException(string.Format(CultureInfo.InvariantCulture, "A Web exception occurred while attempting to issue the request. {0}: {1}", exception.Message, str), exception);
                }
            }

        }

public class WebClientEx : WebClient
        {
            public int Timeout { get; set; }

            protected override WebRequest GetWebRequest(Uri address)
            {
                var request = base.GetWebRequest(address);
                request.Timeout = Timeout;
                return request;
            }
        }

3)  Web Service which calls Create WorkOrder function is given below:

  [HttpPost]
        public async Task CreateWorkOrder([FromBody]string value)
        {
            CRM_DataOperations operations = new CRM_DataOperations();
            OperationResult result = await Task.Run(() => operations.CreateWorkOrder_Daily());
            return Request.CreateResponse(HttpStatusCode.Created, "Message: " + Enum.GetName(result.GetType(), result));
        }

Hope you find this helpful! Thank you.

 


Liked it? Share it.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.