Sunday, 22 December 2013

Get distance between two points using Google API

The following code uses Google API to get distance between two latitude/longitudes.

 static void getGoogleDistance(Args _args)  
 {  
   System.Net.HttpWebRequest  request = null;  
   System.Net.HttpWebResponse response = null;  
   System.IO.Stream      stream = null;  
   System.IO.StreamReader   streamReader = null;  
     
   LogisticsAddressLatitude  fromLatitude, toLatitude;  
   LogisticsAddressLongitude  fromLongitude, toLongitude;  
   
   CLRObject          clro = null;  
   
   real            distance;  
   str             baseUrl, url, xml, disStr;  
   
   XmlDocument         xmlDoc;  
   XmlNodeList         xmlNodes;  
   XmlNode           xmlNode;  
   
   baseUrl = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=%1,%2&destinations=%3,%4&mode=Car&language=gb-en&sensor=false&units=imperial";  
   new InteropPermission(InteropKind::ClrInterop).assert();  
     
   // London  
   fromLatitude = 51.5072;  
   fromLongitude = -0.1275;  
     
   // Manchester  
   toLatitude = 53.4667;  
   toLongitude = -2.2333;  
   
   try  
   {  
     distance = 0;  
   
     url = strFmt(baseUrl, fromLatitude, fromLongitude, toLatitude, toLongitude);  
   
     clro = System.Net.WebRequest::Create(url);  
     request = clro;  
     response = request.GetResponse();  
   
     stream = response.GetResponseStream();  
     streamReader = new System.IO.StreamReader(stream);  
     xml = streamReader.ReadToEnd();  
   
     xmlDoc = XmlDocument::newXml(xml);  
     xmlNodes = xmlDoc.selectNodes('//DistanceMatrixResponse//row//element//distance//text');  
     xmlNode = xmlNodes.nextNode();  
     disStr = strRem(xmlNode.innerText(), ' mi');  
   
     if(disStr != '')  
     {  
       distance = str2num(disStr);  
     }  
   }  
   catch  
   {  
     Global::exceptionTextFallThrough();  
   }  
   CodeAccessPermission::revertAssert();  
   
   info(strFmt('Distance: %1', distance));  
 }  

This posting is provided "AS IS" with no warranties. Use code at your own risk.

Error while printing a report in Dynamics AX

Last week some of the users reported that they are printing invoices directly to the printer but nothing is being printed. We tried printing the invoice to the screen and got the following error.

An item with the same key has already been added.

The error was only on one of our report servers. Restarting the report server service fixed the issue.

This posting is provided "AS IS" with no warranties. Use code at your own risk.

Saturday, 21 December 2013

Effect of Security Policy Change on application pool in IIS

Last week one of our internal application hosted on IIS and communicating with AX through BC.NET stopped working suddenly. The person responsible for looking after the application suspected it was integration with AX that was causing the issue. We started looking into it and soon realised that it was not an AX issue. The application pool started fine but as soon as we accessed the application in a browser the application pool stopped. In the windows event log on the server hosting IIS we found the following entries

Error:
The identity of application pool WhouseAppPool is invalid. The user name or password that is specified for the identity may be incorrect, or the user may not have batch logon rights. If the identity is not corrected, the application pool will be disabled when the application pool receives its first request.  If batch logon rights are causing the problem, the identity in the IIS configuration store must be changed after rights have been granted before Windows Process Activation Service (WAS) can retry the logon. If the identity remains invalid after the first request for the application pool is processed, the application pool will be disabled. The data field contains the error number.

Warnings:
Application pool WhouseAppPool has been disabled. Windows Process Activation Service (WAS) did not create a worker process to serve the application pool because the application pool identity is invalid.

Application pool WhouseAppPool has been disabled. Windows Process Activation Service (WAS) encountered a failure when it started a worker process to serve the application pool.

The error message provided us with the hint. The password under which the pool is running was correct and was not expired. Then we checked for "batch logon rights" as mentioned in the error. This can be checked from

Control Panel\All Control Panel Items\Administrative Tools\Local Security Policy


Usually this policy is configured locally and the IIS_ISURS group is added to the policy. In our case the policy was overridden from the domain due to an admin error. Correcting the error removed the overriding policy and restored local configuration for the policy. This is how it usually looks like


After this change the site started working.

This posting is provided "AS IS" with no warranties. Use code at your own risk.

Friday, 6 September 2013

Export all shared projects

Following code exports all projects in the Shared node. For each run it creates a new folder and then the projects are individually exported to xpo.

static void ExportAllProjects(Args _args)  
{  
 ProjectNode      sharedProject = Infolog.projectRootNode().AOTfindChild("Shared");  
 TreeNodeIterator   treeIterator;  
 TreeNode        childNode;  
 str           folderPath = @"C:\\AXProjects\\";  
 str           folderName;  
 System.DateTime    dateTime = DateTimeUtil::newDateTime(systemDateGet(), timeNow());  

 void exportProject(TreeNode _projectNode)  
 {  
  FileIoPermission   perm;  
  str           exportFileName;  

  if(_projectNode != null)  
  {  
   exportFileName = folderPath + folderName + "\\" + _projectNode.AOTname() + ".xpo";  
   perm = new FileIoPermission(exportFileName, "W");  
   perm.assert();  
   _projectNode.treeNodeExport(exportFileName);  
   CodeAccessPermission::revertAssert();  
  }  
 }  

 folderName = dateTime.ToString("yyyyMMdd_HHmmss");  

 if(sharedProject)  
 {  
  treeIterator = sharedProject.AOTiterator();  

  if(treeIterator)  
  {  
   if(!WinAPI::pathExists(folderPath + folderName))  
   {  
    info(strFmt('Creating the folder %1', folderPath + folderName));  
    WinAPI::createDirectoryPath(folderPath + folderName);  
   }  

   childNode = treeIterator.next();  
   while (childNode)  
   {  
    info(strFmt('Exporting %1', childNode.AOTname()));  
    exportProject(childNode);  

    childNode = treeIterator.next();  
   }  
  }  

  sharedProject.treeNodeRelease();  
 }  
}  

This posting is provided "AS IS" with no warranties. Use code at your own risk.

Monday, 26 August 2013

Model store deployment using batch files

One important step of AX development is deploying code to production. In AX2012 it is recommended by Microsoft to do so by import of model store. The frequency of this task varies from customer to customer. As we use agile development methodology in our organisation so we deploy code to production frequently.

The deployment cycle is weekly/bi-weekly depending on the requirement/urgency/severity of any bugs discovered and fixed etc. With this frequency we decided to semi-automate the process so that the person performing the task don't have to manually issue the commands and make the whole process smooth. Link to the scripts are at the end of the post.

The folder contains the following files


The process consists of 7 steps, two configuration files and two folders containing utility batch files. Lets look at them one by one.

AOSClientRegFiles:
The folder contains the following windows registry files

The first file changes the AOS configuration to a configuration named "Maintenance" and second one changes back to Original. The next two files do the same thing for the client configuration. This is done by merging these files in windows registry. Step 3 & 5 use these files.

StartStopBatch:
This folder contains the files that either starts or stops a windows service on a server remotely.

Step 1 & 6 uses these files.

cAOSServerConfig.txt:
This file contain the details of the services that needs to be stopped/started as part of the import process. The file format is

 1:AX6AOS1:AOS60$01  
 2:AX6AOS2:AOS60$01  
 3:AX6AOS3:AOS60$01  

Each server is on a new line. The file uses : as delimiter. The first field is used for ordering only. The second field is Server Name and the third is Service Name. These don't need to be AOS services only. In fact any service can be stopped/started.

cImportExportConfig.txt:
This file contains the settings for the import process. The contents of these files are

 AOSNAME:AxTest  
 DATABASESERVER:SQL2008\SQL2008  
 DATABASENAME:AxaptaDB  
 IMPORTMODELSTOREFILENAME:AX6AOS01.axmodelstore  
 EXPORTMODELSTOREFILENAME1:AX6AOS1_AxTest  
 EXPORTMODELSTOREFILENAME2:.axmodelstore  
 TEMPSCHEMANAME:AXTempSchema  

Step 0 & 2 uses this file.

Step 0:
This step import the model store in a temporary schema. The reason this step is zero is that it can be performed before the actual import task is carried out. The script reads the setting file cImportExportConfig, presents the user all the details and asks to enter the choice as shown below


If the user enters 1. The batch file then imports the model store into the temporary schema. A log file is generated in the bin folder of the AOS.

Step 1:
This step stops all the services specified in the file cAOSServerConfig as shown below


The scripts stops each service independently and in parallel. The script stops the service and then waits until the service is stopped after which it displays the confirmation. In above case if 4 is entered, 3 different batch process runs each stopping the individual service.

Step 2:
This step applies the model store to the actual schema and in the process creates a log file in bin folder of the AOS as shown below


Step 3:
This step changes the AOS configuration to maintenance. The same is done for the Client configuration. These configuration should already exist. If the configuration names are different than these can be changed in the files by using notepad.

Step 4:
This step just start the AX Client to perform additional step (like synchronisation, report deployment etc.). These step are not automated but can be done.

Step 5:
 This step changes the AOS and Client configuration back to original.

Step 6:
This step uses the file cAOSServerConfig  and starts the services as shown below.

As with the stop script, this will start the services in parallel and wait for the service to start before displaying the confirmation.

Note: The scripts should be tested in a test environment before using them in production. The user should have all the necessary permission to perform different task remotely on a server.


This posting is provided "AS IS" with no warranties. Use code at your own risk.