Friday 23 May 2014

Calling an External Web Service from X++ AX 2012

If you want to call an external web service from AX 2012, then you have to do these two tasks:


1) Create the service reference in Visual studio.
2) Calling the Service from AX.


Creating a Service in VS:



  • Open Visual Studio 2010 and create a new Visual C# Class Library project. Name the project as WeatherTest.
  • In the Solution Explorer window, right-click the project name and then click Add Service Reference.
  • Type the URL for the web service in the Address field. Here, we are using a test service: http://www.webservicex.net/globalweather.asmx?WSDL
  • We are naming this service reference to ServiceReferenceName
  • Click Go to locate the service and then click Ok.
  • Add this solution to the AOT by using the Visual Studio Tools for Microsoft Dynamics AX 2012. The WeatherTest Project will start appearing in the AOT under the node Visual Studio Projects --> C Sharp Projects.

      
Calling the Service from AX:

Create a new job and paste the following code in it. The following example demonstrates how to call the web service. We are calling service’s GetWeather method by passing the parameters Karachi and Pakistan. It returns the weather details XML for the supplied parameters.


static void Job_CallWeatherService(Args _args)
{   
ClrObject clientType;
WeatherTest.ServiceReferenceName.GlobalWeatherSoapClient _client;
str ResultSet;   
System.Exception ex;
    try
   {
  //Construct and configure the service client by retrieving the X++ type for the service and                   //using the AifUtil class Retrieve the X++ type for the service client object.
   clientType = CLRInterop::getType("WeatherTest.ServiceReferenceName.GlobalWeatherSoapClient");
       // Use the AifUtil class to create an instance of the service client object.
       _client = AifUtil::CreateServiceClient(clientType);
       ResultSet = _client.GetWeather('karachi','Pakistan');
       info(ResultSet);
   }
   catch(Exception::CLRError)
   {
     ex = CLRInterop::getLastException();
     info(ex.ToString());
   }
}




Note: When writing this code in any class, it should be considered that "the Code that consumes a Web service must run on the server. Otherwise you will receive an error."