Interview Questions

Sunday, March 30, 2014

Create Find method for any table, automatically by Code.

//In the Xpp Source Class add this methods :
//1 method => Add this Code

Source findMethod(TableName _tableName, boolean _useReplacementKey = false)
{
    DictTable dictTable = new DictTable(tableName2id(_tableName));
    DictIndex dictIndex = new DictIndex(tableName2id(_tableName),
        (_useReplacementKey && dictTable.replacementKey() != 0) ? dictTable.replacementKey() : dictTable.primaryIndex());
    DictField dictField;
    int fieldIndex;

    if (dictIndex == null)
        throw error(strFmt("Couldn't find primary index for table %1", _tableName));

    // method signature returning the table
    source += strFmt('public static %1 find(', _tableName);

    // add the primary key fields as the parameters to the find method
    for (fieldIndex=1; fieldIndex<=dictIndex.numberOfFields(); fieldIndex++)
    {
        dictField = new DictField(dictTable.id(), dictIndex.field(fieldIndex));
        source += strFmt('%1 _%2, ', extendedTypeId2name(dictField.typeId()), dictField.name());
    }
    source += strFmt('boolean _update = false)\n');

    indentLevel = 0;
    this.beginBlock();

    // Declare the table
    source += this.indent() + strFmt('%1 %1;\n', _tableName);
    source += '\n';

    // Set update yes/no
    source += this.indent() + strFmt('%1.selectForUpdate(_update);\n', _tableName);

    // select firstonly
    source += this.indent() + strFmt('select firstOnly %1 where', _tableName);
    // add the primary key fields in the where clause
    for (fieldIndex=1; fieldIndex<=dictIndex.numberOfFields(); fieldIndex++)
    {
        dictField = new DictField(dictTable.id(), dictIndex.field(fieldIndex));
        source += '\n';
        source += this.indent() + strFmt('    %1%2.%3 == _%3', ((fieldIndex>1) ? '&& ' : ''), _tableName, dictField.name());
    }
    source += ';\n';

    source += '\n';

    // return the buffer
    source += this.indent() + strFmt('return %1;\n', _tableName);

    this.endBlock();

    return source;
}

//Now paste this method in Editor Script Class

public void template_method_find(Editor editor)
{
    xppSource       xppSource = new xppSource();
    Source          template;
    str             path = editor.path();
    TreeNode        treeNode = path ? TreeNode::findNode(path) : null;
    TableName       tableName;
    #TreeNodeSysNodeType

    if (treeNode)
    {
        treeNode = treeNode.AOTparent();
        if (treeNode && treeNode.treeNodeType().id() == #NT_MEMBERFUNCLIST)
        {
            treeNode = treeNode.AOTparent();
            if (treeNode && treeNode.treeNodeType().id() == #NT_DBTABLE)
            {
                tableName = treeNode.treeNodeName();
            }
        }
    }

    if (!tableName)
    {
        warning("Find method applies to tables only");
        return;
    }

    template = xppSource.findMethod(tableName);

    editor.insertLines(template);
}
//Now test this code for any table. It will create 1 Find Method on the basis of Recid.

Wednesday, March 26, 2014

Find Date in AX 2009

static void WhatsTheDate(Args _args)
{  ;
   info(date2str(today(),123,2,2,2,2,4));
   info(date2str(systemdateget(),123,2,2,2,2,4));
   info(date2str(DateTimeUtil::date(DateTimeUtil::getSystemDateTime()),123,2,2,2,2,4));
   info(date2str(DateTimeUtil::date(DateTimeUtil::applyTimeZoneOffset(DateTimeUtil::getSystemDateTime(), DateTimeUtil::getUserPreferredTimeZone())),123,2,2,2,2,4));
}

Print All type of Taxes applied on any Purchase Order

static void JobX(Args _args)
{
    TaxOnItem                       TaxOnItem;
    TaxGroupData                    TaxGroupData, TaxGroupData_1;
    real                            tax1,  _TaxAmountloc = 0;
    TaxValue                        TaxValue = 0, TaxValue_1 = 0;
    purchline                      purchline;
    TaxCode                         TaxCode;
    real                           TaxAmountloc

    ;
    select purchline where purchline.PurchId == "Enter Purch ID";
     tax1 = Tax::calcTaxAmount(purchline.TaxGroup, purchline.TaxItemGroup, Systemdateget(), purchline.CurrencyCode, purchline.LineAmount, TaxModuleType::Purch);
    if(purchline.TaxItemGroup && purchline.TaxGroup && purchline.LineAmount != 0)
    {
        while select TaxOnItem where TaxOnItem.TaxItemGroup == purchline.TaxItemGroup
             {
              if(TaxOnItem)
              {
                 while select TaxGroupData  where TaxGroupData.TaxGroup == purchline.TaxGroup
                                                    && TaxGroupData.TaxCode  == TaxOnItem.TaxCode
                       {
                           if(TaxGroupData)
                           {
                                TaxCode   = TaxGroupData.TaxCode;
                                TaxValue  =  TaxData::find(TaxOnItem.TaxCode, Systemdateget(), 0).TaxValue;
                                TaxValue_1  += TaxValue;
                                TaxAmountloc = (purchline.LineAmount * TaxValue)/100;                            
                                 info(strfmt("%1,%2", TaxValue, TaxCode));
                           }
                       }
              }
              }
               info(strfmt("%1", TaxValue));

   }
}

Restrict Numbers in any String

static void JobX(Args _args)
{
boolean ret;
#define.alphabets('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
str     Str1;    //Declare your Field here
;
Str1 = "efrt0211"; // Define the case here
if((strkeep(substr(Str1, 1, strlen(Str1)), #alphabets)  != substr(Str1, 1, strlen(Str1))))
{
ret = checkFailed("You cannot enter other than alphabets");
}
else
{
info (strfmt("%1",str1));
}
}

Find Purchase Order in which items have specific Dimension Group ID

static void X(Args _args)
{
    PurchTable   _purchTable,tableloc;
    PurchLine    _purchLine;
    InventDim    _inventDim;
    InventTable  _inventTable;
    ;
    While select  tableloc // where tableloc.PurchId =='Enter Purch ID'
    while select  _purchLine  where _purchLine.PurchId == tableloc.PurchId
        {
                 if(InventTable::find(_purchLine.ItemId).DimGroupId == 'SWL')
                       {
                                  info (strfmt("%1, %2", _purchLine.PurchId,_purchLine.ItemId));
                       }
        }
}

Delete record from PurchTable and PurchLine for specific record

static void JobX(Args _args)
{
    purchtable  table;
    purchline   line;
    ;
    select table where table.PurchId == '000623';
    {
        select line where line.PurchId == table.PurchId;
        {
            line.doDelete();
            table.doDelete();
            info(strfmt("%1,%2",line.PurchId));
        }
    }
}

Find ItemName on the basis of Item ID

static void JobX(Args _args)
{
    InventTable inventTable;
    InventSum   inventSum;
    ;
    Select itemName from inventTable where inventTable.ItemId=='00000';
    info(strfmt("%1", inventTable.ItemName));
}

Find Minimum On Hand Values (Another Way)

static void JobX(Args _args)
{
    InventTable     inventloc;
    ReqItemTable     reqItemTable;
    InventQtyMinOnhand   minOnhand;
    InventSum     InventSum;
    ;
    select reqItemTable  where  reqItemTable.ItemId  == InventSum.ItemId
                                    && reqItemTable.CovInventDimId ==  '00002607_089';
    {
        minOnhand =  reqItemTable.MinInventOnhand;
    }

    info(strfmt("%1", minOnhand));

}

Find MinOnHand Values in AX 2009

static void JobX(Args _args)
{
        InventTable         inventTable;
        ReqItemTable        reqItemTable;
        ;
        select MinInventOnhand from reqItemTable join inventtable where reqItemTable.itemid == inventTable.itemid && reqItemTable.ItemId == '00000' ;
       // return reqItemTable.MinInventOnhand;
        info(strfmt("%1",reqItemTable.MinInventOnhand));
}

Database synchronization Forcefully by code

static void forceDbSynchronize(Args _args)
{
    Dictionary              dict;
    int                     idx, lastIdx, totalTables;
    TableId                 tableId;
    Application             application;
    SysOperationProgress    progress;
    StackBase               errorStack;
    ErrorTxt                errorTxt;
    ;

    application = new Application();
    dict = new Dictionary();
    totalTables = dict.tableCnt();
    progress = new SysOperationProgress();
    progress.setTotal(totalTables);
    progress.setCaption("@SYS90206");
    errorStack = new StackBase(Types::String);

    lastIdx = 0;
    try
    {
        for (idx = lastIdx+1; idx <= totalTables; idx++)
        {
            tableId = dict.tableCnt2Id(idx);
            progress.setText(dict.tableName(tableId));

            lastIdx = idx;
            application.dbSynchronize(tableId, false, true, false);
            progress.incCount();
        }
    }
    catch (Exception::Error)
    {
        errorTxt = strFmt("Error in table '%1' (%2)", tableId, dict.tableName(tableId));
        errorStack.push(errorTxt);
        retry;
    }

    setPrefix("@SYS86407");
    errorTxt = errorStack.pop();
    while (errorTxt)
    {
        error(errorTxt);
        errorTxt = errorStack.pop();
    }
}

How to create Sales Order with sales Line by code

static void createSalesOrder(Args _args)
{
    AxSalesLine axSalesLine = new axSalesLine();
    AxSalesTable axsalesTable = new axSalesTable();
    SalesId salesId;
    ;

    salesId = axsalesTable.parmSalesId();///Creates sales Id
    axsalesTable.parmCustAccount('1601');
    axsalesTable.save();

    axSalesLine.parmSalesId(axsalesTable.parmSalesId());//assigns sales Id
    axSalesLine.parmItemId('PolyEthylene');// Item Id
    axSalesLine.axInventDim().parmInventSiteId("Unit1");//Site
    axSalesLine.axInventDim().parmInventLocationId("RM");//Warehouse


    axSalesLine.parmSalesQty(1000);//Quantity
    axSalesline.parmSalesPrice(20);//Sales Price per one quantity
    axSalesLine.save();
}

Copy One Field values into Another Field

static void CopyOneFieldToAnotherField(Args _args)

{
    TableA  t1;
    ;
    ttsbegin;
    while select forupdate t1 where t1.Num == t1.num
    {
         t1.SerialNumberFormat = t1.num;
         t1.Num = "";
         t1.update();
    }
    ttscommit;
}

Activate configuration Dimension in Item Master

static void ActivateDimension(Args _args)
{
    InventDimSetup  InventDimSetup;
    ;
    ttsbegin;
    select forupdate InventDimSetup where  InventDimSetup.RecId == (Enter Rec ID of particular line which you want to activate)
                                       && InventDimSetup.dimGroupId == 'scsw';
     {
        info (strfmt("%1,%2", InventDimSetup.Active,InventDimSetup.RecId));
        InventDimSetup.Active = Noyes::Yes;
        InventDimSetup.Update();
        info (strfmt("%1,%2", InventDimSetup.Active,InventDimSetup.RecId));
    }
    ttscommit;
}

Compare two fields value and print a message

static void absExample(Args _args)
{
    real r1;
    real r2;
    ;

    r1 = abs(3.14);
    r2 = abs(3.14);
    if (r1 == r2)
    {
        print "abs of values are the same";
        pause;
    }
}

Create Number Sequence for a new Module in AX 2012

Steps for creating number sequence for New Module: By Gulshan Kumar Gupta
*********************************************************************************
1- First of all, create a "Parameter" table in "Table" node of AOT (Like – “OfcAdminParameters”).

2- Create "Key" field in that table.

3- Create "Index" for "Key" field.

4- Create several methods in "Methods" node of "Parameter" table in AOT. (Like - Delete, Update, exist, and Find,  NumberSeqModule)
***********************************************************************************************    
Methods –

Delete =>
Void delete ()
{
    Throw error ("@SYS23721");
}

Update =>
Void update ()
{
    Super ();
    //just write flush Parameter table name
    Flush OfcAdminParameters;
}


Exist =>
Static Boolean exist ()
{
    Return (select firstonly RecId from OfcAdminParameters).RecId != 0;
}

Find=>
//AOSRunMode::CalledFrom
Static OfcAdminParameters find (Boolean _forupdate = false)
{
    OfcAdminParameters parameter;

    parameter.selectForUpdate(_forupdate);

    Select firstonly parameter
        Index Key
        Where parameter.Key == 0;

    If (!parameter && !parameter.isTmp())
    {
        Company::createParameter(parameter);
    }

    Return parameter;
}

NumberSeqModule=>
Static client server NumberSeqModule numberSeqModule ()
{
    Return NumberSeqModule::OfcMgmt;
}

// If you want to create another module then -
5- Now, add an element to "NumberSeqModule" base eNum.

*********************************************************************************
6- Create a new Number Sequence Class Named "NumberSeqModuleModuleName"

7- Add a method "NumberSeqModule" to that class.

Method’s for NumberSeqModuleModuleName class –
Class Declaration =>
public class NumberSeqModuleOfficeManagement extends NumberSeqApplicationModule
{

}

Number SeqModule =>
Public NumberSeqModule numberSeqModule ()
{
   Return NumberSeqModule::OfcMgmt;
}

*********************************************************************************

8- Create a "Form" to display the new “parameter table's data”.

9- In Class "NumberSeqModuleModuleName" add override method "load module".
    Coding  of Load Module =>
  Public void loadModule ()
  {
    NumberSeqDatatype datatype = NumberSeqDatatype::construct ();
    ;

    //Gulshan
    datatype.parmDatatypeId(extendedtypenum(CourierID));
    datatype.parmReferenceHelp(literalstr("@SYS32633"));
    datatype.parmWizardIsContinuous(true);
    datatype.parmWizardIsManual(NoYes::No);
    datatype.parmWizardIsChangeDownAllowed(NoYes::No);
    datatype.parmWizardIsChangeUpAllowed(NoYes::No);
    datatype.parmWizardHighest(99999);
    datatype.parmSortField(1);

    this.create (datatype);
    }


10-To load "NumberSeqLoadModule" information for module, create “Job”.
Coding for Job =>
Public static void InstallOfficeManagement (Args _args)
{
    NumberSeqModuleOfficeManagement n = new NumberSeqModuleOfficeManagement ();
   // NumberSeqModuleFacilityManagement n = new NumberSeqModuleFacilityManagement ();

    n.loadModule ();
    Print ("Job Executed Successfully");
    Pause;
}


11-Now Setup "Number Sequence" just follows these steps;
    a) Go to CEU> Organization Administration
    b) Then Number Sequences > Number Sequences
    c) Click on "Number Sequence" in "New" tab.
    d) Fill the information in "Identification" tab.
    e) In "Scope parameters" tab select (Shred/Company)
    f) In "Segments" tab set the length of number sequence.
    g) Now in "General" setup click "continuous" option.
    h) Save and generate.
    i) Click "close"

12-Now add "NumRef" method in "parameter table" name “NumRefEDTname”.
Coding for NumRef Method =>
static client server NumberSequenceReference numRefCourierID()

{

    return NumberSeqReference::findReference(extendedTypeNum(CourierID));


}



13-In class declaration of a form add =>
 Public class FormRun extends ObjectRun
{
     NumberSeqFormHandler NumberSeqFormHandler;
}


14-Add "NumberSeqFormHandler" method to the form.
Coding for NumberSeqFormHandler Method =>
NumberSeqFormHandler NumberSeqFormHandler ()
{
    If (!numberSeqFormHandler)
    {
        NumberSeqFormHandler = numberseqformhandler::newForm(OfcAdminParameters::numrefCourierTransID().NumberSequenceId,element,Courier_Invoice_Table_1_ds,fieldNum(Courier_Invoice_Table, CourierTransID));
    }
    Return NumberSeqFormHandler;
}


15-Write "close" method in form methods node and "link active, Validate write, Write, Delete" methods on methods     node of data source of form.
Coding  for “Close” Method=>
void close()
{
    if (NumberSeqFormHandler)
    {
        numberSeqFormHandler.formMethodClose();
    }
    super();
}

Coding  for datasource method’s =>
LinkActive =>
public void linkActive()
{
    ;
    element.numberSeqFormHandler().formMethodDataSourceLinkActive();
    super();
}

ValidateWrite =>
public boolean validateWrite()
{
    boolean         ret;
    ret = super();

    ret = element.numberseqformhandler().formMethodDataSourceValidateWrite(ret) && ret;
    if (ret)
    {
        Courier_Invoice_Table_1.validateWrite();
    }
    return ret;
}

Write =>
public void write()
{
    super();
    element.numberSeqFormHandler().formMethodDataSourceWrite();
}

Delete =>
public void delete()
{
    element.numberSeqFormHandler().formMethodDataSourceDelete();
    super();
}

Create =>
public void create(boolean _append = false)

{

    ;

   super(_append);
    //In the below line we have to write datasource name.fieldname (very very important for number sequence)
   Courier_Invoice_Table_1.courierTransID = NumberSeq::newGetNum(OfcAdminParameters::numrefCourierTransID(),true).num();

    Courier_Invoice_Table_1.InvoiceNumber = NumberSeq::newGetNum(OfcAdminParameters::numrefInvoiceNumber(),true).num();

    Courier_Invoice_Table_1.VoucherNumber = NumberSeq::newGetNum(OfcAdminParameters::numrefVoucherNumber(),true).num();

}


Thursday, March 13, 2014

How to create Inventory Journal through code

static void createInventoryJournal(Args _args)///and also it will import the data from the Excel
{
    InventJournalNameId inventJournalNameId = "IMov";///Assign the journal Name
    AxInventJournalTrans axInventJournalTrans;
    InventJournalTable inventJournalTable;
    Dialog dialog;
    DialogField dialogField,dialogdate;
    Filename filename;
    COMVariant cOMVariant;
    SysExcelApplication sysExcelApp;
    SysExcelWorkbooks workbooks;
    SysExcelWorkbook workbook;
    SysExcelWorksheets worksheets;
    SysExcelWorksheet worksheet;
    SysExcelCells cells;
    SysExcelCell rCell;
    int i,j,k;
    SysOperationProgress simpleProgress;
    Container filterCriteria;
    #avifiles
    ;
    sysExcelApp = SysExcelApplication::construct();///SysExcelApplication
    workbooks = sysExcelApp.workbooks();///Workbooks

    Dialog = new dialog();
    dialogField = dialog.addField(typeId(FileNameOpen),'File Name');
    filterCriteria = ['*.xls','*. xlsx'];//// To filter only Excel files
    filterCriteria = dialog.filenameLookupFilter(filterCriteria);
    dialog.run();
    if(dialog.run())
    fileName = dialogField.value();

    cOMVariant = new COMVariant();
    cOMVariant.bStr(fileName);

    workBook = workBooks.add(cOMVariant);///Workbook
    worksheets = Workbook.worksheets();///WorkSheets
    worksheet = worksheets.itemFromNum(1);///WorkSheet
    Cells = workSheet.cells();///Cells

    i=2;
    rCell = Cells.item(i,1);///rCell

    if(fileName)
    {
        ttsBegin;
        inventJournalTable.JournalNameId = inventJournalNameId;
        inventJournalTable.initFromInventJournalName(InventJournalName::find(inventJournalNameId));
        inventJournalTable.insert();
        simpleProgress = SysOperationProgress::newGeneral(#aviUpdate,'Importing Transactions',100);///SysProgressOperation
        while(RCell.Value().bStr() != '')
        {
            j++;
            simpleProgress.incCount();
            simpleprogress.setText(strfmt("Transaction Imported: %1",i));
            sleep(10);
            simpleprogress.kill();
            axInventJournalTrans = new AxInventJournalTrans();
            axInventJournalTrans.parmJournalId(inventJournalTable.JournalId);
            axInventJournalTrans.parmTransDate(systemdateget());
            axInventJournalTrans.parmLineNum(j);
            rCell = Cells.Item(i, 1);
            axInventJournalTrans.parmItemId(RCell.value().bStr());
            rCell = Cells.Item(i, 2);
            axInventJournalTrans.axInventDim().parmInventSiteId(rCell.value().bStr());
            rCell = Cells.Item(i, 3);
            axInventJournalTrans.axInventDim().parmInventLocationId(rCell.value().bStr());
            rCell = Cells.Item(i, 4);
            axInventJournalTrans.parmQty(rCell.value().double());
            rCell = Cells.Item(i, 5);
            axInventJournalTrans.parmCostPrice(rCell.value().double());
            axInventJournalTrans.save();
            i++;
            rCell = Cells.Item(i, 1);
        }
        ttsCommit;
    }
}

How to create a radio Button in Dialiog


First create a new base enum with the property selected as radiobutton.

Dialog dialog = new Dialog();
DialogField df;
FormRadioControl frc;
;
df = dialog.addField(typeid(BaseEnum1));
frc = df.control();
frc.caption("Whatever the label should be");
frc.helpText("Whatever the help message should be");
dialog.run();

How to pop up a new form through code...

Args args;
FormRun formRun;
;

args = new Args();
args.name(formstr(Your_Form_Name));
args.caller();

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

How to import data from excel file to AX2012

static void XML2AXTABLE(Args _args)
{
MyTables mt;
XMLDocument XMLdoc = XMLDocument::newFile(@"D:\\ABC\\accounts.xml");
int i,CountItemtags=100;
;
XMLdoc.load(XMLdoc.toString());

for (i = 0 ; i < countItemTags; i++)
{
mt.AccountNum =( xmldoc.getElementsByTagName('AccountNum').item(i).text());
mt.BankAccount=( xmldoc.getElementsByTagName('BankAccount').item(i).text());
countItemTags = xmldoc.getElementsByTagName('AccountNum').length();
mt.insert();
}


}

How to show current Date in AX 2009

//Write this in Job

static void Example_date2str(Args _args)
{   ;
    info(date2str(systemdateget(),123,2,1,2,1,4));
}

What are the differences between abstract classes and interface

An abstract class may contain complete or incomplete methods. Interfaces can contain only the signature of a method but no body. Thus an abstract class can implement methods but an interface can not implement methods.

·An abstract class can contain fields, constructors, or destructors and implement properties. An interface can not contain fields, constructors, or destructors and it has only the property's signature but no implementation.

·An abstract class cannot support multiple inheritance, but an interface can support multiple inheritance. Thus a class may inherit several interfaces but only one abstract class.

·A class implementing an interface has to implement all the methods of the interface, but the same is not required in the case of an abstract Class.

·Various access modifiers such as abstract, protected, internal, public, virtual, etc. are useful in abstract Classes but not in interfaces.
·Abstract classes are faster than interfaces.

How to Find Current Active Language in AX 2012

static void defaultLangId(Args _args)
{
Session session = new Session(sessionId());
;
info(session.interfaceLanguage());
}

How to find Mandatory fields in any table in AX2012

static void Mandatoryfields_inTable(Args _args)
{

DictTable dictTable;
DictField dictField;
tableId tableId;
fieldId fieldId;
str result;
#DictField
;
dicttable = new DictTable(tablenum(salestable));
for (fieldId = dictTable.fieldNext(0);fieldId;fieldId = dictTable.fieldNext(fieldId))
{
dictField = dictTable.fieldObject(fieldId);

if (!dictField.isSystem() && bitTest(dictField.flags(), #dbf_visible)
&& bitTest(dictField.flags(), #dbf_mandatory))
{
result += dictField.name();
result +='\n';
}
}
info(result);
}

How to reset "Unbalanced ttsbegin ttscommit pair has been detected" error in AX 2012

//Write this code in Job and Run.

static void TheAxaptaResetTTS(Args _args)
{
    while (appl.ttsLevel() > 0)
    {
        info(strfmt("Level %1 aborted",appl.ttsLevel()));
        ttsAbort;
    }
}