Monday, February 22, 2016

Dynamics AX Caching, Cache lookup

Dynamics AX Caching


Cache Location

Caches are used on both the client and the server. The Microsoft Dynamics AX runtime manages the cache by removing old records when new records are added to the cache.

Client Cache

A client-side cache can be used only by the client. The client cache is used when a select is executed from the client tier. If no record is found in the client cache, the client then searches the server cache for the record. If the record isn't located in the server cache, it's retrieved from the database. The maximum number of records maintained in a client cache is 100 records per table for a given company.

Server Cache

A server-side cache can be used by any connection to the server. The server cache is used when a select is executed on the server tier. If no record is found in the cache, it's retrieved from the database. The maximum number of records maintained in a server cache is 2,000 records per table for a given company.

Record Caching

Microsoft Dynamics AX database record caching is a performance-enhancing feature that helps avoid database access when it's not strictly necessary. Retrieving database records from memory instead of the database significantly speeds up data access. Caching can reduce the performance penalty for repetitively accessing the same database records.

 Types of Caching

Caching is transparent to the application; however, it's important to know how caching works to optimize its performance in Microsoft Dynamics AX. Following are the types of caching:

Single-record
Set-based
Single-record caching has the following characteristics:

Defined at design time
Moves records to the cache based on the table's CacheLookup property and the type of SELECT statement that is used to retrieve the record


Set-based caching has the following characteristics:

Defined either at design time or in X++ code
Moves sets of records to the cache
Implemented either through the table's CacheLookup property or in code by using the RecordViewCache class
 Single-Record Caching

Record caching is enabled for a table when all the following statements are true:

The CacheLookup property on the table is enabled by setting it to one of the following values:
·         notInTTS
·         Found
·         FoundAndEmpty

The table's PrimaryIndex property is set to a unique index that exists on the table. The RecId index does not qualify as a caching index unless you set the table's PrimaryIndex property to this index.
The record buffer disableCache method has not been called with a parameter of true.
The fields in the table's unique index make up the caching key. A record is placed in the cache when the following criteria are met:

The table is cached by setting the CacheLookup property to notInTTS, Found, or FoundAndEmpty.
The SELECT statement that selects the records uses an equal operator (==) on the caching key. The fields in the WHERE clause of the SELECT statement match the fields in the index referenced by the table's PrimaryIndex property.
The table's CacheLookup property defines how and when records are cached as shown in the following table.

CacheLookup  Property :-

None :-
No data is cached or retrieved from the cache for this table.
This property value should be used for tables that are heavily updated or where it's unacceptable to read outdated data.

NotInTTS :-
All successful caching key selects are cached.
When in a transaction (after ttsBegin), no caches made outside the transaction are used. When inside a transaction, the record is read once from database and subsequently from cache. The record is select-locked when read in a transaction, which ensures that the record cached is not updated while the transaction is active.
A typical example of the NotInTTS property is the CustTable in the Microsoft Dynamics AX standard application. It's acceptable to read outdated data from the cache outside a transaction, but when data is used for validation or creating references, it is ensured that the data is real-time.

Found :-
All successful caching key selects are cached. All caching key selects are returned from the cache if the record exists there. A selectforUpdate in a transaction forces reading from the database and replaces the record in the cache.
This is typically used for static (lookup) tables, such as Unit, where the record usually exists.

FoundAndEmpty :-
All selects on caching keys are cached, including selects that are not returning data.
All caching key selects are returned from caching if the record exists there, or the record is marked as nonexistent in the cache. A selectforUpdate in a transaction forces reading from the database and replaces the record in the cache.
An example of FoundAndEmpty record caching is in the Discount table in the Microsoft Dynamics AX standard application. By default, the Discount table has no records. By using a FoundAndEmpty cache on this table, the keys that are queried for but not found are stored in the cache. Subsequent queries for these same non-existent records can be answered from the cache without a round trip to the database.

EntireTable :-
Creates a set-based cache on the server. The entire table is cached as soon as at least one record is selected from the table.


The Found and FoundAndEmpty caches cross transaction boundaries. The NotInTTS cache is newly created inside a transaction. This example, modified for the purposes of this topic, demonstrates how records are retrieved from the cache when the table's CacheLookup property is set to NotInTTS, and the PrimaryIndex property is set to a unique index on the AccountNum field.

static void NotInTTSCache(Args _args)
{
    CustTable custTable;
    ;
// The query looks for records in the cache.
// If records don't exist, the query accesses the database.
    select custTable
        where custTable.AccountNum == '4000';
    // The transaction starts.
    ttsbegin;
    // The cache is not used. The query accesses the database
    // and records are placed in the cache.
    select custTable
        where custTable.AccountNum == '4000';

    // The query uses the database because
    // the forupdate keyword is used.
    select forupdate custTable
        where custTable.AccountNum == '4000';
    // The query uses the cache and not the database.
    select custTable
        where custTable.AccountNum == '4000';
    // The query uses the cache because
    // the forupdate keyword was used previously.
    select forupdate custTable
        where custTable.AccountNum == '4000';

    // The transaction is committed.
    ttscommit;

    // The query will use the cache.
    select custTable
        where custTable.AccountNum == '4000';
}

If the table CacheLookup property was set to Found or FoundAndEmpty, the first select statement inside the transaction (after the TTSBegin statement) would retrieve the record from the cache.


Set-Based Caching

In Microsoft Dynamics AX, groups of records can be cached all at once with set-based caching. Set-based caching can be implemented in two ways:

At design time, by setting the table's CacheLookup property to EntireTable.
In code, by using the RecordViewCache class.

EntireTable Cache
*      
When you set a table's CacheLookup property to EntireTable, all the records in the table are placed in the cache after the first select. This type of caching follows the rules of single record caching in which the SELECT statement WHERE clause fields must match those of the unique index defined in the table's PrimaryIndex property.

The EntireTable cache is located on the server and is shared by all connections to the Application Object Server (AOS). If a select is made on the client tier to a table that is EntireTable cached, it first looks in its own cache and then searches the server-side EntireTable cache. An EntireTable cache is created for each table for a given company. If you have two selects on the same table for different companies the entire table is cached twice.

Joins that include an EntireTable cached table are only performed against the cached copy when all tables participating in the join are EntireTable cached. Otherwise a database join is performed.

Important Note:

Avoid using EntireTable caches for large tables because once the cache size reaches 128 KB the cache is moved from memory to disk. A disk search is much slower than an in-memory search.

Flushing the Cache

An EntireTable cache is flushed whenever an insert, update, or delete is made to the table. At the same time, the AOS notifies other AOSs that their caches of the same table must be flushed. After the cache is flushed, a subsequent select on the table causes the entire table to be cached again. Therefore, avoid caching any table that's frequently updated. Regardless of when updates are made, EntireTable caches are flushed every 24 hours by the AOS.

RecordViewCache Cache
*      
Set-based caching is implemented in code by using the RecordViewCache class. You must first create a record buffer using the nofetch statement and then pass the record buffer to the RecordViewCache class when it's instantiated.

The cache is created on the server and is only accessible by the process that creates the cache object. Once the cache is instantiated, all select statements are issued against the cache, as shown in the following

static void RecordViewCache(Args _args)
{
    CustTrans       custTrans;
    RecordViewCache recordViewCache;
    ;
    // Define records to cache.
    select nofetch custTrans
       where custTrans.AccountNum == '4000';

    // Cache the records.
    recordViewCache = new RecordViewCache(custTrans);

    // Use cache.
    select firstonly custTrans
        where custTrans.AccountNum == '4000' &&
              custTrans.CurrencyCode == 'USD';
}


Due to concurrency issues, the forUpdate keyword on the instantiating X++ SELECT statement should only be used when all of the records in the result set will be updated. Otherwise it's a better strategy to use select forUpdate only for the records that are to be updated.

The RecordViewCache class is used in a select when the select is from a table that's cached, the select statement doesn't participate in a join and the select WHERE clause matches the WHERE clause with which the RecordViewCache was instantiated.

The cache created by the RecordViewCache class stores records in a linked list. Therefore Microsoft Dynamics AX searches the cache sequentially for records that match the search criteria. If the SELECT statement contains an ORDER BY clause, a temporary index is placed on the cache and the runtime uses the index when searching records.


source :- http://dynamicsuser.net/forums/p/30043/157813.aspx

Thursday, February 18, 2016

How to Debug SSRS Report

Method 1:-
----------------------------

1. write breakpoint; from where u want to debug in code.

2.Compile forward the class.

3.Open AX debugger.

4.Now run the debugger, It will hit the breakpoint :)


Method 2:-
------------------------------
 1.   In classDeclaration extend SrsReportDataProviderPreProcess instead of SrsReportDataProviderBase

  2.  Temp table properties should be

     (a) Table type : Regular instead of tempDB

     (b)  Created by : Yes

     (c) Created Transaction Id : Yes

   3. In process report of the class add this line  in Temporarytablename.setConnection(this.parmUserConnection());

   4. write breakpoint; from where u want to debug in code.

Tuesday, February 16, 2016

Sales Order and Purchase Order Tables and Classes

SalesOrder Classes and Tables:
--------------------------------------

SalesTableType and SaleslineType classes will get called while creating the SalesOrders.

SalesFormLetter_Confirm

SalesFormLetter_Invoice

SalesFormLetter_PackingSlip

SalesFormLetter_PickingLlst

classes will be used to post the sales order at various document status (packing, invoice etc).


Tables:
---------------
SalesTable contains all SalesOrder headers regardless whether they have been posted or not.

The SalesParmTable and SalesParmLine contains detailed information regarding posting sales headers and Lines.

CustConfirmJour and CustConfirmTrans tables contains all Sales Confirmation headers and Lines posted in Dynamic Ax originating from Sales Orders and Lines.

CustPackingSlipJour and CustPackingSlipTrans tables contains all sales PackingSlip headers and Lines posted in Dynamic Ax originating from Sales Orders and Lines.

CustInvoiceJour and CustInvoiceTrans tables contains all sales all Sales Invoice headers and Lines posted in Dynamic Ax originating from Sales Orders and Lines.

Purchase Order classes and Tables:
-------------------------------------------

PurchTableType and PurchTableLine classes will get called while creating the PurchaseOrders.

PurchFormLetter_PurchOrder

PurchFormLetter_ApproveJournal

PurchFormLetter_Invoice

PurchFormLetter_PackingSlip

PurchFormLetter_ReceiptsList

classes will be used to post the PurchaseOrder at various document status (packing, invoice etc).


Tables:
---------------------
PurchTable contains all purchase order headers regardless whether they have been posted or not.

PurchParmTable and PurchParmLine contains detailed information regarding posting Purchase headers and Lines.

VendPackingSlipJour and VendPackingSlipTrans tables contains posted packingslip headers and lines.

VendInvoiceJour and VendInvoiceTrans tables contains all invoiced purchase order headers and Lines.

VendReceiptsJour and VendReceiptsTrans tables contains posted receipt header and lines.

VendPurchOrderJour and VendPurchOrderTrans tables contains Purchase requisition headers and lines.

Monday, February 15, 2016

How to refresh the FormGrid after updating the data in AX 2012 using X++

void clicked()
{
    FormRun callerForm;
    Args args = new Args();
 

    callerForm          = element.args().caller(); //caller form
    callerForm.dataSource().refresh(); //refresh the form cache
    callerForm.dataSource().reread(); //will only re-read the CURRENT record from the DB
    callerForm.dataSource().research(); // will rerun the existing form query against the data source, //therefore updating the list with    new/removed records as well as updating existing ones.

}

Creating Journal using X++ tables

static void Job12(Args _args)
{
LedgerJournalTrans      ledgerJournalTrans; //Table
LedgerJournalTable      ledgerJournalTable; //Table
ledgerJournalname       ledgerJournalname;  //Table
NumberSeq               numberSeq;          //Class
NumberSequenceTable     numSeqTable;        //Table
DimensionDefault        DimensionDefault;   //EDT  
DimensionDynamicAccount ledgerDim, offsetledgerDim; //EDT
container               cont1,cont2,ledgerDimension,offSetAcctPattern;  
int                     cnt;
 
ledgerJournalTable = LedgerJournalTable::find("00619");
    try
    {
        ttsbegin;

        ledgerJournalTrans.clear();
        ledgerJournalTrans.initValue();
        ledgerJournalTrans.JournalNum   = ledgerJournalTable.JournalNum;
        ledgerJournalTrans.TransDate    = today();
        ledgerJournalName = ledgerJournalName::find(ledgerJournalTable.JournalName);
         
        select firstOnly numSeqTable
            where numSeqTable.RecId  == ledgerJournalName.NumberSequenceTable;
        if (numSeqTable)
        {
            numberseq = numberseq::newGetVoucherFromCode(numSeqTable.NumberSequence);
            ledgerJournalTrans.voucher = numberseq.voucher();
        }
         
     
        ledgerJournalTrans.AccountType          = LedgerJournalACType::Vend;
        ledgerJournalTrans.OffsetAccountType    = LedgerJournalACType::Ledger;
     
        // Main account dimensions
        cont1=conNull();
        cont2=conNull();
        ledgerDimension =conNull();
        cont2 += ['BusinessUnit','001','Department','022'];
        cnt =2;
        if(ledgerJournalTrans.AccountType  == LedgerJournalACType::Ledger)
        {
            cont1+=['MainAccount','110130',2];
            cont1+=cont2;
            ledgerDim=AxdDimensionUtil::getLedgerAccountId(cont1);

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

            ledgerJournalTrans.LedgerDimension  = ledgerDim;
        }
        else
        {
            ledgerDim = DimensionStorage::getDynamicAccount( '10001',ledgerJournalTrans.AccountType);
            ledgerJournalTrans.LedgerDimension  = ledgerDim;
            ledgerDimension +=cnt;
            ledgerDimension +=cont2;
            DimensionDefault = AxdDimensionUtil::getDimensionAttributeValueSetId(ledgerDimension);
            ledgerJournalTrans.DefaultDimension = DimensionDefault;
        }
        cont1=conNull();
        cont2=conNull();
        ledgerDimension =conNull();
        cont2 += ['BusinessUnit','001','Department','023'];
        cnt =2;
        if(ledgerJournalTrans.OffsetAccountType  == LedgerJournalACType::Ledger)
        {
            cont1+=['MainAccount','110130',2];
            cont1+=cont2;
            offsetledgerDim=AxdDimensionUtil::getLedgerAccountId(cont1);

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

            ledgerJournalTrans.OffsetLedgerDimension  = offsetledgerDim;
        }
        else
        {
            offsetledgerDim = DimensionStorage::getDynamicAccount( '10001',ledgerJournalTrans.AccountType);
            ledgerJournalTrans.OffsetLedgerDimension = offsetledgerDim;
            ledgerDimension +=cnt;
            ledgerDimension +=cont2;
            DimensionDefault = AxdDimensionUtil::getDimensionAttributeValueSetId(ledgerDimension);
            ledgerJournalTrans.OffsetDefaultDimension = DimensionDefault;
        }
       
        //ledgerJournalTrans.LedgerDimension = ledgerDim;
        //ledgerJournalTrans.OffsetLedgerDimension = offsetledgerDim;

        ledgerJournalTrans.Txt                  = "Test";
        ledgerJournalTrans.CurrencyCode         = "USD";
        ledgerJournalTrans.AmountCurDebit       = 500;
     

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

        ttscommit;

       
    }
    catch(Exception::Error)
    {
        info(strFmt('Catched an error in row: %1',ledgerJournalTrans.OffsetDefaultDimension));
    }
    info(strFmt('journal inserted %1',ledgerJournalTable.JournalNum));
    }


Importing Journals from Excel using X++ in AX 2009


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

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

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

    LedgerJournalName              ledgerJournalName;
    LedgerJournalTable             ledgerJournalTable;
    LedgerJournalTrans             ledgerJournalTrans;



    container                      cont1,cont2,offSetAcctPattern;
    int                            cnt;

    LedgerJournalAC                AccountNumb, offsetAccountnum;

    container                      ledgerDimension;

    LedgerJournalACType            LedgerJournalACType;
    boolean                        ret;

}
--------------------------------------------------------------------------------------------------------------------------


public void DataImport()
{
    str         mSBU,mDepartment,mCostCenter,mPurpose;
    str         oSBU,oDepartment,oCostCenter,oPurpose;
    str         invoice;
    str         TDSgroup,salesTaxGroup,itemSalesTax;
    date        documentdate;
    Voucher     voucher;






    SysOperationProgress progress = new SysOperationProgress();
    int                 row = 0;
    workbook    = workbooks.item(1);
    worksheets  = workbook.worksheets();
    worksheet   = worksheets.itemFromNum(1);
    cells       = worksheet.cells();


    ledgerJournalName = ledgerjournalname::find(ledgerjournaltable.JournalName);
    row = 1;

    do
    {
        row++;
        transdate       = cells.item(row, 1).value().date();
        Currency        = cells.item(row, 2).value().bStr();
        accountType     = cells.item(row, 3).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()));
        }
        mSBU            = cells.item(row, 5).value().bStr();
        mDepartment     = cells.item(row, 6).value().bStr();
        mCostCenter     = cells.item(row, 7).value().bStr();
        mPurpose        = cells.item(row, 8).value().bStr();
        invoice         = cells.item(row, 9).value().bStr();
        Text            = cells.item(row, 10).value().bStr();
        Debit           = any2real(cells.item(row, 11).value().double());
        Credit          = any2real(cells.item(row, 12).value().double());
        OffsetAccounttype = cells.item(row, 13).value().bStr();

        switch(cells.item(row, 14).value().variantType())
        {
            case COMVariantType::VT_BSTR:
                offsetAccountnum = strFmt("%1", cells.item(row, 14).value().bStr());
                break;
            case COMVariantType::VT_DECIMAL, COMVariantType::VT_R4, COMVariantType::VT_R8:
                offsetAccountnum = strFmt("%1", any2int(cells.item(row, 14).value().double()));
                break;
            case COMVariantType::VT_I1, COMVariantType::VT_I2, COMVariantType::VT_I4:
                offsetAccountnum = strFmt("%1", cells.item(row, 14).value().int());
                break;
            case COMVariantType::VT_UI1, COMVariantType::VT_UI2, COMVariantType::VT_UI4:
                offsetAccountnum = strFmt("%1", cells.item(row, 14).value().uLong());
                break;
            case COMVariantType::VT_EMPTY:
                offsetAccountnum = '';
                break;
            default:
                throw error(strfmt('Unhandled variant type (%1).', cells.item(row, 1).value().variantType()));
        }
        oSBU            = cells.item(row, 15).value().bStr();
        oDepartment     = cells.item(row, 16).value().bStr();
        oCostCenter     = cells.item(row, 17).value().bStr();
        oPurpose        = cells.item(row, 18).value().bStr();
        TDSgroup        = cells.item(row, 19).value().bStr();
        salesTaxGroup   = cells.item(row, 20).value().bStr();
        itemSalesTax    = cells.item(row, 21).value().bStr();
        documentdate    = cells.item(row, 22).value().date();

        //In Excel cell should be in Text format
        try
        {
            ttsbegin;

            ledgerJournalTrans.clear();
            ledgerJournalTrans.initValue();
            ledgerJournalTrans.JournalNum   = ledgerJournalTable.JournalNum;
            ledgerJournalTrans.TransDate    = transdate;
            ledgerJournalTrans.Dimension[1] = mSBU;
            ledgerJournalTrans.Dimension[2] = mDepartment;
            ledgerJournalTrans.Dimension[3] = mCostCenter;
            ledgerJournalTrans.Dimension[4] = mPurpose;

            //select firstOnly numSeqTable
            //    where numSeqTable.RecId  == ledgerJournalName.NumberSequenceTable;
            if (!voucher)
            {
                numberseq = numberseq::newGetVoucherFromCode(ledgerJournalName.VoucherSeries);
                voucher = numberseq.voucher();
            }
            ledgerJournalTrans.Voucher              = voucher;
            ledgerJournalTrans.AccountType          = str2enum(LedgerJournalACType, accountType);


            ledgerJournalTrans.AccountNum           = AccountNumb;
            ledgerJournalTrans.Txt                  = Text;
            ledgerJournalTrans.CurrencyCode         = Currency;
            ledgerJournalTrans.AmountCurDebit       = Debit;
            ledgerJournalTrans.AmountCurCredit      = Credit;
            ledgerJournalTrans.OffsetAccountType    = str2enum(LedgerJournalACType, offsetaccountType);
            ledgerJournalTrans.OffsetAccount        = offsetAccountnum;
            ledgerJournalTrans.Invoice              = invoice;
            ledgerJournalTrans.TaxGroup             = salesTaxGroup;
            ledgerJournalTrans.TaxItemGroup         = itemSalesTax;
            ledgerJournalTrans.DocumentDate         = documentdate;
            ledgerJournalTrans.TDSGroup_IN          = TDSgroup;


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

            }

            ttscommit;


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


        info(strFmt('journal inserted %1',ledgerJournalTable.JournalNum));

    }

    while (type != COMVariantType::VT_EMPTY);
    application.quit();
}

-------------------------------------------------------------------------------------------------------------------------

public void run(Args _args)
{

    ;
    LedgerJournalTable = _args.record();
    dialog = new dialog('Excel Import');
    dialogfield = dialog.addField(TypeId(FilenameOpen), 'File Name');

    dialog.run();

    if(dialog.run())
    {
        filename =(dialogfield.value());
    }

    application = SysExcelApplication::construct();
    workbooks = application.workbooks();
    if(filename)
    {
        try
        {
            workbooks.open(filename);
        }
        catch (Exception::Error)
        {
            throw error('File cannot be opened.');
        }
        this.DataImport();



    }
}

-------------------------------------------------------------------------------------------------------------------------

public static void main(Args args)
{
    DIPL_ImportVendInvoiceJournalLines import = new DIPL_ImportVendInvoiceJournalLines();
    import.run(args);

}

--------------------------------------------------------------------------------------------------------------------------

void clicked()
{
    FormRun callerForm;
    Args args = new Args();

    DIPL_ImportVendInvoiceJournalLines DIPL_ImportVendInvoiceJournalLines = new         DIPL_ImportVendInvoiceJournalLines();
    ;
    args.record(ledgerjournaltable);
    DIPL_ImportVendInvoiceJournalLines.run(args);

    callerForm          = element.args().caller();
    callerForm.dataSource().refresh();
    callerForm.dataSource().reread();
    callerForm.dataSource().research();

}

Importing Invoice Journal lines From CSV file using X++ AX 2012


 
 
     
   
        class KPMG_VendInvoiceJournalLineImport
        {
            Dialog              dialog;
            DialogField         dialogfield;
            Filename            filename;
     
            #AviFiles
            SysExcelApplication     application;
            SysExcelWorkbooks       workbooks;
            SysExcelWorkbook        workbook;
            SysExcelWorksheets      worksheets;
            SysExcelWorksheet       worksheet;
            SysExcelCells           cells;
            COMVariantType          type;
            COMVariantType          typeModule;
            NumberSeq               numberSeq;
            NumberSequenceTable     numSeqTable;
     
            str                     Name, num,text, currency,businessunit,account,accountType, department,offsetaccount,OffsetAccounttype;
            int64                   costcenter;
            real                    debit, credit;
            container               Account1, offsetaccount1;
            str                     acc;
            date                    transdate;
     
            LedgerJournalName       ledgerJournalName;
            LedgerJournalTable      ledgerJournalTable;
            LedgerJournalTrans      ledgerJournalTrans;
     
     
            container               cont1,cont2,offSetAcctPattern;
            int                     cnt;
            DimensionDynamicAccount ledgerDim, offsetledgerDim;
            LedgerJournalAC         AccountNumb, offsetAccountnum;
     
            container               ledgerDimension;
            DimensionDefault        DimensionDefault;
            LedgerJournalACType     LedgerJournalACType;
            boolean                 ret;
     
            AsciiIo importFile;
            List        list;
            ListIterator            listIterator;
     
            //Comma
            CommaTextIo        commaTextIo;
            container          containFromRead;
            ledgerJournalTransTaxExtensionIN    ledgerJournalTransTaxExtensionIN;
        }

--------------------------------------------------------------------------------------------------------------------------


        public void CSV_DataImport()
        {
            str         mCostCenter,mEmployee,mIntercompany,mProject;
            str         oCostCenter,oEmployee,oIntercompany,oProject;
            str         invoice;
            str         TDSgroup,salesTaxGroup,itemSalesTax;
            date        documentdate;
            Voucher     voucher;
            container   mCnt;
            container   record, recordData;
            int                cols;
     
            recordData = commaTextIo.read();
     
     
            While(recordData)
            {
                transdate       = str2Date(conPeek(recordData,1),231);
                Currency        =  strFmt("%1", conPeek(recordData,2));
                accountType     = strFmt("%1", conPeek(recordData,3));
                AccountNumb     = strFmt("%1", conPeek(recordData,4));
                mCostCenter     = strFmt("%1", conPeek(recordData,5));
                mEmployee       = strFmt("%1", conPeek(recordData,6));
                mIntercompany   = strFmt("%1", conPeek(recordData,7));
                mProject        = strFmt("%1", conPeek(recordData,8));
                invoice         = strFmt("%1", conPeek(recordData,9));
                Text            = strFmt("%1", conPeek(recordData,10));
                Debit           = any2real(conPeek(recordData,11));
                Credit          = any2real(conPeek(recordData,12));
                OffsetAccounttype = strFmt("%1", conPeek(recordData,13));
                offsetAccountnum = strFmt("%1",conPeek(recordData,14));
                oCostCenter     = strFmt("%1", conPeek(recordData,15));
                oEmployee       = strFmt("%1", conPeek(recordData,16));
                oIntercompany   = strFmt("%1", conPeek(recordData,17));
                oProject        = strFmt("%1", conPeek(recordData,18));
                TDSgroup        = strFmt("%1",conPeek(recordData,19));
                salesTaxGroup   = strFmt("%1",conPeek(recordData,20));
                itemSalesTax    = strFmt("%1",conPeek(recordData,21));
                documentdate    = str2DateDMY(conPeek(recordData,22));
     
     
                //In Excel cell should be in Text format
                try
                {
                    ttsbegin;
     
                    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 = numberseq.voucher();
                    }
                    ledgerJournalTrans.Voucher              = voucher;
                    ledgerJournalTrans.AccountType          = str2enum(LedgerJournalACType, accountType);
     
                   cont1=conNull();
                    cont2=conNull();
                    ledgerDimension =conNull();
     
                    //Account type
                    if(mCostCenter != '')
                    {
                        cnt++;
                        cont2+=['Costcentre',mCostCenter];
                    }
                    if(mEmployee != '')
                    {
                        cnt++;
                        cont2+=['Employee',mEmployee];
                    }
                    if(mIntercompany != '')
                    {
                        cnt++;
                        cont2+=['Intercompany',mIntercompany];
                    }
                    if(mProject != '')
                    {
                        cnt++;
                        cont2+=['Project_Customer_Property_HIPE',mProject];
                    }
     
                    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.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(oCostCenter != '')
                    {
                       cnt++;
                        cont2+=['Costcentre',oCostCenter];
                    }
                    if(oEmployee != '')
                    {
                        cnt++;
                        cont2+=['Employee',oEmployee];
                    }
                    if(oIntercompany != '')
                    {
                        cnt++;
                        cont2+=['Intercompany',oIntercompany];
                    }
                    if(oProject != '')
                    {
                        cnt++;
                        cont2+=['Project_Customer_Property_HIPE',oProject];
                    }
                    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;
     
                    if (ledgerJournalTrans.validateWrite())
                    {
                        ledgerJournalTrans.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;
     
                }
                catch(Exception::Error)
                {
                    info(strFmt('Catched an error in row: %1'));
                }
                info(strFmt('journal inserted %1',ledgerJournalTable.JournalNum));
            }
     
        }
   
  ------------------------------------------------------------------------------------------------------------------------  
        public void DataImport()
        {
            str         mCostCenter,mEmployee,mIntercompany,mProject;
            str         oCostCenter,oEmployee,oIntercompany,oProject;
            str         invoice;
            str         TDSgroup,salesTaxGroup,itemSalesTax;
            date        documentdate;
            Voucher     voucher;
            container   mCnt;
     
     
            SysOperationProgress progress = new SysOperationProgress();
            int                 row = 0;
            workbook    = workbooks.item(1);
            worksheets  = workbook.worksheets();
            worksheet   = worksheets.itemFromNum(1);
            cells       = worksheet.cells();
     
            row = 1;
     
            do
            {
                row++;
                transdate       = cells.item(row, 1).value().date();
                Currency        = cells.item(row, 2).value().bStr();
                accountType     = cells.item(row, 3).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()));
                }
                mCostCenter     = cells.item(row, 5).value().bStr();
                mEmployee       = cells.item(row, 6).value().bStr();
                mIntercompany   = cells.item(row, 7).value().bStr();
                mProject        = cells.item(row, 8).value().bStr();
                invoice         = cells.item(row, 9).value().bStr();
                Text            = cells.item(row, 10).value().bStr();
                Debit           = any2real(cells.item(row, 11).value().double());
                Credit          = any2real(cells.item(row, 12).value().double());
                OffsetAccounttype = cells.item(row, 13).value().bStr();
     
                switch(cells.item(row, 14).value().variantType())
                {
                    case COMVariantType::VT_BSTR:
                        offsetAccountnum = strFmt("%1", cells.item(row, 14).value().bStr());
                        break;
                    case COMVariantType::VT_DECIMAL, COMVariantType::VT_R4, COMVariantType::VT_R8:
                        offsetAccountnum = strFmt("%1", any2int(cells.item(row, 14).value().double()));
                        break;
                    case COMVariantType::VT_I1, COMVariantType::VT_I2, COMVariantType::VT_I4:
                        offsetAccountnum = strFmt("%1", cells.item(row, 14).value().int());
                        break;
                    case COMVariantType::VT_UI1, COMVariantType::VT_UI2, COMVariantType::VT_UI4:
                        offsetAccountnum = strFmt("%1", cells.item(row, 14).value().uLong());
                        break;
                    case COMVariantType::VT_EMPTY:
                        offsetAccountnum = '';
                        break;
                    default:
                        throw error(strfmt('Unhandled variant type (%1).', cells.item(row, 1).value().variantType()));
                }
                oCostCenter     = cells.item(row, 15).value().bStr();
                oEmployee       = cells.item(row, 16).value().bStr();
                oIntercompany   = cells.item(row, 17).value().bStr();
                oProject        = cells.item(row, 18).value().bStr();
                TDSgroup        = cells.item(row, 19).value().bStr();
                salesTaxGroup   = cells.item(row, 20).value().bStr();
                itemSalesTax    = cells.item(row, 21).value().bStr();
                documentdate    = cells.item(row, 22).value().date();
     
                //In Excel cell should be in Text format
                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 = numberseq.voucher();
                    }
                    ledgerJournalTrans.Voucher              = voucher;
                    ledgerJournalTrans.AccountType          = str2enum(LedgerJournalACType, accountType);
                    // Main account dimensions
                    cont1=conNull();
                    cont2=conNull();
                    ledgerDimension =conNull();
     
                    //Account type
                    if(mCostCenter != '')
                    {
                        cnt++;
                        cont2+=['Costcentre',mCostCenter];
                    }
                    if(mEmployee != '')
                    {
                        cnt++;
                        cont2+=['Employee',mEmployee];
                    }
                    if(mIntercompany != '')
                    {
                        cnt++;
                        cont2+=['Intercompany',mIntercompany];
                    }
                    if(mProject != '')
                    {
                        cnt++;
                        cont2+=['Project_Customer_Property_HIPE',mProject];
                    }
     
                    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.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(oCostCenter != '')
                    {
                       cnt++;
                        cont2+=['Costcentre',oCostCenter];
                    }
                    if(oEmployee != '')
                    {
                        cnt++;
                        cont2+=['Employee',oEmployee];
                    }
                    if(oIntercompany != '')
                    {
                        cnt++;
                       cont2+=['Intercompany',oIntercompany];
                    }
                    if(oProject != '')
                    {
                        cnt++;
                        cont2+=['Project_Customer_Property_HIPE',oProject];
                    }
                    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;
     
                    if (ledgerJournalTrans.validateWrite())
                    {
                        ledgerJournalTrans.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));
                }
                info(strFmt('journal inserted %1',ledgerJournalTable.JournalNum));
            }
     
            while (type != COMVariantType::VT_EMPTY);
            application.quit();
        }
   
        public void run(Args    _args)
        {
           ledgerJournalTable  = _args.record() as ledgerJournalTable;
            dialog = new dialog('Excel Import');
     
            dialogfield = dialog.addField(extendedTypeStr(FilenameOpen), 'File Name');
            dialog.run();
            if(dialog.run())
            {
                filename =(dialogfield.value());
                importFile = new AsciiIo(filename, 'R');
                commaTextIo = new CommaTextIO(filename,'R');
                if(importFile)
                {
                    this.CSV_DataImport();
                }
            }
        }
   
--------------------------------------------------------------------------------------------------------------------------
        public static void main(Args args)
        {
           KPMG_VendInvoiceJournalLineImport  import = new                  KPMG_VendInvoiceJournalLineImport();
          //  import.run();
     
        }
   

How to enable the dimension fields based on the Item selected on the form.

[Form] public class KMTShipFromWarehouses extends FormRun {     InventDimCtrl_Frm_EditDimensions        inventDimFormSetup;     /// &l...