Showing posts with label AX 2012. Show all posts
Showing posts with label AX 2012. Show all posts

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();
}

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

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.

Wednesday, February 20, 2013

Create contact by code


static void ContactCreate(Args _args)
{
    DirPartyRecId               party;
    DirPartyContactInfoView     contactView;
    DirParty                    dirParty;
    LogisticsLocationRoleRecId  role;
    LogisticsLocationRole       LogisticsLocationRole;

    party = CustTable::find('CUSTOMER ID').Party;

    contactView.LocationName = "Name";
    contactView.Locator      = "www.microsoft.com";
    contactView.Type         = LogisticsElectronicAddressMethodType::URL;
    contactView.Party        = party;
    contactView.IsPrimary    = false;
    contactView.LocatorExtension = "";

    role = LogisticsLocationRole::findBytype(LogisticsLocationRoleType::Business).RecId;
    dirParty = dirParty::constructFromPartyRecId(party);
    dirParty.createOrUpdateContactInfo(contactView,[role]);

}

Friday, November 30, 2012

AX 2012 Financial dimension update

Here are 2 ways to update a financial dimension, while keeping the other dims. The result should be the same, just use whatever you prefer

To use those two method proceed like so:

  purchTable = purchTable::find('PURCHID', true);  
  purchTable.DefaultDimension = getNewDefaultDimension(purchTable.DefaultDimension, "COSTCENTER", "YOURVALUE");  
  purchTable.update();  

METHOD NUMBER 1:

 static RecId getNewDefaultDimension(RecId defaultDimension, Name dimName, str 255 dimValue)  
 {  
   DimensionAttributeValueSetStorage  dimStorage;  
   Counter               i;  
   DimensionAttribute         dimAttributeCostCenter;  
   DimensionAttributeValue       dimAttributeValue;  
   dimStorage = DimensionAttributeValueSetStorage::find(defaultDimension);  
   dimAttributeCostCenter = DimensionAttribute::findByName(dimName);  
   if(dimValue)  
   {  
     dimAttributeValue = DimensionAttributeValue::findByDimensionAttributeAndValue(dimAttributeCostCenter, dimValue, true, true);  
     dimStorage.addItem(dimAttributeValue);  
   }  
   else  
     dimStorage.removeDimensionAttribute(DimensionAttribute::findByName(dimName).RecId);  
   return dimStorage.save();  
 }  


METHOD NUMBER 2:

 static RecId getNewDefaultDimension(RecId defaultDimension, Name dimName, str 255 dimValue)  
 {  
   container c;  
   RecId   newdefaultDimension;  
   int    i;  
   c = AxdDimensionUtil::getDimensionAttributeValueSetValue(defaultDimension);  
   i = conFind(c, dimName);      
   if(!i && !dimValue)  
     return defaultDimension;  
   if(i)  
   {      
     c = conDel(c, i+1, 1);   
     c = conDel(c, i, 1);    
   }  
   if(dimValue)  
   {  
     c += dimName;  
     c += dimValue;  
   }  
   c = conDel(c, 1, 1);  
   c = conIns(c, 1, conLen(c) / 2);  
   newdefaultDimension = AxdDimensionUtil::getDimensionAttributeValueSetId(c);  
   return newdefaultDimension;  
 }  

To get the current value of a financial dimension:

 static str 255 getDimensionValue(RecId defaultDimension, Name dimName)  
 {  
   DimensionAttributeValueSetStorage  dimStorage;  
   Counter               i;  
   DimensionAttribute         dimAttributeCostCenter;  
   DimensionAttributeValue       dimAttributeValue;  
    dimStorage = DimensionAttributeValueSetStorage::find(defaultDimension);  
   return dimStorage.getDisplayValueByDimensionAttribute(DimensionAttribute::findByName(dimName).RecId);  
 }  

Monday, November 05, 2012

Enable SalesInvoice report on Enterprise Portal

Continuing the series of articles in SSRS, here I explain how to print the salesInvoice (or any other custom report) in Enterprise Portal.

Despite Packing Slip, this report is not supported in the standard Enterprise portal installation (you don't have the button to print an invoice on the EP invoices list page)

That's because Sales Invoice use a report controller that has not been implemented for the use in EP.

The solution I propose here is a little tricky, but it works pretty well :)

The key is to modify the class EPDocuGet that manages the download of reports or attachments from EP.

In that class you can write some code to print the SalesInvoice PDF to a temporary directory (how to do that is explained in a post before) and then write out the data in HTTP response of the Web request

So in the method run you can do something like:


 void run(Args args = null)  
 {  
   IISResponse       response = new IISResponse();  
 ;  
   // Transition to a server function to avoid  
   // Security problems  
   if (args)  
   {  
     if (args.record().TableId == tableNum(DocuRef))  
     {  
       EPDocuGet::runDocument(args.record().data(), response);  
     }  
     // Begin change  
     // Description:  
     else if (args.record().TableId == tableNum(CustInvoiceJour))  
     {  
       EPDocuGet::DWrunReportSalesInvoice(args.record().data(), response);  
     }  
     // End  
     else  
     {  
       EPDocuGet::runReport(args.record().data(), response);  
     }  
   }  
 }  

So if you got a CustInvoiceJour record you run your custom code. The method DWrunReportSalesInvoice is a copy of the runDocument method, a little bit modified:

 #define.BUFFER_SIZE(4096)  
 #File  
 client static void DWrunReportSalesInvoice(Common callerRecord, IISResponse response)  
 {  
   Query          query = new Query();  
   QueryBuildDataSource  qbds;  
   QueryRun        queryRun;  
   //EPSendDocument     document;  
   BinData         binData;  
   str           fileName;  
   int           fileOffset;  
   DictTable        table = new DictTable(callerRecord.TableId);  
   str           tempFileName;  
   boolean         emptyReport;  
   CustInvoiceJour     custInvoiceJour = callerRecord;  
   ;  
   if (EPDocuGet::hasTableAccess(callerRecord.TableId))  
   {  
     qbds = query.addDataSource(callerRecord.TableId);  
     if (callerRecord && callerRecord.TableId != tableNum(DocuRef))  
     {  
       // Requery the record to test record level security  
       qbds.addRange(table.fieldName2Id('RecId')).value(SysQuery::value(callerRecord.RecId));  
       query.recordLevelSecurity(true);  
       queryRun = new QueryRun(query);  
       if (queryRun.next())  
       {  
         //document = new EPSendDocument(callerRecord);  
         tempFileName = System.IO.Path::GetTempFileName();  
         EPDocuGet::DWPrintInvoicePdf(callerRecord, tempFileName);  
         infolog.clear();  
         //document.parmOriginal(true);  
         //document.parmFileName(tempFileName);  
         // Make document will run the report and send it to a PDF file with  
         // the path specified in tempFileName  
         //document.makeDocument();  
         fileName = custInvoiceJour.InvoiceId + ".pdf";  
         // remove all ';' from the filename. These are treated as delimiters by Ie  
         fileName = strReplace(fileName, ';', '_');  
         emptyReport = (WinAPI::fileSize(tempFileName) == 0);  
         response.clear();  
         binData = new BinData();  
         if (emptyReport)  
         {  
           response.contentType('application/Octet-Stream');  
           response.addHeader('Content-Disposition', 'attachment;filename="' + fileName + #txt + '"');  
           response.writeTxt(strFmt("@SYS58533", fileName));  
         }  
         else  
         {  
           response.contentType('application/pdf');  
           response.addHeader('Content-Disposition', 'attachment;filename="' + fileName + #pdf + '"');  
           // Loop over the stored file and chunk it down to the client  
           fileOffset = 0;  
           // Assert permission and get the temp filename  
           new FileIOPermission(tempFileName, #io_read).assert();  
           while(true)  
           {  
             // BP Deviation Documented  
             if (!binData.loadFile(tempFileName, fileOffset, #BUFFER_SIZE))  
             {  
               break;  
             }  
             fileOffset += #BUFFER_SIZE;  
             response.binaryWrite(binData.getVariant());  
           }  
           CodeAccessPermission::revertAssert();  
         }  
         binData = null;  
         WinAPI::deleteFile(tempFileName);  
       }  
     }  
   }  
 }  

And here is the method to print the invoice in PDF:

 client static void DWPrintInvoicePdf(Common _record, Filename filename)  
 {  
   args args = new args();  
   CustInvoiceJour custInvoiceJour = _record;  
   SRSPrintDestinationSettings printSettings;  
   SalesInvoiceController controller = new SalesInvoiceController();  
   str pdfPath = filename;  
   args.record(_record);  
   //pdfPath = WinAPI::getTempPath() + custInvoiceJour.InvoiceId + ".pdf";  
   // imposta nome report  
   controller.parmReportName(ssrsReportStr(SalesInvoice, Report));  
   // get print settings from contract  
   printSettings = controller.parmReportContract().parmPrintSettings();  
   // set print medium  
   printSettings.printMediumType(SRSPrintMediumType::File);  
   printSettings.fileFormat(SRSReportFileFormat::PDF);  
   printSettings.overwriteFile(true);  
   printSettings.fileName(pdfPath);  
   // forzo che non vengano cambiati i parametri di stampa che gli passo io  
   controller.DEVparmLockDestinationProperties(true);  
   // suppress the parameter dialog  
   controller.parmShowDialog(false);  
   controller.parmArgs(args);  
   // start operation  
   controller.startOperation();  
 }  


At this point, all you have to do is to create an Output Menu Item with the value "EPDocuGet" in the property "WebMenuItemName" and add this menu item to the EPCustInvoiceListPage form or whatever form you like.

Friday, October 12, 2012

Enhanced table browser

If you find it hard to find fields on the Ax Table Browser, this tool may help you.

It will simply show the visible fields on the right, and you can check/uncheck those that you want to see.

If you experience some problem after installation, clear Usage data for the form



XPO download HERE

Thursday, October 11, 2012

Create custom Alert for AX with Go to Source support

To create an Alert in AX, you can use the class EventNotification and its derivates

I got some problems using these standard classes, particularly in making the button "Go to source" work.

To avoid those problem, here is some code that may help:

 public static void CreateAlert(str message,  
               str subject,  
               UserId userId = curUserId(),  
               NoYes showPopup = NoYes::Yes,  
               NoYes sendEmail = NoYes::No,  
               Common record = null,  
               str dataSourcename = '',  
               MenuFunction menuFunction = null)  
 {  
   EventInbox inbox;  
   DictTable table;  
   EventContextInformation eci;  
   EventInboxData inboxData;  
   Args args = new Args();  
   List list;  
   EventInboxId inboxId = EventInbox::nextEventId();  
   FormRun formRun;  
   WorkflowRecordCaptionGenerator recordCaptionGenerator;  
   UserInfo userInfo;  
   inboxId = EventInbox::nextEventId();  
   inbox.initValue();  
   inbox.ShowPopup      = showPopup;  
   inbox.Subject       = subject;  
   inbox.Message       = message;  
   inbox.SendEmail      = sendEmail;  
   inbox.EmailRecipient    = SysUserInfo::find().Email;  
   inbox.UserId        = userId;  
   inbox.InboxId       = inboxId;  
   inbox.AlertCreatedDateTime = DateTimeUtil::getSystemDateTime();  
   if (record)  
   {  
     table = new DictTable(record.TableId);  
     eci = new EventContextInformation();  
     if (!menuFunction)  
     {  
       menuFunction = new MenuFunction(table.formRef(),MenuItemType::Display);  
       if (!menuFunction)  
         throw error(strFmt("@SYS104114",table.formRef()));  
     }  
     //Build the data to drill down to from the notification  
     args.menuItemName(menuFunction.name());  
     args.menuItemType(MenuItemType::Display);  
     args.name(menuFunction.object());  
     eci.parmPackedArgs(args);  
     eci.parmAlertBuffer(record);  
     eci.parmAlertFormDsName(dataSourceName);  
     //eci.parmDontUseFormRunFromMenuItem(true);  
     inboxData.InboxId = inboxId;  
     inboxData.DataType = EventInboxDataType::Context;  
     inboxData.Data = eci.pack();  
     inboxData.insert();  
     inbox.AlertTableId = table.id();  
     inbox.ParentTableId = table.id();  
     recordCaptionGenerator = WorkflowRecordCaptionGenerator::construct(record);  
     inbox.AlertedFor = recordCaptionGenerator.caption();  
     list = SysDictTable::getUniqueIndexFields(table.id());  
     if (list)  
     {  
       inbox.keyFieldList(list.pack());  
       inbox.keyFieldData(SysDictTable::mapFieldIds2Values(list,record).pack());  
     }  
     inbox.CompanyId = record.company();  
   }  
   inbox.insert();  
 }  

To use this code
 static void Job155(Args _args)  
 {  
   InventTable inventTable;  
   select firstOnly inventTable;  
   DEVUtils::CreateAlert("message", "subject", curUserId(), true, false, inventTable, "InventTable", new MenuFunction(menuitemDisplayStr(EcoResProductDetailsExtended), MenuItemType::Display));  
 }  

Sending PEC (Certified E-mail) with AX

A PEC (Certified E-mail) is not very different from a usual e-mail.

You just have to use SSL to secure the connection while sending the mail.

Usually I use the class System.Net.Mail to send mails with Ax, and this one has a useful property named EnableSsl that could work. But with a PEC, no, this isn't working.

That's because, to send a PEC you need an Implicit SSL, while System.Net.Mail only supports “Explicit SSL”.

 Reference: HERE

 And, as stated in the MSDN:

The EnableSsl property specifies whether SSL is used to access the specified SMTP mail server.
The default value for this property can also be set in a machine or application configuration file. Any changes made to the EnableSsl property override the configuration file settings.
The SmtpClient class only supports the SMTP Service Extension for Secure SMTP over Transport Layer Security as defined in RFC 3207. In this mode, the SMTP session begins on an unencrypted channel, then a STARTTLS command is issued by the client to the server to switch to secure communication using SSL. See RFC 3207 published by the Internet Engineering Task Force (IETF) for more information.
An alternate connection method is where an SSL session is established up front before any protocol commands are sent. This connection method is sometimes called SMTP/SSL, SMTP over SSL, or SMTPS and by default uses port 465. This alternate connection method using SSL is not currently supported.

So, if you want to send a mail with Implicit SSL, you have to use a deprecated class from the old 2.0 .NET Framework, that is System.Web.Mail

Using this class is not difficult, and you can find a working sample down here:


 static void SendPECMail(Args _args)  
 {  
   System.Web.Mail.MailMessage  newMail;  
   System.Collections.IDictionary fields;  
   System.Collections.IList    attachementCollection;  
   System.Web.Mail.MailAttachment attachment;  
   try  
   {  
     new InteropPermission(InteropKind::ClrInterop).assert();  
     newMail = new System.Web.Mail.MailMessage();  
     fields = newMail.get_Fields();  
     fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", "smtps.pec.aruba.it");  
     fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465");  
     fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", "2");  
     fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");  
     fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "lmattiuzzo@pec.it");  
     fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "password");  
     fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");  
     newMail.set_From("lmattiuzzo@pec.it");  
     newMail.set_To("santa@klaus.com");  
     newMail.set_Subject("subject");  
     newMail.set_BodyFormat(System.Web.Mail.MailFormat::Html);  
     newMail.set_Body("body of your message");  
     newMail.set_Priority(System.Web.Mail.MailPriority::High);  
     attachementCollection = newMail.get_Attachments();  
     attachment = new System.Web.Mail.MailAttachment(@"c:\file.pdf");  
     attachementCollection.Add(attachment);  
     System.Web.Mail.SmtpMail::set_SmtpServer("smtps.pec.aruba.it:465");  
     System.Web.Mail.SmtpMail::Send(newMail);  
     CodeAccessPermission::revertAssert();  
   }  
   catch( Exception::CLRError )  
   {  
     throw error(AifUtil::DEVgetClrErrorMessage());  
   }  
 }  

Thursday, July 26, 2012

Print a SalesInvoice, PackingSlip or similar report to PDF in AX 2012

Printing a report in PDF in AX 2012 is pretty simple, but SalesInvoice report, or packing slip and similar seems not to work with the standard way.

That's because even if you pass printSettings parameters those are overriden by the controller class.

In AX 2009 there was a useful method called LockDestinationProperties in printSettings parameters that solve this problem, but this is gone in AX 2012.

So, If you want to reenable this feature, you have to do this:

Open the class SrsPrintMgmtFormLetterController and change those methods:


 void public abstract class SrsPrintMgmtFormLetterController extends SrsPrintMgmtController
{
    FormLetterReport formLetterReport;

    // Begin - Modify by lmattiuz on 27/06/2012
    boolean DEVLockDestinationProperties;
    SRSPrintDestinationSettings DEVfixedprintSettings;
    // End - Modify by lmattiuz
}

// Begin - Modify by lmattiuz on 27/06/2012 - Project: 120301_DevopmentTools_DEV
public Boolean DEVparmLockDestinationProperties(Boolean _DEVLockDestinationProperties = DEVLockDestinationProperties)
{
    DEVLockDestinationProperties = _DEVLockDestinationProperties;

    return DEVLockDestinationProperties;
}

protected void outputReport()
{
    // Begin - Modify by lmattiuz on 27/06/2012 - Project: 120301_DevopmentTools_DEV
    // Description:
    if(DEVLockDestinationProperties)
        formLetterReport.getCurrentPrintSetting().parmPrintJobSettings(DEVfixedprintSettings);
    // End - Modify by lmattiuz

    // execute report.
    if(formLetterReport)
    {
        formLetterReport.execute();
    }
}

public SysOperationStartResult startOperation()
{
    // Begin - Modify by lmattiuz on 27/06/2012 - Project: lmat_120301_DevopmentTools_DEV
    // Description:
    if(DEVLockDestinationProperties)
        DEVfixedprintSettings = this.parmReportContract().parmPrintSettings();
    // End - Modify by lmattiuz

    this.init();

    return super();
}       

Then you can print reports in PDF as you usually do:


 protected void printReportPdf(Common _record)
{
    args args = new args();
    CustInvoiceJour custInvoiceJour = _record;
    SRSPrintDestinationSettings printSettings;
    SalesInvoiceController controller = new SalesInvoiceController();

    args.record(_record);

    pdfPath = WinAPI::getTempPath() + custInvoiceJour.InvoiceId + ".pdf";

    // imposta nome report
    controller.parmReportName(ssrsReportStr(SalesInvoice, Report));

    // get print settings from contract
    printSettings = controller.parmReportContract().parmPrintSettings();

    // set print medium
    printSettings.printMediumType(SRSPrintMediumType::File);
    printSettings.fileFormat(SRSReportFileFormat::PDF);
    printSettings.overwriteFile(true);
    printSettings.fileName(pdfPath);

    // forzo che non vengano cambiati i parametri di stampa che gli passo io
    controller.DEVparmLockDestinationProperties(true);

    // suppress the parameter dialog
    controller.parmShowDialog(false);
    controller.parmArgs(args);

    // start operation
    controller.startOperation();
}

Saturday, May 12, 2012

AX Project Finder Tool

Here's a small and handy tools that let you search for projects inside AX.

Just start typing something on the search bar and you will get a list of the projects found.


With a double click you can open the selected project

How it works:

with the call of:


projectListNode = SysTreeNode::getSharedProject(); 


you get the AOT node for the shared project. Then all the child of this node are looped, and the name is checked against the input text


treeNodeIterator = projectListNode.AOTiterator();  
   treeNode = treeNodeIterator.next();  
   while(treeNode)  
   { ... }  


 void FindProject()  
 {  
   ProjectSharedPrivate  projectType;  
   TreeNode treeNode;  
   ProjectListNode projectListNode;  
   TreeNodeIterator treeNodeIterator;  
   str aotName;  
   ;  
   ListboxResult.clear();  
   projectListNode = SysTreeNode::getSharedProject();  
   treeNodeIterator = projectListNode.AOTiterator();  
   treeNode = treeNodeIterator.next();  
   while(treeNode)  
   {  
     aotName = treeNode.AOTname();  
     //return;  
     if(DEVString::contains(aotName, projectName.text()))  
     {  
       ListboxResult.add(aotName);  
     }  
     treeNode = treeNodeIterator.next();  
   }  
 }  



Download link below

Friday, May 04, 2012

AX 2012 Create new project tool

Here's a port of the tool to create a new project template found on Axaptapedia.

This one will work on AX 2012, and has been entirely rewritten.

It support all the new nodes of the AOT made available with AX 2012


As usual, link to download is below