Quantcast
Channel: Ebbes Nørderi (Ebbes Nerdery)
Viewing all 53 articles
Browse latest View live

Manage printer settings for SSRS Report in AX 2012

$
0
0

Goal: how to manage the printer settings for reports in AX 2012.

The following example is based on the new report Quality Orders in the Invent Module.
STEP 1
Create the SSRS Report
  • Report name:          InventQualityOrder
  • Contract name:       InventQualityOrderTableContract
  • Controller name:    InventQualityOrderTableController
STEP 2
Add new values to the BaseEnums:
  • PrintMgmtNodeType; add “QualityOrders”
  • PrintMgmtDocumentType; add “QualityOrders”
STEP 3
Create an extension of the PrintMgmtNode class:
public class PrintMgmtNode_QualityOrder extends PrintMgmtNode

public List getDocumentTypes() { List docTypes = new List(Types::Enum);   docTypes.addEnd(PrintMgmtDocumentType::QualityOrders);   return docTypes; }   public RefTableId getReferencedTableId() { return tablenum(InventQualityOrderTable); } 
STEP 4
Modify the following classes:
PrintMgmtNode
1) Add the following code to the method “construct”:
case PrintMgmtNodeType::QualityOrdersWCH:
return new PrintMgmtNode_QualityOrderWCH();
A PrintMgmtNode class defines a level at which Print Management information can be associated.
PrintMgmtDocType
1) Method getDefaultReportFormat()
case PrintMgmtDocumentType::QualityOrders:
return ssrsReportStr(InventQualityOrder, Report);
2) Method getQueryRangeFields()
case PrintMgmtDocumentType::QualityOrders:
fields.addEnd(fieldNum(InventQualityOrderTable, QualityOrderId));
break;
3) Method getQueryTableId()
case PrintMgmtDocumentType::QualityOrders:
tableId = tableNum(InventQualityOrderTable);
break;
The PrintMgmtDocType class represents the document types that are available in print management.
PrintMgmtHierarchy_Invent
1) Method getNodesImplementation()
supportedNodes.addEnd(PrintMgmtNodeType::QualityOrders);
2) Method getParentImplementation()
case PrintMgmtNodeType::QualityOrders:
result.parmReferencedTableBuffer(null);
result.parmNodeDefinition(PrintMgmtNode::construct(PrintMgmtNodeType::Invent));
break;
PrintMgmtNode_Invent
1) Method getDocumentTypes()
docTypes.addEnd(PrintMgmtDocumentType::QualityOrders);
The PrintMgmtNode_Invent class is responsible for managing print management settings at the module level in the inventory module. Add the new document type in the method getDocumentTypes().
STEP 5
Create an extension of the FormLetterReport class:
class InventFormLetterReport_QualityOrder extends FormLetterReport
{
    InventTransType transType;
}   protected container getDefaultPrintJobSettings(PrintSetupOriginalCopy _printCopyOriginal)
{
    return new PrintJobSettings().packPrintJobSettings();
}   protected PrintMgmtDocumentType getPrintMgmtDocumentType()
{
    return PrintMgmtDocumentType::QualityOrders;
}   protected PrintMgmtHierarchyType getPrintMgmtHierarchyType()
{
    return PrintMgmtHierarchyType::Invent;
}   protected PrintMgmtNodeType getPrintMgmtNodeType()
{
    return PrintMgmtNodeType::QualityOrders;
}
STEP 6
Modify the FormLetterReport class: 
1) Method construct()  
case PrintMgmtDocumentType::QualityOrders:
return new InventFormLetterReport_QualityOrder();
The FormLetterReport class controls the printing of documents.
STEP 7
Create the controller, which extends the TradeDocumentReportController class, which allows to manage multiple prints.
The following dialog aims to provide the possibility to choose printer settings that are different from the ones defined in the standard configuration (Inventory and warehouse management > Setup > Inventory and warehouse management parameters > Print management):
The dialog offers two scenarios:
- “Use print management destination” is flagged – in this case the system takes the settings from Inventory and warehouse management parameters
- Otherwise, the system takes the printer settings from the dialog (“Current print destination”).
In any case, it is necessary to overwrite the following methods in the controller:
initFormLetterReport()
protected void initFormLetterReport()
{
    printCopyOriginal = this.parmArgs().parmEnum();   this.initializeJournalLists(this.parmArgs());   formLetterReport = FormLetterReport::construct(PrintMgmtDocumentType::QualityOrders);   formLetterReport.parmPrintType(printCopyOriginal);   if (printCopyOriginal == PrintCopyOriginal::OriginalPrint)
    {
        // Always use the print mgmt destinations when reprinting for the OriginalPrint case.
        formLetterReport.parmUsePrintMgmtDestinations(true);
    }   super();
}  
output()
This method is called from the runPrintManagement method, for every selected journal.
protected void output()
{
    InventQualityOrderTableContractWCH rdpContract = this.parmReportContract().parmRdpContract() as InventQualityOrderTableContractWCH;   //If the flag is not set, I set the current print destination in case of original/copy printing
    if (!rdpContract.parmUsePrintManagementSettings())
    {
        formLetterReport.parmDefaultCopyPrintJobSettings(this.parmReportContract().parmPrintSettings()); formLetterReport.parmDefaultOriginalPrintJobSettings(this.parmReportContract().parmPrintSettings());        formLetterReport.parmUsePrintMgmtDestinations(false);
    }      // load the new setup for printing the report    formLetterReport.loadPrintSettings(inventQualityOrderTable, inventQualityOrderTable, CompanyInfo::languageId());    this.parmReportContract().parmRdlContract().parmLanguageId(CompanyInfo::languageId());      super();
}
For further information see also:
- SalesQuotationController class – for example
- http://msdn.microsoft.com/en-us/library/tradedocumentreportcontroller.aspx
- http://dynamicsaxgyan.wordpress.com/2011/08/19/learn-quick-first-ssrs-report-in-dynamics-ax-2012/ – create a new SSRS report

—————————–

I found this at: http://axmartina.wordpress.com/2013/07/01/manage-printer-settings-for-ssrs-report-in-ax-2012/

 


Axapta : Enable/Disable Dialog Control at runtime

$
0
0

 

disable_runtime_dialog_control

class SCI_Costing extends RunBase
{
    FormStringControl   SalesIdCtrl, ItemIdCtrl;
    FormCheckBoxControl bAllCtrl;
    SalesId     salesId;
    ItemId      itemId;
    NoYes       bAll;
    #define.CurrentVersion(1)
    #localmacro.CurrentList
        salesId,
        itemId,
        bAll
    #endmacro
}

protected Object dialog(Dialog dialog, boolean forceOnClient)
{
    DialogRunBase ret;
    ;
    ret = super(dialog, forceOnClient);
    ret.caption(‘Costing report by order’);
    ret.allowUpdateOnSelectCtrl(true); //อนุญาตให้ update control ได้
    SalesIdCtrl = ret.formBuildDesign().addControl(FormControlType::String,’SalesId’);
    SalesIdCtrl.extendedDataType(extendedTypeNum(‘SalesId’));
    bAllCtrl = ret.formBuildDesign().addControl(FormControlType::CheckBox,’bAll’);
    bAllCtrl.label(‘All’);
    ItemIdCtrl = ret.formBuildDesign().addControl(FormControlType::String,’ItemId’);
    ItemIdCtrl.extendedDataType(extendedTypeNum(‘ItemId’));
    return ret;
}

public void dialogPostRun(DialogRunbase dialog)
{
    ;
    super(dialog);
    dialog.dialogForm().formRun().controlMethodOverload(true);
    dialog.dialogForm().formRun().controlMethodOverloadObject(this);
    SalesIdCtrl = dialog.dialogForm().formRun().design().controlName(‘SalesId’);
    ItemIdCtrl = dialog.dialogForm().formRun().design().controlName(‘ItemId’);
    bAllCtrl = dialog.dialogForm().formRun().design().controlName(‘bAll’);
}

public void dialogSelectCtrl()
{
    ;
    if (bAllCtrl.value()== 0)
    {
        ItemIdCtrl.allowEdit(true);
    }
    else
    {
        ItemIdCtrl.allowEdit(false);
    }
}

Found here: http://www.komkid.net/2009/10/axapta-enabledisable-dialog-control-at-runtime/

Report with out dialog interactions

$
0
0

View the reports without dialog interactions.

static void RunReportWithOutDialogInteraction(Args _args)

{

    Args args;

    SysReportRun reportRun;

    ;

    args = new Args();

    args.name(reportstr(myReport));

    args.record(myRecord);

    reportRun = classFactory.reportRunClass(args);

    reportRun.query().interactive(false);

    reportRun.report().interactive(false);

    reportRun.setTarget(PrintMedium::Screen);

    reportRun.run();

}

https://community.dynamics.com/ax/b/axsantoshkumar/archive/2008/09/20/report-with-out-dialog-interactions.aspx

Get number of items on stock / inventory / Invent On Hand

$
0
0

InventOnHand = InventSumDatePhysicalDim::onHandQty(systemDateGet(),itemId,inventDim::find(inventDimId),inventDimParm);

Clear or Flush cash in price disc / PriceDisc

$
0
0

static void my_flushPriceDiscCache(Args _args)
{
    PriceDisc::flushPriceDiscCache();
    info(‘PriceDisc::flushPriceDiscCache() – DONE’);
}

Simple Dialog Box in Axapta

$
0
0

Simple Dialog Box in Axapta 2012

The following example displays the dialog box and prints the value entered to the screen.

Code:

static void theAxapta_DialogBox(Args _args)

{
    dialog              dialog;
    dialogGroup    dialogGroup;
    dialogField      dialogField;
    ;
    dialog              = new Dialog("Simple Dialog");
    dialogGroup    = dialog.addGroup("Customer");
    dialogField      = dialog.addField(extendedTypeStr(custAccount));
    if (dialog.run())
    {
        print dialogField.value();
        pause;

    }
}

Output:

Note:


    1. The dialog.run() method returns true if OK is clicked, and false if Cancel is     clicked.

    2. Dialog Group is used to group dialog fields which are logically same.

Found here: http://theaxapta.blogspot.dk/2013/09/simple-dialog-box-in-axapta-2012.html

An other example:

A dialog in Microsoft Dynamics AX is a simple form with a standardized layout, created by using the Dialog system class.

Dialogs should allow users to enter some simple values. Do not create complex dialogs—create forms instead.

Dialogs are non-modal. The dialog should not open a secondary window that requires user interaction. All user interaction should be carried out within the dialog.

Dialog Methods

Following are some of the most commonly used methods in the Dialog class:

  • Use the addField method to add fields to the dialog. The addField method returns objects of the DialogField type.

  • Use the addGroup method to group related fields.

  • Use the addTabPage method to add tabbed pages.

  • Use the value method to set and get values in the dialog.

  • Use the run method to launch the dialog. When the user clicks OK or Cancel, the run method returns true or false, respectively.

Dialog Classes

Dialog is the main class used to construct dialogs. DialogRunBase is an extension of the Dialog class that is used by the RunBase framework. The DialogControl class defines a single control in the dialog.DialogControl is extended by classes for the following control types:

  • DialogField

  • DialogGroup

  • DialogTabPage

  • DialogText

  • DialogWindow

Example

Example of a simple dialog

The following code sample implements the dialog shown in the previous figure.

X++

boolean myDialog(str FromChequeNum="1000", str NumOfCheque="300")
{
    Dialog dialog = new Dialog("@SYS23133");
    DialogField dialogAccountId = dialog.addField(
        extendedTypeStr(BankAccount));
    DialogField dialogFromChequeNum = dialog.addField(
        extendedTypeStr(BankChequeStartNum),
        "@SYS4083");
    DialogField dialogNumOfCheque = dialog.addField(
        extendedTypeStr(BankChequeQty),
        "@SYS14578");
    ;
    dialogAccountId.Value("456");
    dialogAccountId.Active(false);
    dialogFromChequeNum.Value(FromChequeNum);
    dialogNumOfCheque.Value(NumOfCheque);
    if (dialog.run())
    {
        FromChequeNum = dialogFromChequeNum.Value();
        NumOfCheque = dialogNumOfCheque.Value();
        return true;
    }
    return false;
}

Found here: http://msdn.microsoft.com/en-us/library/aa877843.aspx

Prevent Java Updater from Installing Ask Toolbar

$
0
0

Windows Registry Solution

Copy the following text into Notepad or other editor and save it as a .REG file.

Windows 32-bit

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft]
"SPONSORS"="DISABLE"

Windows 64-bit

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft]
"SPONSORS"="DISABLE"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft]
"SPONSORS"="DISABLE"

Run the files on you’re set. Those entries will prevent the installation of Ask Toolbar every time you install Java updates.

—————————————-

Found here: Prevent Java Updater from Installing Ask Toolbar

Export to Excel

$
0
0

static void My_ExportToExcel(Args _args)
{
    CustTable custTable;

    AssetTrans assetTrans;
    SysExcelApplication application;
    SysExcelWorkBooks workbooks;
    SysExcelWorkBook workbook;
    SysExcelWorksheets worksheets;
    SysExcelWorksheet worksheet;
    SysExcelCells cells;
    SysExcelCell cell;
    int row;
    ;
    application = sysExcelApplication::construct();
    workbooks = application.workbooks();
    workbook = workbooks.add();
    worksheets = workbook.worksheets();
    worksheet = worksheets.itemFromNum(1);
    cells = worksheet.cells();
    cells.range(‘A:A’).numberFormat(‘@’); // Format as text

    // Generate header
    row++;
    cells.item(row,01).value("AccountNum");
    cells.item(row,02).value("Name");
    cells.item(row,03).value("InvoiceAccount");
    cells.item(row,04).value("CustGroup");

    // Generate DataArea rows

    while select custTable
    {
        row++;
        cells.item(row,01).value(StrFmt(‘%1′,CustTable.AccountNum));
        cells.item(row,02).value(StrFmt(‘%1′,CustTable.name()));
        cells.item(row,03).value(StrFmt(‘%1′,CustTable.InvoiceAccount));
        cells.item(row,04).value(StrFmt(‘%1′,CustTable.CustGroup));
    }
    application.visible(true); // opens the excel worksheet
    info("Export finished");
}


Import or update from Excel

$
0
0

static void My_ImportFromExcel(Args _args)
{
    #AviFiles
    #Excel
    #define.Star(‘*’)
    #define.Space(‘ ‘)

    CustTable   custTable;
    Dialog      dialog;
    DialogField dlgFilename;
    Filename    filename;

    int         rowIdx;
    int         colIdx;
    Counter     linesImported;
    int         lastRow;
    boolean     ok = true;
    str         colContent[];
    str         input;

    SysExcelApplication     application;
    SysExcelWorkBooks       workBooks;
    SysExcelWorkSheets      workSheets;
    SysExcelWorkSheet       workSheet;
    SysExcelCells           cells;
    SysOperationProgress    progress_;

    // convert into str from excel cell value
    str COMVariant2Str(COMVariant _cv, int _decimals = 0, int _characters = 0, int _separator1 = 0, int _separator2 = 0)
    {
        switch (_cv.variantType())
        {
            case (COMVariantType::VT_BSTR):
                return _cv.bStr();

            case (COMVariantType::VT_R4):
                return num2str(_cv.float(),_characters,_decimals,_separator1,_separator2);

            case (COMVariantType::VT_R8):
                return num2str(_cv.double(),_characters,_decimals,_separator1,_separator2);

            case (COMVariantType::VT_DECIMAL):
                return num2str(_cv.decimal(),_characters,_decimals,_separator1,_separator2);

            case (COMVariantType::VT_DATE):
                return date2str(_cv.date(),123,2,3,2,3,4);

            case (COMVariantType::VT_EMPTY):
                return "";

            default:
                throw error(strfmt("@SYS26908", _cv.variantType()));
        }
        return "";
    }

    // Find last row from excel
    int findLastRow(SysExcelWorkSheet _workSheet)
    {
        SysExcelRange range;
        ;

        range = _workSheet.cells().range(#ExcelTotalRange);

        try
        {
            // Finds the row where the first contents is found.
            range = range.find(#Star, null, #xlFormulas, #xlWhole, #xlByRows, #xlPrevious);
        }
        catch (Exception::Error)
        {
            error("@SYS59926");
            return 0;
        }

        if (range)
        {
            return range.row();
        }
        else
        {
            return 0;
        }
    }
    ;
    dialog = new dialog();
    dlgFilename = dialog.addField(extendedTypeStr(FilenameOpen));
    dialog.filenameLookupFilter(["Microsoft Excel-files",’*.xls;*.xlsx’]);
    dialog.filenameLookupTitle("Import fra Excel");
    if (!dialog.run())
        return;

    filename = dlgFilename.value();

    ttsbegin;

    application = SysExcelApplication::construct();
    workBooks = application.workbooks();
    workBooks.open(filename,0,true);
    workSheets = workBooks.item(1).worksheets();

    //input = "Sheet1";
    //workSheet = workSheets.itemFromName(input);
    workSheet = workSheets.itemFromNum(1);
    cells = workSheet.cells();
    lastRow = findLastRow(workSheet);
    rowIdx = 1;

    progress_ = new SysOperationProgress();
    progress_.setCaption("Vendor Importing");
    progress_.setTotal(lastRow);
    progress_.setAnimation(#AviTransfer);
    setprefix("Opdatering af kunder");

    while (rowIdx < lastRow)
    {
        rowIdx++;
        setPrefix(strfmt("Excel Row: %1", rowIdx));

        for (colIdx = 1 ; colIdx <= 4; colIdx++)
            colContent[colIdx] = COMVariant2Str(cells.item(rowIdx,colIdx).value());

        custTable = CustTable::find(cells.item(rowIdx,1).value().bStr(),true);
        if (custTable)
        {
            //custTable.AccountNum                 = colContent[01];
            //custTable.Name                       = colContent[02];
            custTable.InvoiceAccount             = colContent[03];
            custTable.CustGroup                  = colContent[04];

            custTable.update();
        }
        else
            info(strfmt("Unknown customer",cells.item(rowIdx,1).value().bStr()));

        linesImported++;

        progress_.setText("Importing " + cells.item(rowIdx,1).value().bStr());
        progress_.setCount(linesImported);
    }

    application.quit();
    application = null;

    ttscommit;
    info(strfmt("File %1 imported",filename));
}

AX usefull methods when working with Excel

$
0
0
findLastColumn

int findLastColumn(SysExcelWorksheet _sysExcelWorksheet, boolean _data = true)

{   
    #Excel

    #define.Star(‘*’)

    SysExcelRange   sysExcelRange;

    int             ret;

    ;  
    sysExcelRange = _data ?

                    _sysExcelWorksheet.cells().range(#ExcelDataRange) :

                    _sysExcelWorksheet.cells().range(#ExcelTotalRange);

    try

    {

        sysExcelRange = sysExcelRange.find(#Star, null, #xlFormulas, #xlWhole, #xlByColumns, #xlPrevious);

    }

    catch (Exception::Error)

    {

        error("@SYS59926");       
    }

    if (sysExcelRange)

        ret = sysExcelRange.column();

    return ret;

}

————————————————-

findLastRow

int findLastRow(SysExcelWorksheet _sysExcelWorksheet)

{

    #Excel   
    #define.Star(‘*’)

    #define.ExcelDataRange("A1:IV65536")

    SysExcelRange   sysExcelRange = _sysExcelWorksheet.cells().range(#ExcelDataRange);

    int             ret;

    ;  
    try

    {

        sysExcelRange = sysExcelRange.find(#Star, null, #xlFormulas, #xlWhole, #xlByRows, #xlPrevious);

    }

    catch (Exception::Error)

    {

        error("@SYS59926");

    }

    if (sysExcelRange)

        ret = sysExcelRange.row();

    return ret;

}

Found here: http://www.cnblogs.com/Fandyx/p/3462794.html

————————————————-

ExcelFormating

static void ExcelFormating(Args _args)

{

    #Excel

    SysExcelApplication         excel;

    SysExcelWorkbooks           books;

    SysExcelWorkbook            book;

    SysExcelWorksheet           sheet;

    SysExcelRange               range;

    SysExcelStyles              styles;

    SysExcelStyle               style;

    SysExcelInterior            interior;

    SysExcelFont                font;

    COM                         _char, _r;

    ;

    excel       = SysExcelApplication::construct();

    excel.visible(true);

    books       = excel.workbooks();

    book        = books.add();

    sheet       = excel.activeSheet();

    range       = sheet.range(‘A1′);

    styles      = book.styles();

    style       = styles.add(‘MyStyle’);

    interior    = style.interior();

    interior.color(WinApi::RGB2int(246, 233, 206));

    font        = style.font();

    font.bold(true);

    font.color(winapi::RGB2int(153, 204, 255));

    range.style(‘MyStyle’);

    range.locked(true);

    _r          = range.comObject();

    _char       = _r.characters(1);

    _char.insert(‘MyStyle’);

}

Found here: https://www.mail-archive.com/development-axapta@yahoogroups.com/msg02755.html

————————————————-

Rotate text in Excel using axapta X++

public void setCellProperty(int _r1, int _c1,int _r2, int _c2,
       int _orientation = 0,
       int _horizontalAlignment = 1,
       int _verticalAlignment = 1,
       boolean _wrapText = False,  
       boolean _addIndent = False,
       int     _indentLevel = 0,
       boolean _shrinkToFit = False,
       int     _readingOrder = 0, 
       boolean _mergeCells = False)
{
    COM cell1,cell2;
    str range;
    ;
    cell1        = null;
    cell2        = null;
    cell1 = worksheet.cells();
    this.variant2COM(cell1, cell1.item(_r1,_c1));
    cell2 = worksheet.cells();
    this.variant2COM(cell2, cell2.item(_r2,_c2));
    range   =strfmt("%1:%2",cell1.address(),cell2.address());
    cellRange   =worksheet.Range(range);
    cellRange.Mergecells(_mergeCells); 
    cellRange.IndentLevel(_indentLevel);
    cellRange.AddIndent(_addIndent);
    cellRange.Orientation(_orientation);
    cellRange.VerticalAlignment(_verticalAlignment);
    cellRange.HorizontalAlignment(_horizontalAlignment);
}
Found here: http://stackoverflow.com/questions/12777147/rotate-text-in-excel-using-axapta-x

More export from AX til Excel and import to AX from Excel

$
0
0
 
I found some code that: 
 - show how to create a template in a method.
 - demonstrate importing with excel using a method.
 - show an export of data using excel via a method.
 - demonstrate how you can update existing data in AX using excel via  method

All you see below is copy/paste Smiley with some cosmetic changes.
The first thing I will do is create a template in a method.
void createTemplate()
{
 SysExcelApplication xlsApplication;
 SysExcelWorkBooks xlsWorkBookCollection;
 SysExcelWorkBook xlsWorkBook;
 SysExcelWorkSheets xlsWorkSheetCollection;
 SysExcelWorkSheet xlsWorkSheet;
 SysExcelRange xlsRange;
 CustTable custTable;
 WfsRMCustAssignedRoute assignedRoute;
 int row = 1;
 str fileName;
 ;
 //Filename
 fileName = "C:\\Test.xlsx";

 //Initialize Excel instance
 xlsApplication = SysExcelApplication::construct();

 //Open Excel document
 //xlsApplication.visible(true);

 //Create Excel WorkBook and WorkSheet
 xlsWorkBookCollection = xlsApplication.workbooks();
 xlsWorkBook = xlsWorkBookCollection.add();
 xlsWorkSheetCollection = xlsWorkBook.worksheets();
 xlsWorkSheet = xlsWorkSheetCollection.itemFromNum(1);

 //Excel columns captions
 xlsWorkSheet.cells().item(row,1).value("Item number");
 // xlsWorkSheet.cells().item(row,2).value("Item name ");
 xlsWorkSheet.cells().item(row,2).value("Quanitity");
 xlsWorkSheet.cells().item(row,3).value("UM");

 row++;

 xlsWorkSheet.columns().autoFit();

 //Check whether the document already exists
 if(WinApi::fileExists(fileName))
 WinApi::deleteFile(fileName);

 //Save Excel document
 // xlsWorkbook.saveAs(fileName);

 //Open Excel document
 xlsApplication.visible(true);

 //Close Excel
 //xlsApplication.quit();
 //xlsApplication.finalize();
}

Next I will demonstrate importing with excel using a method 
void importToExcel()
{

 SysExcelApplication application;
 SysExcelWorkbooks workbooks;
 SysExcelWorkbook workbook;
 SysExcelWorksheets worksheets;
 SysExcelWorksheet worksheet;
 SysExcelCells cells;
 COMVariantType type;
 System.DateTime ShlefDate;
 FilenameOpen filename;
 dialogField dialogFilename;
 Dialog dialog;
 //Table Declarations Starts
 WfsRMTruckPlanItems items;
 WfsRMTruckPlanItems checkRoute;
 //Table Declartions Ends
 ItemId itemId;
 ItemName itemName;
 str qty;
 UnitId unitId;
 CustTable findCustTable;
 str delSeq;
 InventTable inventTable;
 int row = 1;

 #Excel
 // convert into str from excel cell value
 str COMVariant2Str(COMVariant _cv, int _decimals = 0, int _characters = 0, int _separator1 = 0, int _separator2 = 0)
 {
  switch (_cv.variantType())
  {
   case (COMVariantType::VT_BSTR):
    return _cv.bStr();
   case (COMVariantType::VT_R4):
    return num2str(_cv.float(),_characters,_decimals,_separator1,_separator2);
   case (COMVariantType::VT_R8):
    return num2str(_cv.double(),_characters,_decimals,_separator1,_separator2);
   case (COMVariantType::VT_DECIMAL):
    return num2str(_cv.decimal(),_characters,_decimals,_separator1,_separator2);
   case (COMVariantType::VT_DATE):
    return date2str(_cv.date(),123,2,1,2,1,4);
   case (COMVariantType::VT_EMPTY):
    return "";
   default:
    throw error(strfmt("@SYS26908", _cv.variantType()));
  }
  return "";
 }
 ;
 ttsbegin;
 delete_from checkRoute where checkRoute.TruckPlanVerId == WfsRMTruckPlanVer.TruckPlanVerId;
 ttscommit;

 info("Excel import template must be used with the following columns, A) Item number B) Quantity C) UM");

 dialog = new Dialog("Upload Route plan items import file");
 dialogFilename = dialog.addField(typeId(FilenameOpen));
 dialog.filenameLookupFilter(["@SYS28576",#XLSX,"@SYS28576",#XLS]);
 dialog.filenameLookupTitle("Route plan items import");
 dialog.caption("Route plan items import");
 dialogFilename.value(filename);
 
 if(!dialog.run())
  return;
 
 filename = dialogFilename.value();
 application = SysExcelApplication::construct();
 workbooks = application.workbooks();
 try
 {
  workbooks.open(filename);
 }
 catch (Exception::Error)
 {
  throw error("File cannot be opened.");
 }
 workbook = workbooks.item(1);
 worksheets = workbook.worksheets();
 worksheet = worksheets.itemFromNum(1);
 cells = worksheet.cells();
 try
 {
  ttsbegin;
  do
  {
   row++;
   ItemId = COMVariant2Str(cells.item(row, 1).value());
   // ItemName = COMVariant2Str(cells.item(row,2).value());
   Qty = COMVariant2str(cells.item(row, 2).value());
   UnitId = COMVariant2Str(cells.item(row, 3).value());

   if(row > 1)
   {
    if(InventTable::find(itemId))
    {
     items.clear();
     items.selectForUpdate();
     items.ItemId = itemId;
     items.Qty = str2num(qty);
     items.UnitId = unitId;
     items.TruckPlanVerId = WfsRMTruckPlanVer.TruckPlanVerId;
     items.insert();
    }
   }
   type = cells.item(row+1, 1).value().variantType();
  }while (type != COMVariantType::VT_EMPTY);
  application.quit();
  ttscommit;
 }
 catch
 {
  Error("Import Failed");
 }
}
------------------------------------------------------------------------------------
Next I will show an export of data using excel via a method
void exportToExcel()
{
 CustTable custTable;
 SysExcelApplication application;
 SysExcelWorkBooks workbooks;
 SysExcelWorkBook workbook;
 SysExcelWorksheets worksheets;
 sysExcelWorksheet worksheet;
 SysExcelCells cells;
 SysExcelCell cell;
 int row;
 WfsCSWalkupCustInfo custInfo;
 ;
 application = SysExcelApplication::construct();
 workbooks = application.workbooks(); //gets the workbook object
 workbook = workbooks.add(); // creates a new workbook
 worksheets = workbook.worksheets(); //gets the worksheets object
 worksheet = worksheets.itemFromNum(1);//Selects the first worksheet in the workbook to insert data
 cells = worksheet.cells();
 cells.range('A:A').numberFormat('@'); // numberFormat ‘@’ is to insert data as Text

 while select custInfo
 //The following loop will provide the data to be populated in each column
 {
  row++;
  cell = cells.item(row,1);
  cell.value(custInfo.CompanyName);
  cell = cells.item(row,2);
  cell.value(custInfo.FirstName);
  cell = cells.item(row,3);
  cell.value(custInfo.LastName);
  cell = cells.item(row,4);
  cell.value(custInfo.Phone);
  cell = cells.item(row,5);
  cell.value(custInfo.Email);
  cell = cells.item(row,6);
  cell.value(custInfo.Street);
  cell = cells.item(row,7);
  cell.value(custInfo.StateId);
  cell = cells.item(row,8);
  cell.value(custInfo.City);
  cell = cells.item(row,9);
  cell.value(custInfo.Country);
  cell = cells.item(row,10);
  cell.value(custInfo.ZipCodeId);
 }
 application.visible(true); // opens the excel worksheet
}
----------------------------------------------

Now I will demonstrate how you can update existing data in AX using excel via  method

static void WfsRMUpdateCustomers(Args _args)
{

 SysExcelApplication application;
 SysExcelWorkbooks workbooks;
 SysExcelWorkbook workbook;
 SysExcelWorksheets worksheets;
 SysExcelWorksheet worksheet;
 SysExcelCells cells;
 COMVariantType type;
 System.DateTime ShlefDate;
 FilenameOpen filename;
 dialogField dialogFilename;
 Dialog dialog;
 wfsRMParameters parms = wfsRMParameters::find();
 FileIOPermission fioPermission;
 str filename2 = "CustomerUpdateErrorLog" + strltrim(date2str(systemdateget(),213,1,1,2,1,4))+".txt";// "C:\\Users\\dstevenson\testing.txt";
 str sTempPath;

 Args args = new args();
 wfsRMPickListSummary lines;
 ReportRun reportRun;
 //"C:\\Users\\dstevenson\\CustomerUpdateErrorLog" + date2str(systemdateget(),213,2,4,2,4,4)+".txt";
 AsciiIo txIoRead,
 txIoWrite;
 // txIoWrite = new TextIo( sTempPath + sFileName ,"W");
 //Table Declarations Starts
 CustTable custTable;
 AddressCountryRegion AddressCountryRegion;
 AddressState AddressState;
 AddressZipCode AddressZipCode;
 AddressCounty AddressCounty;
 CustGroup custGroupTbl;
 smmBusRelSegmentGroup smmBusRelSegmentGroup;
 smmBusRelSubSegmentGroup smmBusRelSubSegmentGroup;
 LineOfBusiness LineOfBusiness;
 CustStatisticsGroup CustStatisticsGroup;
 CustClassificationGroup CustClassificationGroup;
 WfsCustSICCode WfsCustSICCode;
 WfsCustNaicsCode WfsCustNaicsCode;
 WfsCustClassification1 WfsCustClassification1;
 WfsCustClassification2 WfsCustClassification2;
 WfsCustClassification3 WfsCustClassification3;
 WfsCustClassification4 WfsCustClassification4;
 WfsCustClassification5 WfsCustClassification5;
 wfsArea wfsArea;
 wfsRegion wfsRegion;
 DirPartyTable DirPartyTable;
 Address Address;
 wfsRMRouteTable routeTable;
 wfsRMCustomerUpdateErrorLog wfsRMCustomerUpdateErrorLog;

 //Table Declartions Ends
 custAccount custAccount;
 Addressing addressing;
 AddressStateId state;
 AddressCountyId county;
 AddressCity city;
 AddressZipCodeId zip;
 AddressCountryRegionId country;
 smmSegmentId segment;
 smmSubsegmentId subSegment;
 CustGroupId custGroup;
 CustLineOfBusinessId lineOfBusinessID;
 CustClassificationId channel;
 CustStatGroupId stats;
 WfsCustSicCodeID sicCodeId;
 str NAICS;
 WfsCustClassification1Id cust1;
 WfsCustClassification2Id cust2;
 WfsCustClassification3Id cust3;
 WfsCustClassification4Id cust4;
 WfsCustClassification5Id cust5;
 wfsAreaId area;
 wfsRegionId region;
 wfsRMRouteId route;
 CustAccount oldCustomer;
 EmplId tradeMarketingRep;
 EmplId salesRep;

 str delSeq;
 InventTable inventTable;
 int row = 1;
 Counter x = 0, y = 0;
 boolean ret = true;

 #Excel
 // convert into str from excel cell value
 str COMVariant2Str(COMVariant _cv, int _decimals = 0, int _characters = 0, int _separator1 = 0, int _separator2 = 0)
 {
 switch (_cv.variantType())
 {
 case (COMVariantType::VT_BSTR):
 return _cv.bStr();
 case (COMVariantType::VT_R4):
 return num2str(_cv.float(),_characters,_decimals,_separator1,_separator2);
 case (COMVariantType::VT_R8):
 return num2str(_cv.double(),_characters,_decimals,_separator1,_separator2);
 case (COMVariantType::VT_DECIMAL):
 return num2str(_cv.decimal(),_characters,_decimals,_separator1,_separator2);
 case (COMVariantType::VT_DATE):
 return date2str(_cv.date(),123,2,1,2,1,4);
 case (COMVariantType::VT_EMPTY):
 return "";
 default:
 throw error(strfmt("@SYS26908", _cv.variantType()));
 }
 return "";
 }
 ;

 // info("Excel import template must be used with the following columns, A) Item number B) Quantity C) UM");

 dialog = new Dialog("Update customer table from excel spreadsheet");
 dialogFilename = dialog.addField(typeId(FilenameOpen));
 dialog.filenameLookupFilter(["@SYS28576",#XLSX,"@SYS28576",#XLS]);
 dialog.filenameLookupTitle("Customer update file");
 dialog.caption("Customer update");
 dialogFilename.value(filename);
 if(!dialog.run())
 return;
 filename = dialogFilename.value();
 application = SysExcelApplication::construct();
 workbooks = application.workbooks();
 fioPermission = new FileIOPermission
 (filename2 ,"RW");
 fioPermission.assert();
 sTempPath = parms.CustomerImportFileName;//WINAPI::getTempPath();
 // sTempPath = WINAPI::getTempPath();
 txIoWrite = new AsciiIo( sTempPath + filename2 ,"W");
 try
 {
 workbooks.open(filename);
 }
 catch (Exception::Error)
 {
 throw error("File cannot be opened.");
 }
 workbook = workbooks.item(1);
 worksheets = workbook.worksheets();
 worksheet = worksheets.itemFromNum(1);
 cells = worksheet.cells();

 try
 {
 ttsbegin;
 do
 {
 row++;
 ret = true;

 custAccount = COMVariant2Str(cells.item(row, 1).value());
 addressing = COMVariant2Str(cells.item(row, 2).value());
 city = COMVariant2str(cells.item(row, 3).value());
 State = COMVariant2Str(cells.item(row, 4).value());
 Zip = COMVariant2Str(cells.item(row, 5).value());
 country = COMVariant2Str(cells.item(row, 6).value());
 segment = COMVariant2Str(cells.item(row, 7).value());
 subSegment = COMVariant2Str(cells.item(row, 8).value());
 custGroup = COMVariant2Str(cells.item(row, 9).value());
 channel = COMVariant2Str(cells.item(row, 10).value());
 stats = COMVariant2Str(cells.item(row, 11).value());
 lineOfBusinessId = COMVariant2Str(cells.item(row, 12).value());
 sicCodeId = COMVariant2Str(cells.item(row, 13).value());
 NAICS = COMVariant2Str(cells.item(row, 14).value());
 cust1 = COMVariant2Str(cells.item(row, 15).value());
 cust2 = COMVariant2Str(cells.item(row, 16).value());
 cust3 = COMVariant2Str(cells.item(row, 17).value());
 cust4 = COMVariant2Str(cells.item(row, 18).value());
 cust5 = COMVariant2Str(cells.item(row, 19).value());
 area = COMVariant2Str(cells.item(row, 20).value());
 region = COMVariant2Str(cells.item(row, 21).value());
 route = COMVariant2Str(cells.item(row, 22).value());
 oldCustomer = COMVariant2Str(cells.item(row, 23).value());
 tradeMarketingRep = COMVariant2Str(cells.item(row, 24).value());
 salesRep = COMVariant2Str(cells.item(row, 25).value());

 if(row > 1)
 {

 custTable = custTable::find(custAccount,true);
 if(!custTable && oldCustomer)
 {
 select firstonly forupdate custTable where custTable.WfsOldAccountNum == oldCustomer;
 }
 DirPartyTable = DirPartyTable::find(custTable.PartyId);
 Address = Address::find(DirPartyTable.TableId,DirPartyTable.RecId,AddressType::Invoice,true);
 if(custTable)
 {
 if(address)
 {
 if(addressing && ret)
 {
 address.Street = addressing;
 }
 if(city && ret)
 {
 address.City = city;
 }

 if(state && country && ret)
 {
 AddressCountryRegion = AddressCountryRegion::find(country);
 AddressState = AddressState::find(country,state);
 if(AddressState && AddressCountryRegion)
 {
 address.CountryRegionId = country;
 address.State = state;
 }
 else
 {
 ret = false;
 wfsRMCustomerUpdateErrorLog.clear();
 wfsRMCustomerUpdateErrorLog.CustAccount = custAccount;
 wfsRMCustomerUpdateErrorLog.OldCustAcct = oldCustomer;
 wfsRMCustomerUpdateErrorLog.State = state;
 wfsRMCustomerUpdateErrorLog.Country = country;
 wfsRMCustomerUpdateErrorLog.insert();
 y++;

 }
 }
 if(AddressCountryRegion && country && ret == true)
 {
 address.CountryRegionId = country;
 }

 AddressZipCode = AddressZipCode::find(zip);
 if(AddressZipCode && zip && ret == true)
 {
 Address.ZipCode = zip;
 }
 else
 {
 if(zip && !AddressZipCode)
 {
 ret = false;
 wfsRMCustomerUpdateErrorLog.clear();
 wfsRMCustomerUpdateErrorLog.CustAccount = custAccount;
 wfsRMCustomerUpdateErrorLog.OldCustAcct = oldCustomer;
 wfsRMCustomerUpdateErrorLog.ZipCode = zip;
 wfsRMCustomerUpdateErrorLog.insert();
 y++;
 //continue;
 }
 }
 AddressCounty = AddressCounty::find(country,state,county);
 if(AddressCounty && county && ret)
 {
 if(county)
 {
 address.County = county;
 }
 else
 {
 ret = false;
 wfsRMCustomerUpdateErrorLog.clear();
 wfsRMCustomerUpdateErrorLog.CustAccount = custAccount;
 wfsRMCustomerUpdateErrorLog.County = county;
 wfsRMCustomerUpdateErrorLog.insert();
 y++;
 // continue;
 }
 }
 if(ret)
 {
 address.Address = address::formatAddress(address.Street,address.ZipCode,address.City,
 address.CountryRegionId,address.State,address.County);
 address.update();
 }
 }

 //Attributes
 if(segment)
 {
 smmBusRelSegmentGroup = smmBusRelSegmentGroup::find(segment);
 if(smmBusRelSegmentGroup && segment && ret)
 {
 custTable.SegmentId = segment;
 }
 else
 {
 ret = false;
 wfsRMCustomerUpdateErrorLog.clear();
 wfsRMCustomerUpdateErrorLog.CustAccount = custAccount;
 wfsRMCustomerUpdateErrorLog.OldCustAcct = oldCustomer;
 wfsRMCustomerUpdateErrorLog.segment = segment;
 wfsRMCustomerUpdateErrorLog.insert();
 y++;
 // continue;
 }
 }
 if(subSegment)
 {
 select firstonly smmBusRelSubSegmentGroup where smmBusRelSubSegmentGroup.SubsegmentId == subsegment &&
 smmBusRelSubSegmentGroup.SegmentId == segment;
 if( smmBusRelSubSegmentGroup && ret)
 {

 custTable.SubsegmentId = subsegment;
 }
 else
 {
 ret = false;
 wfsRMCustomerUpdateErrorLog.clear();
 wfsRMCustomerUpdateErrorLog.CustAccount = custAccount;
 wfsRMCustomerUpdateErrorLog.Subsegment = subSegment;
 wfsRMCustomerUpdateErrorLog.insert();
 y++;
 }
 }
 if(lineofBusinessId && ret)
 {
 LineOfBusiness = LineOfBusiness::find(lineOfBusinessId);
 if(LineOfBusiness)
 {
 custTable.LineOfBusinessId = lineofBusinessId;
 }
 else
 {
 ret = false;
 wfsRMCustomerUpdateErrorLog.clear();
 wfsRMCustomerUpdateErrorLog.CustAccount = custAccount;
 wfsRMCustomerUpdateErrorLog.LineOfBusiness = LineOfBusinessId;
 wfsRMCustomerUpdateErrorLog.OldCustAcct = oldCustomer;
 wfsRMCustomerUpdateErrorLog.insert();
 y++;

 }
 }
 if(stats && ret)
 {
 CustStatisticsGroup = CustStatisticsGroup::find(stats);
 if(CustStatisticsGroup)
 {
 custTable.StatisticsGroup = stats;
 }
 else
 {
 wfsRMCustomerUpdateErrorLog.clear();
 wfsRMCustomerUpdateErrorLog.CustAccount = custAccount;
 wfsRMCustomerUpdateErrorLog.SalesLocation = stats;
 wfsRMCustomerUpdateErrorLog.OldCustAcct = oldCustomer;
 wfsRMCustomerUpdateErrorLog.insert();
 y++;
 // continue;
 }
 }
 if(channel && ret)
 {
 custTable.CustClassificationId = channel;
 }
 if(SicCodeId && ret)
 {
 WfsCustSICCode = WfsCustSICCode::find(sicCodeId);
 if(WfsCustSICCode)
 {
 custTable.WfsSicCodeID = sicCodeId;
 }
 else
 {
 ret = false;
 wfsRMCustomerUpdateErrorLog.clear();
 wfsRMCustomerUpdateErrorLog.CustAccount = custAccount;
 wfsRMCustomerUpdateErrorLog.SICCodeId = sicCodeId;
 wfsRMCustomerUpdateErrorLog.OldCustAcct = oldCustomer;
 wfsRMCustomerUpdateErrorLog.insert();
 y++;
 //continue;
 }
 }
 if(NAICS && ret)
 {
 WfsCustNaicsCode = WfsCustNaicsCode::find(naics);
 if(WfsCustNaicsCode)
 {
 custTable.WfsNaicsCode = naics;
 }
 else
 {
 ret = false;
 wfsRMCustomerUpdateErrorLog.clear();
 wfsRMCustomerUpdateErrorLog.CustAccount = custAccount;
 wfsRMCustomerUpdateErrorLog.NACISCode = naics;
 wfsRMCustomerUpdateErrorLog.OldCustAcct = oldCustomer;
 wfsRMCustomerUpdateErrorLog.insert();
 y++;
 }
 }
 if(cust1 && ret)
 {
 select firstonly WfsCustClassification1 where WfsCustClassification1.Classification1 == cust1;
 if(cust1)
 {
 custTable.WfsCustClassification1Id = cust1;
 }
 else
 {
 ret = false;
 wfsRMCustomerUpdateErrorLog.clear();
 wfsRMCustomerUpdateErrorLog.CustAccount = custAccount;
 wfsRMCustomerUpdateErrorLog.Class1 = cust1;
 wfsRMCustomerUpdateErrorLog.OldCustAcct = oldCustomer;
 wfsRMCustomerUpdateErrorLog.insert();
 y++;
 }
 }
 if(cust2 && ret)
 {
 select firstonly WfsCustClassification2 where WfsCustClassification2.Classification2 == cust2;
 if(cust2)
 {
 custTable.WfsCustClassification2Id = cust2;
 }
 else
 {
 ret = false;
 wfsRMCustomerUpdateErrorLog.clear();
 wfsRMCustomerUpdateErrorLog.CustAccount = custAccount;
 wfsRMCustomerUpdateErrorLog.Premise = cust2;
 wfsRMCustomerUpdateErrorLog.OldCustAcct = oldCustomer;
 wfsRMCustomerUpdateErrorLog.insert();
 y++;
 }
 }
 if(cust3 && ret )
 {
 select firstonly WfsCustClassification3 where WfsCustClassification3.Classification3 == cust3;
 if(cust3)
 {
 custTable.WfsCustClassification3Id = cust3;
 }
 else
 {
 ret = false;
 wfsRMCustomerUpdateErrorLog.clear();
 wfsRMCustomerUpdateErrorLog.CustAccount = custAccount;
 wfsRMCustomerUpdateErrorLog.OldCustAcct = oldCustomer;
 wfsRMCustomerUpdateErrorLog.AccountType = cust3;
 wfsRMCustomerUpdateErrorLog.insert();
 y++;
 }
 }
 if(cust4 && ret)
 {
 select firstonly WfsCustClassification4 where WfsCustClassification4.Classification4 == cust4;
 if(cust4)
 {
 custTable.WfsCustClassification4Id = cust4;
 }
 else
 {
 ret = false;
 wfsRMCustomerUpdateErrorLog.clear();
 wfsRMCustomerUpdateErrorLog.CustAccount = custAccount;
 wfsRMCustomerUpdateErrorLog.Class4 = cust4;
 wfsRMCustomerUpdateErrorLog.OldCustAcct = oldCustomer;
 wfsRMCustomerUpdateErrorLog.insert();
 y++;
 // continue;
 }
 }
 if(cust5 && ret)
 {
 select firstonly WfsCustClassification5 where WfsCustClassification5.Classification5 == cust5;
 if(cust5)
 {
 custTable.WfsCustClassification5Id = cust5;
 }
 else
 {
 ret = false;
 wfsRMCustomerUpdateErrorLog.clear();
 wfsRMCustomerUpdateErrorLog.CustAccount = custAccount;
 wfsRMCustomerUpdateErrorLog.Class5 = cust5;
 wfsRMCustomerUpdateErrorLog.OldCustAcct = oldCustomer;
 wfsRMCustomerUpdateErrorLog.insert();
 y++;
 }
 }
 if(area && ret)
 {
 wfsArea = wfsArea::find(area);
 if(wfsArea)
 {
 custTable.wfsAreaId = area;
 }
 else
 {
 ret = false;
 wfsRMCustomerUpdateErrorLog.clear();
 wfsRMCustomerUpdateErrorLog.CustAccount = custAccount;
 wfsRMCustomerUpdateErrorLog.Area = area;
 wfsRMCustomerUpdateErrorLog.OldCustAcct = oldCustomer;
 wfsRMCustomerUpdateErrorLog.insert();
 y++;
 }
 }
 if(region && area && ret)
 {
 wfsRegion = wfsREgion::find(region,area);
 if(wfsRegion)
 {
 custTable.wfsRegionId = region;
 }
 else
 {
 ret = false;
 wfsRMCustomerUpdateErrorLog.clear();
 wfsRMCustomerUpdateErrorLog.CustAccount = custAccount;
 wfsRMCustomerUpdateErrorLog.Region = region;
 wfsRMCustomerUpdateErrorLog.OldCustAcct = oldCustomer;
 wfsRMCustomerUpdateErrorLog.insert();
 y++;
 }
 }
 if(route)
 {
 routeTable = wfsRMRouteTable::find(route);

 }
 if(tradeMarketingRep)
 {
 if(EmplTable::find(tradeMarketingRep))
 {
 custTable.wfsRMTradeMarketingRep = tradeMarketingRep;
 }
 else
 {
 ret = false;
 wfsRMCustomerUpdateErrorLog.clear();
 wfsRMCustomerUpdateErrorLog.CustAccount = custAccount;
 wfsRMCustomerUpdateErrorLog.TradeMarketRep = tradeMarketingRep;
 wfsRMCustomerUpdateErrorLog.OldCustAcct = oldCustomer;
 wfsRMCustomerUpdateErrorLog.insert();
 y++;
 }
 }
 if(salesRep)
 {
 if(EmplTable::find(salesRep))
 {
 custTable.wfsRMTradeMarketingRep = salesRep;
 }
 else
 {
 ret = false;
 wfsRMCustomerUpdateErrorLog.clear();
 wfsRMCustomerUpdateErrorLog.CustAccount = custAccount;
 wfsRMCustomerUpdateErrorLog.SalesRep = salesRep;
 wfsRMCustomerUpdateErrorLog.OldCustAcct = oldCustomer;
 wfsRMCustomerUpdateErrorLog.insert();
 y++;
 }
 }
 if(ret)
 {
 custTable.update();
 x++;
 }

 }
 else
 {
 ret = false;
 wfsRMCustomerUpdateErrorLog.clear();
 wfsRMCustomerUpdateErrorLog.CustAccount = custAccount;
 wfsRMCustomerUpdateErrorLog.OldCustAcct = oldCustomer;
 wfsRMCustomerUpdateErrorLog.insert();
 y++;
 }
 }
 if(oldCustomer && !custAccount)
 {
 type = cells.item(row+1, 23).value().variantType();
 }
 if(!oldCustomer && custAccount)
 {
 type = cells.item(row+1, 1).value().variantType();
 }
 }
 while (type != COMVariantType::VT_EMPTY);
 application.quit();
 ttscommit;
 if(wfsRMCustomerUpdateErrorLog)
 {
 args = new Args();
 args.name(reportStr(wfsRMCustomerUpdateImportErrorLog));

 args.record(wfsRMCustomerUpdateErrorLog);

 reportRun = classfactory.reportRunClass(args);
 reportRun.init();
 reportRun.run();
 }
 info(int2str(x) + " " + "customer record(s) updated successfully." + " " + int2str(y) + " " + "customer record(s) have errors.");
}
 catch
 {
 Error("Import Failed");
 }

}

———————————————-—————————————–

Found here: http://www.winfosoft.com/blog/microsoft-dynamics-ax/data-importing-and-exporting-using-excel

Calculate date out of year, week number and day of week

$
0
0

static void Test_Wk2Date(Args _args)
{
// Week2Date
// _y = Year
// _w = WeekNo
// _d = Day of week (1=Monday,7=Sunday)
// Result: Date for day _d in week _y in year _w

    date Wk2Date(int _y, int _w, int _d)
    {
        return Num2Date(Date2Num(MkDate(1,1,_y))+((((WkOfYr(MkDate(1,1,_y))==1)?(1):(8))-(DayOfWk(MkDate(1,1,_y)))) mod 7)+(_w-1)*7+_d-1);
    }
   
    info(strFmt("%1",Wk2Date(2014,48,WeekDays::Sunday)));
    info(strFmt("%1",Wk2Date(2014,49,WeekDays::Monday)));
   
}

Number of decimals based on Ectended data type (EDT)

$
0
0

//http://bmdax.blogspot.dk/2010/08/num2str-decimals-based-on-edt.html
// http://www.rgagnon.com/pbdetails/pb-0181.html
static str num2strEDT(
    real _number,           //The real number to convert to a string
    ExtCodeValue _edt,      //The EDT to be used as basis for required number of decimal places.
    int _character = 0,     //The minimum number of characters required in the text.
    int _DecSeparator = DecimalSeparator::Comma,    //DecimalSeparator
    int _ThouSeparator = ThousandSeparator::Dot)    //ThousandSeparator
{
    #DEFINE.AUTO(‘Auto’)
    #DEFINE.LOCALE_USER_DEFAULT(1024)
    #DEFINE.LOCALE_ICURRDIGITS(25)

    #AOT
    #PROPERTIES
    #WinAPI // Used for regional settings

    TreeNode treeNode;
    int decimalPlaces;
    ;
    treeNode = infolog.findNode(#ExtendedDataTypesPath + ‘\\’ + _edt);
    if (!treeNode)
        return strfmt("%1", _number);

    if (findproperty(treeNode.AOTgetProperties(),#PropertyNoOfDecimals) == #AUTO)
    {
        // get the number of decimals from the regional settings
        decimalPlaces = str2int((WinAPI::getLocaleInfo(#LOCALE_USER_DEFAULT,   #LOCALE_ICURRDIGITS)));
    }
    else
    {
        // get the number of decimals set by the developer in the property inspector
        decimalPlaces = str2int(findproperty(treeNode.AOTgetProperties(),#PropertyNoOfDecimals));
    }

    return num2str(_number, _character, decimalPlaces, _DecSeparator, _ThouSeparator);
}

Non-visible fields in the Table browser

$
0
0
Found here: http://daxrunbase.blogspot.dk/2010/04/non-visible-fields-in-table-browser.html

An alternative: http://gotdax.blogspot.dk/2013/06/showing-hidden-fields-in-table-browser.html

As developers and consultants often require the ability to check the content of hidden fields without writing a select statement / query, or taking a quick look in the database for retrieving information, I was wondering if there is a way to do that.
The SysTableBrowser class is using the FormBuildControl.addDataField(int dataSourceId, fieldId fieldId) method for bound and FormBuildControl.addControl(FormControlType controlType, str controlName) as an unbound control. These methods are on kernel level, and they are forcing to hide any bound controls where the field property Visible is set to No.
We can add the hidden fields as extra columns in the SysTableBrowser class with a highlighted color, but as the display grid is tied to the datasource we are using it is not possible to populate it with the right values per record.

protected void AddField(tableId tableId,
    fieldId fieldId,
    FormBuildDataSource formBuildDataSource,
    FormBuildGridControl formBuildGridControl,
    boolean allowControlEdit)
{
    FormBuildStringControl formBuildStringControl;
    Object formBuildControl;
    SysDictField dictField;
    int j;
    // WIK -->
    FormControlType     formControlType;
    // WIK <--
    ;

    dictField = new SysDictField(tableId, fieldId);
    if (dictField.saveContents())
    {

// (...)

                    formBuildControl.displayLengthValue(5);
                    formBuildControl.lookupButton(2);
                }

            }

            // WIK -->
            if (! dictField.visible())
            {
                switch (dictField.baseType())
                {
                    case Types::Integer :       formControlType = FormControlType::Integer; break;
                    case Types::Int64  :        formControlType = FormControlType::Int64; break;
                    case Types::Guid :          formControlType = FormControlType::Guid; break;
                    case Types::Real :          formControlType = FormControlType::Real; break;
                    case Types::Date :          formControlType = FormControlType::Date; break;
                    case Types::Time :          formControlType = FormControlType::Time; break;
                    case Types::UtcDateTime :   formControlType = FormControlType::DateTime; break;
                    default :                   formControlType = FormControlType::String;
                }

                formBuildControl = formBuildGridControl.addControl(formControlType, dictField.name());
                formBuildControl.label(dictField.name());
                formBuildControl.colorScheme(FormColorScheme::RGB);
                formBuildControl.backgroundColor(WinAPI::rgb2int(220, 70, 70));
                formBuildControl.helpText(dictField.label());
                formBuildControl.allowEdit(false);
            }
            // WIK <--
        }
    }
}

What we can do though is create a temporary table where we reference the current table, record and field identifiers, and store the relevant data in the dedicated base type fields:

Then we have to add our temporary table to the \\AOT\Forms\SysTableBrowser form, prepare the link to the datasource by the record id reference in it’s initialization:

public void init()
{
    QueryBuildDataSource        qbds;
    ;

    super();

    qbds    = TmpSysTableBrowser_ds.query().dataSourceTable(tablenum(TmpSysTableBrowser));
    // QueryBuildRange qbr -- Global declaration
    qbr     = SysQuery::findOrCreateRange(qbds, fieldnum(TmpSysTableBrowser, RefRecId));
}

When the actual cursor moves on a record (the FormDataSource.active() method is called), we want to populate our table with the right data, then it can be displayed in the TmpGrid grid control which is hidden by default:

public int active()
{
    TmpSysTableBrowser  tmpSysTableBrowserLocal;
    DictTable           dictTableLocal;
    SysDictField        dictField;
    int                 i;
    int                 fieldCnt;
    int                 ret;
    ;

    ret = super();

    element.lockWindowUpdate(true);

    dictTableLocal  = new DictTable(ds.TableId);
    fieldCnt        = dictTableLocal.fieldCnt();

    for (i = 1; i <= fieldCnt; i++)
    {
        dictField   = new SysDictField(ds.TableId, dictTableLocal.fieldCnt2Id(i));

        if (dictField && ! dictField.visible())
        {
            tmpSysTableBrowserLocal.clear();
            switch (dictField.baseType())
            {
                case Types::Integer :
                    tmpSysTableBrowserLocal.IntegerValue    = ds.(dictField.id());
                    TmpSysTableBrowser_IntegerValue.visible(true);
                    break;
                case Types::Guid :
                    tmpSysTableBrowserLocal.GuidValue       = ds.(dictField.id());
                    TmpSysTableBrowser_GuidValue.visible(true);
                    break;
                case Types::Real :
                    tmpSysTableBrowserLocal.RealValue       = ds.(dictField.id());
                    TmpSysTableBrowser_RealValue.visible(true);
                    break;
                case Types::Date :
                    tmpSysTableBrowserLocal.DateValue       = ds.(dictField.id());
                    TmpSysTableBrowser_DateValue.visible(true);
                    break;
                case Types::Time :
                    tmpSysTableBrowserLocal.TimeValue       = ds.(dictField.id());
                    TmpSysTableBrowser_TimeValue.visible(true);
                    break;
                case Types::UtcDateTime :
                    tmpSysTableBrowserLocal.DateTimeValue   = ds.(dictField.id());
                    TmpSysTableBrowser_DateTimeValue.visible(true);
                    break;
                case Types::Int64 :
                    tmpSysTableBrowserLocal.Int64Value   = ds.(dictField.id());
                    TmpSysTableBrowser_Int64Value.visible(true);
                    break;
                case Types::Container :
                    tmpSysTableBrowserLocal.StringValue  = con2str(ds.(dictField.id()));
                    TmpSysTableBrowser_StringValue.visible(true);
                    break;
                default :
                    tmpSysTableBrowserLocal.StringValue  = strfmt('%1', ds.(dictField.id()));
                    TmpSysTableBrowser_StringValue.visible(true);
            }

            tmpSysTableBrowserLocal.FieldName    = dictField.name();
            tmpSysTableBrowserLocal.FieldLabel   = dictField.label();
            tmpSysTableBrowserLocal.DictTableId  = dictTableLocal.id();
            tmpSysTableBrowserLocal.FieldId      = dictField.id();
            tmpSysTableBrowserLocal.RefRecId     = ds.RecId;
            tmpSysTableBrowserLocal.insert();
        }
    }

    if (tmpSysTableBrowserLocal)
    {
        qbr.value(SysQuery::value(ds.RecId));
        TmpSysTableBrowser.setTmpData(tmpSysTableBrowserLocal);
        TmpSysTableBrowser_ds.executeQuery();

        TmpGrid.visible(true);
    }

    element.lockWindowUpdate(false);

    return ret;
}

The final result looks like this, all of our non-visible fields are added to the Table browser and we can see the rest of the data too:

The XPO file is available on the following link for download, with column highlighting and hidden group hiding additions

PrivateProject_WIK_SysTableBrowser.xpo

Hope you like the tool, you may leave feedbacks as comments.

Correct number of decimals on amount

$
0
0

amount = Currency::amount(amount, currencyCode);


Get default dimension – update default dimension

$
0
0

static void My_ShowDefaultDimension(Args _args)
{
    InventTable inventTable;
    DimensionAttributeValueSetStorage dimStorage;
    DimensionAttribute dimAttrOpDiv;
    DimensionAttributeValue dimAttributeValue;
    Counter i;
   
    ;
    while select inventTable
    {
        dimStorage = DimensionAttributeValueSetStorage::find(inventTable.DefaultDimension);

        for (i=1 ; i<= dimStorage.elements() ; i++)
        {
            info(strFmt("Item; %1 – %2 = %3", inventTable.ItemId, DimensionAttribute::find(dimStorage.getAttributeByIndex(i)).Name,       
                                   dimStorage.getDisplayValueByIndex(i)));
        }       
    }
}

static void My_UpdateDefaultDimension(Args _args)
{
    InventTable inventTable;
    DimensionAttributeValueSetStorage dimStorage;
    DimensionAttribute dimAttrOpDiv;
    DimensionAttributeValue dimAttributeValue;

    void updateDimStorage(str _group, str _value)
    {
        if (_value)
        {
            dimAttrOpDiv = DimensionAttribute::findByName(_group);
            dimAttributeValue = DimensionAttributeValue::findByDimensionAttributeAndValueNoError(dimAttrOpDiv, _value, true, true);
            if (dimAttributeValue)
                dimStorage.addItem(dimAttributeValue);
            else
                info(strFmt("Attribute value not found: %1, %2 / %3", inventTable.ItemId, _group, _value));
        }
    }

    ;
    if (Box::yesNo("Update dimensions?", DialogButton::No) == DialogButton::Yes)
    {
        ttsBegin;
        while select forUpdate inventTable
        {
            dimStorage = DimensionAttributeValueSetStorage::find(inventTable.DefaultDimension);

            updateDimStorage(‘AAAAAA’, ‘xxxx’);
            updateDimStorage(‘BBBBBB’, ‘yyyy’);
            updateDimStorage(‘CCCCCC’, ‘zzzz’);

            inventTable.DefaultDimension = dimStorage.save();
            inventTable.doUpdate();
        }
        //ttsAbort;
        ttsCommit;
        info("DONE!");
    }
    else
        info("ABORTED!");
}

get languageId

$
0
0

To get system languageID use:

SystemParameters::getSystemLanguageId();

To get company languageID use:

companyinfo::languageId();

or

infolog.language()

To get the user language use:

SRSConfiguration::getUserLanguage();

AX 2012 Find Ledger transactions

$
0
0

static void My_findLedgerTransactions(Args _args)
{
    MainAccount mainAccount;
    GeneralJournalEntry generalJournalEntry;
    GeneralJournalAccountEntry generalJournalAccountEntry;
    DimensionAttributeValueCombination dimAttrValueComb;
    SubledgerVoucherGeneralJournalEntry subledgerVoucherGeneralJournalEntry;
    ledgerEntry ledgerEntry;
    ledgerEntryJournal ledgerEntryJournal;
    ledgerEntryJournalizing ledgerEntryJournalizing;

    date    dateFrom = str2Date("20130101",321);
    date    dateTo = str2Date("20131231",321);

    MainAccountNum  accountFrom = ”;
    MainAccountNum  accountTo = ‘999999999’;

    Voucher         voucherFrom = ”;
    Voucher         voucherTo = ‘99999999999999999999’;
    ;
    while select AccountingCurrencyAmount, TransactionCurrencyAmount, TransactionCurrencyCode
            from generalJournalAccountEntry
        join dimAttrValueComb
            where dimAttrValueComb.RecId == generalJournalAccountEntry.LedgerDimension
        join AccountingDate, JournalNumber from generalJournalEntry
            where generalJournalAccountEntry.GeneralJournalEntry == generalJournalEntry.RecId
            && generalJournalEntry.AccountingDate >= dateFrom
            && generalJournalEntry.AccountingDate <= dateTo
            && generalJournalEntry.PostingLayer == CurrentOperationsTax::Current
            && generalJournalEntry.Ledger == Ledger::current()
        join MainAccountId, Name from mainAccount
            where mainAccount.RecId == dimAttrValueComb.MainAccount
             && mainAccount.MainAccountId >= accountFrom
             && mainAccount.MainAccountId <= accountTo
        join subledgerVoucherGeneralJournalEntry
            where subledgerVoucherGeneralJournalEntry.GeneralJournalEntry == GeneralJournalEntry.RecId
             && subledgerVoucherGeneralJournalEntry.Voucher >= voucherFrom
             && subledgerVoucherGeneralJournalEntry.Voucher <= voucherTo
        outer join RecId from ledgerEntry
            where ledgerEntry.GeneralJournalAccountEntry == generalJournalAccountEntry.RecId
        outer join RecId from ledgerEntryJournal
            where ledgerEntryJournal.RecId == generalJournalEntry.LedgerEntryJournal
        outer join RecId from ledgerEntryJournalizing
            where ledgerEntryJournalizing.GeneralJournalAccountEntry == generalJournalAccountEntry.RecId
    {
        info(strFmt("%1-%2, %3, %4, %5, %6, %7, %8", mainAccount.MainAccountId, mainAccount.Name,
                    generalJournalEntry.AccountingDate, subledgerVoucherGeneralJournalEntry.Voucher,
                    generalJournalAccountEntry.TransactionCurrencyCode, generalJournalAccountEntry.TransactionCurrencyAmount,
                    generalJournalAccountEntry.AccountingCurrencyAmount,
                    generalJournalEntry.JournalNumber));
    }
}

 

Found it here: http://www.cnblogs.com/Fandyx/archive/2012/11/20/2779405.html

Loop through AOT Tables and export selected proporties

$
0
0

static void GITS_ESH_ExportTableProporties(Args _args)
{
    xInfo               xInfo;
    TreeNode            node;
    TreeNode            childNode;
    TreeNodeIterator    nodeIterator;
   
    str                 filename = @’C:\TEMP\TableProporties.csv';
    AsciiIo             expFile;
    str                 wStr;
    str                 recDel = ‘\r\n';
    str                 fldDel = ‘;';
    ;
    expFile = new AsciiIo(filename,’W’);

    xInfo = new xInfo();
    node = xInfo.rootNode().AOTfindChild(‘Data Dictionary’);
    node = node.AOTfindChild(‘Tables’);
    nodeIterator = node.AOTiterator();

    childNode = nodeIterator.next();
    while (childNode)
    {
        wStr = childNode.AOTgetProperty(‘name’);
        wStr += fldDel + childNode.AOTgetProperty(‘TableGroup’);
        wStr += RecDel;
        expFile.writeRaw(wStr);
        childNode = nodeIterator.next();
    }
    expFile.finalize();
}

Delete last value information

$
0
0

xSysLastValue::deleteLast(this);

Viewing all 53 articles
Browse latest View live