Thursday, January 14, 2016

AX2009 Call Webservice from X++

As we know AX2009 does not allow for consuming web-services as AX2012 does, so to call the web-service you either need to build a separate windows service that calls the web service and update the AX tables via the AX Connector or use the .NET Classes to call the web service

I have recently discovered a method of consuming a web-service directly out of AX2009 X++ code.

for this instance I used the google maps API where I provide two coordinate points and the google maps API will give me the distance back.


static void googleAPITest(Args _args)
{
    System.Net.WebRequest request;
    System.Net.WebResponse response;
    str origin, destination, url, content, status, distance;
    System.IO.StreamReader reader;
   
    System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
    System.Xml.XmlNodeList xnListStatus, xnList;
    System.Xml.XmlNode xnNode;
    ;

    //-33.914561, 18.421480
    origin = strFmt("%1, %2", '-33.914561', '18.421480');
    //-33.971872, 18.580566
    destination = strFmt("%1, %2", '-33.971872', '18.580566');

    url = "http://maps.googleapis.com/maps/api/directions/xml?origin=" + origin + "&destination=" + destination + "&sensor=false";
    content = "";

    try
    {
        request = System.Net.WebRequest::Create(url);
        response = request.GetResponse();

        reader = new System.IO.StreamReader(response.GetResponseStream());
        content = reader.ReadToEnd();

        xmlDoc.LoadXml(content);
        xnListStatus = xmlDoc.SelectNodes("/DirectionsResponse/status");
        xnNode = xnListStatus.Item(0);
        status = xnNode.get_InnerText();

        if (status == "OK")
        {
            xnList = xmlDoc.SelectNodes("/DirectionsResponse/route/leg/distance/text");
            xnNode = xnList.Item(0);
            distance = xnNode.get_InnerText();
            status = "OK";
        }
        else
        {
            distance = '-1';
            status = "ZERO_RESULTS";
        }
    }
    catch
    {
        distance = '-1';
        status = "NO_RESPONSE";
    }
   
    info(StrFmt('The distance between the 2 points is: %1 and the status is: %2', distance, status));

}

No comments:

Post a Comment