Sunday, July 3, 2016

Open Debugger in x++

static void main(Args args)
{
    str filePath;
    str cmdLine;
    int pos;
    ;
    filePath = xInfo::componentName();
    pos = strfind(filePath, '\\', strlen(filePath), -strlen(filePath));
    if (pos < 0)
    {
        return;
    }
    filePath  = substr(filePath, 1, pos);
    filePath += 'axdebug.exe';
    cmdLine   = ' "-debugee=axapta"';
    if (!WinAPI::fileExists(filePath))
    {
        error("@SYS70498");
    }
    else if (!WinAPI::shellExecute(filePath, cmdLine))
    {
        error("@SYS70499");
    }
}

To join Table InventDim ExistsJoin Ax 2012 Macro

// To join Table InventDim ExistsJoin Ax 2012

#inventDimExistsjoin(InventDimId(Field),InventDim(Table Buffer),InventDim(Table Buffer),InventDimParm(set flag for Dim Parm);

#inventDimSelect(InventDim,InventDim,inventDimParm,forcePlaceholders tableId(InventDim) from,serialIdIdx(index Name))

On Hand Opening Qty for item wise and dimension Wise by date

Onhand Opening Qty
// Opening Qty for item wise and dimension Wise

enable flag in InventDimParm

Class -->InventSumFinancial
Class--> InventSettlement

static void Fcc_OnhandOpenQTyTest(Args _args)
{
    InventDim           inventDimSum;
    InventDimParm       inventDimParm;
    InventSum           inventSum;
    InventSumFinancial  inventSumFinancial;
    TransDate           Start = mkDate(1,1,2016);
    Qty                 balanceQty;
    Amount              totalBal;
    Amount              amount;
    ;
   
    inventDimParm.ItemIdFlag            = NoYes::Yes;
    inventDimParm.InventLocationIdFlag  = NoYes::Yes;
    inventDimParm.InventSiteIdFlag  = NoYes::Yes;
    while select inventSum
            where inventSum.ItemId == "CW-AR-PCB-4CX25MM"
    {
        inventDimSum = inventSum.inventDim();
        inventSumFinancial                  = InventSumFinancial::newSumReport(Start-1, inventSum, inventDimSum, inventDimParm);
        balanceQty                          = inventSumFinancial.qty(); // on hand Physical Qty
        totalBal                            = inventSumFinancial.value(); // On Hand Financial COst Amount Posted
        amount = InventSettlement::dateCostAmountAdjustment(Start -1 ,inventSum.ItemId,inventDimSum,inventDimParm); // Cost Amount Adjustment
        info(strFmt("%1,%2,  %3,%4,%5",inventSum.ItemId,balanceQty,totalBal,inventSum.costPricePcs(),amount));
    }
}
Write into the System Event Viewer from Dynamics AX

Source Link :

https://chaituax.wordpress.com/2014/04/09/write-into-the-system-event-viewer-from-dynamics-ax/


static void writeEventLogEntry(Args _args)
{
    System.Diagnostics.EventLog eventlog;
#Define.LogSource(“Dynamics AX”)
  #Define.LogName(“Application”)    ;
// check if the log already exists
 if(!System.Diagnostics.EventLog::SourceExists(#LogSource))
{
// create new log        System.Diagnostics.EventLog::CreateEventSource(#LogSource, #LogName);
}
 eventlog = new System.Diagnostics.EventLog();    eventlog.set_Source(#LogSource);
// write info entry    eventlog.WriteEntry(“<Info>: Just writing in the event viewer.”);
// write error entry    eventlog.WriteEntry(“<Error>: Please check the stack trace below. \n\n” +    con2str(xSession::xppCallStack()), System.Diagnostics.EventLogEntryType::Error);
// write warning entry    eventlog.WriteEntry(“Job finished.” , System.Diagnostics.EventLogEntryType::Warning);
}

static void WriteEventLog(Exception _exception, str _event)
 {
 str eventSource = “AX event”;
 str logType = “Application”;
 System.Diagnostics.EventLogEntryType eventLogEntryType;
 int eventCategory = 9999;
 ;
switch(_exception)
 {
 case Exception::Info:
 eventLogEntryType = System.Diagnostics.EventLogEntryType::Information;
 break;
 case Exception::Warning:
 eventLogEntryType = System.Diagnostics.EventLogEntryType::Warning;
 break;
default:
eventLogEntryType = System.Diagnostics.EventLogEntryType::Error;
 }
 if (!System.Diagnostics.EventLog::Exists(eventSource))
 {
 System.Diagnostics.EventLog::CreateEventSource(eventSource, logType);
 }
        System.Diagnostics.EventLog::WriteEntry(eventSource, _event, eventLogEntryType, eventCategory);
 }





static void EventViewer(Args _args)
{
     System.Diagnostics.EventLog eventlog;
     #Define.LogSource("Dynamics AX")
     #Define.LogName("Dynamics AX Log")
    
     ;
     // check if the log already exists
     if(!System.Diagnostics.EventLog::SourceExists(#LogSource))
     {
         // create new log
         System.Diagnostics.EventLog::CreateEventSource(#LogSource, #LogName);
     }
     eventlog = new System.Diagnostics.EventLog();
     eventlog.set_Source(#LogSource);
     // write info entry
     eventlog.WriteEntry("Just writing in the event viewer.");
     // write error entry
     eventlog.WriteEntry("Error! Please check the stack trace below. \n\n" +
         con2str(xSession::xppCallStack()), System.Diagnostics.EventLogEntryType::Error);
     // write warning entry
     eventlog.WriteEntry("Job finished." , System.Diagnostics.EventLogEntryType::Warning);
    
     info("Check the event viewer!");
}

Number Generation by EDT's reference without Parameter Number Sequence Reference

Number Sequence

Number Generation by EDT's reference without Parameter Number Sequence Reference

static void testnumseq(Args _args)
{
     theaxaptaEDT   _theaxaptaEDT   ;
     ExtendedTypeId id = TypeID2ExtendedTypeId(TypeId(theaxaptaEDT));//EDT NAME
     NumberSeq num = NumberSeq::newGetNum(NumberSequenceReference::find(id));
     ;
     //_theaxaptaEDT.NextNumseq = num.num();//NEXT NUM SEQ
     num.used(); // mark the number as used
     info(num.num()); // NEXT NUM SEQ
}
NumberSeq  num;
num = NumberSeq::newGetNumFromCode('SAO-Y');
info(num.num());

Sunday, March 6, 2016

Delete AOT Object via Code X++

// Delete AOT Object via Code X++

//Sample 1
tatic void TestJob_San(Args _args)
{
    #AOT
    TreeNode treeNode;
    TreeNode treeNodeTable; ;
    treeNode = TreeNode::findNode(#JobsPath);
    treeNodeTable = treeNode.AOTfindChild('Job1');
    treeNodeTable.AOTdelete();
}

//Sample 2
static void DeleteTables(Args _args)
{
    TreeNode tree1, tree2;
    ;
    tree1 = TreeNode::findNode("Data Dictionary\\Tables");
    if (tree1 != null)
    {
        tree2 = tree1.AOTfindChild("tablename");
        if (tree2 != null)
        {
            tree2.AOTdelete();
        }
    }
}

//Sample 3
static void Job1(Args _args)
{
    UtilIdElements utilElement;
    ;
    ttsbegin;
    select utilElement
        where utilElement.name == 'myElementName'
        && utilElement.utilLevel == utilEntryLevel::cus // any layer
        && utilElement.recordType == utilElementType::Table; // object type
    if (utilelement)
    {
        utilElement.delete();
        ttscommit;
        info('Record should be deleted now.');
    }
    else
    {
        ttsAbort;
        info('Could not delete record, or it was not found.');
    }
}

Dimension Create Default Dimension

DimensionAttributeValueSetStorage valueSetStorage = new DimensionAttributeValueSetStorage();
    DimensionDefault result;
    int i;
    DimensionAttribute dimensionAttribute;
    DimensionAttributeValue dimensionAttributeValue;
    container conAttr = ["BusinessUnit","Department" ,"Project"];
    container conValue;
    str dimValue;
conValue = ["", "", reqLine.ProjId];
            dimValue = "";
            i = 0;
            for (i = 1; i <= conLen(conAttr); i++)
            {
                dimensionAttribute = dimensionAttribute::findByName(conPeek(conAttr,i));
                if (dimensionAttribute.RecId == 0)
                {
                    continue;
                }
                dimValue = conPeek(conValue,i);
                if (dimValue != "")
                {
                    dimensionAttributeValue =
                    dimensionAttributeValue::findByDimensionAttributeAndValue(dimensionAttribute,dimValue,false,true);
                    valueSetStorage.addItem(dimensionAttributeValue);
                }
            }
            result = valueSetStorage.save();

SQL ODBC Connection to another DB

//SQL ODBC Connection to another DB
static void SQLODBCConnection(Args _args)
{
    OdbcConnection con;
    SqlSystem       sq;
    LoginProperty   loginProperty;
    Statement statement1;
    ResultSet myResult1;
    str sqlStmnt;
    SqlStatementExecutePermission perm;
    sq = new SqlSystem();
    loginProperty = new LoginProperty();
    loginProperty.setServer("AOSSERVER");
    loginProperty.setDatabase("MicrosoftDynamicsAX");
    con = new OdbcConnection(loginProperty);
    sqlStmnt = strFmt("select * from Fcc_BankChequeMenus"); //write your query here
    statement1 = con.createStatement();
    perm = new SqlStatementExecutePermission(sqlStmnt);
    perm.assert();
    myResult1  = statement1.executeQuery(sqlStmnt);
    while(myResult1.next())
    {
        info(myResult1.getString(4));
        info(myResult1.getString(5));
        info(myResult1.getString(6));
        info(myResult1.getString(7));
    }
}

Fact Box visiblity in Form Ax 2012 X++

//Fact Box visiblity in Form Ax 2012 X++
PartList       partListFactBox  = new PartList(element);
 FormRun     formRunFactBox;
 int                i;
 for (i = 1; i <= partListFactBox.partCount(); i++)
 {
       formRunFactBox = partListFactBox.getPartById(i);
       formRunFactBox.design().visible(false);
 }

Wednesday, February 10, 2016

Issue with Intercompany GL journal Validation of Rounding off Amount... rounding Differ

// Issue with Intercompany Validation of Rounding off Amount
Class --> LedgerVoucherTransObject
Replace Method


private boolean checkRounding(LedgerPostingMessageLog _ledgerPostingMessageCollection)
{
    AmountMST roundedAmount,beforeRound;
    CurrencyCode accountingCurrency;
    accountingCurrency = CompanyInfo::standardCurrency();
    beforeRound = generalJournalAccountEntry.AccountingCurrencyAmount;
    if(Currency::find(accountingCurrency).RoundingPrecision >= 0.010
        && Currency::find(accountingCurrency).RoundingPrecision <= 0.090)
    {
        generalJournalAccountEntry.AccountingCurrencyAmount = decRound(generalJournalAccountEntry.AccountingCurrencyAmount,2);
    }
    else if(Currency::find(accountingCurrency).RoundingPrecision >= 0.001)
    {
        generalJournalAccountEntry.AccountingCurrencyAmount = decRound(generalJournalAccountEntry.AccountingCurrencyAmount,3);
    }
    else if(Currency::find(accountingCurrency).RoundingPrecision >= 0.100)
    {
        generalJournalAccountEntry.AccountingCurrencyAmount = decRound(generalJournalAccountEntry.AccountingCurrencyAmount,1);
    }
    roundedAmount = CurrencyExchangeHelper::round(generalJournalAccountEntry.AccountingCurrencyAmount, accountingCurrency);
    if (generalJournalAccountEntry.AccountingCurrencyAmount != roundedAmount)
    {
        error(strFmt(
            "@SYS27168",
            accountingCurrency,
            Currency::roundingPrecisionAdjusted(accountingCurrency)));
            //the message includes "penny rounding threshhold" which seems wrong
            //The unit of %1 %2 being posted to account %3 is outside the current penny rounding threshold.
        return _ledgerPostingMessageCollection.logCheckFailed(strFmt(
            "@SYS18429",
            num2str(generalJournalAccountEntry.AccountingCurrencyAmount, 0, 16, -1, -1),
            accountingCurrency,
            DimensionAttributeValueCombination::getDisplayValue(generalJournalAccountEntry.LedgerDimension)));
    }
    generalJournalAccountEntry.AccountingCurrencyAmount = beforeRound;
    beforeRound = 0;
    if (generalJournalAccountEntry.TransactionCurrencyCode != ''
            && generalJournalAccountEntry.TransactionCurrencyCode == accountingCurrency)
    {
        roundedAmount =
            CurrencyExchangeHelper::round(generalJournalAccountEntry.TransactionCurrencyAmount, generalJournalAccountEntry.TransactionCurrencyCode);
        if (generalJournalAccountEntry.TransactionCurrencyAmount != roundedAmount)
        {
            error(strFmt(
                "@SYS27168",
                generalJournalAccountEntry.TransactionCurrencyCode,
                Currency::roundingPrecisionAdjusted(generalJournalAccountEntry.TransactionCurrencyCode)));
            return _ledgerPostingMessageCollection.logCheckFailed(strFmt(
                "@SYS18429",
                num2str(generalJournalAccountEntry.TransactionCurrencyAmount, 0, 16, -1, -1),
                generalJournalAccountEntry.TransactionCurrencyCode,
                DimensionAttributeValueCombination::getDisplayValue(generalJournalAccountEntry.LedgerDimension)));
        }
    }
    else if (generalJournalAccountEntry.TransactionCurrencyCode != ''
            && generalJournalAccountEntry.TransactionCurrencyCode != accountingCurrency)
    {
         beforeRound = generalJournalAccountEntry.TransactionCurrencyAmount;
        if(Currency::find(accountingCurrency).RoundingPrecision >= 0.010
            && Currency::find(accountingCurrency).RoundingPrecision <= 0.090)
        {
            generalJournalAccountEntry.TransactionCurrencyAmount = decRound(generalJournalAccountEntry.TransactionCurrencyAmount,2);
        }
        else if(Currency::find(accountingCurrency).RoundingPrecision >= 0.001)
        {
            generalJournalAccountEntry.TransactionCurrencyAmount = decRound(generalJournalAccountEntry.TransactionCurrencyAmount,3);
        }
        else if(Currency::find(accountingCurrency).RoundingPrecision >= 0.100)
        {
            generalJournalAccountEntry.TransactionCurrencyAmount = decRound(generalJournalAccountEntry.TransactionCurrencyAmount,1);
        }
       roundedAmount =
            CurrencyExchangeHelper::round(generalJournalAccountEntry.TransactionCurrencyAmount, accountingCurrency);
        if (generalJournalAccountEntry.TransactionCurrencyAmount != roundedAmount)
        {
            error(strFmt(
                "@SYS27168",
                accountingCurrency,
                Currency::roundingPrecisionAdjusted(accountingCurrency)));
            return _ledgerPostingMessageCollection.logCheckFailed(strFmt(
                "@SYS18429",
                num2str(generalJournalAccountEntry.TransactionCurrencyAmount, 0, 16, -1, -1),
                accountingCurrency,
                DimensionAttributeValueCombination::getDisplayValue(generalJournalAccountEntry.LedgerDimension)));
        }
        generalJournalAccountEntry.TransactionCurrencyAmount = beforeRound;
        beforeRound = 0;
    }
    return true;
}

Skip Inventory reservation on Sales order lines in D365FO

[ExtensionOf(classStr(InventUpd_Reservation))] final class InventUpd_ReservationCls_SAN_Extension {     void updateNow()     {         if(mo...