Friday, March 21, 2014

Test Query by X++ code

// Test Query by X++ code

static void QueryPacking(Args _args)
{
   date           _fromDate,_todate;
    #AviFiles
    SysOperationProgress progress = new SysOperationProgress();

    int i;
    boolean _unposted;
    InventTrans        inventTransactions,inventTrans;
    InventTransOrigin  inventTransOrigin;
    VendPackingSlipTrans    packingTrans;
    VendPackingSlipJour     packingJour;
    PurchTable              purchTable;
    EcoResDistinctProductVariant    ecoResDistinctProdVariant;

    //POView  poViewTable;
    InventDim inventdim;
    boolean UPDATE;

    Query query;
    QueryRun    qr;
    QueryBuildDataSource qbdsTrans,qbdsJour,qbdsTransOrgin,qbdsinventTrans;
    ItemId  itemID;
    ;

    //super();
    progress.setCaption("Purchase Report");
    progress.setAnimation(#AviUpdate);

   // delete_from poView;
   // ttsBegin;

    _fromDate = 11\10\2007;//fdate.dateValue();
    _todate   = 11\10\2007;//tDate.dateValue();
    ItemId = "9007";

    query = new Query();
    qbdsJour = query.addDataSource(tablenum(VendPackingSlipJour));
    qbdsJour.addRange(fieldnum(VendPackingSlipJour,PurchId)).value("000246");
   
    if(_fromDate && _todate)
    {
        qbdsJour.addRange(fieldnum(VendPackingSlipJour, Deliverydate)).value(SysQuery::range(_fromDate,_toDate));
    }
    qbdsTrans  = qbdsJour.addDataSource(tablenum(VendPackingSlipTrans));  
    qbdsTrans.joinMode(JoinMode::InnerJoin);
    qbdsTrans.relations(true);
    //qbdsTrans.addRange(fieldnum(VendPackingSlipTrans,OrigPurchId)).value("000246");
   
    qbdsTransOrgin = qbdsTrans.addDataSource(tablenum(inventTransOrigin));
    qbdsTransOrgin.joinMode(JoinMode::InnerJoin);
    qbdsTransOrgin.relations(true);
    qbdsTransOrgin.addLink(fieldnum(VendPackingSlipTrans, InventTransId), fieldnum(inventTransOrigin, InventTransId));

    qbdsinventTrans = qbdsTransOrgin.addDataSource(tablenum(inventTrans));
    qbdsinventTrans.joinMode(JoinMode::InnerJoin);
    qbdsinventTrans.relations(false);
    qbdsinventTrans.addLink(fieldnum(inventTrans, InventTransOrigin), fieldnum(inventTransOrigin, RecId));
   
    if(ItemId)
    {
        qbdsinventTrans.addRange(fieldnum(inventTrans, itemID)).value(ItemID);
    }

    //qbdsJour = qbdsTrans.addDataSource(tablenum(VendPackingSlipJour));
    //qbdsJour.joinMode(JoinMode::ExistsJoin);
    //qbdsJour.relations(true);
    ////qbdsJour.addLink(fieldnum(VendPackingSlipTrans, VendPackingSlipJour), fieldnum(VendPackingSlipJour, RecId));
    //qbdsJour.addRange(fieldnum(VendPackingSlipJour, PurchId)).value("000246");


    //if(_fromDate && _todate)
    //{
        //qbdsJour.addRange(fieldnum(VendPackingSlipJour, Deliverydate)).value(SysQuery::range(_fromDate,_toDate));
    //}

    //qbdsTransOrgin = qbdsTrans.addDataSource(tablenum(inventTransOrigin));
    //qbdsTransOrgin.joinMode(JoinMode::InnerJoin);
    //qbdsTransOrgin.relations(true);
    //qbdsTransOrgin.addLink(fieldnum(VendPackingSlipTrans, InventTransId), fieldnum(inventTransOrigin, InventTransId));

    //qbdsinventTrans = qbdsTransOrgin.addDataSource(tablenum(inventTrans));
    //qbdsinventTrans.joinMode(JoinMode::InnerJoin);
    //qbdsinventTrans.relations(false);
    //qbdsinventTrans.addLink(fieldnum(inventTrans, InventTransOrigin), fieldnum(inventTransOrigin, RecId));

    //if(Item.valueStr())
    //{
        //qbdsinventTrans.addRange(fieldnum(inventTrans, RetailVariantId)).value(Item.valueStr());
    //}

                    //while select * from packingTrans
                        //join packingJour where packingJour.RecId == packingTrans.VendPackingSlipJour
                        //&& packingJour.PurchId == "000246"
                        //join inventTransOrigin where inventTransOrigin.InventTransId == packingTrans.InventTransId
                    //{
                        //inventTrans = inventTrans::findByInventTransOrigin(inventTransOrigin.RecId);
                        //info(strFmt("%1,%2",packingJour.PurchId,packingTrans.ItemId));

    qr = new QueryRun(query);
    qr.prompt();

    while (qr.next())
    {
        packingTrans= qr.get(tableNum(VendPackingSlipTrans));
        packingJour =qr.get(tablenum(VendPackingSlipJour));
        inventTransOrigin= qr.get(tableNum(InventtransOrigin));
        inventTrans =qr.get(tablenum(Inventtrans));
        info(strFmt("%1,%2,%3,%4",packingJour.PurchId,packingJour.DeliveryDate,packingTrans.ItemId,inventTransOrigin.InventTransId));
    }
}

Sorting Cointainer

// Sorting Cointainer

static void SortContainer(Args _args)
{
container con = [5,1,2,'Sangeeth B.Tech',9, 'MBA Sangeeth', NoYes::No];
str temp1;
str temp2;
int i;
int j;
container sorCon;
;

sorCon = con;

// Sort the container
    for (i = 1; i <= conlen(sorCon); i++)
    {
        for (j = i + 1; j <= conlen(sorCon); j++)
        {
            temp1 = conpeek(sorCon, j);
            temp2 = conpeek(sorCon, i);

            if (temp1 < temp2)
            {
                sorCon = condel(sorCon, j, 1);
                sorCon = conins(sorCon, j, temp2);
                sorCon = condel(sorCon, i, 1);
                sorCon = conins(sorCon, i, temp1);
            }
        }
    }

conview(sorCon);
}

ReleaseProducts Creation through X++

static void ReleaseProducts_detailed(Args _args)
{
EcoResProduct ecoResProduct;
InventTable inventTable;
InventTableModule inventTableModule;
NumberSequenceTable numberSequenceTable;
ItemId itemId;
InventItemSetupSupplyType inventItemSetupSupplyType;

EcoResStorageDimensionGroupProduct ecoResStorageDimensionGroupProduct;
EcoResTrackingDimensionGroupProduct ecoResTrackingDimensionGroupProduct;
EcoResStorageDimensionGroupItem ecoResStorageDimensionGroupItem;
EcoResTrackingDimensionGroupItem ecoResTrackingDimensionGroupItem;
;

select firstOnly ecoResProduct where EcoResProduct.DisplayProductNumber == “20003?; //Audio system

changecompany (‘CEU’)
{
ttsBegin;
inventTable = null;
inventTableModule = null;
inventItemSetupSupplyType = null;
ecoResStorageDimensionGroupProduct = null;
ecoResTrackingDimensionGroupProduct = null;
ecoResStorageDimensionGroupItem = null;
ecoResTrackingDimensionGroupItem = null;

numberSequenceTable = InventParameters::numRefItemId().numberSequenceTable();
//get item id from:
//1. Product number if number seq for item ID is not set up or manual or return blank value
if (!numberSequenceTable.RecId || numberSequenceTable.Manual)
{
itemId = ecoResProduct.productNumber();
}
else //number sequence auto, get a number
{
itemId = NumberSeq::newGetNumFromId(numberSequenceTable.RecId).num();
}

inventTable.initValue();
inventTable.initFromEcoResProduct(ecoResProduct);
inventTable.ItemId = ItemId;
inventTable.NameAlias = ecoResProduct.SearchName;
inventTable.insert(true);

// Create inventTableModules

inventTableModule.initValue();
inventTableModule.ItemId = inventTable.ItemId;
inventTableModule.ModuleType = ModuleInventPurchSales::Invent;
inventTableModule.insert();

inventTableModule.initValue();
inventTableModule.ItemId = inventTable.ItemId;
inventTableModule.ModuleType = ModuleInventPurchSales::Purch;
inventTableModule.insert();

inventTableModule.initValue();
inventTableModule.ItemId = inventTable.ItemId;
inventTableModule.ModuleType = ModuleInventPurchSales::Sales;
inventTableModule.insert();

//Create inventItemLocation
InventItemLocation::createDefault(inventTable.ItemId);

// Creates a new item default order type for the product that is released.

inventItemSetupSupplyType.initValue();
inventItemSetupSupplyType.ItemId = inventTable.ItemId;
inventItemSetupSupplyType.ItemDataAreaId = inventTable.DataAreaId;
inventItemSetupSupplyType.insert();

//create relationship tables to dimension groups.

ecoResStorageDimensionGroupProduct = EcoResStorageDimensionGroupProduct::findByProduct(ecoResProduct.RecId);
ecoResTrackingDimensionGroupProduct = EcoResTrackingDimensionGroupProduct::findByProduct(ecoResProduct.RecId);

if (ecoResStorageDimensionGroupProduct.RecId)
{ // mandatory storage dimension group for the product
ecoResStorageDimensionGroupItem.ItemDataAreaId = inventTable.DataAreaId;
ecoResStorageDimensionGroupItem.ItemId = inventTable.ItemId;
ecoResStorageDimensionGroupItem.StorageDimensionGroup = ecoResStorageDimensionGroupProduct.StorageDimensionGroup;
ecoResStorageDimensionGroupItem.insert();
}

if (ecoResTrackingDimensionGroupProduct.RecId)
{ // mandatory tracking dimension group for the product
ecoResTrackingDimensionGroupItem.ItemDataAreaId = inventTable.DataAreaId;
ecoResTrackingDimensionGroupItem.ItemId = inventTable.ItemId;
ecoResTrackingDimensionGroupItem.TrackingDimensionGroup = ecoResTrackingDimensionGroupProduct.TrackingDimensionGroup;
ecoResTrackingDimensionGroupItem.insert();
}
ttsCommit;
info(strfmt(“Product successfully released to 'CEU 'legal entity”));
}
}

Total time Consumed to run a business logic

// Total time Consumed to run a business logic

static void TimeConsumed(Args _args)
{
    FromTime startTime = timeNow();
    int i;
    str dummyStr;
    ;
   
    for (i = 1 ; i <= 500000; i++)
    {
        dummyStr += int2str(i);     
    }
       
    info(strFmt("Total time consumed is  %1", timeConsumed(startTime, timeNow())));
}

GetExchangeRates

//GetExchangeRates
error :

static void getExchangeRates(Args _args)
{
    int         curPos, endPos, startPos;
    TextBuffer  tb = new TextBuffer();
    System.Net.WebRequest webRequest;
    System.Net.WebResponse webResponse;
    str page;
    System.IO.StreamReader streamReader;

    try
    {
        webRequest = System.Net.WebRequest::Create("http://www.x-rates.com/d/INR/table.html");

        // this will throw an webexception if cannot be reached.
        webResponse = webRequest.GetResponse();
        streamReader = new System.IO.StreamReader(webResponse.GetResponseStream());

        tb.setText('');
        page = streamReader.ReadToEnd();

        streamReader.Close();

        tb.setText(page);
        curpos   = 1;
        startPos = 1;
        tb.regularExpressions(false);

        tb.find('<a href="/d/INR/EUR/graph120.html" class="menu">', curpos);

        startpos = tb.matchPos();

        tb.find('</a>&nbsp;</font></td>', startpos);
        endpos = tb.matchPos();

        page = tb.subStr(startpos, endpos - startpos);
        info(strFmt("1 EUR = %1 INR",strreplace(page,'<a href="/d/INR/EUR/graph120.html" class="menu">','')));

        // Close the webResonse
        webResponse.Close();
    }
    catch(Exception::CLRError)
    {
        throw error(AifUtil::getClrErrorMessage());
    }
}

Form Lookup thorugh code

// Form Lookup thorugh code

public void lookup()

{
    HcmWorker               selectedRecord;
    Args                    args;
    FormRun                 formRun;
    Form                    workerLookupForm = new Form(formStr(HcmWorkerLookup));
    FormControl             control = this;
    FormStringControl       stringControl       = control as FormStringControl;

    args = new Args();
    args.name(formStr(HcmWorkerLookup));
    args.caller(this);

    args.parmObject(this);

    // position the lookup to highlight the current record
    // a string control supposed to contain a personnel number value
    selectedRecord = HcmWorker::findByPersonnelNumber(stringControl.text());

    if (selectedRecord.RecId != 0)
    {
        args.lookupRecord(selectedRecord);
    }

    // perform form lookup on the caller form control
    formRun = FormAutoLookupFactory::buildLookupFromCustomForm(stringControl, workerLookupForm , AbsoluteFieldBinding::construct(fieldStr(HcmWorker, PersonnelNumber), tableStr(HcmWorker)), args);
    stringControl.performFormLookup(formRun);

    //selectedRecord = formRun.selectRecordModeSelectedRecord();

}

Merging Two pdf file in AX 2012 through Code

// Merging Two pdf file in AX 2012 through Code

static void MergePDFs(Args _args)
{
    PdfSharp.Pdf.PdfDocument outPutPDFDocument = new PdfSharp.Pdf.PdfDocument(); // First u add pdfsharp.dll to AOT-->References , it can download from http://www.4shared.com/get/1LJNZy7i/pdfsharp.html?sd=true#
    PdfSharp.Pdf.PdfDocument inputPDFDocument = new PdfSharp.Pdf.PdfDocument();
    PdfSharp.Pdf.PdfPages pdfPages;
    container con = ["c:\\QUANTITATIVE APTITUDE.pdf","c:\\R S aggarwal verbal reasoning.pdf"]; // This has been hardcoded for now – use winapi::findfirstfile and next to get pdf’s -folder
    int i, j, pageCount;
    FileName pdfFile;
    InteropPermission permission;
    str errorMessage;
    ;

    try
    {
        permission = new InteropPermission(InteropKind::ClrInterop);
        permission.assert();
        for (i = 1; i <= conLen(con); i++)
        {
            pdfFile = conPeek(con,i);
            inputPDFDocument = PdfSharp.Pdf.IO.PdfReader::Open(pdfFile, PdfSharp.Pdf.IO.PdfDocumentOpenMode::Import);
            outputPDFDocument.set_Version(inputPDFDocument.get_Version());
            pageCount = inputPDFDocument.get_PageCount();
            pdfPages = inputPDFDocument.get_Pages();

            if (pageCount > 0)
            {
                for (j = 1 ; j <= pageCount; j++)
                {
                    outputPDFDocument.AddPage(pdfPages.get_Item(j));
                }
            }
        }
        outputPDFDocument.Save("c:\\mergedFile.pdf");
        CodeAccessPermission::revertAssert();
    }
    catch(Exception::CLRError)
    {
        // Get the CLR error before any other CLR operation
        errorMessage = AifUtil::getClrErrorMessage();
        CodeAccessPermission::revertAssert();
        throw error(errorMessage);
    }

}

How to get the count of number of pages printed on to SSRS report [AX 2012 , X++]

//How to get the count of number of pages printed on to SSRS report [AX 2012 , X++]

public void reportViewerRefreshComplete(SRSReportExecutionInfo _executionInfo)
{
    int page;
    super(_executionInfo);

    page = this.getReportContract().parmReportExecutionInfo().parmPrintedPhysicalPages();
    info("Total number of pages:" + int2str(page));
}

Test Dialog Enum Combo Box through Class

//TestDialogEnumComboBox

public class TestDialogEnumComboBox extends RunBaseBatch
{
    DialogEnumComboBox  dialogEnumComboBox;
    DialogField         dialogType;
    DialogRunBase dialog;
    SalesStatus salesStatus;


    #define.FieldNoTmp(600)
}
public Object dialog()
{
    Set enumSet = new Set(Types::Enum);
    dialog = super();


    dialogType = new DialogField(dialog, enumStr(SalesStatus), #FieldNoTmp);  
    dialog.addCtrlDialogField(dialogType.name());
    dialogType.init(dialog);
    dialogType.label("Sales status");
    dialogType.helpText("Select sales status.");
    dialogType.value();


    enumSet.add(SalesStatus::Canceled);
    enumSet.add(SalesStatus::Invoiced);


dialogEnumComboBox = DialogEnumComboBox::newParameters(null, dialogType.control().id(), enumNum(SalesStatus), enumSet, dialog.form());


    return dialog;
}
public void dialogPostRun(DialogRunbase _dialog)
{
    super(_dialog);  
    _dialog.dialogForm().formRun().controlMethodOverload(true);
    _dialog.dialogForm().formRun().controlMethodOverloadObject(this);
    _dialog.formRun().controlMethodOverload(true);
    _dialog.formRun().controlMethodOverloadObject(this);


    if (dialogEnumComboBox)
    {
        // Specify the formRun (at this point the formRun is already available)
        // This is needed to track selection in the comboBox
        dialogEnumComboBox.parmFormRun(dialog.dialogForm().formRun());


        // Select a specific entry in the comboBox, if needed
        dialogEnumComboBox.select(SalesStatus::Invoiced);


    }
}
public boolean getFromDialog()
{
    boolean ret;
    ret = super();


    if (dialogEnumComboBox)
    {
        salesStatus = dialogEnumComboBox.selection();
    }
    return ret;
}
client server static ClassDescription description()
{
    return "DialogEnumComboBox example";
}
public static void main(Args _args)

{

    SR_TestDialogEnumComboBox testDialogComboBox = new SR_TestDialogEnumComboBox();


    if (testDialogComboBox.prompt())
    {
        testDialogComboBox.run();
    }
}
public void run()
{
    info(enum2str(salesStatus));
}

Remove Aplhabet in Prefix and Suffix through X++

//Remove Aplhabet in Prefix and Suffix


static void removeAplhabetic_Prefix_Suffix(Args _args)
{
    int i = 0;
    int whereFound;
    str myString = "Sangeeth91004352000DynamicsAX";
    ;
    if(!isInteger(myString))
    {
        for(i=0 ; i < strlen(myString); i++)
        {
            whereFound = strnFind(myString, "ABCDEFGHIJKLMNOPQRSTUVWXYZ" , 1, strLen(myString));
            if(whereFound > 1)
            {
                myString = strdel(myString,1,1);
            }
        }
        for(i=strlen(myString); i > 0; i--)
        {
            whereFound = strnFind(myString, "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ,strLen(myString), -strLen(myString));
            if(whereFound <= strlen(myString)-1)
            {
                myString = strdel(myString,strlen(myString),1);
            }
        }
    }
    info(myString);
}

Format String Special Character

// Format String Special Character

static void formatString(Args _args)
{
    str value = "   Hello \t Sangeeth        \n Welcom to Dynamics AX";
    str replace(str _source, str _what, str _with)
    {
        int found = 0;
        str target = _source;
        ;
        do
        {
            found = strscan(target, _what, found, strlen(target));
            if (found != 0)
            {
                target = strdel(target, found, strlen(_what));
                target = strins(target, _with, found);
                found += strlen(_with);
            }
        } while (found != 0);
        return target;
    }
    ;
    info(value);
    value = replace(value, '\n', ");
    value = replace(value, '\r', ");
    value = replace(value, '\t', ");
    value = replace(value, ' ', ");
    info(value);
}

To create a form at Run time in x++

// To create a form at Run time

static void formCreation(Args _args)
{
    Form                    form;
    FormTreeControl         tree;
    FormRun                 formRun;
    Args                    args;
    ImageList               imageList;
    int                     imageNum;
    int                     parentIdx;
    int                     treeItemIdx, treeItemIdx1;
    ImageRes                imageRes = imageNum;
    TreeNode                treeNode;
    ;

    form = new Form('Folder', true);
    form.design().width(350);
    form.design().height(150);
    form.design().caption('Folder structure');
    form.design().addControl(FormControlType::Tree, 'TreeCtrl');

    args = new Args(form.name());
    args.name(form.name());
    args.object(form);

    formRun = classFactory.formRunClass(args);
    formRun.init();
    formRun.run();

    tree = formRun.design().controlName('TreeCtrl');
    tree.width(330);
    tree.height(130);
    tree.hasButtons(false);
    tree.border(3);
    tree.colorScheme(2);
    tree.backgroundColor(11072224);
    tree.font('Arial');
    tree.fontSize(8);
    tree.bold(7);

    imagelist = new Imagelist(25, 25);
    imageNum = imagelist.add(new Image(3114));

    tree.setImagelist(imagelist);
    tree.deleteAll();

    parentIdx = SysFormTreeControl::addTreeItem(Tree,
                                                'SangeethTest',
                                                FormTreeAdd::Root,
                                                'Data on root',
                                                imageRes,
                                                true);
    treeItemIdx = SysFormTreeControl::addTreeItem(Tree,
                                                'SangeethTest1',
                                                parentIdx,
                                                'Data on element2',
                                                imageRes,
                                                true);
    treeItemIdx1 = SysFormTreeControl::addTreeItem(Tree,
                                                'SangeethTest2',
                                                treeItemIdx,
                                                'Data on element3',
                                                imageRes,
                                                false);
    SysFormTreeControl::expandTree(Tree, Tree.getRoot(), 3);
    formRun.detach();
}

To write Data WordDocument thrugh X++

static void writeWordData(Args _args)
{
    COM                 document;
    COM                 wordDocument;
    COM                 range;
    COM                 app;
    COM                 font;
    COM                 shading;
    ;
    app = new COM(‘Word.Application’);
    app.visible(true);
    document     = app.Documents();
    wordDocument = document.add();
    wordDocument.activate();
    range = wordDocument.range();
    range.insertBefore(‘Welcom To AX Document’);
   
    font = range.font();
    font.Size(16);
    font.bold(2);
   
    shading = font.shading();
   
    //You can use either the integer directly or better way is to use RGB2Int
    //shading.BackgroundPatternColor(65535); //Yellow
    shading.BackgroundPatternColor(WinApi::RGB2int(255, 255, 0)); //Yellow
}

To get a color window

// To get a color window

static void colors(Args _args)
{
    #DEFINE.COLORVALUE (64)
    int             r, g, b;
    container       chosenColor;
    Binary          customColors        = new Binary(#COLORVALUE);
    CCColor         colorValue;
    chosenColor = WinAPI::chooseColor(infolog.hWnd(), r, g, b, customColors, true);
    if (chosenColor)
    {
        [r, g, b] = chosenColor;
        colorValue  = WinAPI::RGB2int(r, g, b);
        print (colorValue);
        pause;
    }
}

Data Base ODBC Connection

static void dbODBCConnection(Args _args)
{
    LoginProperty   loginProp;
    ODBCConnection  conn;
    Resultset       resultSet, resultSetCount;
    Statement       statement1, statement2;
    ;

    loginProp = new LoginProperty();

    loginProp.setServer('name');
    loginProp.setDatabase(‘Database name');

    conn = new ODBCConnection(loginProp);

    statement1  = conn.createStatement();
    resultSet   = statement1.executeQuery("SELECT * from CustTable where DATAAREAID = ‘CEU’");

    while (resultSet.next())
    {
        info(resultSet.getString(1));
    }
 }

To Fetch Ledger transaction in x++

// To Fetch Ledger transaction

static void findLedgerTransactions(Args _args)
{
    MainAccount                         mainAccount; //Holds the main accounts
    GeneralJournalEntry                 generalJournalEntry; //Used to hold Ledger transactions
    GeneralJournalAccountEntry          generalJournalAccountEntry; //Used to hold Ledger transactions
    SubledgerJournalEntry               subLedgerJournalEntry; //Used to hold sub Ledger transactions (Like sales/purch invoice etc.)
    SubledgerJournalAccountEntry        subLedgerJournalAccountEntry;  //Used to hold sub Ledger transactions (Like sales/purch invoice etc.)
    DimensionAttributeValueCombination  dimAttrValueComb; //Used to store the combination of main accounts and dimensions

    while select AccountingCurrencyAmount, TransactionCurrencyAmount,  TransactionCurrencyCode
            from generalJournalAccountEntry
            join dimAttrValueComb
                where dimAttrValueComb.RecId == generalJournalAccountEntry.LedgerDimension
            join AccountingDate, JournalNumber from generalJournalEntry
                where generalJournalAccountEntry.GeneralJournalEntry == generalJournalEntry.RecId
                   && generalJournalEntry.AccountingDate == 017\2010
                   && generalJournalEntry.PostingLayer == OperationsTax::Current
                   && generalJournalEntry.Ledger == Ledger::current()
                join MainAccountId, Name from mainAccount
                    where mainAccount.RecId == dimAttrValueComb.MainAccount
                        && mainAccount.MainAccountId == ’130100'
            join subLedgerJournalAccountEntry
                where subLedgerJournalAccountEntry.GeneralJournalAccountEntry == generalJournalAccountEntry.RecId
                   && subLedgerJournalAccountEntry.LedgerDimension == generalJournalAccountEntry.LedgerDimension
                join Voucher from subLedgerJournalEntry
                    where subLedgerJournalAccountEntry.SubledgerJournalEntry == subLedgerJournalEntry.RecId
                       //&& subLedgerJournalEntry.Ledger == Ledger::current()

    {
        info(strFmt("%1-%2, %3, %4, %5, %6, %7, %8", mainAccount.MainAccountId, mainAccount.Name,
                    generalJournalEntry.AccountingDate, subLedgerJournalEntry.Voucher,
                    generalJournalAccountEntry.TransactionCurrencyCode, generalJournalAccountEntry.TransactionCurrencyAmount,
                    generalJournalAccountEntry.AccountingCurrencyAmount,
                    generalJournalEntry.JournalNumber));
    }
}

Replacing Financial Dimension in Ledger Dimension

Replacing Financial Dimension in Ledger Dimension



1]Get the target ledger dimension
2]Break it into its component parts (Main account and active dimensions)
3]Prepare the hash key array for each of them except main account (for only financial dimensions)
4]In this hash key array replace the hash key of the required financial dimension with the hash key of attribute value to be replaced
5]Find or create the DimensionAttributeValueSet table
Then use the “serviceCreateLedgerDimension” method of DimensionDefaultingService to get the new ledger dimension and use it

static void replaceLedgerDimensions(Args _args)
{
    #LedgerSHA1Hash
    DimensionSHA1Hash               hash; //To store the calculated hash for DimensionAttributeValueSet
    HashKey                         valueKeyHashArray[]; //To store the has key of dimension in question
    Map                             dimAttrIdx, dimAttrRecId; //to store the dimension index and backing entity type
    DimensionAttributeSetItem       dimAttrSetItem; // Contains the number of dimensions active for a account structure ledger
    DimensionAttribute              dimAttr; // Contains the financial dimensions records
    DimensionAttributeValue         dimAttrValue; // Contains used financial dimension values
    DimensionAttributeValueSet      dimAttrValueSet; //Contains default dimension records
    DimensionAttributeValueSetItem  dimAttrValueSetItem; //Contains individual records for default dimensions
    DimAttributeHcmWorker           dimAttrWorker; //Backing entity view for Employee type dimension
    DimensionEnumeration            dimensionSetId; //Record id for table that contains active dimensions for current ledger
    LedgerDimensionAccount          targetDimension = 5637145829; //Record Id DimensionAttributeValueCombination table in which attribute value is to be replaced
    LedgerDimensionAccount          ledgerDimension; // To hold the resultant DimensionAttributeValueCombination record id
    LedgerDimensionAccount          mainAccDimension; // Record id for LedgerDimension(DimensionAttributeValueCombination) containing default account for main account RecId
    DimensionStorage                dimensionStorage; // Class Dimension storage is used to store and manipulate the values of combination
    DimensionStorageSegment         segment; // Class DimensionStorageSegment will get specfic segments based on hierarchies

    int     segmentCount, segmentIndex;
    int     hierarchyCount, hierarchyIndex;
    SysDim  segmentValue, mainAccountValue;
    int     dimAttrCount, i;
    int     emplBackEntityType; //Stores the backing entity type for Employee type dimension
    str     valueStrArray[]; //To store the dimension attribute values
    int64   valueKeyArray[]; //To store the record ids of DimensionAtrributeValue table
    int     backingEntityInstance;
    ;

    //The employee backing entity will be the view DimAttributeHcmWorker
    emplBackEntityType = tableNum(DimAttributeHcmWorker);

    //Initialize the map to store the backing entity types
    dimAttrIdx = new Map(Types::Integer, Types::Integer);
    dimAttrRecId = new Map(Types::Integer, Types::Int64);

    //Get the record Id (dimension set id) for current ledger to find active dimensions
    dimensionSetId = DimensionCache::getDimensionAttributeSetForLedger();

    //Find all the active dimensions for current ledger except main account and store there
    //backing entity type in the map
    while select * from dimAttr
            order by Name
            where dimAttr.Type != DimensionAttributeType::MainAccount
        join RecId from dimAttrSetItem
            where dimAttrSetItem.DimensionAttribute == dimAttr.RecId &&
                dimAttrSetItem.DimensionAttributeSet == dimensionSetId
    {
        dimAttrCount++;
        dimAttrIdx.insert(dimAttr.BackingEntityType, dimAttrCount);
        dimAttrRecId.insert(dimAttr.BackingEntityType, dimAttr.RecId);
    }

    //initialize hash key array to null
    for (i = 1; i<= dimAttrCount; i++)
    {
        valueKeyHashArray[i] = emptyGuid();
        valueStrArray[i] = ”;
        valueKeyArray[i] = 0;
    }

    // Default hash key array with required dimension value
    // Get dimension storage
    dimensionStorage = DimensionStorage::findById(targetDimension);
    if (dimensionStorage == null)
    {
        throw error("@SYS83964");
    }

    // Get hierarchy count
    hierarchyCount = dimensionStorage.hierarchyCount();
    //Loop through hierarchies to get individual segments
    for(hierarchyIndex = 1; hierarchyIndex <= hierarchyCount; hierarchyIndex++)
    {
        //Get segment count for hierarchy
        segmentCount = dimensionStorage.segmentCountForHierarchy(hierarchyIndex);

        //Loop through segments and display required values
        for (segmentIndex = 1; segmentIndex <= segmentCount; segmentIndex++)
        {
            // Get segment
            segment = dimensionStorage.getSegmentForHierarchy(hierarchyIndex, segmentIndex);

            // Get the segment information
            if (segment.parmDimensionAttributeValueId() != 0)
            {
                //Get the backing entity type;
                backingEntityInstance = DimensionAttribute::find(DimensionAttributeValue::find(segment.parmDimensionAttributeValueId()).DimensionAttribute).BackingEntityType;

                if (backingEntityInstance == tableNum(DimAttributeMainAccount))
                    mainAccountValue = segment.parmDisplayValue();

                //Default the required arrays
                if (dimAttrIdx.exists(backingEntityInstance))
                {
                    i = dimAttrIdx.lookup(backingEntityInstance);
                    valueKeyHashArray[i]    = segment.parmHashKey();
                    valueKeyArray[i]        = segment.parmDimensionAttributeValueId();
                    valueStrArray[i]        = segment.parmDisplayValue();
                }
            }
        }
    }

    //Find the Dimension attribute record for the dimension to work on, in our case it is HcmWorker
    dimAttr.clear();
    dimAttr = DimensionAttribute::find(dimAttrRecId.lookup(emplBackEntityType));

    //Get the backing entity type for the dimension value to process
    select firstOnly dimAttrWorker
        where dimAttrWorker.Value == "51011";

    //Find the required Dimension Attribute Value record
    //Create if necessary
    dimAttrValue = DimensionAttributeValue::findByDimensionAttributeAndEntityInst(dimAttr.RecId, dimAttrWorker.RecId, false, true);

    //Replace the required combination hash keys and other value arrays
    i = dimAttrIdx.lookup(emplBackEntityType);
    valueKeyHashArray[i]    = dimAttrValue.HashKey;
    valueStrArray[i]        = dimAttrWorker.Value;
    valueKeyArray[i]        = dimAttrValue.RecId;

    //Calculate the hash for the current values
    hash = DimensionAttributeValueSetStorage::getHashFromArray(valueKeyHashArray, dimAttrCount);

    //Null hash indicates no values exist, which may occur if the user entered an invalid value for one dimension attribute
    if (hash == conNull())
    {
        throw error("Wrong value for Employee Dimension");
    }

    // Search for existing value set
    dimAttrValueSet = DimensionAttributeValueSet::findByHash(hash);

    // This value set does not exist, so it must be persisted
    if (!dimAttrValueSet)
    {
        ttsbegin;

        // Insert the value set with appropriate hash
        dimAttrValueSet.Hash = hash;
        dimAttrValueSet.insert();

        // Insert only specified set items use this
        for (i = 1; i <= dimAttrCount; i++)
        {
            if (valueKeyArray[i] != 0)
            {
                dimAttrValueSetItem.clear();
                dimAttrValueSetItem.DimensionAttributeValueSet = dimAttrValueSet.RecId;
                dimAttrValueSetItem.DimensionAttributeValue = valueKeyArray[i];
                dimAttrValueSetItem.DisplayValue = valueStrArray[i];
                dimAttrValueSetItem.insert();
            }
        }

        ttscommit;
    }

    // Get the default account for main account
    mainAccDimension = DimensionStorage::getDefaultAccountForMainAccountNum(mainAccountValue);

    //Find or create the LedgerDimension record for required combination
    ledgerDimension = DimensionDefaultingService::serviceCreateLedgerDimension(
                                                            mainAccDimension,
                                                            dimAttrValueSet.RecId);

    info(strFmt("Original %1: %2", targetDimension, DimensionAttributeValueCombination::find(targetDimension).DisplayValue));
    info(strFmt("Replaced %1: %2", ledgerDimension, DimensionAttributeValueCombination::find(ledgerDimension).DisplayValue));

}

Replace a Financial Dimension in Default Dimensions–Condensed in ax 2012

// Replace a Financial Dimension in Default Dimensions–Condensed [AX 2012]

static void replaceDefaultDimensionsCondense(Args _args)
{
    /*
     * In this job, we will replace the Business Unit Value from BU-001 to BU-002
     * and fill in the values for Department as Dep-001 and Worker as 114
     */
    CustTable                       custTable = CustTable::find(‘CUS-00004'); //Customer Record containing Financial Dimension
    Struct                          struct = new Struct(); //Structure to hold the dimension values to replace
    container                       defDimensionCon; //Container to prepare the required values and dimension attribute combination
    DimensionDefault                dimensionDefault; //Get the replaced dimension recid
    DimensionAttributeSetItem       dimAttrSetItem; //Table to get active dimensions for the legal entity
    DimensionAttribute              dimAttribute; //Table to get the Financial dimensions
    int i; //For looping

    //Loop for required dimensions
    while select Name, BackingEntityType from dimAttribute
        where dimAttribute.BackingEntityType == tableNum(DimAttributeOMBusinessUnit) ||
              dimAttribute.BackingEntityType == tableNum(DimAttributeOMDepartment) ||
              dimAttribute.BackingEntityType == tableNum(DimAttributeHcmWorker) &&
              dimAttribute.Type              != DimensionAttributeType::DynamicAccount
              join dimAttrSetItem
                where dimAttrSetItem.DimensionAttribute == dimAttribute.RecId &&
                      dimAttrSetItem.DimensionAttributeSet == DimensionCache::getDimensionAttributeSetForLedger()
    {
        //Add the Dimension name and display value to struct
        if (dimAttribute.BackingEntityType == tableNum(DimAttributeOMBusinessUnit))
        {
            struct.add(dimAttribute.Name, ‘BU-002');
        }
        else if (dimAttribute.BackingEntityType == tableNum(DimAttributeOMDepartment))
        {
            struct.add(dimAttribute.Name, ‘DEP-002');
        }
        else if (dimAttribute.BackingEntityType == tableNum(DimAttributeHcmWorker))
        {
            struct.add(dimAttribute.Name, ’114');
        }
    }

    //Prepare the container
    defDimensionCon += struct.fields();

    for (i = 1; i <= struct.fields(); i++)
    {
        defDimensionCon += struct.fieldName(i);
        defDimensionCon += struct.valueIndex(i);
    }

    //if there are fields in struct
    if (struct.fields())
    {
        //Get the DimensionAttributeValueSet table’s Record ID
        dimensionDefault = AxdDimensionUtil::getDimensionAttributeValueSetId(defDimensionCon);
     
        //Update to Customer
        ttsBegin;
        custTable.selectForUpdate(true);
        if (custTable.DefaultDimension)
        {
            custTable.DefaultDimension = DimensionDefaultingService::serviceMergeDefaultDimensions(dimensionDefault, custTable.DefaultDimension);
        }
        else
        {
            custTable.DefaultDimension = dimensionDefault;
        }
        custTable.doUpdate();
        ttsCommit;
    }
}

// Replace Finical Dimension:

static void replaceLedgerDimensions1(Args _args)
{
    #LedgerSHA1Hash
    DimensionSHA1Hash               hash; //To store the calculated hash for DimensionAttributeValueSet
    HashKey                         valueKeyHashArray[]; //To store the has key of dimension in question
    Map                             dimAttrIdx, dimAttrRecId; //to store the dimension index and backing entity type
    DimensionAttributeSetItem       dimAttrSetItem; // Contains the number of dimensions active for a account structure ledger  
    DimensionAttribute              dimAttr; // Contains the financial dimensions records
    DimAttributeHcmWorker           dimAttrWorker; //Backing entity view for Employee type dimension
    DimensionAttributeValue         dimAttrValue; // Contains used financial dimension values
    DimensionAttributeValueSet      dimAttrValueSet; //Contains default dimension records
    DimensionAttributeValueSetItem  dimAttrValueSetItem; //Contains individual records for default dimensions
    LedgerDimensionAccount          sourceDimension = 5637145829, targetDimension; //Record Id DimensionAttributeValueCombination table in which attribute value is to be replaced
    DimensionDefault                sourceDefDimension, targetDefDimension; //To hold the default dimension combination from a Ledger dimension
    LedgerDimensionDefaultAccount   defaultLedgerAccount;
    DimensionEnumeration            dimensionSetId; //Record id for table that contains active dimensions for current ledger
 
    int     dimAttrCount, i;
    int     emplBackEntityType; //Stores the backing entity type for Employee type dimension
    ;
 
    //The employee backing entity will be the view DimAttributeHcmWorker
    emplBackEntityType = tableNum(DimAttributeHcmWorker);
 
    //Initialize the map to store the backing entity types
    dimAttrIdx = new Map(Types::Integer, Types::Integer);
    dimAttrRecId = new Map(Types::Integer, Types::Int64);

    //Get the record Id (dimension set id) for current ledger to find active dimensions
    dimensionSetId = DimensionCache::getDimensionAttributeSetForLedger();

    //Find all the active dimensions for current ledger except main account and store there
    //backing entity type in the map
    while select * from dimAttr
            order by Name
            where dimAttr.Type != DimensionAttributeType::MainAccount
        join RecId from dimAttrSetItem
            where dimAttrSetItem.DimensionAttribute == dimAttr.RecId &&
                dimAttrSetItem.DimensionAttributeSet == dimensionSetId
    {
        dimAttrCount++;
        dimAttrIdx.insert(dimAttr.BackingEntityType, dimAttrCount);
    }

    //initialize hash key array to null
    for (i = 1; i<= dimAttrCount; i++)
    {
        valueKeyHashArray[i] = emptyGuid();
    }
 
    // Get the default dimensions from Ledger dimensions
    sourceDefDimension      = DimensionStorage::getDefaultDimensionFromLedgerDimension(sourceDimension);
 
    //Get the default account from Ledger dimensions
    defaultLedgerAccount    = DimensionStorage::getLedgerDefaultAccountFromLedgerDim(sourceDimension);
 
    //Find the Dimension attribute record for the dimension to work on, in our case it is HcmWorker
    dimAttr.clear();
    select firstOnly dimAttr
        where dimAttr.BackingEntityType == emplBackEntityType
           && dimAttr.Type  != DimensionAttributeType::DynamicAccount;

    //Get the backing entity type for the dimension value to process
    select firstOnly dimAttrWorker
        where dimAttrWorker.Value == "51011";
 
    //Find the required Dimension Attribute Value record
    //Create if necessary
    dimAttrValue = DimensionAttributeValue::findByDimensionAttributeAndEntityInst(dimAttr.RecId, dimAttrWorker.RecId, false, true);
 
    //Store the required combination hash keys
    valueKeyHashArray[dimAttrIdx.lookup(emplBackEntityType)] = dimAttrValue.HashKey;

    //Calculate the hash for the current values
    hash = DimensionAttributeValueSetStorage::getHashFromArray(valueKeyHashArray, dimAttrCount);

    //Null hash indicates no values exist, which may occur if the user entered an invalid value for one dimension attribute
    if (hash == conNull())
    {
        throw error("Wrong value for Employee Dimension");
    }

    // Search for existing value set
    dimAttrValueSet = DimensionAttributeValueSet::findByHash(hash);

    // This value set does not exist, so it must be persisted
    if (!dimAttrValueSet)
    {
        ttsbegin;

        // Insert the value set with appropriate hash
        dimAttrValueSet.Hash = hash;
        dimAttrValueSet.insert();

        //Insert Employee dimension set item
        dimAttrValueSetItem.clear();
        dimAttrValueSetItem.DimensionAttributeValueSet = dimAttrValueSet.RecId;
        dimAttrValueSetItem.DimensionAttributeValue = dimAttrValue.RecId;
        dimAttrValueSetItem.DisplayValue = dimAttrWorker.Value;
        dimAttrValueSetItem.insert();

        ttscommit;
    }
 
    //Replace the value in default dimension
    targetDefDimension = DimensionDefaultingService::serviceReplaceAttributeValue(sourceDefDimension, dimAttrValueSet.RecId, dimAttr.RecId);
 
    //Combine the target default dimension, default ledger account to get the resultant ledger dimension
    targetDimension = DimensionDefaultingService::serviceCreateLedgerDimension(defaultLedgerAccount, targetDefDimension);
 
    info(strFmt("Before: %1", DimensionAttributeValueCombination::find(sourceDimension).DisplayValue));
    info(strFmt("Before: %1", DimensionAttributeValueCombination::find(targetDimension).DisplayValue));
}




//Remove a Financial Dimension Value

static void sgxRemoveWorkerDimension(Args _args)
{
    /*
     * We will Remove a worker dimension in this example
    */
    CustTable                       custTable = CustTable::find(‘CUS-00004'); //Customer Record containing Financial Dimension
    DimensionSHA1Hash               hash; //To store the calculated hash for DimensionAttributeValueSet
    DimensionAttribute              dimAttr; // Contains the financial dimensions records
    DimensionAttributeValue         dimAttrValue; // Contains used financial dimension values
    DimensionAttributeValueSet      dimAttrValueSet; //Contains default dimension records
    DimensionAttributeValueSetItem  dimAttrValueSetItem; //Contains individual records for default dimensions
    DimensionAttributeSetItem       dimAttrSetItem; // Contains the number of dimensions active for a account structure ledger

    HashKey     valueKeyHashArray[]; //To store the has key of dimension in question
    Map         dimAttrRecId, dimAttrStr; //To store the dimension attribute recid and dimension attribute value display value
    Set         dimAttrValueRecId;
    SetEnumerator   setEnum;
    int dimAttrCount, i;

 
    //Initialize the map to store the backing entity types
    dimAttrRecId = new Map(Types::Int64, Types::Integer);
    dimAttrValueRecId = new Set(Types::Int64);
    dimAttrStr = new Map(Types::Int64, Types::String);

    //Find all the active dimensions for current ledger except main account and store there
    //backing entity type in the map
    while select RecId from dimAttr
            order by Name
            where dimAttr.Type != DimensionAttributeType::MainAccount
            join RecId from dimAttrSetItem
                where dimAttrSetItem.DimensionAttribute == dimAttr.RecId &&
                      dimAttrSetItem.DimensionAttributeSet == DimensionCache::getDimensionAttributeSetForLedger()
    {
        dimAttrCount++;
        dimAttrRecId.insert(dimAttr.RecId, dimAttrCount);
    }

    //initialize hash key array to null
    for (i = 1; i<= dimAttrCount; i++)
        valueKeyHashArray[i] = emptyGuid();

    //Get individual dimension attribute records and display values except worker dimension
    //Store them in sets
    while select DisplayValue, DimensionAttributeValue from dimAttrValueSetItem
            where dimAttrValueSetItem.DimensionAttributeValueSet == custTable.DefaultDimension
            join DimensionAttribute, HashKey from dimAttrValue
                where dimAttrValue.RecId == dimAttrValueSetItem.DimensionAttributeValue
                join RecId from dimAttr
                    where dimAttr.RecId == dimAttrValue.DimensionAttribute
                       && dimAttr.BackingEntityType != tableNum(DimAttributeHcmWorker) //As we ignore worker dimension, its hash key remains blank
    {
        dimAttrValueRecId.add(dimAttrValueSetItem.DimensionAttributeValue);
        dimAttrStr.insert(dimAttrValueSetItem.DimensionAttributeValue, dimAttrValueSetItem.DisplayValue);
        valueKeyHashArray[dimAttrRecId.lookup(dimAttrValue.DimensionAttribute)] = dimAttrValue.HashKey;
    }

    //Calculate the hash for the current values
    hash = DimensionAttributeValueSetStorage::getHashFromArray(valueKeyHashArray, dimAttrCount);

    //Null hash indicates no values exist, which may occur if the user entered an invalid value for one dimension attribute
    if (hash == conNull())
    {
        throw error(“Wrong value for Dimensions”);
    }

    // Search for existing value set
    dimAttrValueSet = DimensionAttributeValueSet::findByHash(hash);

    // This value set does not exist, so it must be persisted
    if (!dimAttrValueSet)
    {
        ttsbegin;
        // Insert the value set with appropriate hash
        dimAttrValueSet.Hash = hash;
        dimAttrValueSet.insert();

        // Insert only specified set items use this
        setEnum = dimAttrValueRecId.getEnumerator();

        while (setEnum.moveNext())
        {
            dimAttrValueSetItem.clear();
            dimAttrValueSetItem.DimensionAttributeValueSet = dimAttrValueSet.RecId;
            dimAttrValueSetItem.DimensionAttributeValue = setEnum.current();
            dimAttrValueSetItem.DisplayValue = dimAttrStr.lookup(setEnum.current());
            dimAttrValueSetItem.insert();
        }
        ttscommit;
    }
 
    ttsBegin;
    custTable.selectForUpdate(true);
    custTable.DefaultDimension = dimAttrValueSet.RecId;
    custTable.doUpdate();
    ttsCommit;
}

Getting Individual Dimension Combination Values–Using Views [AX 2012]

// Getting Individual Dimension Combination Values–Using Views [AX 2012]


static void sgxIndividualDimensionValuesUsingView(Args _args)
{
    GeneralJournalAccountEntry          generalJournalAccountEntry; //Table that stores ledger transactions
    DimensionAttributeLevelValueAllView dimAttrView; //View that will display all values for ledger dimensions
    DimensionAttribute                  dimAttr; //Main dimension attribute table
    int i;
 
    setPrefix(‘Ledger dimension breakup’);
    while select generalJournalAccountEntry
    {
        i++;
        if (i > 100)
            break;
     
        setPrefix(int2str(i) + “. “ + DimensionAttributeValueCombination::find(generalJournalAccountEntry.LedgerDimension).DisplayValue);
        while select DisplayValue from dimAttrView  
            where dimAttrView.ValueCombinationRecId == generalJournalAccountEntry.LedgerDimension
            join BackingEntityType from dimAttr
                where dimAttr.RecId == dimAttrView.DimensionAttribute
        {
            switch (dimAttr.BackingEntityType)
            {
                case tableNum(DimAttributeMainAccount):
                    info(strFmt(“Main Account: %1?, dimAttrView.DisplayValue));
                    break;
             
                case tableNum(DimAttributeOMBusinessUnit):
                    info(strFmt(“Business Unit: %1?, dimAttrView.DisplayValue));
                    break;

                case tableNum(DimAttributeCustTable):
                    info(strFmt(“Customer: %1?, dimAttrView.DisplayValue));
                    break;

                case tableNum(DimAttributeOMDepartment):
                    info(strFmt(“Department: %1?, dimAttrView.DisplayValue));
                    break;

                case tableNum(DimAttributeHcmWorker):
                    info(strFmt(“Worker: %1?, dimAttrView.DisplayValue));
                    break;
            }  
        }
    }
 
}

To get Current AX time

//To get Current AX time

static void timeinAX(Args _args)
{
    //time2str(timeNow(),1,1)
    info(time2str(timeNow(),1,1));
}

Random Number generator in AX

// Random Number generator in AX

static void Random(Args _args)
{
    Random  Random = new Random();
    int RandomNo,Randomwithmod;
    ;
    RandomNo = Random.nextInt();
    Randomwithmod = Random.nextInt() mod 1000;
    info(strFmt("%1  %2",RandomNo,Randomwithmod));
}

Purchase order Packing Slip query by code and DP

// Purchase order Packing Slip query by code and DP process..

static void POtrans(Args _args)
{
    date           _fromDate,_todate;

    #AviFiles
    SysOperationProgress progress = new SysOperationProgress();

    int i;
    boolean _unposted;

    InventTrans             inventTransactions,inventTrans;
    InventTransOrigin       inventTransOrigin;
    VendPackingSlipTrans    packingTrans;
    VendPackingSlipJour     packingJour;
    PurchTable              purchTable;
    EcoResDistinctProductVariant    ecoResDistinctProdVariant;
    //POView  poViewTable;
    InventDim inventdim;
    boolean UPDATE;
    ItemId      itemID;
    Query query;
    QueryRun    qr;
    QueryBuildDataSource qbdsTrans,qbdsJour,qbdsTransOrgin,qbdsinventTrans;


    ;

    progress.setCaption("Purchase Report");
    progress.setAnimation(#AviUpdate);


    //delete_from poView;
    //ttsBegin;

    //_fromDate = 11\10\2007;//fdate.dateValue();
    //_todate   = 11\10\2007;//tDate.dateValue();
    //ItemId = "9007";

    query = new Query();
    qbdsJour = query.addDataSource(tablenum(VendPackingSlipJour));
    qbdsJour.addRange(fieldnum(VendPackingSlipJour,PurchId)).value("000253");

    //if(_fromDate && _todate)
    //{
        //qbdsJour.addRange(fieldnum(VendPackingSlipJour, Deliverydate)).value(SysQuery::range(_fromDate,_toDate));
    //}
    qbdsTrans  = qbdsJour.addDataSource(tablenum(VendPackingSlipTrans));
    qbdsTrans.joinMode(JoinMode::InnerJoin);
    qbdsTrans.relations(true);

    qbdsTransOrgin = qbdsTrans.addDataSource(tablenum(inventTransOrigin));
    qbdsTransOrgin.joinMode(JoinMode::InnerJoin);
    qbdsTransOrgin.relations(true);
    qbdsTransOrgin.addLink(fieldnum(VendPackingSlipTrans, InventTransId), fieldnum(inventTransOrigin, InventTransId));

    qbdsinventTrans = qbdsTransOrgin.addDataSource(tablenum(inventTrans));
    qbdsinventTrans.joinMode(JoinMode::InnerJoin);
    qbdsinventTrans.relations(false);
    qbdsinventTrans.addLink(fieldnum(inventTrans, InventTransOrigin), fieldnum(inventTransOrigin, RecId));

    //if(ItemId)
    //{
        //qbdsinventTrans.addRange(fieldnum(inventTrans, itemID)).value(ItemID);
    //}


    qr = new QueryRun(query);
    qr.prompt();

    while (qr.next())
    {
        packingTrans= qr.get(tableNum(VendPackingSlipTrans));
        packingJour =qr.get(tablenum(VendPackingSlipJour));
        inventTransOrigin= qr.get(tableNum(InventtransOrigin));
        inventTrans =qr.get(tablenum(Inventtrans));
        info(strFmt("%1,%2,%3,%4",packingJour.PurchId,packingJour.DeliveryDate,packingTrans.ItemId,inventTransOrigin.InventTransId));
    }

    //while select * from packingTrans
        //join packingJour where packingJour.RecId == packingTrans.VendPackingSlipJour
        //&& packingJour.PurchId == "000253 "
        //join inventTransOrigin where inventTransOrigin.InventTransId == packingTrans.InventTransId
    //{
        //inventTrans = inventTrans::findByInventTransOrigin(inventTransOrigin.RecId);
        //info(strFmt("%1 - %2 ",packingJour.PurchId,packingTrans.ItemId));
    //}

}

DP Logic Example

///
/// Processes the report business logic.
///
///
/// Provides the ability to write the report business logic. This method will be called by
/// SSRS at runtime. The method should compute data and populate the data tables that will be
/// returned to SSRS.
///
[SysEntryPointAttribute(false)]
public void processReport()
{
    CommercialEvaluationContract commercialEvaluationContract;

    PurchRFQTable   rfqTable;
    PurchRFQLine    rfqLine;
    PurchRFQReplyTable  rfqReplyTable;
    PurchRFQReplyLine   rfqReplyLine;
    PurchRFQCaseId purchRFQCaseId;
    ;

    commercialEvaluationContract = this.parmDataContract() as CommercialEvaluationContract;

    purchRFQCaseId = CommercialEvaluationContract.parmPurchRFQCaseId();

    while select rfqTable where rfqTable.RFQCaseId == purchRFQCaseId
              join rfqLine
              where rfqLine.RFQId == rfqTable.RFQId
    {
        while select rfqReplyLine where rfqReplyLine.RFQLineRecId == rfqLine.RecId
        {


            rfqCommericalEvaluationTemp.Description         =  rfqLine.ItemName;
            rfqCommericalEvaluationTemp.Qty                 =  rfqLine.QtyOrdered;
            rfqCommericalEvaluationTemp.UnitOfMeasureSymbol =  rfqLine.PurchUnit;

            rfqCommericalEvaluationTemp.VendName            =  rfqTable.VendAccount;

            rfqCommericalEvaluationTemp.Vendor_Description =  rfqReplyLine.Name;
            rfqCommericalEvaluationTemp.Vendor_Qty         =  rfqReplyLine.QtyOrdered;
            rfqCommericalEvaluationTemp.ScopeOf             = "SCOPE OF WORK as per attached Demag offer (95032463 dated 19/09/2013)";
            rfqCommericalEvaluationTemp.insert();

         }

    }
}

// Item Transaction Dp


[SysEntryPointAttribute(false)]
public void processReport()
{
    ItemTransactionsContract  ItemTransactionsContract;
    InventTable inventtable;
    InventTrans inventTrans;
    ItemId itemid;
    CompanyImage    image;
    CompanyInfo     CompanyInfo=CompanyInfo::find();
    ;

    ItemTransactionsContract = this.parmDataContract() as ItemTransactionsContract;
    itemid = ItemTransactionsContract.parmItemid();

    while select inventtable where inventtable.ItemId == itemid
        //join inventTrans where inventTrans.ItemId == inventtable.itemid
    {

        select inventTrans where inventTrans.ItemId == inventtable.itemid;
        if(inventTrans)
        {
            ItemTransactionsTmp.ItemId = inventtable.ItemId;
            ItemTransactionsTmp.ItemName = inventtable.itemName();
            ItemTransactionsTmp.createdByy = inventtable.createdBy;
            //ItemTransactionsTmp.CreatedDt = inventtable.createdDateTime;
            ItemTransactionsTmp.CreatedDtTime = inventtable.createdDateTime;
            ItemTransactionsTmp.CompanyLogo =   FormLetter::companyLogo();
            ItemTransactionsTmp.insert();
        }
    }

}


Create General Ledger JournalPost through X++

//Create General Ledger JournalPost

static void CreateGLJournalPost(Args _args)
{
    AxLedgerJournalTable journalTable; // class
    AxLedgerJournalTrans journalTrans; // class

    container acctPattern;
    container offSetAcctPattern;

    MainAccountNum                      mainAccount;
    MainAccountNum                      OffmainAccount ;

    LedgerJournalTable ledgerJournalTable; // table
    ledgerJournalCheckPost ledgerJournalCheckPost;// table

    LedgerAccountContract               ledgerAccountContract,OffledgerAccountContract;     //ModifiedBy
    str                                 costcenter,department,assetcode,customer,description;
    DimensionAttributeValueContract     attributeValueContract;
    DimensionStorage                    DimensionStorage;

    Amount                              amountCurDebit,amountCurCredit;

    mainAccount = "110110"; //IntegPostingProf.RentalRevenue;//
    OffmainAccount  =  "USA OPER"; //401100 IntegPostingProf.Revenue;



    /*costcenter = dimensionMappingRg.DimValue;//  Creating dimension for OffsetAcc
    department = dimensionMappingBr.DimValue;
    assetcode  = RentalRevenueStagingTable.AssetCode;
    customer   = RentalRevenueStagingTable.AccountNum;//
    ;
    */


    journalTable = new AxLedgerJournalTable();
    journalTrans = new AxLedgerJournalTrans();





    //Journal Name


    journalTable.parmJournalName("GenJrn");
    journalTable.save();


    journalTrans.parmJournalNum(journalTable.ledgerJournalTable().JournalNum);
    journalTrans.parmTransDate(systemDateGet());
    journalTrans.parmCurrencyCode("USD");
    journalTrans.parmAmountCurDebit(1200);
    journalTrans.parmAccountType(LedgerJournalACType::Vend);
   


   

                    journalTrans.parmJournalNum(journalTable.ledgerJournalTable().JournalNum);//

                      //AccountNum
                    ledgerAccountContract = new LedgerAccountContract();
                    ledgerAccountContract.parmValues(new List(Types::Class));


                    ledgerAccountContract.parmMainAccount(mainAccount);
                    if (department)
                    {
                        attributeValueContract = new DimensionAttributeValueContract();
                        attributeValueContract.parmName("@SYS850");
                        attributeValueContract.parmValue(department);

                        ledgerAccountContract.parmValues().addEnd(attributeValueContract);
                    }
                    if (costcenter)
                    {
                        attributeValueContract = new DimensionAttributeValueContract();
                        attributeValueContract.parmName("@SYS343410");
                        attributeValueContract.parmValue(costcenter);

                        ledgerAccountContract.parmValues().addEnd(attributeValueContract);
                    }
                    if (assetcode)
                    {
                        attributeValueContract = new DimensionAttributeValueContract();
                        attributeValueContract.parmName("@SYS343374");
                        attributeValueContract.parmValue(assetcode);

                        ledgerAccountContract.parmValues().addEnd(attributeValueContract);
                    }
                    if (customer)
                    {
                        attributeValueContract = new DimensionAttributeValueContract();
                        attributeValueContract.parmName("Customer");
                        attributeValueContract.parmValue(customer);

                        ledgerAccountContract.parmValues().addEnd(attributeValueContract);
                    }

                    dimensionStorage = DimensionServiceProvider::buildDimensionStorageForLedgerAccount(ledgerAccountContract);//

                    journalTrans.parmLedgerDimension(dimensionStorage.save());
                    //-------------------------------------



                    //OffsetAccount
                    OffledgerAccountContract = new LedgerAccountContract();
                    OffledgerAccountContract.parmValues(new List(Types::Class));


                    OffledgerAccountContract.parmMainAccount(OffmainAccount);

                    if (department)
                    {
                        attributeValueContract = new DimensionAttributeValueContract();
                        attributeValueContract.parmName("@SYS850");
                        attributeValueContract.parmValue(department);

                        OffledgerAccountContract.parmValues().addEnd(attributeValueContract);
                    }
                    if (costcenter)
                    {
                        attributeValueContract = new DimensionAttributeValueContract();
                        attributeValueContract.parmName("@SYS343410");
                        attributeValueContract.parmValue(costcenter);

                        OffledgerAccountContract.parmValues().addEnd(attributeValueContract);
                    }
                    if (assetcode)
                    {
                        attributeValueContract = new DimensionAttributeValueContract();
                        attributeValueContract.parmName("@SYS343374");
                        attributeValueContract.parmValue(assetcode);

                        OffledgerAccountContract.parmValues().addEnd(attributeValueContract);
                    }
                    if (customer)
                    {
                        attributeValueContract = new DimensionAttributeValueContract();
                        attributeValueContract.parmName("Customer");
                        attributeValueContract.parmValue(customer);

                        OffledgerAccountContract.parmValues().addEnd(attributeValueContract);
                    }

                    //dimensionStorage = DimensionServiceProvider::(OffledgerAccountContract);
                    journalTrans.parmOffsetAccountType(LedgerJournalACType::Bank);
                    journalTrans.parmOffsetLedgerDimension(dimensionStorage.save());

                     journalTrans.save();


    /*
    journalTrans.parmOffsetAccountType(LedgerJournalACType:: Ledger );
    //journalTrans.parmOffsetLedgerDimension( = "401100";
    offSetAcctPattern = ["401100-Disp","401100", 0];//,"BusinessUnit", "10", "Department","800","CostCenter", "07","CustomerGroup","10" ];
    journalTrans.parmOffsetLedgerDimension(AxdDimensionUtil::getLedgerAccountId(offSetAcctPattern));

    journalTrans.save(); */

    info(strFmt("Journal %1 created", journalTable.ledgerJournalTable().JournalNum));
    /*ledgerJournalCheckPost = ledgerJournalCheckPost::newLedgerJournalTable(journalTable.ledgerJournalTable(),NoYes::Yes);
    ledgerJournalCheckPost.run();
    info(strFmt("Journal No. %1.", journalTable.ledgerJournalTable().JournalNum)); */
}

Convert Call stack to readable format in D365FO X++

//Input --container _xppCallStack = xSession::xppCallStack();  Public static str POL_formatXppCallStack(container _xppCallStack, int _skipFr...