Thursday, July 28, 2016

AX 2009/2012 FTP operations

Here is a class that I wrote to perform operations via FTP file transfer

There is an interface to:
  • Upload a file
  • Upload text as a file
  • Rename file
  • Delete file
  • Get a list of files from an FTP server
  • Download file
The class is tested to work on the client and on the server (batch)

Everything is based on the .NET class FtpWebRequest




HOW TO USE


Lud_FtpClient ftpClient = Lud_FtpClient::construct("FTP URL", "user", "pwd");
;
ftpClient.uploadText("text you want to upload", "FC/test.txt");

ftpClient.uploadFile(@"c:\IFRToolLog.txt", "FC/IFRToolLog.txt");

ftpClient.getFileList("", "xml");

ftpClient.downloadFile("/assets/ISB_PAGE 36.pdf", @"\\192.168.100.44\temp\test.pdf");

ftpClient.deleteFile("/images.jpg");

Code sample:

void downloadFile(str fileUrl, str destination)
{
    System.Object               ftpo;
    System.Object               ftpResponse;
    System.Net.FtpWebRequest    request;
    System.IO.Stream            responseStream;
    System.IO.StreamReader      reader;
    System.IO.FileStream        writeStream;

    System.String               xmlContent;
    System.Net.FtpWebResponse   response;

    System.Byte[]               buffer;
    int                         bufferLenght = 2048;
    int                         bytesRead;
    ;

    new InteropPermission(InteropKind::ClrInterop).assert();

    try
    {
        ftpo = System.Net.WebRequest::Create("ftp://" + ftpUrl + (strEndsWith(ftpUrl, "/") ? fileUrl : "/" + fileUrl));
        request = ftpo;

        // se vengono fatte chiamate consecutive ricreando sempre le credential ogni tanto va in errore (Bad request)
        // per evitare il problema keepAlive = false, ma così va più lento. Con questo hack se la classe non viene ricreata
        // ogni volta dovrebbe andare meglio
        if(!credential)
        {
            credential = new System.Net.NetworkCredential(username, password);
            request.set_Credentials(credential);
            request.set_KeepAlive(false);
        }
        else
        {
            request.set_Credentials(credential);
            request.set_KeepAlive(true);
        }

        request.set_Method("RETR");
        // "Bypass" a HTTP Proxy (FTP transfer through a proxy causes an exception)
        request.set_Proxy( System.Net.GlobalProxySelection::GetEmptyWebProxy() );
        ftpResponse = request.GetResponse();
        response = ftpResponse;
        responseStream = response.GetResponseStream();

        buffer = new System.Byte[bufferLenght]();
        writeStream = new System.IO.FileStream(destination, System.IO.FileMode::Create);
        bytesRead = responseStream.Read(buffer, 0, bufferLenght);

        while (bytesRead > 0)
        {
            writeStream.Write(buffer, 0, bytesRead);
            bytesRead = responseStream.Read(buffer, 0, bufferLenght);
        }
        writeStream.Close();

        response.Close();

    }
    catch(Exception::CLRError)
    {
        throw error(this.getClrErrorMessage());
    }

    CodeAccessPermission::revertAssert();
}

Tuesday, December 15, 2015

JQuery Tag plugin compatible with Twitter Typeahead, TypeTags

Hi guys, here it is a simple tag manager for JQuery that work nicely with twitter typeahead.

I tried a lot of plugin out there, but no one would work exactly as I wanted, so I had to do it by myself.

The plugin is pretty simple, with just a few of functions and 2Kb minified.

You can find an example here:





The plugin is pretty simple:

HTML MARKUP:

 <input id="tag-input" type="text" value=""/>  
 <div id="tag-list"></div>  
 <input type="hidden" id="tag-hidden" value="one tag,another tag" /> 

SCRIPT INITIALIZATION:

 $("#tag-input").typeTags({  
  containerSelector: "#tag-list",
  hiddenSelector: "#tag-hidden"  
 });  

If you want to use that with twitter typeahead (tested with twitter typeahead 0.11.1) just bind typeahead before the typeTags plugin initialization.

Every tag that is entered will be put in the specified HiddenField to be able to post the values.



PLUGIN OPTIONS

 $("#tag-input").typeTags({  
  containerSelector: "#tag-list",     // the container where the tags will be added
  hiddenSelector: "#tag-hidden",      // the hidden field where to put the tags (optional)
  delimiters: [9, 13, 44],            // delimeters key to enter tags, default to TAB, ENTER, COMMA
  deleteOnBackspace: true             // delete tag on backspace
 });  


EVENTS

There's only one event, invoked on tag add

  $("#tag-input").typeTags({options}).on('tt:added', function (e, tag_txt, tag_node, suggestion) {   
      tag_node.addClass("new class");       
     });   

The parameters that you get on this event are:

  • tag_txt (the text entered)
  • tag_node (the jquery node added, you can manipulate it here like in the sample)
  • suggestion (the twitter typeahead suggestion object, if the tag was entered clicking on a twitter typeahead node. Here you have all custom parameters that could have been sent from a remote ajax call or whatever)
PUBLIC METHODS
  • clear  (Clears all the tags)
  • pushTag (add a tag to the list)
 $('#tag-input').data('typeTags').pushTag('third tag');  



Complete example markup


 <html>  
 <head>  
 <link href="style.css" rel="stylesheet" />  
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
 </head>  
 <body>  
      <input type="hidden" id="tag-hidden" value="one tag,another tag" />    
      <div id="tag-list"></div>  
      <input id="tag-input" type="text" value="" class="form-control" />  
 <script src="type-tags.js"></script>  
 <script>          
      // init typeahead here!
      // .........

      // plugin initialization
      $("#tag-input").typeTags(  
      {  
           hiddenSelector: "#tag-hidden",          
           containerSelector: "#tag-list"                 
      }).on('tt:added', function (e, tagTxt, tagNode, sugg) {  
           console.log(tagTxt);  
      });  
      // example method  
      $('#tag-input').data('typeTags').pushTag('third tag');  
 </script>  
 </body>  
 </html>  




Friday, November 20, 2015

Dynamics AX, How to post an invoice / packing slip / confirm for multiple orders

Here is the code to post multiple orders invoices or packing slip at once.

If you want to post only a subset of the quantities of each row just change the deliverNow/invoiceNow field of the salesId and set the proper specQty enum value

   SalesFormLetter salesFormLetter;  
   QueryRun queryRun;  
   Query query;  
   ;  
   ttsbegin;  

   salesFormLetter = SalesFormLetter::construct(DocumentStatus::PackingSlip);  
   salesFormLetter.transDate(systemdateget());  
   salesFormLetter.specQty(SalesUpdate::All);  
   salesFormLetter.printFormLetter(false);  
   salesFormLetter.createParmUpdate(false);  
   salesFormLetter.sumBy(AccountOrder::Account);  

   query = new Query(QueryStr(SalesUpdate));  
   query.dataSourceTable(tablenum(SalesTable)).addRange(fieldnum(SalesTable, SalesId));  
   queryRun = new QueryRun(query);  
   salesFormLetter.chooseLinesQuery(queryRun);  

   queryRun.query().dataSourceTable(tablenum(SalesTable)).findRange(fieldnum(SalesTable, SalesId)).value('A15000438');  
   salesFormLetter.chooseLines(null, true);  

   queryRun.query().dataSourceTable(tablenum(SalesTable)).findRange(fieldnum(SalesTable, SalesId)).value('A15000439');  
   salesFormLetter.chooseLines(null, true);  

   // insert here other orders  
   // ...  

   salesFormLetter.reArrangeNow(true);  
   salesFormLetter.run();  

   ttscommit;  

Friday, August 29, 2014

Read an XML file in AX with namespaces

If you have to read an XML file containing namespaces you have to use the class XmlNamespaceManager.

So, to read this sample XML, that contain 4 namespaces:

<?xml version="1.0" encoding="utf-8"?>
<ns1:Structure xmlns:ns1="http://www.influe.com/xns/2000/xmlfile/deffile/definition" 
               xmlns:gr="http://www.influe.com/xns/2000/xmlfile/deffile/groupe" 
               xmlns:li="http://www.influe.com/xns/2000/xmlfile/deffile/line" 
               xmlns:zn="http://www.influe.com/xns/2000/xmlfile/deffile/zone">
  <gr:MESSAGE>
    <li:TESTATA>
      <zn:TIPO_RECORD_EN>EN</zn:TIPO_RECORD_EN>
      <zn:MITTENTE_MESSAGGIO>4324234</zn:MITTENTE_MESSAGGIO>
 </li:TESTATA>
 <gr:group1>
      <li:GERARCHIA>
  <zn:NUMERO_DESADV_HE>DDT1</zn:NUMERO_DESADV_HE>
   </li:GERARCHIA>
 </gr:group1>
 <gr:group1>
      <li:GERARCHIA>
  <zn:NUMERO_DESADV_HE>DDT2</zn:NUMERO_DESADV_HE>
   </li:GERARCHIA>
 </gr:group1>
 <gr:group1>
      <li:GERARCHIA>
  <zn:NUMERO_DESADV_HE>DDT3</zn:NUMERO_DESADV_HE>
   </li:GERARCHIA>
 </gr:group1> 
  </gr:MESSAGE>
</ns1:Structure>

You can proceed like that:

static void Job92(Args _args)
{
    XmlDocument xmlDoc = XmlDocument::newFile(@"YOURPATH\file.xml");
    XmlNamespaceManager nmgr = new XmlNamespaceManager(new XmlNameTable());
    XmlNode node;
    XmlNodeList nodeList;
    ;
    
    nmgr.addNamespace("ns1", "http://www.influe.com/xns/2000/xmlfile/deffile/definition");
    nmgr.addNamespace("li", "http://www.influe.com/xns/2000/xmlfile/deffile/line");
    nmgr.addNamespace("gr", "http://www.influe.com/xns/2000/xmlfile/deffile/groupe");
    nmgr.addNamespace("zn", "http://www.influe.com/xns/2000/xmlfile/deffile/zone");
    
    // nodo TESTATA
    node = xmldoc.selectSingleNode("//li:TESTATA", nmgr);
    
    infO(node.xml());
    
    // lista group1
    nodeList = xmldoc.selectNodes("//gr:group1");
    
    while(true)
    {
        node = nodeList.nextNode();
        if(node == null)
            break;
            
        // esempio lettura elemento all"interno di group1
        node = node.selectSingleNode("li:GERARCHIA/zn:NUMERO_DESADV_HE", nmgr);
        info(node.text());
    }
}

Tuesday, July 01, 2014

AX separated instances on Windows taskbar

This one is a little trick that I find very useful.

If you have to work with multiple AX instances, you will surely get annoyed by the way windows group the icons on the taskbar.

Multiple instances of the same program are not grouped separately, thus it get very hard to switch between a window or another.


Having separated AX instances on the taskbar is much better, imho


To accomplish that you have to create an hard link to the AX32 executable on the filesystem, like that:
  1. Open command prompt (CMD.exe)
  2. Go to the AX installation folder (usally C:\Program Files (x86)\Microsoft Dynamics AX\50\Client\Bin)
  3. Create N hard link for every different instance of AX:

    mklink /h ax32_DEV.exe ax32.exe
    mklink /h ax32_PROD.exe ax32.exe



  4. Create a shortcut to the newly created file (ax32_DEV.exe) wherever you want, and edit the shortcut to open the specific AXC file pointing to the desired AX instance.


  5. Open AX from that shortcut
That should work with Windows 7, 8, Vista and XP

Have fun

Tuesday, May 20, 2014

AX 2009 - Reduce file size of PDF generated from report

AX 4.0 and 2009 doesn't have a good PDF generation engine. The problems are basically 2:

  1. Duplicated images
  2. Fonts included on the PDF

Duplicated images

If you include an image on the report and this image is repeated across pages, the image will be included N times (depending on the number of the pages)

Company logos are usually included in every report, and that will cause a drastic increase on the file size of the generated PDF.

To solve this problem, some changes has to be made to the class PDFViewer.

Add this method to the class:


 int FindOrAddToCache(str data, int imageObjectNo)  
 {  
   int hashCode;  
   System.String netStr = data;  
   ;  
   hashCode = netStr.GetHashCode();  
     
   if (resourceIdImageMap.exists(hashCode))  
     imageObjectNo = resourceIdImageMap.lookup(hashCode);  
   else  
   {  
     resourceIdImageMap.insert(hashCode, imageObjectNo);  
   }  
   return imageObjectNo;  
 }  

That method will build an hash out of the image, and thus will be possible to reuse the latter without increasing the file size.

To do that the following modification will be needed on the method writeBitmap (I will not include all the method since it's too long. So, declare an int variable named newImageObjectNo, add the following code starting approximately at line 140 and close the else bracket at the end) 



       // revert previous assertion  
       CodeAccessPermission::revertAssert();  
       // assert read permissions  
       readPermission = new FileIOPermission(fn, #io_read);  
       readPermission.assert();  
       // BP deviation documented (note that the file io assert IS included above)  
       bin.loadFile(fn);  
       data = bin.getData();  
       // Get rid of the temporary file.  
       WinAPI::deleteFile(fn);  
       if (bitmapEncode85)  
         s = bin.ascii85Encode();  
       else  
         s = BinData::dataToString(data);  
       // Begin modify  
       newImageObjectNo = this.ABM_FindOrAddToCache(s, imageObjectNo);  
       if(newImageObjectNo != imageObjectNo)  
       {  
         imageObjectNo = newImageObjectNo;  
         nextObjectNumber -= 1;  
       }  
       else  
       {  
       // End modify  

That would do the trick for the duplicated images!

Fonts included on the PDF

AX lacks the possibility to only include a subset of the characters used in the report.

This cause the whole font to be included in the generated PDF, causing a huge increase of the file size.

To solve this problem you can avoid to embed fonts on generated PDF (but who does not have the font installed on his system will not be able to view it)

Or you can use one of these fonts (please note that if you use those on a report, the characters are case sensitive):

Courier
Courier-Bold
Courier-Oblique
Courier-BoldOblique
Helvetica
Helvetica-Bold
Helvetica-Oblique
Helvetica-BoldOblique
Times
Times-Roman
Times-Bold
Times-Italic
Times-BoldItalic
ZapfDingbats

Those fonts are default fonts that should be readed in every PDF reader, even if someone does not have the font installed on the system.

When you consider to use a predefined font then you have to do the following code change in the endReport method of PDFViewer class:
...
// Delete the fonts stored in the fontdescrs map
mapEnumerator = fontDescrs.getEnumerator();
while (mapEnumerator.moveNext())
{
    font = mapEnumerator.currentValue();
//->Begin
    if(font.isTrueType())
//<-End
        font.deleteFont();
}

The above piece of code is taken from here

Please note that if you plan to use one of the default fonts, you can only use ASCII characters on your reports! This should be usually enough, but there are some character like "€" that are not available.

Some unsafe characters are:

€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ

You can force the PDF generation engine to substitute those characters with something else, like € with EUR, if you change the method \Classes\PDFViewer\writeStringField like that:


   fn = this.getFontName(currentPage, _section, _field);  
   if (fn != fontNameLast)  
   {  
     fontNameLast = fn;  
     fontIdLast = this.addFont(fn);  
     fontDescrLast = fontDescrs.lookup(fontIdLast);  
   }  
   fontId = fontIdLast;  
   fontDescr = fontDescrLast;  
   fontsOnPage.add(fontId);  
   // Begin modify  
   if(this.isPredefinedFont(fn))  
     _fieldValue = strReplace(_fieldValue, "€", "EUR");  
   // End modify  


Following these tricks the generated PDF file should be viewed on windows, mac, linux and android, and without images the file size will be less than 10Kb

Thursday, November 14, 2013

Dynamics AX 2012 FAST synchronization

Database synchronization on AX 2012 is usually pretty slow.

This is due to the Ax database becoming bigger and bigger. Actually an Ax 2012 R2 installation has something like 5000+ tables.

Slowliness on the synchronization process can be a problem when it come to update a production environment, since it will take the system unavailable for 20-30 minutes.

Deploying changes via model store using the AXUTIL temporary schema technique is very useful, but then you still have to waste a lot of time synchronizing the database.

However, to speed things up, you can synchronize only tables that are actually changed since the last update.

You really don't need to synchronize all those 5000 tables every time you update the system.

So here is a tool to come to rescue.

Ax keep track of changes you made to the aot on the Model* tables. With the query below you can find the last date on which a table or table field has been changed.


 SysModelElementData modelElementData;  
   SysModelElement   modelElement;  
   SysModelElementData modelElementDataRoot;  
   SysModelElement   modelElementRoot;  
   delete_from tmpFrmVirtual;  

   while select modelElement  
     group by modelElement.RootModelElement, modelElementRoot.Name, modelElementRoot.AxId  
     join maxOf(ModifiedDateTime) from modelElementData  
     where modelElementData.ModelElement == modelElement.RecId  
      && (modelElement.ElementType == UtilElementType::TableField || modelElement.ElementType == UtilElementType::TableIndex || modelElement.ElementType == UtilElementType::Table)  
      //&& modelElementData.Layer == UtilEntryLevel::cus + 1  
      && modelElementData.modifiedDateTime > DateTimeUtil::newDateTime(transDate, 0)  
     join modelElementRoot  
       where modelElementRoot.RecId == modelElement.RootModelElement  
   {  

So with that query you can filter down tables modified within the last X days, and synchronize only those tables.

I've built a tool that does exactly this, you got a screenshot below:


In the date field you can filter tables modified since this date. Pressing OK the synchronization of the selected tables will occour.

That way, I can usually synchronize the system in about... 10 seconds?

XPO project download link HERE


P.S.: please note that this is not a complete replacement for the DB synchronization, but a procedure that synchronize only a small subset of the database!
There are cases in wich a modification of a table is not tracked in the SysModel* tables, for example if you change a string extended data type lenght, or completely delete a table layer. So use at your own risk.