Monday, 4 June 2018

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;

}

Importing Ledger Account Details in Ax 2009

static void Na_ExcelImporting2009(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;
    int                             row=0;

    //Table Declarations Starts
    LedgerTable                     ledgerTable;
    LedgerAccountCategory           ledgerAccountCategory;
    AccountNum                      accountNum,accountName,accountNameAlias,accountCategory;
    LedgerAccountType               LedgerAccountType;
    str                             LockedJournal,accountPlType;



    #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 "";
    }
    ;
    dialog              =   new Dialog("Excel Upoad");
    dialogFilename      =   dialog.addField(typeId(FilenameOpen));
    dialog.filenameLookupFilter(["@SYS28576",#XLSX,"@SYS28576",#XLS]);
    dialog.filenameLookupTitle("Upload from Excel");
    dialog.caption("Excel Upload");
    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();

    do
    {
        try
        {
            ttsbegin;
            row++;
               accountNum       = COMVariant2Str(cells.item(row, 1).value());
               accountName      = COMVariant2Str(cells.item(row, 2).value());
               accountNameAlias = COMVariant2Str(cells.item(row, 3).value());
               accountPlType    = COMVariant2Str(cells.item(row, 4).value());
               accountCategory  = COMVariant2Str(cells.item(row, 5).value());
               LockedJournal    = COMVariant2Str(cells.item(row, 6).value());
           if(row > 1)
           {
                //Insert into _CustTable Table
                ledgerTable.clear();
                select ledgerTable where ledgerTable.AccountNum == accountNum;
                if(!ledgerTable.AccountNum)
                {
                    ledgerTable.initValue();
                    ledgerTable.AccountNum          = accountNum;
                    ledgerTable.AccountName         = accountName;
                    ledgerTable.AccountNameAlias    = accountNameAlias;
                    ledgerTable.AccountPlType       = str2enum(LedgerAccountType,accountPlType);
                    if( LockedJournal == "Yes")
                    {
                        ledgerTable.BlockedInJournal   = Noyes::Yes;
                    }
                    else
                    {
                         ledgerTable.BlockedInJournal   = Noyes::No;
                    }
                    select ledgerAccountCategory where ledgerAccountCategory.AccountCategory == accountCategory;
                    if(!ledgerAccountCategory.AccountCategory)
                    {
                        ledgerAccountCategory.AccountCategory = accountCategory;
                        ledgerAccountCategory.insert();
                        ledgerTable.AccountCategoryRef = ledgerAccountCategory.AccountCategoryRef;
                    }
                    else
                    {
                        ledgerTable.AccountCategoryRef = ledgerAccountCategory.AccountCategoryRef;
                    }
                    ledgerTable.doInsert();
               }
           }
         ttscommit;
        }
        catch
        {
            Error(strfmt("Upload Failed in row %1", row));
        }

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

    info(strfmt("Ledger Accounts  uploaded successfully"));
    application.quit();
}

To Change the Environment Color in Ax 2012

To Change Environment Color in Ax 2012

1.Go go SysSetupFormRun Class.
2.Create Override method RUN .

write the bellow code.

public void run()
{
    super();
    this.design().colorScheme(FormColorScheme::RGB);
    this.design().backgroundColor(WinAPI::RGB2int(0,254, 0));--->Green.
   this.design().backgroundColor(WinAPI::RGB2int(255,0, 0));---->Red.
}

Friday, 1 June 2018

Display Method for table Extension in Ax7

Hi All,
This posts helps you to understand and create a "display"  method for the table extension.
Lets say, the requirement is to add a method in the standard table, it can be achieved either by creating a table extension.
So in this scenario we had a requirement to add a display method in the standard table "CustTrans".
In Dynamics 365 we wont be able to add the new method or modify the existing method to the standard table or to an extension table.
It can be achieved by using the extension class.
Step 1: Create a new class and name it as <Classname>_<Extension>.
<Class-name> - can be any name, but it is preferred to give the table name for which the extension is being created. 
postfix <_Extension> is must.
public static class CustTrans_Extension
{
}
Step 2 : Now add the display methods in the class which is required to be shown.
public static class CustTrans_Extension
{
[SysClientCacheDataMethodAttribute(true)]
public static display AgreementId agreementId(CustTrans _this)
{
LedgerJournalTrans ledgerJournalTrans;
select ledgerJournalTrans
where ledgerJournalTrans.TransactionType == LedgerTransType::Payment &&
LedgerJournalTrans.CustTransId == _this.RecId;

return ledgerJournalTrans.AgreementId;
}
}
Step 3: To use this display method in the form.
Create a string control in the form design and set the following properties
Data source: CustTrans
DataMethod: CustTrans_Extension::agreementId
CacheDataMethod: Yes
Below is the screen shot for reference.
Step 4: Build/Rebuild the project/solution and check the output in the URL.
Thanks,