Showing posts with label Json. Show all posts
Showing posts with label Json. Show all posts

Tuesday, August 27, 2019

validate UK postcode using a free WebService in x++ Dynamics Ax 2012

in Uk there is this free service http://postcodes.io/ which can be used to validate a uk postcode.

here an example on how to use it in x++ using a Web Service and parse the returned Json

static void JobEF_WebServiceTestInDialog(Args _args)
{
    Dialog dialog;
    DialogField zipCodeField;
    LogisticsAddressZipCodeId postcode;
    str result = '"result":';
    str postcodeServiceUri = 'http://api.postcodes.io/postcodes/%1/validate';
    str values, ret;
    int ptr, len;
    System.Net.WebClient webclient;
    str uri;
    NoYesId validPostCode;
    
    webclient = new System.Net.WebClient();
    
    dialog = new Dialog('Validate UK postcode using Web Service');
    
    zipCodeField = dialog.addField(ExtendedTypeStr(LogisticsAddressZipCodeId));
    
    if (dialog.run())
    {
        postcode = zipCodeField.value();
        if (!postcode)
        {
            warning('please select a post code');
            return;
        }
        
        uri = strfmt(postcodeServiceUri, postcode);
        
        // Get the value from the server given the URL.
        values = webclient.DownloadString(uri);

        // Find the result value from the JSON
        len = strLen(values);
        ptr = strScan(values, result, 1, len);
        ret = subStr(values, ptr + strLen(result), len - ptr - strLen(result));
        validPostCode = ret == 'true';
        
        info(strFmt('"%1" is %2', postcode, validPostCode ? 'a valid postcode' : 'an invalid postcode'));
    }
}

Serialize to json using x++ in Dynamics Ax 2012

here an example how to create from x++ a simple json object.

static void JobEF_ListToJson(Args _args)
{
    int i;
    str myJson;
    System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
    System.Object oVar;
    System.Type listType = System.Type::GetType('System.Collections.ArrayList');
    CLRObject arrayList = System.Activator::CreateInstance(listType);

    new InteropPermission(InteropKind::ClrInterop).assert();
    for( i = 0; i <= 5 ; i++)
    {
        oVar = strFmt('%1 is the value %2', i, DateTimeUtil::utcNow());
        arrayList.Add(oVar);
    }

    myJson = ser.Serialize(arrayList);

    info(myJson);
}