Thursday, March 19, 2015

Reading URL in x++ code through a proxy

The case was simple enough: For all items, attach any and all drawings that are available in the online repository to the item's attached documents.

I could google an example of using the .NET webrequest to retrieve the content (and validity) of a URL. All went well and smooth until I ran the code from a different PC, that was connected to the web through a proxy.

Setting the proxy on the webrequest turned out to be a bit of undocumented trial and error. All I could find on the net were C# and VB examples that didn't seem to be close tot the correct calls in x++.
So without further ado, here is some basic code to test the validity of a URL and more importantly... set your proxy in AX.
static void TestURL(Args _args)
{    // REF https://msdn.microsoft.com/en-us/library/456dfw4f(v=vs.110).aspx

    System.Net.WebRequest      webReq;
    System.Net.WebResponse     webRes;

    ProxyIPAddress             address = "10.170.16.160";
    ProxyPortNum               port = 8080;
    System.Net.WebProxy        proxy = new System.Net.WebProxy(address, port);



    URL                        url = "https://msdn.microsoft.com";
    //URL url = "https://msdn.microsoft.baloney";

    url = System.Web.HttpUtility::UrlPathEncode(url);
    webReq = System.Net.WebRequest::Create(url);
    webReq.set_Proxy(proxy);

    try
    {
        webRes = webReq.GetResponse();
        info("URL exists");
        webRes.Close();
    }
    catch
    {
        info("URL does not exist.");
    }
}



And that's how you set the proxy from x++.
Consider that you might need to set the proxy regardless of your Windows/browser settings. That's just the way things are.

So if you ever need to set your webrequest, then this is a proxy mately how to do it.











No comments:

Post a Comment