Thursday 7 June 2018

Generate ProgressBar in AX 2012

Static void SysOperationProgress_PrimeNumber(Args _args)
{
    #avifiles
    boolean                 checkPrime,_showProgess = true;
    SysOperationProgress    progressBar = new SysOperationProgress();
    int                     counter,out;
   
    ;
   
    counter = 1;
    out     = 1000;
   
    while(counter < out)
    {
        checkPrime = ((counter mod 2)!=0 && (counter mod 3) !=0);
        if(checkPrime)
        {
            info(strfmt("its a prime number %1",counter));
        }
        progressBar.setCaption(strfmt("Generating the prime number for %1",counter));
        progressBar.setAnimation(#aviUpdate);//#AviFindFile);//progress.setAnimation(#AviTransfer);
        progressBar.setText(strfmt("Processing %1 out of %2",counter,out));
        counter++;
    }
}

Monday 4 June 2018

Importing Assert Details in X++

static void importAsset2(Args _args)
{
    Dialog                      dialog;
    Dialogfield                 dialogfield;

    SysExcelApplication         application;
    SysExcelWorkbooks           workBooks;
    SysExcelWorkbook            workBook;
    SysExcelWorksheets          workSheets;
    SysExcelWorksheet           workSheet;
    SysExcelCells               cells;

    AssetLocation               assetLocation;
    AssetGroup                  assetGroup;
    AssetTable                  assetTable;
    AssetBook                   assetBook;
    AssetBookTable              assetBookTable;

    AssetLocationId             location;
    AssetGroupId                assetGrp;
    AssetBookId                 assetBkId;
    AssetId                     assetId;
    Name                        name;
    AssetAcquisitionDate        assetAcqDate;
    AssetAcquisitionPrice       assetAcqPrice;
    AssetDepreciate             assetDepreciate;
    AssetServiceLife            assetServiceLife;
    AssetPostingProfile         assetPostingProfile;
    AssetStatus                 assetStatus;

    Filename                    fileName;
    COMVariantType              type;
    int                         row = 1   ;
    int                         recordcnt;
    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 "";
        }

    application =   SysExcelApplication::construct();
    workBooks   =   application.workbooks();
    dialog      = new Dialog("FileOpen");
    dialogfield = dialog.addField(extendedTypeStr(Filenameopen), "File Name");
    dialog.run();

    if (dialog.run())
    {
    filename = (dialogfield.value());
    }
    //fileName    =   @"C:\Users\Naresh.Tumu\Desktop\assert.xlsx";
    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();

    do
    {
        row++;
        location            = strLRTrim(cells.item(row, 11).value().bStr());
        assetGrp            = cells.item(row, 1).value().bStr();
        assetBkId           = cells.item(row, 3).value().bStr();
        assetId             = cells.item(row, 2).value().bStr();
        name                = cells.item(row, 4).value().bStr();
        assetAcqDate        = cells.item(row, 6).value().date();
        assetDepreciate     = str2enum(assetDepreciate,cells.item(row, 10).value().bStr());
        assetPostingProfile = cells.item(row, 7).value().bstr();
        assetServiceLife    = cells.item(row, 8).value().double();
        assetAcqPrice       = cells.item(row, 5).value().double();

        ttsBegin;

        select assetLocation where assetLocation.Location == location;
        select assetGroup where assetGroup.GroupId        == assetGrp;
        select assetBookTable where assetBookTable.BookId == assetBkId;
        select assetTable where assetTable.AssetId        == assetId;
        select assetBook where assetBook.BookId           == assetBkId;
        if(!assetLocation::find(location).Location)
        {
            assetlocation.clear();
            assetLocation.initValue();
            assetLocation.Location = location;
            assetLocation.Name     = location;
            assetLocation.insert();
        }
        if(!assetGroup.GroupId)
        {
            assetGroup.clear();
            assetGroup.initValue();
            assetGroup.GroupId  =   assetGrp;
            assetGroup.Name     =   assetGrp;
            assetGroup.Location =   location;
            assetGroup.insert();
        }
        if(assetTable.AssetId)
        {
            select forUpdate assetTable where  assetTable.AssetId    == assetId;
            ttsBegin;
            assetTable.initValue();
            assetTable.AssetId  =   assetId;
            assetTable.Name     =   name;
            assetTable.AssetGroup = assetGrp;
            assetTable.Location   = location;
            assetTable.Update();
            ttsCommit;
        }
        else
        {
            assetTable.clear();
            assetTable.initValue();
            assetTable.AssetId  =   assetId;
            assetTable.Name     =   name;
            assetTable.AssetGroup = assetGrp;
            assetTable.Location   = location;
            assetTable.insert();
        }
        if(!assetBookTable.BookId)
        {
            assetBookTable.clear();
            assetBookTable.initValue();
            assetBookTable.BookId = assetBkId;
            assetBookTable.Description = assetBkId;
            assetBookTable.insert();
        }

       select forupdate assetBook join  assetTable  where assetBook.AssetId == assetTable.AssetId
                                                      && assetTable.AssetId == assetId
                                                      && assetBook.BookId   == assetBkId;

        if(assetBook.BookId)
        {

            ttsBegin;
            assetBook.BookId    =   assetBkId;
            assetBook.AcquisitionDate = assetAcqDate;
            assetBook.AcquisitionPrice = assetAcqPrice;
            assetBook.ServiceLife      = assetServiceLife;
            assetBook.PostingProfile   = assetPostingProfile;
            assetBook.Status           = assetStatus::NoAcquisition;
            assetBook.Depreciation     = assetDepreciate;
            assetBook.AssetId          = assetTable.AssetId;
            //assetBook.selectForUpdate(true);
            assetBook.Update();
            ttsCommit;

    }

        else
        {
            assetBook.clear();
           
            select assetBookTable where assetBookTable.BookId == assetBkId;

            select assetTable where assetTable.AssetId == assetId;
           
            assetBook.initValue();
            assetBook.BookId           = assetBkId;
            assetBook.AcquisitionDate  = assetAcqDate;
            assetBook.AcquisitionPrice = assetAcqPrice;
            assetBook.ServiceLife      = assetServiceLife;
            assetBook.PostingProfile   = assetPostingProfile;
            assetBook.Status           = assetStatus;
            assetBook.Depreciation     = assetDepreciate;
            assetBook.AssetId          = assetTable.AssetId;
            assetBook.insert();
        }
        ttsCommit;
        type = cells.item(row+1, 1).value().variantType();
        info(strFmt("Records %1-%2 inserted",assetTable.AssetId,assetTable.Location));
    }
    while (type != COMVariantType::VT_EMPTY);
    application.quit();
    workbooks.close();
    info("Done");
}

Importing Assert Details in AX 2012

static void ImportAsset(Args _args)
{
    Dialog                      dialog;
    Dialogfield                 dialogfield;

    SysExcelApplication         application;
    SysExcelWorkbooks           workBooks;
    SysExcelWorkbook            workBook;
    SysExcelWorksheets          workSheets;
    SysExcelWorksheet           workSheet;
    SysExcelCells               cells;

    AssetLocation               assetLocation;
    AssetGroup                  assetGroup;
    AssetTable                  assetTable;
    AssetBook                   assetBook;
    AssetBookTable              assetBookTable;

    AssetLocationId             location;
    AssetGroupId                assetGrp;
    AssetBookId                 assetBkId;
    AssetId                     assetId;
    Name                        name;
    AssetAcquisitionDate        assetAcqDate;
    AssetAcquisitionPrice       assetAcqPrice;
    AssetDepreciate             assetDepreciate;
    AssetServiceLife            assetServiceLife;
    AssetPostingProfile         assetPostingProfile;
    AssetStatus                 assetStatus;

    Filename                    fileName;
    COMVariantType              type;
    int                         row = 1  ;
    int                         recordcnt;
    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 "";
        }

    application =   SysExcelApplication::construct();
    workBooks   =   application.workbooks();
    dialog      = new Dialog("FileOpen");
    dialogfield = dialog.addField(extendedTypeStr(Filenameopen), "File Name");
    dialog.run();

    if (dialog.run())
    {
    filename = (dialogfield.value());
    }
    //fileName    =   @"C:\Users\Naresh.Tumu\Desktop\Assert.xlsx";
    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();

    do
    {

        row++;
        location    = cells.item(row, 11).value().bStr();
        assetGrp    = cells.item(row, 1).value().bStr();
        assetBkId   = cells.item(row, 3).value().bStr();
        assetId     = cells.item(row, 2).value().bStr();
        name        = cells.item(row, 4).value().bStr();
        assetAcqDate = cells.item(row, 6).value().date();
        assetDepreciate = str2enum(assetDepreciate,cells.item(row, 10).value().bStr());
        assetStatus = str2enum(assetStatus,cells.item(row, 9).value().bstr());
        assetPostingProfile = cells.item(row, 7).value().bstr();
        assetServiceLife = cells.item(row, 8).value().double();
        assetAcqPrice   =  cells.item(row, 5).value().double();

        assetLocation.clear();
        select assetLocation where assetLocation.Location == location;

        assetGroup.clear();
        select assetGroup where assetGroup.GroupId == assetGrp;

        assetBookTable.clear();
        select assetBookTable where assetBookTable.BookId == assetBkId;

        assetTable.clear();
        select assetTable where assetTable.AssetId == assetId;

        assetBook.clear();
        select assetBook where assetBook.BookId == assetBkId;

        ttsBegin;

        if(!assetLocation.RecId  && !assetBookTable.recid && !assetTable.RecId && !assetBook.RecId && !assetGroup.RecId )
        {
            assetLocation.initValue();
            assetLocation.Location   =   location;
            assetLocation.Name       =   location;
            assetLocation.insert();

            assetGroup.initValue();
            assetGroup.GroupId       =   assetGrp;
            assetGroup.Name          =   assetGrp;
            assetGroup.insert();

            assetBookTable.initValue();
            assetBookTable.BookId = assetBkId;
            assetBookTable.Description = assetBkId;
            assetBookTable.insert();


            assetTable.initValue();
            assetTable.AssetId  =   assetId;
            assetTable.Name     =   name;
            assetTable.AssetGroup = assetGroup.GroupId;
            assetTable.Location   = assetLocation.Location;
            assetTable.insert();

            assetBook.initValue();
            assetBook.BookId    =   assetBookTable.BookId;
            assetBook.AcquisitionDate = assetAcqDate;
            assetBook.AcquisitionPrice = assetAcqPrice;
            assetBook.ServiceLife      = assetServiceLife;
            assetBook.PostingProfile   = assetPostingProfile;
            assetBook.Status           = assetStatus;
            assetBook.Depreciation     = assetDepreciate;
            assetBook.AssetId          = assetTable.AssetId;
            assetBook.insert();
        }
        else if(assetLocation.RecId|| assetGroup.RecId || assetBookTable.RecId)
        {
            if(assetLocation && assetGroup && assetBookTable)
            {
                assetTable.Location   = assetLocation.Location;
                assetTable.AssetGroup = assetGroup.GroupId;
                assetBook.BookId    =   assetBookTable.BookId;
            }
            else if(assetLocation && !assetBookTable && !assetGroup)
            {
                assetGroup.initValue();
                assetGroup.GroupId       =   assetGrp;
                assetGroup.Name          =   assetGrp;
                assetGroup.insert();

                assetBookTable.initValue();
                assetBookTable.BookId = assetBkId;
                assetBookTable.Description = assetBkId;
                assetBookTable.insert();

                assetTable.Location   = assetLocation.Location;
                assetTable.AssetGroup = assetGroup.GroupId;
                assetBook.BookId      =   assetBookTable.BookId;
            }
            else if(assetGroup && !assetBookTable && !assetLocation)
            {
                assetLocation.initValue();
                assetLocation.Location   =   location;
                assetLocation.Name       =   location;
                assetLocation.insert();

                assetBookTable.initValue();
                assetBookTable.BookId = assetBkId;
                assetBookTable.Description = assetBkId;
                assetBookTable.insert();
               
                assetTable.AssetGroup = assetGroup.GroupId;
                assetTable.Location   = assetLocation.Location;
                assetBook.BookId      =   assetBookTable.BookId;
            }
            else if(!assetGroup && assetBookTable && !assetLocation)
            {
                assetLocation.initValue();
                assetLocation.Location   =   location;
                assetLocation.Name       =   location;
                assetLocation.insert();

                assetGroup.initValue();
                assetGroup.GroupId       =   assetGrp;
                assetGroup.Name          =   assetGrp;
                assetGroup.insert();

                assetBook.BookId      =   assetBookTable.BookId;
                assetTable.Location   = assetLocation.Location;
                assetTable.AssetGroup = assetGroup.GroupId;
            }
            else if(assetLocation && assetBookTable && !assetGroup)
            {
                assetGroup.initValue();
                assetGroup.GroupId       =   assetGrp;
                assetGroup.Name          =   assetGrp;
                assetGroup.insert();

                assetBook.BookId      =   assetBookTable.BookId;
                assetTable.Location   = assetLocation.Location;
                assetTable.AssetGroup = assetGroup.GroupId;
            }
            else if(assetGroup && !assetBookTable && assetLocation)
            {
                assetBookTable.initValue();
                assetBookTable.BookId = assetBkId;
                assetBookTable.Description = assetBkId;
                assetBookTable.insert();

                assetBook.BookId      = assetBookTable.BookId;
                assetTable.AssetGroup = assetGroup.GroupId;
                assetTable.Location   = assetLocation.Location;
            }
            else if(assetGroup && assetBookTable && !assetLocation)
            {
                assetLocation.initValue();
                assetLocation.Location   =   location;
                assetLocation.Name       =   location;
                assetLocation.insert();

                assetTable.Location     =   assetLocation.Location;
                assetTable.AssetGroup   = assetGroup.GroupId;
                assetBook.BookId        =   assetBookTable.BookId;
            }
            assetTable.clear();
            assetTable.initValue();
            assetTable.clear();
           
            assetTable.AssetId   =   assetId;
            assetTable.Name      =   name;
            assetTable.insert();

            assetBook.clear();
            assetBook.initValue();
            //assetBook.BookId           =   assetBkId;
            assetBook.AcquisitionDate  = assetAcqDate;
            assetBook.AcquisitionPrice = assetAcqPrice;
            assetBook.ServiceLife      = assetServiceLife;
            assetBook.PostingProfile   = assetPostingProfile;
            assetBook.Status           = assetStatus;
            assetBook.Depreciation     = assetDepreciate;
            assetBook.AssetId          = assetTable.AssetId;
            assetBook.insert();
        }

        ttsCommit;
        type = cells.item(row+1, 1).value().variantType();
    }
    while (type != COMVariantType::VT_EMPTY);

        application.quit();
        workbooks.close();
        info("Done");
    }

Create Sample Dialog using EDT in Ax 2012

static void 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())
    {
        info(dialogField.value());
    }
}

Default Dimensions for Customers in Ax 2012

static void DefaultFinancialDim(Args _args)
{
    DimensionAttributeValue             dimAttrBUValue,dimAtrrCCValue,dimAtrrDepValue,dimAttrIGValue,dimAtrrProjValue;
    DimensionAttribute                  dimAttrBU,dimAtrrCC,dimAtrrDep,dimAttrIG,dimAtrrProj;
    DimensionAttributeValueSetStorage   davss;
    RecId                               defaultDimension;
    CustTable                           custTable;

    while select forUpdate custTable
    {
        if(custTable.AccountNum)
        {
            davss = DimensionAttributeValueSetStorage::find(CustTable::find(custTable.AccountNum).DefaultDimension);

            dimAttrBU = DimensionAttribute::findByName('BusinessUnit');
            dimAtrrCC = DimensionAttribute::findByName('CostCenter');
            dimAtrrDep = DimensionAttribute::findByName('Department');
            dimAttrIG = DimensionAttribute::findByName('ItemGroup');
            dimAtrrProj = DimensionAttribute::findByName('Project');

            dimAttrBUValue = DimensionAttributeValue::findByDimensionAttributeAndValue(dimAttrBU, "003", false, true);
            dimAtrrCCValue = DimensionAttributeValue::findByDimensionAttributeAndValue(dimAtrrCC, "009", false, true);
            dimAtrrDepValue = DimensionAttributeValue::findByDimensionAttributeAndValue(dimAtrrDep, "024", false, true);
            dimAttrIGValue = DimensionAttributeValue::findByDimensionAttributeAndValue(dimAttrIG, "AudioRM", false, true);
            dimAtrrProjValue = DimensionAttributeValue::findByDimensionAttributeAndValue(dimAtrrProj, "000006", false, true);

            if(dimAttrBUValue || dimAtrrCCValue ||dimAtrrDepValue || dimAttrIGValue || dimAtrrProjValue)
            {
                davss.addItem(dimAttrBUValue);
                davss.addItem(dimAtrrCCValue);
                davss.addItem(dimAtrrDepValue);
                davss.addItem(dimAttrIGValue);
                davss.addItem(dimAtrrProjValue);
                ttsBegin;
                custTable.DefaultDimension = davss.save();
                custTable.update();
                ttsCommit;
                info(custTable.AccountNum);
            }
        }
    }
}

Default Dimensions for Purchase Order in Ax 2012

static void DefaultFinancialDimension(Args _args)
{
    DimensionAttributeValue             dimAttrBUValue,dimAtrrCCValue,dimAtrrDepValue,dimAttrIGValue,dimAtrrProjValue;
    DimensionAttribute                  dimAttrBU,dimAtrrCC,dimAtrrDep,dimAttrIG,dimAtrrProj;
    DimensionAttributeValueSetStorage   davss;
    RecId                               defaultDimension;
    Inventdim                           inventdim;
    PurchTable                          purchtable;
    purchline                           purchline;

    davss = DimensionAttributeValueSetStorage::find(PurchTable::find("PRQ-000000068").DefaultDimension);

    dimAttrBU = DimensionAttribute::findByName('BusinessUnit');
    dimAtrrCC = DimensionAttribute::findByName('CostCenter');
    dimAtrrDep = DimensionAttribute::findByName('Department');
    dimAttrIG = DimensionAttribute::findByName('ItemGroup');
    dimAtrrProj = DimensionAttribute::findByName('Project');

    dimAttrBUValue = DimensionAttributeValue::findByDimensionAttributeAndValue(dimAttrBU, "003", false, true);
    dimAtrrCCValue = DimensionAttributeValue::findByDimensionAttributeAndValue(dimAtrrCC, "011", false, true);
    dimAtrrDepValue = DimensionAttributeValue::findByDimensionAttributeAndValue(dimAtrrDep, "024", false, true);
    dimAttrIGValue = DimensionAttributeValue::findByDimensionAttributeAndValue(dimAttrIG, "AudioRM", false, true);
    dimAtrrProjValue = DimensionAttributeValue::findByDimensionAttributeAndValue(dimAtrrProj, "000006", false, true);

    if(dimAttrBUValue || dimAtrrCCValue ||dimAtrrDepValue || dimAttrIGValue || dimAtrrProjValue)
    {
        davss.addItem(dimAttrBUValue);
        davss.addItem(dimAtrrCCValue);
        davss.addItem(dimAtrrDepValue);
        davss.addItem(dimAttrIGValue);
        davss.addItem(dimAtrrProjValue);
        purchtable = Purchtable::find("PRQ-000000068", true);
        purchtable.DefaultDimension = davss.save();
        ttsBegin;
        purchtable.selectForUpdate(true);
        purchtable.update();
        ttsCommit;

       while select  purchline where purchline.PurchId == purchtable.PurchId
       {
          inventdim.InventSiteId = 'NonHO';
          inventdim.InventLocationId = InventDim::find(purchline.InventDimId).InventLocationId;
          inventdim = InventDim::findOrCreate(inventdim);
          purchline.InventDimId = InventDim.inventDimId;
          purchline.DefaultDimension = davss.save();
          purchline.selectForUpdate(true);
          ttsBegin;
          purchline.update();
          ttsCommit;
          info(strFmt('%1',purchline.InventTransId));
       }
    }
}

Get CustTrans Details and Voucher Details in Ax 2012.

static void CustTransDetails(Args _args)
{
    CustTable   custTable;
    CustTrans   custTrans;
    int         i;
   
    while select AccountNum from custTable
    {
        i++;
        while select AccountNum,TransDate,Voucher from custTrans
                  where custTrans.AccountNum == custTable.AccountNum
        {
            info(strFmt("%1,%2,%3,%4",i, custTable.AccountNum,custTrans.TransDate , custTrans.Voucher));
        }
    }
}

Calculate Amount Credit using index hint in Ax 2012

static void CalculateAmountCredit(Args _args)
{
    CustTable   custTable;
    CustTrans   custTrans;

    while select sum(AmountCur),AccountNum from custTrans
        index hint voucherdateIdx
        //group by AccountNum
        join custTable where CustTable.AccountNum == CustTrans.AccountNum
    {
        info(strFmt("%1,",custTrans.AmountCur));
    }
}

Get Customer Details using Dynamic Query in Ax 2012

static void CustTableListPageDynamicQuery(Args _args)
{
    CustTable                   custTable;
    DirPartyTable               dirPartyTable;
    LogisticsPostalAddress      postalAddress;
    LogisticsElectronicAddress  electronicAddress;

    Query                       query;
    QueryRun                    queryRun;
    QueryBuildDataSource        qbds1,qbds2,qbds3,qbds4, qbds5;
    QueryBuildRange             range;

    query   =   new Query();
    qbds1   =   query.addDataSource(tableNum(CustTable));
    range   =   qbds1.addRange(fieldNum(custTable, AccountNum));
    range.value("1122");

    qbds2   =   qbds1.addDataSource(tableNum(dirPartyTable));
    qbds2.addSortField(fieldNum(dirPartyTable, Name), SortOrder::Ascending);
    qbds2.fetchMode(1);
    qbds2.joinMode(JoinMode::InnerJoin);

    qbds2.relations(true);

    qbds3   =   qbds2.addDataSource(tableNum(LogisticsPostalAddress));
    qbds3.joinMode(JoinMode::OuterJoin);
    qbds3.addLink(fieldNum(DirPartyTable, PrimaryAddressLocation), fieldNum(LogisticsPostalAddress , Location));

    qbds4   =   qbds2.addDataSource(tableNum(LogisticsElectronicAddress));
    qbds4.joinMode(JoinMode::OuterJoin);
    qbds4.addLink(fieldNum(DirPartyTable,PrimaryContactPhone), fieldNum(LogisticsElectronicAddress , RecId));

    qbds5   =   qbds2.addDataSource(tableNum(LogisticsElectronicAddress));
    qbds5.joinMode(JoinMode::OuterJoin);
    qbds5.addLink(fieldNum(DirPartyTable,PrimaryContactEmail), fieldNum(LogisticsElectronicAddress , RecId));

    queryRun    =   new QueryRun(query);

    while(queryRun.next())
    {
        custTable   =   queryRun.get(tableNum(CustTable));
        dirPartyTable   =  queryRun.get(tableNum(DirPartyTable));
        postalAddress   =   queryRun.get(tableNum(LogisticsPostalAddress));
        electronicAddress   =   queryRun.get(tableNum(LogisticsElectronicAddress));
        info(strFmt("%1, %2, %3",custTable.AccountNum, dirPartyTable.Name, postalAddress.Address));
    }
}

Customer Details Exporting in Ax 2012

static void customerExport(Args _args)
{

    SysExcelApplication         application;
    SysExcelWorkbooks           workbooks;
    SysExcelWorkbook            workbook;
    SysExcelWorksheets          worksheets;
    SysExcelWorksheet           worksheet;
    SysExcelCells               cells;
    SysExcelCell                cell;
    int                         row;
    container                   conCompanies = [ 'USMF', 'DEMF', 'DAT' ];

    CustTable                   custTable;
    DirPartyTable               dirPartyTable;
    LogisticsLocation           logisticsLocation;
    LogisticsPostalAddress      postalAddress;
    LogisticsElectronicAddress  electronicAddress;


    application = SysExcelApplication::construct();
    workbooks = application.workbooks();
    workbook = workbooks.add();
    worksheets = workbook.worksheets();
    worksheet = worksheets.itemFromNum(1);

    cells = worksheet.cells();
    cells.range('A:A').numberFormat('@');
    cell = cells.item(1,1);
    cell.value("AccountNum");
    cell = cells.item(1,2);
    cell.value("CustGroup");
    cell = cells.item(1,3);
    cell.value("Name");
    cell = cells.item(1,4);
    cell.value("Currency");
    cell = cells.item(1,5);
    cell.value("counrtyRegionId");
    cell = cells.item(1,6);
    cell.value("Address");
    cell = cells.item(1,7);
    cell.value("Type");
    cell = cells.item(1,8);
    cell.value("Locator");
    row = 1;

    while select crossCompany:conCompanies * from custTable join dirPartyTable  where custTable.Party == dirPartyTable.RecId
                        join electronicAddress
                            where electronicAddress.RecId == dirPartyTable.PrimaryContactPhone
                                    || dirPartyTable.PrimaryContactEmail == electronicAddress.RecId
                                    || dirPartyTable.PrimaryContactFax == electronicAddress.RecId

                                join logisticsLocation where logisticsLocation.RecId == dirPartyTable.PrimaryAddressLocation
                                    join postalAddress where postalAddress.Location == logisticsLocation.RecId

    {
    row++;

    cell = cells.item(row,1);
    cell.value(custtable.AccountNum);
    cell = cells.item(row, 2);
    cell.value(custtable.custgroup);
    cell = cells.item(row, 3);
    cell.value(dirPartyTable.name);
    cell = cells.item(row, 4);
    cell.value(custtable.currency);
    cell = cells.item(row, 5);
    cell.value(postalAddress.countryRegionId);
    cell = cells.item(row, 6);
    cell.value(postalAddress.Address);
    cell = cells.item(row, 7);
    cell.value(electronicAddress.Type);
    cell = cells.item(row, 8);
    cell.value(electronicAddress.locator);
    }

     application.visible(true);


}

Customer Contract Address Update in Ax 2012

static void Cust_contactUpdate(Args _args)
{
      LogisticsPostalAddress      address;
      CustTable                   custtable;
      DirPartyPostalAddressView   postaladdressView;
      DirParty                    dirparty;
      LogisticsLocation           location;
      DirPartyTable               dirPartyTable;
      container                   roles;
      LogisticsElectronicAddress  eAddress;
      DirPartyLocation            dirlocation;



    while  select custtable where custtable.AccountNum == "US-001"
             join  dirPartyTable where custtable.Party ==   dirPartyTable.RecId
             join  dirlocation where dirlocation.Party ==  dirPartyTable.RecId
             join  location    where location.recid == dirlocation.location
             join  eAddress where eAddress.Location == location.RecId
    {
                         //dirPartyTable.PrimaryContactEmail    == eAddress.RecId
                                             //|| dirPartyTable.PrimaryContactFax      == eAddress.RecId
                                             //|| dirPartyTable.PrimaryContactPhone    == eAddress.RecId
                                             //|| dirPartyTable.PrimaryContactTelex    == eAddress.RecId
                                             //|| dirPartyTable.PrimaryContactURL      == eAddress.RecId
                                             //|| dirPartyTable.PrimaryAddressLocation == eAddress.RecId;
    if(location.RecId)
    {
        ttsBegin;
            eAddress.Locator = "222444555";
            eAddress.selectForUpdate(true);
            eAddress.update();
        ttsCommit;
    }
    //if(address.RecId)
    //{
        //ttsBegin;
//
        //address.Street  =   "prakashnagar";
        //address.ZipCode =   "555111";
        //address.City    = "hyderabad";
        //address.CountryRegionId = "Ind";
        //address.Address = address.Street +" "+ address.ZipCode +" "+ address.City +" "+address.CountryRegionId;
        //address.selectForUpdate(true);
        //address.validTimeStateUpdateMode(ValidTimeStateUpdate::Correction);
        //address.update();
        //ttsCommit;
//
    //}
        info(strFmt("%1---- %2",eAddress.Locator, custtable.AccountNum));
        info("Done");
    }
}

Convert CSV file to Excel file in Ax 2012

static void CsvFileToExcell(Args _args)
{
#Excel
      SysExcelApplication excel;
      SysExcelWorkBooks books;
      Filename excelFileName;
      Filename csvFileName;
      ;
      csvFileName = 'D:\\csv.txt';
      excelFileName = ' D:\\csvtoexcell.xls';
      excel = SysExcelApplication ::construct( );
      excel.displayAlerts (false);
      books = excel.workbooks( );
      books.open(csvFileName,0,false,2,"","",false,#xlWindows,",",false,false,1,false,false,1,false);

      books.item(1).saveAs(excelFileName);
      excel.quit() ;
}

Create Purchase Order,Confirm,Packing slip,Invoice in Ax 2012 through x++

static void createPO(Args _args)
{
    NumberSeq       numberSeq;
    Purchtable      Purchtable;
    PurchLine       PurchLine;
    PurchFormLetter purchFormLetter;

    ;
    ttsbegin;
    numberSeq =NumberSeq::newGetNum(purchparameters::numRefPurchId(),true);

    // Initialize Purchase order values
    Purchtable.initValue();
    Purchtable.PurchId = numberSeq.num();
    Purchtable.OrderAccount = 'US-101';
    Purchtable.CurrencyCode = 'USD';
    Purchtable.initFromVendTable();
    if (!Purchtable.validateWrite())
    {
        throw Exception::Error;
    }
    Purchtable.insert();

    // Initialize Purchase Line items
    PurchLine.PurchId = Purchtable.PurchId;
    PurchLine.ItemId = 'C0001';
    PurchLine.PurchQty = 2;
    PurchLine.createLine(true, true, true, true, true, false);
    PurchLine.clear();


    PurchLine.PurchId = Purchtable.PurchId;
    PurchLine.ItemId = 'C0002';
    PurchLine.PurchQty = 1;
    PurchLine.createLine(true, true, true, true, true, false);
    ttscommit;

        ////PO confirmation
    ttsBegin;
    purchTable = PurchTable::find(purchTable.PurchId);
    purchFormLetter = PurchFormLetter::construct(DocumentStatus::PurchaseOrder);
    purchFormLetter.update(purchTable, strFmt("Inv_%1", purchTable.PurchId));
    ttsCommit;

        //PO Product Receipt
    ttsBegin;
    purchFormLetter = purchFormLetter::construct(DocumentStatus::PackingSlip);
    purchFormLetter.update(purchtable, // Purchase record Buffer
    "PO_"+purchTable.PurchId, // Invoice Number
    systemdateget()); // Transaction date
    ttsCommit;
   

    //PO Invoice
    ttsBegin;
    purchFormLetter = purchFormLetter::construct(DocumentStatus::Invoice);
    //purchFormLetter.update(purchtable,"Inv_123",systemdateget()); // Transaction date
    //purchFormLetter.update(purchTable, strFmt("PO_%1", purchTable.PurchId));
    purchFormLetter.update(purchtable, // Purchase record Buffer
    "INV-"+purchTable.PurchId, // Invoice Number
    systemdateget()); // Transaction date
   
    ttscommit;
    if (PurchTable::find(purchTable.PurchId).DocumentStatus == DocumentStatus::Invoice)
    {
        info(strfmt("Posted invoiced journal for purchase order %1",purchTable.PurchId));
    }

}

XML metadata Generator in Ax 2012

static void MetadataXMLGenrator(Args _args)
{
    Dictionary      dictionary;
    Counter         tableCounter;
    SysDictTable    table;
    Counter         fieldCounter;
    SysDictField    field;
    str             result;

    boolean         isRecID;
    boolean         isTableID;
    boolean         isDatatypeID;
    boolean         isClassID;
    boolean         isFieldID;
    boolean         IsIndexID;
    boolean         isConfigurationKeyId;
    boolean         isEnumId;
    boolean         isLicenseCodeId;
    boolean         isperspectiveId;
    boolean         issecurityKeyId;


    SysModelElement modelElement;
    str             elementType;
    str             tmpfolderpath;
    str             relatedtTableName;

    void write(str _directory, str _name, str _text)
    {
        str path;
        ;

        _text = System.Text.RegularExpressions.Regex::Replace(_text, '\n', '\r\n');
        if (!System.IO.Directory::Exists(_directory))
        {
            System.IO.Directory::CreateDirectory(_directory);
        }
        path = System.IO.Path::Combine(_directory, _name);
        System.IO.File::WriteAllText(path, _text, System.Text.Encoding::get_UTF8());
    }

    boolean isExcluded(SysDictTable _table)
    {
        ;

        return
           _table.isView()
        || _table.isMap()
        || _table.isTmp()
        || _table.isTempDb();
    }

    guid tableOrigin(SysDictTable _table)
    {
        ;
        modelElement = null;
        select firstOnly * from modelElement where modelElement.AxId == _table.id() && modelElement.ElementType == 44;
        if (modelElement)
        {
            return modelElement.Origin;
        }

        return emptyGuid();
    }

    str fmt(guid value, int64 id)
    {
        str digits;
        str o = strReplace(strReplace(guid2str(value), '{', ''), '}', '');

        if (o != '00000000-0000-0000-0000-000000000000')
        {
            return o;
        }

        digits = int642str(id);
        return subStr(o, 0, strLen(o) - strLen(digits)) + digits;
    }

    dictionary = new Dictionary();

    result += '<tables>\n';

    for (tableCounter = 1; tableCounter <= dictionary.tableCnt(); ++tableCounter)
    {
        table = new SysDictTable(Dictionary.tableCnt2Id(tableCounter));

        if (!isExcluded(table))
        {
            result += strFmt('\t<table axid="%1" origin="%2" name="%3" sqlname="%4" %5>\n', table.id(), fmt(tableOrigin(table), table.id()), table.name(), table.name(DbBackend::Sql), table.supportInheritance() ? 'supportsinheritance="true" ' :  '' );

            for (fieldCounter = 1; fieldCounter <= table.fieldCnt(); ++fieldCounter)
            {
                relatedtTableName = '';
                field = new SysDictField(table.id(), table.fieldCnt2Id(fieldCounter));

                if (field.isSql())
                {
                    isRecID = field.isDerivedFrom(extendedTypeNum(RecId));
                    isTableID = field.isDerivedFrom(extendedTypeNum(RefTableId)) || field.isDerivedFrom(extendedTypeNum(RelationType)) || (field.name() == 'InstanceRelationType' && table.supportInheritance() && table.extends() == 0);
                    isDatatypeID = field.isDerivedFrom(extendedTypeNum(ExtendedTypeId));
                    isClassID = field.isDerivedFrom(extendedTypeNum(ClassId));
                    isFieldID = field.isDerivedFrom(extendedTypeNum(FieldId));
                    IsIndexID = field.isDerivedFrom(extendedTypeNum(IndexId));
                    isConfigurationKeyId = field.isDerivedFrom(extendedTypeNum(ConfigurationKeyId));
                    isEnumId = field.isDerivedFrom(extendedTypeNum(EnumId));
                    isLicenseCodeId = field.isDerivedFrom(extendedTypeNum(LicenseCodeId));
                    isperspectiveId = field.isDerivedFrom(extendedTypeNum(PerspectiveId));
                    issecurityKeyId = field.isDerivedFrom(extendedTypeNum(SecurityKeyId));

                    if (isTableID)
                    {
                        elementType = "Table";
                    }
                    else if (isClassID)
                    {
                        elementType = "Class";
                    }
                    else if (isDataTypeID)
                    {
                        elementType = "DataType";
                    }
                    else if (isFieldID)
                    {
                        elementType = "Field";
                        relatedtTableName = field.relatedTableName();
                    }
                    else if (IsIndexID)
                    {
                        elementType = "Index";
                        relatedtTableName = field.relatedTableName();
                    }
                    else if(isConfigurationKeyId)
                    {
                        elementType = "ConfigurationKey";
                    }
                    else if(isEnumId)
                    {
                        elementType = "Enum";
                    }
                    else if(isLicenseCodeId)
                    {
                        elementType = "LicenseCode";
                    }
                    else if(issecurityKeyId)
                    {
                        elementType = "SecurityKey";
                    }
                    else if(isperspectiveId)
                    {
                        elementType = "Perspective";
                    }
                    else
                    {
                        elementType = '';
                    }

                    result += strFmt('\t\t<field axid="%1" origin="%2" name="%3" sqlname="%4" type="%5" %6%7/>\n',
                        field.id(), fmt(field.origin(), field.id()), field.name(), field.name(DbBackend::Sql), field.typeName(),
                        elementType != '' ? ((elementType == ('Field') || elementType == ('Index'))?'elementType="' + elementType + '" '+'relatedTable="'+relatedtTableName + '" ' :'elementType="' + elementType + '" ') : '',
                        isRecID ? 'recid="true" ' : ''
                        );
                }
            }

            result += '\t</table>\n';
        }
    }

    result += '</tables>\n';
    tmpfolderpath = System.Environment::GetEnvironmentVariable('TEMP');
    write(tmpfolderpath, 'Metadata.xml', result);

    info(strFmt("Metadata xml file is created and here is the full path to the file %1\\Metadata.xml",tmpfolderpath));
}

Import Journals using Excel x++ code Ax 2012


class HM_GeneralJournalLineImport
{
    Dialog              dialog;
    DialogField         dialogfield;
    Filename            filename;

    #AviFiles
    SysExcelApplication     application;
    SysExcelWorkbooks       workbooks;
    SysExcelWorkbook        workbook;
    SysExcelWorksheets      worksheets;
    SysExcelWorksheet       worksheet;
    SysExcelCells           cells;
    COMVariantType          type;
    COMVariantType          typeModule;
    COM                     excelCOM;
    NumberSeq               numberSeq;
    NumberSequenceTable     numSeqTable;

    str                     Name, num,text, currency,businessunit,account,accountType, department,offsetaccount,OffsetAccounttype, transType;
    int64                   costcenter;
    real                    debit, credit;
    container               Account1, offsetaccount1;
    str                     acc;
    date                    transdate;
    boolean check;


    LedgerJournalName       ledgerJournalName;
    LedgerJournalTable      ledgerJournalTable;
    LedgerJournalTrans      ledgerJournalTrans;
    LedgerJournalTrans_Asset    ledgerJournalTrans_Asset;


    container               cont1,cont2,offSetAcctPattern;
    int                     cnt;
    DimensionDynamicAccount ledgerDim, offsetledgerDim;
    LedgerJournalAC         AccountNumb, offsetAccountnum;

    container               ledgerDimension;
    DimensionDefault        DimensionDefault;
    LedgerJournalACType     LedgerJournalACType;
    //AssetTransTypeJournal   assetTransTypeJournal;
    boolean                 ret;

    AsciiIo importFile;
    List        list;
    ListIterator            listIterator;

    //Comma
    //CommaTextIo        commaTextIo;
    //container          containFromRead;
    ledgerJournalTransTaxExtensionIN    ledgerJournalTransTaxExtensionIN;
}


public void run(Args _args)
{
    boolean     validate;
    ledgerJournalTable  = _args.record() as ledgerJournalTable;
    dialog = new dialog('Excel Import');
    check  = true;
    dialogfield = dialog.addField(extendedTypeStr(FilenameOpen), 'File Name');

    if(dialog.run())
    {
        filename =(dialogfield.value());
        application = SysExcelApplication::construct();
        workbooks = application.workbooks();

        if(filename)
        {
            validate = this.validate();   //for validating Excel financial dimensions whether it is valid or not
            if(validate)
            {
                this.DataImport();
            }
            application.quit();
        }
    }
}

//validating dimensions
public boolean validate()
{
    CustTable                       custTable;
    VendTable                       vendTable;
    ProjTable                       projTable;
    MainAccount                     mainAccount;
    str                             mBusinessUnit,mUnit,mProject,mWorker,mVendor,mCustomer,mIntercompany;
    str                             oBusinessUnit,oUnit,oProject,oWorker,oVendor,oCustomer,oIntercompany;
    Name                            accountName;
    boolean                         mret,oret;
    container   mAccPattern,oAccPattern;
    SysOperationProgress progress = new SysOperationProgress();
    int                 row = 0;
    try
    {
        workbooks.open(filename);
    }

    catch (Exception::Error)
    {
        throw error("@SYS19358");
    }
    workbook    = workbooks.item(1);
    worksheets  = workbook.worksheets();
    worksheet   = worksheets.itemFromNum(1);
    cells       = worksheet.cells();

    row = 1;
    progress.setCaption("Journal import");
    progress.setAnimation(#AviUpdate);

    do
    {
        row++;
        progress.setText(strfmt("Validating journal row - %1", row));
        try
        {
            accountType     = cells.item(row, 3).value().bStr();
            AccountNumb     = strFmt("%1", cells.item(row, 4).value().bStr());

            switch(cells.item(row, 4).value().variantType())
            {
                case COMVariantType::VT_BSTR:
                    AccountNumb = strFmt("%1", cells.item(row, 4).value().bStr());
                    break;
                case COMVariantType::VT_DECIMAL, COMVariantType::VT_R4, COMVariantType::VT_R8:
                    AccountNumb = strFmt("%1", any2int(cells.item(row, 4).value().double()));
                    break;
                case COMVariantType::VT_I1, COMVariantType::VT_I2, COMVariantType::VT_I4:
                    AccountNumb = strFmt("%1", cells.item(row, 4).value().int());
                    break;
                case COMVariantType::VT_UI1, COMVariantType::VT_UI2, COMVariantType::VT_UI4:
                    AccountNumb = strFmt("%1", cells.item(row, 4).value().uLong());
                    break;
                case COMVariantType::VT_EMPTY:
                    AccountNumb = '';
                    break;
                default:
                    throw error(strfmt('Unhandled variant type (%1).', cells.item(row+1, 1).value().variantType()));
            }

            accountName         = cells.item(row, 5).value().bStr();
            mbusinessUnit       = cells.item(row, 6).value().bStr();
            mUnit               = cells.item(row, 7).value().bStr();
            mProject            = cells.item(row, 8).value().bStr();
            mWorker             = cells.item(row, 9).value().bStr();
            mVendor             = cells.item(row, 10).value().bStr();
            mCustomer           = cells.item(row, 11).value().bStr();
            mIntercompany       = cells.item(row, 12).value().bStr();

            maccPattern = connull();
            maccPattern = [7,'BusinessUnit',mbusinessUnit,'Unit',mUnit,'Project',mProject,'Vendor',mVendor,'Customer',mCustomer,'Worker',mWorker,'Intercompany',mIntercompany];
            mret        = this.checkMainAccountDimensions(maccPattern);

            OffsetAccounttype = cells.item(row, 19).value().bStr();

            switch(cells.item(row, 20).value().variantType())
            {
                case COMVariantType::VT_BSTR:
                    offsetAccountnum = strFmt("%1", cells.item(row, 20).value().bStr());
                    break;
                case COMVariantType::VT_DECIMAL, COMVariantType::VT_R4, COMVariantType::VT_R8:
                    offsetAccountnum = strFmt("%1", any2int(cells.item(row, 20).value().double()));
                    break;
                case COMVariantType::VT_I1, COMVariantType::VT_I2, COMVariantType::VT_I4:
                    offsetAccountnum = strFmt("%1", cells.item(row, 20).value().int());
                    break;
                case COMVariantType::VT_UI1, COMVariantType::VT_UI2, COMVariantType::VT_UI4:
                    offsetAccountnum = strFmt("%1", cells.item(row, 20).value().uLong());
                    break;
                case COMVariantType::VT_EMPTY:
                    offsetAccountnum = '';
                    break;
                default:
                    throw error(strfmt('Unhandled variant type (%1).', cells.item(row, 20).value().variantType()));
            }
            obusinessUnit       = cells.item(row, 21).value().bStr();
            oUnit               = cells.item(row, 22).value().bStr();
            oProject            = cells.item(row, 23).value().bStr();
            oWorker             = cells.item(row, 24).value().bStr();
            oVendor             = cells.item(row, 25).value().bStr();
            oCustomer           = cells.item(row, 26).value().bStr();
            oIntercompany       = cells.item(row, 27).value().bStr();

            oAccPattern = conNull();
            oAccPattern = [7,'BusinessUnit',obusinessUnit,'Unit',oUnit,'Project',oProject,'Vendor',oVendor,'Customer',oCustomer,'Worker',oWorker,'Intercompany',oIntercompany];
            oret        = this.checkoffsetDimensions(oAccPattern);

            type = cells.item(row+1, 1).value().variantType();
        }
        catch(Exception::Error)
        {
            info(strFmt('Catched an error in row: %1',row));

        }
    }
     while (type != COMVariantType::VT_EMPTY);

    return (mret && oret) ? true : false ;
}


public void DataImport()
{
    str         mBusinessUnit,mUnit,mProject,mWorker,mVendor,mCustomer,mIntercompany;
    str         oBusinessUnit,oUnit,oProject,oWorker,oVendor,oCustomer,oIntercompany;
    str         invoice;
    str         TDSgroup,salesTaxGroup,itemSalesTax;
    date        documentdate;
    Voucher     voucher;
    NoYes       noyes;
    container   mCnt;
    Name        accountName,postingProfile,termsofPayment;
    ExchRate    exchRate;
    boolean            _selectTriangulation = true;
    UnknownNoYes      triangulationResult,triangulation;

    //Creating of new Vouchers
    LedgerJournalTrans  ledgerjourDebit,ledgerJourCredit;


    SysOperationProgress progress = new SysOperationProgress();
    int                 row = 0;
    try
    {
        workbooks.open(filename);
    }

    catch (Exception::Error)
    {
        throw error("@SYS19358");
    }
    workbook    = workbooks.item(1);
    worksheets  = workbook.worksheets();
    worksheet   = worksheets.itemFromNum(1);
    cells       = worksheet.cells();

    row = 1;
    progress.setCaption("Journal import");
    progress.setAnimation(#AviUpdate);

    do
    {
        row++;
        progress.setText(strfmt("Journals inserting row - %1", row));
        transdate       = cells.item(row, 1).value().date();
        //voucher         = cells.item(row, 2).value().bStr();
        accountType     = cells.item(row, 3).value().bStr();
        AccountNumb     = strFmt("%1", cells.item(row, 4).value().bStr());

        switch(cells.item(row, 4).value().variantType())
        {
            case COMVariantType::VT_BSTR:
                AccountNumb = strFmt("%1", cells.item(row, 4).value().bStr());
                break;
            case COMVariantType::VT_DECIMAL, COMVariantType::VT_R4, COMVariantType::VT_R8:
                AccountNumb = strFmt("%1", any2int(cells.item(row, 4).value().double()));
                break;
            case COMVariantType::VT_I1, COMVariantType::VT_I2, COMVariantType::VT_I4:
                AccountNumb = strFmt("%1", cells.item(row, 4).value().int());
                break;
            case COMVariantType::VT_UI1, COMVariantType::VT_UI2, COMVariantType::VT_UI4:
                AccountNumb = strFmt("%1", cells.item(row, 4).value().uLong());
                break;
            case COMVariantType::VT_EMPTY:
                AccountNumb = '';
                break;
            default:
                throw error(strfmt('Unhandled variant type (%1).', cells.item(row+1, 1).value().variantType()));
        }
        accountName         = cells.item(row, 5).value().bStr();
        mbusinessUnit       = cells.item(row, 6).value().bStr();
        mUnit               = cells.item(row, 7).value().bStr();
        mProject            = cells.item(row, 8).value().bStr();
        mWorker             = cells.item(row, 9).value().bStr();
        mVendor             = cells.item(row, 10).value().bStr();
        mCustomer           = cells.item(row, 11).value().bStr();
        mIntercompany       = cells.item(row, 12).value().bStr();
        postingProfile      = cells.item(row, 13).value().bStr();

        invoice         = cells.item(row, 14).value().bStr();
        Text            = cells.item(row, 15).value().bStr();
        Debit           = any2real(cells.item(row, 16).value().double());
        Credit          = any2real(cells.item(row, 17).value().double());
        Currency        = cells.item(row, 18).value().bStr();
        OffsetAccounttype = cells.item(row, 19).value().bStr();


        switch(cells.item(row, 20).value().variantType())
        {
            case COMVariantType::VT_BSTR:
                offsetAccountnum = strFmt("%1", cells.item(row, 20).value().bStr());
                break;
            case COMVariantType::VT_DECIMAL, COMVariantType::VT_R4, COMVariantType::VT_R8:
                offsetAccountnum = strFmt("%1", any2int(cells.item(row, 20).value().double()));
                break;
            case COMVariantType::VT_I1, COMVariantType::VT_I2, COMVariantType::VT_I4:
                offsetAccountnum = strFmt("%1", cells.item(row, 20).value().int());
                break;
            case COMVariantType::VT_UI1, COMVariantType::VT_UI2, COMVariantType::VT_UI4:
                offsetAccountnum = strFmt("%1", cells.item(row, 20).value().uLong());
                break;
            case COMVariantType::VT_EMPTY:
                offsetAccountnum = '';
                break;
            default:
                throw error(strfmt('Unhandled variant type (%1).', cells.item(row, 20).value().variantType()));
        }
        obusinessUnit       = cells.item(row, 21).value().bStr();
        oUnit               = cells.item(row, 22).value().bStr();
        oProject            = cells.item(row, 23).value().bStr();
        oWorker             = cells.item(row, 24).value().bStr();
        oVendor             = cells.item(row, 25).value().bStr();
        oCustomer           = cells.item(row, 26).value().bStr();
        oIntercompany       = cells.item(row, 27).value().bStr();

        TDSgroup        = cells.item(row, 28).value().bStr();
        salesTaxGroup   = cells.item(row, 29).value().bStr();
        itemSalesTax    = cells.item(row, 30).value().bStr();
        exchRate        = any2real(cells.item(row, 31).value().double());
        documentdate    = cells.item(row, 32).value().date();
        termsofPayment  = cells.item(row, 33).value().bStr();

        try
        {
            ttsbegin;

            ledgerJournalTrans.clear();
            ledgerJournalTrans.initValue();
            ledgerJournalTrans.JournalNum   = ledgerJournalTable.JournalNum;
            ledgerJournalTrans.TransDate    = transdate;
            ledgerJournalTrans.Approved     = NoYes::Yes;
            ledgerJournalTrans.Approver     = HcmWorker::userId2Worker(curuserid());
            select firstOnly numSeqTable
                where numSeqTable.RecId  == LedgerJournalName::find(ledgerJournalTable.JournalName).NumberSequenceTable;
            /*if (numSeqTable && !voucher)
            {
                //numberseq = numberseq::newGetVoucherFromCode(numSeqTable.NumberSequence);
                voucher = new JournalVoucherNum(JournalTableData::newTable(ledgerJournalTable)).getNew(false);
                //voucher = numberseq.voucher();
            }*/

      select sum(AmountCurDebit) from ledgerjourDebit
                where ledgerjourDebit.JournalNum == ledgerJournalTable.JournalNum;
         
      select sum(AmountCurCredit) from ledgerJourCredit
                where ledgerJourCredit.journalnum == ledgerJournalTable.journalnum;
         
     if(ledgerjourDebit.AmountCurDebit == ledgerJourCredit.AmountCurCredit)//!voucher &&
      {
         voucher = new
         JournalVoucherNum(JournalTableData::newTable(ledgerJournalTable)).getNew(false);
      }
     else if(offsetAccountnum)
      {
         voucher = new                JournalVoucherNum(JournalTableData::newTable(ledgerJournalTable)).getNew(false);

      }


            ledgerJournalTrans.Voucher              = voucher;
            ledgerJournalTrans.AccountType          = str2enum(LedgerJournalACType, accountType);
            //ledgerJournalTrans.PostingProfile

            // Main account dimensions
            cont1=conNull();
            cont2=conNull();
            ledgerDimension =conNull();
            cnt=0;

            //Account type
            if(mBusinessUnit != '')
            {
                cnt++;
                cont2+=['BusinessUnit',mBusinessUnit];
            }
            if(mUnit != '')
            {
                cnt++;
                cont2+=['Unit',mUnit];
            }
            if(mProject != '')
            {
                cnt++;
                cont2+=['Project',mProject];
            }
            if(mWorker != '')
            {
                cnt++;
                cont2+=['Worker',mWorker];
            }
            if(mVendor != '')
            {
                cnt++;
                cont2+=['Vendor',mVendor];
            }
            if(mCustomer != '')
            {
                cnt++;
                cont2+=['Customer',mCustomer];
            }
            if(mIntercompany != '')
            {
                cnt++;
                cont2+=['Intercompany',mIntercompany];
            }


            if(ledgerJournalTrans.AccountType  == LedgerJournalACType::Ledger)
            {
                cont1+=['MainAccount',AccountNumb,cnt];
                cont1+=cont2;
                ledgerDim = AxdDimensionUtil::getLedgerAccountId(cont1);

                if(ledgerDim==0)
                {
                        offSetAcctPattern = [AccountNumb,AccountNumb];
                        ledgerDim = AxdDimensionUtil::getLedgerAccountId( offSetAcctPattern);
                }

                ledgerJournalTrans.LedgerDimension  = ledgerDim;
            }
            else
            {
                ledgerDim = DimensionStorage::getDynamicAccount( AccountNumb,ledgerJournalTrans.AccountType);
                ledgerDimension +=cnt;
                ledgerDimension +=cont2;
                DimensionDefault = AxdDimensionUtil::getDimensionAttributeValueSetId(ledgerDimension);
                ledgerJournalTrans.LedgerDimension  = ledgerDim;
                LedgerJournalTrans.modifiedField(fieldNum(LedgerJournalTrans,LedgerDimension));
                ledgerJournalTrans.DefaultDimension = DimensionDefault;
            }
            ledgerJournalTrans.PostingProfile       = postingProfile;
            ledgerJournalTrans.Txt                  = Text;
            ledgerJournalTrans.CurrencyCode         = Currency;
            ledgerJournalTrans.AmountCurDebit       = Debit;
            ledgerJournalTrans.AmountCurCredit      = Credit;
            if(offsetaccountType)
            {
                ledgerJournalTrans.OffsetAccountType    = str2enum(LedgerJournalACType, offsetaccountType);
            }
            else
            {
                   ledgerJournalTrans.OffsetAccountType    = LedgerJournalACType::Ledger;
            }
            cont1=conNull();
            cont2=conNull();
            ledgerDimension =conNull();
            cnt=0;
            //Offset Account Type

            if(oBusinessUnit != '')
            {
                cnt++;
                cont2+=['BusinessUnit',oBusinessUnit];
            }
            if(oUnit != '')
            {
                cnt++;
                cont2+=['Unit',oUnit];
            }
            if(oProject != '')
            {
                cnt++;
                cont2+=['Project',oProject];
            }
            if(oWorker != '')
            {
                cnt++;
                cont2+=['Worker',oWorker];
            }
            if(oVendor != '')
            {
                cnt++;
                cont2+=['Vendor',oVendor];
            }
            if(oCustomer != '')
            {
                cnt++;
                cont2+=['Customer',oCustomer];
            }
            if(oIntercompany != '')
            {
                cnt++;
                cont2+=['Intercompany',oIntercompany];
            }

            if (ledgerJournalTrans.OffsetAccountType  == LedgerJournalACType::Ledger && offsetAccountnum)
            {
                cont1+=['MainAccount',offsetAccountnum,cnt];
                cont1+=cont2;
                offsetledgerDim =AxdDimensionUtil::getLedgerAccountId(cont1);

                if(offsetledgerDim == 0)
                {
                    offSetAcctPattern = [offsetAccountnum,offsetAccountnum];
                    offsetledgerDim = AxdDimensionUtil::getLedgerAccountId( offSetAcctPattern);
                }
                ledgerJournalTrans.OffsetLedgerDimension = offsetledgerDim;
            }
            else
            {
                if(offsetAccountnum)
                {
                    offsetledgerDim = DimensionStorage::getDynamicAccount(offsetAccountnum,ledgerJournalTrans.OffsetAccountType);
                    ledgerDimension +=cnt;
                    ledgerDimension +=cont2;
                    DimensionDefault = AxdDimensionUtil::getDimensionAttributeValueSetId(ledgerDimension);
                    ledgerJournalTrans.OffsetLedgerDimension = offsetledgerDim;
                    LedgerJournalTrans.modifiedField(fieldNum(LedgerJournalTrans,OffsetLedgerDimension));
                    ledgerJournalTrans.OffsetDefaultDimension = DimensionDefault;
                }
            }
            ledgerJournalTrans.TaxGroup     = salesTaxGroup;
            ledgerJournalTrans.TaxItemGroup = itemSalesTax;
            ledgerJournalTrans.DocumentDate = documentdate;
            ledgerJournalTrans.TDSGroup_IN  = TDSgroup;
            ledgerJournalTrans.Invoice      = invoice;
            ledgerJournalTrans.Payment      = termsofPayment;

            /*exchRate = ExchRates::findExchRateDate(CompanyInfo::find().CurrencyCode);
            ledgerJournalTrans.ExchRate = exchRates.ExchRate;
            exchRates = ExchRates::findExchRateDate(CompanyInfo::find().SecondaryCurrencyCode);
            ledgerJournalTrans1.SecondaryExchRate_ABC           = exchRates.ExchRate; */

            //Exchange rate
            if (_selectTriangulation)
            {
                triangulation = Currency::noYes2UnknownNoYes(Currency::triangulation(currency,
                                                                            transdate));
            }
            else
            {
                triangulation = Currency::noYes2UnknownNoYes(ledgerJournalTrans.Triangulation);
            }
            if (triangulation == UnknownNoYes::Yes && !Currency::findEuroCurrencyCode())
            {
                throw error("@SYS70752");
            }
            ledgerJournalTrans.exchRate          = Currency::exchRate(currency,
                                                        transdate,
                                                        UnknownNoYes::No);

            ledgerJournalTrans.exchRateSecond   = Currency::exchRateSecond(currency,
                                                        transdate,
                                                        UnknownNoYes::No);
            ledgerJournalTrans.Triangulation = Currency::unknownNoYes2Noyes(triangulation);
            //

            ledgerJournalTrans.ReverseEntry  = str2enum(NoYes,cells.item(row,34).value().bStr());
            if(ledgerJournalTrans.ReverseEntry==NoYes::Yes)
            {
                ledgerJournalTrans.ReverseDate   = cells.item(row,35).value().date();
            }

            if (ledgerJournalTrans.validateWrite())
            {
                ledgerJournalTrans.insert();
            }
         

           //Fixed assets--- if any incase FA
            if(ledgerJournalTrans.Accounttype == FA)
         {
            if(ledgerJournalTrans.RecId)
            {
                ledgerJournalTrans_asset.RefRecId = ledgerJournalTrans.RecId;
                ledgerJournalTrans_asset.AssetId  = ledgerJournalTrans.getAssetId();
                ledgerJournalTrans_Asset.Company  = ledgerJournalTrans.getAssetCompany();
                ledgerJournalTrans_asset.BookId   = valMod;
                ledgerJournalTrans_asset.TransType = AssetTransTypeJournal::Acquisition;
                else
                    ledgerJournalTrans_asset.TransType = AssetTransTypeJournal::Depreciation;
                ledgerJournalTrans_asset.insert();
            }

         
         
            ttscommit;
            ttsBegin;
            delete_from ledgerJournalTransTaxExtensionIN
                where ledgerJournalTransTaxExtensionIN.LedgerJournalTrans == ledgerJournalTrans.RecId;

            if(ledgerJournalTrans.recid)
            {
                ledgerJournalTransTaxExtensionIN.initValue();
                ledgerJournalTransTaxExtensionIN.TaxModelDocLineExtensionIN::init(ledgerJournalTrans);
                ledgerJournalTransTaxExtensionIN.LedgerJournalTrans = ledgerJournalTrans.RecId;
                ledgerJournalTransTaxExtensionIN.insert();
            }
            ttsCommit;



            type = cells.item(row+1, 1).value().variantType();
        }
        catch(Exception::Error)
        {
            info(strFmt('Catched an error in row: %1',row));
            break;
        }
        info(strFmt('journal inserted %1 - %2',ledgerJournalTable.JournalNum,row));
    }

    while (type != COMVariantType::VT_EMPTY);

    application.quit();
}


public boolean checkMainAccountDimensions(container   accPattern)
{
    DimensionAttribute              dimensionAttribute;
    DimensionAttributeValue         dimensionAttributeValue;
    int                             containerElementIndex;
    int                             attributeCount, attributeIndex;
    str                             attributeName, attributeValue;

    //boolean check = true;
    containerElementIndex = 1;
    // Get attribute count
    attributeCount = conPeek(accPattern, containerElementIndex);
    containerElementIndex++;
    // Get attributes
    for (attributeIndex = 1; attributeIndex <= attributeCount; attributeIndex++)
    {
        dimensionAttributeValue = null;
        // Get attribute name
        attributeName = conPeek(accPattern, containerElementIndex);
        containerElementIndex++;
        // Validate the Financial Dimenion that was passed in.
        dimensionAttribute = AxdDimensionUtil::validateFinancialDimension(attributeName);
        // Get attribute value
        attributeValue = conPeek(accPattern, containerElementIndex);
        containerElementIndex++;
        // Validate the Financial Dimenion Value that was passed in.
        dimensionAttributeValue = DimensionAttributeValue::findByDimensionAttributeAndValueNoError(dimensionAttribute, attributeValue, false, true);

        if (!dimensionAttributeValue)
        {
            if(attributeValue)
            {
                warning(strfmt('Dimension Name = %1, Dimension Value %2 does not exists',attributeName, attributeValue));
                check = false;
            }
        }
    }

    return check;

}



public boolean checkoffsetDimensions(container   accPattern)
{
    DimensionAttribute              dimensionAttribute;
    DimensionAttributeValue         dimensionAttributeValue;
    int                             containerElementIndex;
    int                             attributeCount, attributeIndex;
    str                             attributeName, attributeValue;
    //boolean check=true ;

    containerElementIndex = 1;
    // Get attribute count
    attributeCount = conPeek(accPattern, containerElementIndex);
    containerElementIndex++;
    // Get attributes
    for (attributeIndex = 1; attributeIndex <= attributeCount; attributeIndex++)
    {
        dimensionAttributeValue = null;
        // Get attribute name
        attributeName = conPeek(accPattern, containerElementIndex);
        containerElementIndex++;
        // Validate the Financial Dimenion that was passed in.
        dimensionAttribute = AxdDimensionUtil::validateFinancialDimension(attributeName);
        // Get attribute value
        attributeValue = conPeek(accPattern, containerElementIndex);
        containerElementIndex++;
        // Validate the Financial Dimenion Value that was passed in.
        dimensionAttributeValue = DimensionAttributeValue::findByDimensionAttributeAndValueNoError(dimensionAttribute, attributeValue, false, true);

        if (!dimensionAttributeValue)
        {
            if(attributeValue)
            {
                warning(strfmt('Dimension Name = %1, Dimension Value %2 does not exists',attributeName, attributeValue));
                check = false;
            }
        }
    }

    return check;

}