Saturday 29 September 2018

Create Number Sequence In Ax2012

Simple Steps To Create Number Sequence In Ax2012


           
Creating number seq:

 Hello Friends,
Today i want to describe about how to create number sequence in AX2012

It is same as like as we know in Ax2009 but small steps is added in AX2012.don't worry just follow the below steps simply we will get number sequence in AX2012.

We will Take a EDT name as "Car Id" and create in number sequence.For that first we should select a module for new number sequence for example project module.
                                   
steps:

1.  Create an edt : CarId .

     AOT >> Extended Data Types >> New  >> Properties >> Name  >> Car Id.

2. Write a code on lode module() on NumberSeqModuleProject

{
     datatype.parmDatatypeId(extendedTypeNum(Car Id));
     datatype.parmReferenceHelp(literalStr("@SYS334483"));
     datatype.parmWizardIsManual(NoYes::No);
     datatype.parmWizardIsChangeDownAllowed(NoYes::No);
     datatype.parmWizardIsChangeUpAllowed(NoYes::No);
     datatype.parmWizardHighest(999999);
     datatype.parmSortField(20);
     datatype.addParameterType(NumberSeqParameterType::DataArea, truefalse);
     this.create(datatype);
}

3.Write a method on Projparameters Table

     client server static NumberSequenceReference numRefcarId()
{
     return NumberSeqReference::findReference(extendedTypeNum(car Id));
}

4.Write a job and run that

static void Carid(Args _args)
{
    NumberSeqModuleProject  NumberSeqModuleProject = new NumberSeqModuleProject();
    ;
    NumberSeqModuleProject.load();
}


5. Then run the wizard

   Organization Administration >> CommonForms >> Numbersequences>>Numbersequences>> Generate >> run the wizard.

6.Now we have to check the number sequence  is correctly working  for that write a job:

static void number(Args _args)
{
    NumberSeq  numberSeq;
    CarId num;
    ;
    numberSeq = NumberSeq::newGetNum(ProjParameters::numRefcarId());
    num = numberSeq.num();
    info(num);
}

  Run the above job.We will find the generated Number     sequence.                                                    .

7. Now we want that Number Sequence in form level(Car Table):

Declare the number sequence On Form Declaration:
 
public class FormRun extends ObjectRun
{
    NumberSeqFormHandler numberSeqFormHandler;

}

 8. Write the NumberSeqFormHandler() in form methods node.

NumberSeqFormHandler numberSeqFormHandler()
{
    if (!numberSeqFormHandler)
    {
        numberSeqFormHandler = NumberSeqFormHandler::newForm(ProjParameters::numRefcarId      ().NumberSequenceId,
                                                             element,
                                                             CarTable_DS,
                                                             fieldNum(CarTable, Car Id)
                                                            );
    }
    return numberSeqFormHandler;
}


9.Write the close() on the form methods node.

void close()
{
    if (numberSeqFormHandler)
    {
        numberSeqFormHandler.formMethodClose();
    }
    super();
}

10. Then final add the below methods on data source methods node
Create()

void create(boolean append = false,
            boolean extern = false)  // If created externally
{
    element.numberSeqFormHandler().formMethodDataSourceCreatePre();

    super(append);

    if (!extern)
    {
        element.numberSeqFormHandler().formMethodDataSourceCreate(true);
    }
}

Delete()

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

Write()

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

Validate Write()

public boolean validateWrite()
{
    boolean         ret;
    ret = super();
    ret = element.numberSeqFormHandler().formMethodDataSourceValidateWrite(ret) && ret;
    if (ret)
    {
        CarTable.validateWrite();
    }
    return ret;
}

Link Active()

public void linkActive()
{
    ;
    element.numberSeqFormHandler().formMethodDataSourceLinkActive();
    super();
}

 Now our numberseqence is generated .

*** Set the field or Tabpage Allowedit property to No.
***Check the continues on wizard.

Friday 28 September 2018

Import Invoice Journal in Ax 2012

void clicked()
{
    LedgerJournalTableExt            ledgerJournalTableExt;
    LedgerJournalTransExt            ledgerJournalTransExt;
    int                                             WrkShtNum;
    Dimension                                accountingRegion;
    ledgerJournalTable                  ledgerJournalTableloc;
    LedgerJournalTrans                 LedgerJournalTransloc;
    COMVariantType                     type;
    Name                                        Dim1,dim2,dim3,dim4,dim5,AccountNum,LedgerAccountValue,
                                                     LedgerOffsetAccountValue,OffsetAccount,dim6,dim7,offdim1,
                                                     formatValue,offdim3,offdim4,offdim5,offdim6,offdim7;
    LedgerJournalTransTaxExtensionIN    LedgerJournalTransTaxExtensionIN;
    LedgerDimensionAccount                   LedgerDim,DefDimension;
    LedgerDimensionAccount                   OffsetledgerDim;
    LedgerJournalACType                        OffsetAccountType;
    TransDate                                            transDate;
    CurrencyCode                                     currencyCode;
    NoYes                                                 noYes;
    numberSeq                                         numberSeq;

    name formatcheck(int val)
    {
        formatValue = "";
         switch(excelcells.item(row, val).value().variantType())
        {
            case COMVariantType::VT_BSTR:
                formatValue = strFmt("%1", excelcells.item(row, val).value().bStr());
                break;
            case COMVariantType::VT_DECIMAL, COMVariantType::VT_R4, COMVariantType::VT_R8:
                formatValue = strFmt("%1", any2int(excelcells.item(row, val).value().double()));
                break;
            case COMVariantType::VT_I1, COMVariantType::VT_I2, COMVariantType::VT_I4:
                formatValue = strFmt("%1", excelcells.item(row, val).value().int());
                break;
            case COMVariantType::VT_UI1, COMVariantType::VT_UI2, COMVariantType::VT_UI4:
                formatValue = strFmt("%1", excelcells.item(row, val).value().uLong());
                break;
            case COMVariantType::VT_EMPTY:
                formatValue = '';
                break;
            default:
                throw error(strfmt("Issue in file coloum type.", excelcells.item(row+1, 1).value().variantType()));
        }
        return formatValue;
    }
    ;
    excelApp = SysExcelApplication::construct();
    startLengthyOperation();
    if(StrLTrim(StrRTrim(OpenExcelFile.text()))=="")
    {
        ExcelCells = NULL;
        excelWorksheet = NULL;
        excelApp.quit();
        throw error("Empty File Name");
    }
    else
    {
        WrkShtNum      = WorkSheetNum.value();
        excelApp.workbooks().open(OpenExcelFile.text());
        excelWorksheet = excelApp.worksheets().itemFromNum(WrkShtNum);
        excelCells     = excelWorksheet.cells();
        //Row = Element.FindFirstValidRowNum();
        Row=1;
        if(Row == 0)
        {
            ExcelCells = NULL;
            excelWorksheet = NULL;
            excelApp.quit();
            throw error("ERROR: Excel upload aborted...");
        }
        ttsBegin;
        ledgerJournalTableloc.JournalName = "APInv";
        ledgerJournalTableloc.initFromLedgerJournalName(ledgerJournalTableloc.JournalName);
        ledgerJournalTableloc.insert();

        select ledgerJournalTableExt
            where ledgerJournalTableExt.LedgerJournalTable == ledgerJournalTableloc.RecId;
        if(!ledgerJournalTableExt)
        {
            ledgerJournalTableExt.LedgerJournalTable = ledgerJournalTableloc.RecId;
            ledgerJournalTableExt.insert();
        }
        ttsCommit;
        do
        {
            try
            {
                ttsBegin;
                Row++;
                if(row > 1)
                {
                    transDate                             = excelcells.item(Row,1).value().date();
                    currencyCode                          = formatcheck(2);
                    if(transDate && currencyCode)
                    {
                        numberSeq = NumberSeq::newGetVoucherFromCode(NumberSequenceTable::find(ledgerJournalName::find(ledgerJournalTableloc.JournalName).NumberSequenceTable).NumberSequence);
                        LedgerJournalTransloc.voucher          = numberseq.voucher();
                        LedgerJournalTransloc.initValue();
                        LedgerJournalTransloc.initFromLedgerJournalTable_LT(ledgerJournalTable);
                        LedgerJournalTransloc.TransDate       = transDate ;
                        LedgerJournalTransloc.CurrencyCode    = currencyCode;
                        LedgerJournalTransloc.Company         = formatcheck(3);
                        LedgerJournalTransloc.AccountType     = str2enum(OffsetAccountType,formatcheck(4));
                        LedgerJournalTransloc.JournalNum      = LedgerJournalTableloc.JournalNum;
                        LedgerAccountValue                    = formatcheck(5);
                        Dim1                                  = formatcheck(6);
                        Dim2                                  = formatcheck(7);
                        Dim3                                  = formatcheck(8);
                        Dim4                                  = formatcheck(9);
                        Dim5                                  = formatcheck(10);
                        Dim6                                  = formatcheck(11);
                        DefDimension                          = element.DefaultDimension(Dim1, Dim2,Dim3,Dim4,Dim5,Dim6,"");
                        LedgerJournalTransloc.Invoice         = formatcheck(12);
                        LedgerJournalTransloc.TaxGroup        = formatcheck(13);
                        LedgerJournalTransloc.TaxItemGroup    = formatcheck(14);
                        LedgerJournalTransloc.Txt             = excelcells.item(Row,15).value().bStr();
                        LedgerJournalTransloc.AmountCurDebit  = excelcells.item(Row,16).value().double();
                        LedgerJournalTransloc.AmountCurCredit = excelcells.item(Row,17).value().double();
                        LedgerJournalTransloc.OffsetCompany   = formatcheck(18);
                        OffsetAccountType                     = str2enum(OffsetAccountType,formatcheck(19));
                        LedgerOffsetAccountValue              = formatcheck(20);
                        LedgerJournalTransloc.DocumentDate    = excelcells.item(Row,21).value().date();
                        LedgerJournalTransloc.Approved        = NoYes::Yes;
                        LedgerJournalTransloc.Approver        = HcmWorker::userId2Worker(curUserId());
                        LedgerJournalTransloc.Due             = LedgerJournalTransloc.TransDate;
                        LedgerJournalTransloc.TransactionType = LedgerTransType::Vend;

                        if(LedgerAccountValue)
                        {
                            if(LedgerJournalTransloc.AccountType == LedgerJournalACType::Ledger)
                            {
                                ledgerDim                           = DimensionDefaultingService::serviceCreateLedgerDimension(DimensionStorage::getDefaultAccountForMainAccountNum(LedgerAccountValue), DefDimension);
                                LedgerJournalTransloc.LedgerDimension  = DimensionAttributeValueCombination::find(ledgerDim).Recid;
                            }
                            else
                            {
                                LedgerJournalTransloc.DefaultDimension = DefDimension;

                                ledgerDim                           = DimensionStorage::getDynamicAccount(LedgerAccountValue, LedgerJournalTransloc.AccountType);
                                LedgerJournalTransloc.LedgerDimension  = DimensionAttributeValueCombination::find(ledgerDim).Recid;

                                if(LedgerJournalTransloc.AccountType == LedgerJournalACType::cust)
                                {
                                    LedgerJournalTransloc.PostingProfile  = CustParameters::findByCompany(LedgerJournalTransloc.Company).PostingProfile;
                                }
                                if(LedgerJournalTransloc.AccountType == LedgerJournalACType::Vend)
                                {
                                    LedgerJournalTransloc.PostingProfile  = VendParameters::find().PostingProfile;
                                }
                            }
                        }

                        LedgerJournalTransloc.OffsetAccountType = OffsetAccountType;

                        if(LedgerOffsetAccountValue)
                        {
                            if(LedgerJournalTransloc.OffsetAccountType == LedgerJournalACType::Ledger)
                            {
                                OffsetledgerDim                          = DimensionDefaultingService::serviceCreateLedgerDimension(DimensionStorage::getDefaultAccountForMainAccountNum(LedgerOffsetAccountValue), DefDimension);
                                LedgerJournalTransloc.OffsetLedgerDimension = OffsetledgerDim;
                            }
                            else
                            {
                                OffsetledgerDim                           = DimensionStorage::getDynamicAccount(LedgerOffsetAccountValue, LedgerJournalTransloc.OffsetAccountType);
                                LedgerJournalTransloc.OffsetLedgerDimension  = DimensionAttributeValueCombination::find(OffsetledgerDim).Recid;
                                LedgerJournalTransloc.OffsetDefaultDimension = DefDimension;
                            }
                        }

                        LedgerJournalTransloc.LineNum          = LedgerJournalTrans::lastLineNum(LedgerJournalTransloc.JournalNum) + 1;
                        LedgerJournalTransloc.ExchRate         = Currency::exchRate(LedgerJournalTransloc.CurrencyCode, LedgerJournalTransloc.TransDate);
                        LedgerJournalTransloc.insert();

                        ledgerJournalTransExt.LedgerJournalTrans = LedgerJournalTransloc.RecId;
                        ledgerJournalTransExt.insert();

                        ledgerJournalTransTaxExtensionIN.LedgerJournalTrans = LedgerJournalTransloc.RecId;
                        ledgerJournalTransTaxExtensionIN.TaxInformation_IN  = TaxInformation_IN::findDefaultbyLocation(CompanyInfo::findByCompany_IN().PrimaryAddressLocation).RecId;
                        ledgerJournalTransTaxExtensionIN.insert();
                    }
                }
                ttsCommit;
            }
            catch
            {
                Error(strfmt("Upload Failed in row %1", row));
            }
            type = excelcells.item(row+1, 1).value().variantType();
        }
        while (type != COMVariantType::VT_EMPTY);

        info(strfmt("Journals %1 imported successfully",ledgerJournalTableloc.JournalNum));
        excelapp.quit();

    }
    endLengthyOperation();
    LedgerJournalTable_ds.executeQuery();
}

-------------------------------------------------------validated Excel-----------------------------------

int FindFirstValidRowNum()
{
    int R = 1;
    ;
    while(R < 28)
    {
        if(excelCells.item(R,1).value().bStr() == "TransDate"
        && excelCells.item(R,2).value().bStr() == "Currency"
        && excelCells.item(R,3).value().bStr() == "Company Code"
        && excelCells.item(R,4).value().bStr() == "AccountType"
        && excelCells.item(R,5).value().bStr() == "AccountNumber"
        && excelCells.item(R,6).value().bStr() == "ProfitCenter"
        && excelCells.item(R,7).value().bStr() == "Department"
        && excelCells.item(R,8).value().bStr() == "Offset account type"
        && excelCells.item(R,9).value().bStr() == "Offset account"
        && excelCells.item(R,10).value().bStr() == "Credit"
        && excelCells.item(R,11).value().bStr() == "Department"
        && excelCells.item(R,12).value().bStr() == "Divisons"
        && excelCells.item(R,13).value().bStr() == "BusinessUnit"
        && excelCells.item(R,14).value().bStr() == "Classes"
        && excelCells.item(R,15).value().bStr() == "Products"
        && excelCells.item(R,16).value().bStr() == "SubProducts"
        && excelCells.item(R,17).value().bStr() == "Invoice"
        && excelCells.item(R,18).value().bStr() == "Sales tax group"
        && excelCells.item(R,19).value().bStr() == "Item sales tax group"
        && excelCells.item(R,20).value().bStr() == "Description"
        && excelCells.item(R,21).value().bStr() == "Debit"
        && excelCells.item(R,22).value().bStr() == "Credit"
        && excelCells.item(R,23).value().bStr() == "Offset Company Code"
        && excelCells.item(R,24).value().bStr() == "OffsetAccount type"
        && excelCells.item(R,25).value().bStr() == "Offset account number"
        && excelCells.item(R,26).value().bStr() == "DocumentDate"
        && excelCells.item(R,27).value().bStr() == "Reverse"
        && excelCells.item(R,28).value().bStr() == "Reverse date")
            return R+1;

        R++;
    }
    error("ERROR: Not a valid ledger journal import excel file !!!");
    return 0;
}

Enable/Disable and Edit Form Control Fields in Ax 2012

Enable/Disable  and  Edit  Form Control Fields .

ledgerJournalTrans_DS.object(fieldnum(LedgerJournalTrans, TransDate)).allowEdit(false);
ledgerJournalTrans_DS.object(fieldnum(LedgerJournalTrans, TransDate)).Enable(false);
ledgerJournalTrans_DS.object(fieldnum(LedgerJournalTrans, TransDate)).Enable(true);

// validate record using exist method------------------------------------

if(!LedgerJournalTable::exist(JourNo))
 {
          error(strfmt("ERROR: Invalid Journal Number !!!",JourNo));
          return false;
}

Filter Query Before Open the Form Based on Condition in Ax 2012

Filter Query Before Open the Form Based on Condition.
-----> Init Method and
----->ExecuteQuery

this.query().dataSourceTable(tablenum(LedgerJournalTable)).addRange(fieldnum(LedgerJournalTable, JournalType)).value(queryValue(LedgerJournalType::Daily));
    this.query().dataSourceTable(tablenum(LedgerJournalTable)).addRange(fieldnum(LedgerJournalTable, Posted)).value(queryValue(NoYes::No));

Monday 17 September 2018

Clear Range and Add Range in ExecuteQuery in Ax 2012.

public void executeQuery()
{
    DimensionMappingTable_DS.query().dataSourceTable(tableNum(DimensionMappingTable)).clearRanges();
    if(TransType.selection() >= 0)
    {
               DimensionMappingTable_DS.query().dataSourceTable(tableNum(DimensionMappingTable))
            .addRange(fieldNum(DimensionMappingTable,Dimensions))
            .value(SysQuery::value(TransType.selection()));
    }

    super();
}

Friday 14 September 2018

Using Struct insert default Dimensions in Ax 2012

public RecId defaultDimension(Name _Dim1, Name  _Dim2)
{
    container          defDimensionCon;
    DimensionDefault   dimensionDefault;
    int                i;
    Struct             struct = new Struct();
    ;
    if(_Dim1||_Dim2)
    {
        if (_Dim1)
        {
            struct.add("Products", _Dim1);
        }

        if (_Dim2)
        {
            struct.add("SubProducts", _Dim2);
        }
    }
    defDimensionCon += struct.fields();
    for (i = 1; i <= struct.fields(); i++)
    {
        defDimensionCon += struct.fieldName(i);
        defDimensionCon += struct.valueIndex(i);
    }
    if (struct.fields() &&(_Dim1||_Dim2))
    {
        dimensionDefault = AxdDimensionUtil::getDimensionAttributeValueSetId(defDimensionCon);
    }
    return dimensionDefault;
}

Import User Mail ids in Ax 2012

static void  Na_AlertUserEmailImporting(Args _args)
{
    Dialog                                    dialog;
    Dialogfield                             dialogfield;

    SysExcelApplication             application;
    SysExcelWorkbooks              workBooks;
    SysExcelWorkbook               workBook;
    SysExcelWorksheets             workSheets;
    SysExcelWorksheet              workSheet;
    SysExcelCells                       cells;

    UserInfo                                  userInfo;
    SysUserInfo                             sysUserInfo;

    LogisticsElectronicAddress      logisticsElectronicAddress;
    LogisticsLocation                     logisticsLocation;
    HcmWorker                              hcmWorker;
    DirPerson                                 dirPerson;
    DirPartyTable                           dirPartyTable;
    DirPartyContactInfoView        contactView;
    DirParty                                   dirParty;

    DirPersonRecId                      dirPersonRecid;
    DirPersonUser                        personUser;

    Email                                      usermail;
    Name                                     Userid;
    Filename                                fileName;
    COMVariantType                  type;
    int                                          row = 1   ;
    int                                         recordcnt;

    str COMVariant2Str(COMVariant _cv, int _decimals = 0,int _characters = 0,int _separator1 = 0,int _separator2 = 0)
        {
            switch(_cv.variantType())
            {
                case (COMVariantType::VT_BSTR):
                    return _cv.bStr();
                case (COMVariantType::VT_R4):
                    return num2str(_cv.float(),_characters,_decimals, _separator1,_separator2);
                case (COMVariantType::VT_R8):
                    return num2str(_cv.double(),_characters,_decimals,_separator1,_separator2);
                case (COMVariantType::VT_DECIMAL):
                    return num2str(_cv.decimal(),_characters,_decimals, _separator1, _separator2);
                case (COMVariantType::VT_DATE):
                    return date2str(_cv.date(),123,2,1,2, 1,4);
                case (COMVariantType::VT_EMPTY):
                    return "";
                default:
                    throw error(strfmt("@SYS26908",_cv.variantType()));
            }
            return "";
        }


    application =   SysExcelApplication::construct();
    workBooks   =   application.workbooks();
    dialog      = new Dialog("FileOpen");
    dialogfield = dialog.addField(extendedTypeStr(Filenameopen), "File Name");
    dialog.run();

    if (dialog.run())
    {
        filename = (dialogfield.value());
    }
    try
    {
        workBooks.open(fileName);
    }
    catch (Exception::Error)
    {
        throw error("File Cannot be opened");
    }

    workBook    =   workBooks.item(1);
    workSheets  =   workBook.worksheets();
    workSheet   =   workSheets.itemFromNum(1);
    cells       =   workSheet.cells();
    do
    {
        row++;
        Userid          = cells.item(row, 1).value().bStr();
        usermail        = COMVariant2Str(cells.item(row, 2).value());

        select id,name from userInfo where userInfo.id == Userid
                join id from sysUserInfo where sysUserInfo.Id == userInfo.id;

        if(userInfo.Id)
        {
            select forUpdate sysUserInfo where sysUserInfo.id == userInfo.id;
            ttsBegin;
            sysUserInfo.Email = usermail;
            sysUserInfo.update();
            ttsCommit;
            select * from hcmWorker
                exists join personUser
                    where hcmWorker.Person == personUser.PersonParty
                       && personUser.User == userInfo.id;
            if(hcmWorker.RecId)
            {
                dirPersonRecid   = hcmWorker.Person;
                DirParty = DirParty::constructFromPartyRecId(dirPersonRecid);

                contactView.clear();
                contactView.LocationName                =   userInfo.name;
                contactView.Locator                            =   usermail;
                contactView.Type                                =    LogisticsElectronicAddressMethodType::Email;
                contactView.Party                                =    dirPersonRecid;
                contactView.IsPrimary                         =    NoYes::No;
                contactView.IsPrivate                           =   NoYes::Yes;
                dirParty.createOrUpdateContactInfo(contactView);
                info(strFmt("User-%1 Email- %2 is successfully Updated",userInfo.id,usermail));
            }
            else
            {
                info(strFmt("User-%1 Email- %2 is not Updated in worker",userInfo.id,usermail));
            }


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

Thursday 13 September 2018

Financial dimension lookup in form level in Ax 2012

public void lookup()
{

    DimensionAttribute                            dimensionAttribute;
    DimensionAttributeDirCategory       dimAttributeDirCategory;
    Query                                                 query = new Query();
    QueryBuildDataSource                      qbds;
    SysTableLookup                               sysTableLookup;

    dimensionAttribute     = DimensionAttribute::findByName('Products');
    if (dimensionAttribute.Type == DimensionAttributeType::CustomList)
    {
        select firstonly DirCategory from dimAttributeDirCategory
            where dimAttributeDirCategory.DimensionAttribute == dimensionAttribute.RecId;

        sysTableLookup = SysTableLookup::newParameters(tableNum(DimensionFinancialTag), this);
        sysTableLookup.addLookupfield(fieldNum(DimensionFinancialTag, Value));
        sysTableLookup.addLookupfield(fieldNum(DimensionFinancialTag, Description));

        qbds = query.addDataSource(tableNum(DimensionFinancialTag));
        qbds.addRange(fieldNum(DimensionFinancialTag, FinancialTagCategory)).value(queryValue(dimAttributeDirCategory.DirCategory));

        sysTableLookup.parmQuery(query);
        sysTableLookup.performFormLookup();
    }

}
-----------------------------------------------------------------------------------------------------------
1.)create New Class...................
class  NaSyslookup extends SysLookup
{
}
Public void lookupDimension(FormStringControl _stringControl, Name _dimensionName)
{
     syslookup::lookupDimension(_stringControl,_dimensionName);
}

2.)write code in Lookup override...........................

public void lookup()
{
    NaSyslookup cicsyslookup        = new NaSyslookup();
    Query query = new Query();
    QueryBuildDataSource queryBuildDataSource;
    SysTableLookup sysTableLookup =  new SysTableLookup();
    //super();
    switch (TransType.selection())
    {
        case 0:
            sysTableLookup =                  SysTableLookup::newParameters(tableNum(DimAttributeOMBusinessUnit), this);
            queryBuildDataSource = query.addDataSource(tableNum(DimAttributeOMBusinessUnit));
            sysTableLookup.addLookupfield(fieldNum(DimAttributeOMBusinessUnit, Value),true);
            sysTableLookup.addLookupfield(fieldNum(DimAttributeOMBusinessUnit, Name));
            sysTableLookup.addSelectionField(fieldNum(DimAttributeOMBusinessUnit, Value));
            sysTableLookup.parmQuery(query);
            sysTableLookup.performFormLookup();
            break;

        case 1:
            sysTableLookup = SysTableLookup::newParameters(tableNum(DimAttributeOMDepartment), this);
            queryBuildDataSource = query.addDataSource(tableNum(DimAttributeOMDepartment));
            sysTableLookup.addLookupfield(fieldNum(DimAttributeOMDepartment, Value),true);
            sysTableLookup.addLookupfield(fieldNum(DimAttributeOMDepartment, Name));
            sysTableLookup.addSelectionField(fieldNum(DimAttributeOMDepartment, Value));
            sysTableLookup.parmQuery(query);
            sysTableLookup.performFormLookup();
            break;

        case 2:
            sysTableLookup = SysTableLookup::newParameters(tableNum(DimensionFinancialTag), this);
            queryBuildDataSource = query.addDataSource(tableNum(DimensionFinancialTag));
            sysTableLookup.addLookupfield(fieldNum(DimensionFinancialTag, Value),true);
            sysTableLookup.addLookupfield(fieldNum(DimensionFinancialTag, Description));
            sysTableLookup.addSelectionField(fieldNum(DimensionFinancialTag, Value));
            sysTableLookup.parmQuery(query);
            sysTableLookup.performFormLookup();
            break;

 default:
    }
}

Show the data in table format while send mail in ax 2012

static void Na_SendingMailPurchRequisition(Args _args)
{
    AlertUserInfo                   alertUserInfo;
    sysUserInfo                      sysUserInfo,sysUserInfolog;
    PurchReqTableExt            purchReqTableExt;
    PurchReqTable                 purchReqTable;
    PurchReqLine                  purchReqLine;
    EcoResCategory              ecoResCategory;
    str                                    PRid,Journalno,netamt,sumAmount,Unitprice,unit;
    str                                    ItemId,Productname,procurementcategory,purchqty,postDate;
    str                                    linedetails;
    TransDate                        PostedDate;
    Amount                           netamount,amount;

    SysEmailBatch               batch = new SysEmailBatch();
    #Define.AdminMailID("joseph.waititu@cic.co.ke")
    #define.Opentablerowdiv("<tr><td>")
    #define.Closetablediv("</td><td>")
    #define.Open("<td>")
    #define.Close("</td")
    #define.Closetablerowdiv("</td></tr>")
    #define.Header1("<p> Dear ")
    #define.Header2(",</p><p>Kindly find the Payment Receipt Confirmation for the below Internal Purchase Requisition:</p>");
    #define.header3("<table width= 40% border='2'><tr><td><h5>User Id</h5></td><td>")
    #define.Header4("<tr><td><h5>User Name</h5></td><td>")
    #define.Header5("<tr><td><h5>PR Id</h5></td><td>")
    #define.Header6("<tr><td><h5>Journal no</h5></td><td>")
    #define.Header7("<tr><td><h5>Posted Date</h5></td><td>")
    #define.Header8("<tr><td><h5>Amount</h5></td><td>")
    #define.Header9("</table>")
    #define.Header10("<p>Product Details: </p><table width= 100% border='2'><tr><th>Product Code</th><th>Product Name</th><th>Procurement category</th><th>Qty</th><th>Unit</th><th>Unit Price</th><th>Net amount</th></tr>")
    #define.Subject("Payment Receipt Confirmation  ")

    try
    {
        ttsbegin;
        while select forupdate purchReqTableExt
            where purchReqTableExt.BeforeSent  == NoYes::Yes
               && purchReqTableExt.PaymentSent == NoYes::No
               && purchReqTableExt.JournalNum != ""
        join sysUserInfolog
            where sysUserInfolog.Id == purchReqTableExt.createdBy
        join purchReqTable
            where purchReqTable.RecId == purchReqTableExt.PurchReqTable
        {
            while select purchReqLine
                where purchReqLine.PurchReqTable == purchReqTable.RecId
            {
                PRid                       = purchReqTable.PurchReqId;
                Journalno               = purchReqTableExt.JournalNum;
                PostedDate            = purchReqTable.TransDate;
                netamount              = purchReqLine.LineAmount;
                amount                  += netamount;
                ItemId                     = purchReqLine.ItemId;
                Productname          = InventTable::find(purchReqLine.ItemId).NameAlias;
                Unitprice                = strFmt("%1",purchReqLine.PurchPrice);
                purchqty                 = strFmt("%1",purchReqLine.PurchQty);
                netamt                    = strFmt("%1",purchReqLine.LineAmount);
                sumAmount           = strFmt("%1",amount);
                postDate                 = strFmt("%1",purchReqTable.TransDate);
                unit                         = unitOfMeasure::find(purchReqLine.purchunitofmeasure).Symbol;
                select firstOnly name from ecoResCategory
                    where ecoResCategory.recid == purchReqLine.ProcurementCategory;
                procurementcategory = ecoResCategory.Name;
                linedetails       += strFmt(#Opentablerowdiv + purchReqLine.ItemId + #Closetablediv + Productname +#Closetablediv + procurementcategory +  #Closetablediv + purchqty +  #Closetablediv+ unit+ #Closetablediv+ Unitprice +#Closetablediv+netamt +  #Closetablerowdiv);
            }
            while select Email from sysUserInfo
            join alertUserInfo
                where alertUserInfo.PRPayment == NoYes::Yes
                    && alertUserInfo.id       == sysUserInfo.Id
            {
                batch.parmSenderAddr(#AdminMailID);
                batch.parmEmailAddr("aslam.p@dhanushinfotech.net");//sysUserInfo.Email);
                batch.parmMessageBody(#Header1 + alertUserInfo.Id + #Header2 + #Header3 + alertUserInfo.Id +#Closetablerowdiv + #Header4 + UserInfoHelp::userName(alertUserInfo.Id) +#Closetablerowdiv+ #Header5 + PRid +#Closetablerowdiv + #Header6 + Journalno +#Closetablerowdiv+ #Header7 + postDate +#Closetablerowdiv + #Header8 + sumAmount +#Closetablerowdiv+ #Header9 + #Header10 + linedetails+  #Header9);
                batch.parmSubject(#Subject + PRid);
                batch.run();
            }

            if (sysUserInfolog.Email)
            {
                batch.parmSenderAddr(#AdminMailID);
                batch.parmEmailAddr("raghava.r@dhanushinfotech.net");//sysUserInfolog.Email);
                batch.parmMessageBody(#Header1 + sysUserInfolog.Id + #Header2 + #Header3 + sysUserInfolog.Id +#Closetablerowdiv + #Header4 + UserInfoHelp::userName(sysUserInfolog.Id) +#Closetablerowdiv+ #Header5 + PRid +#Closetablerowdiv + #Header6 + Journalno +#Closetablerowdiv+ #Header7 + postDate +#Closetablerowdiv + #Header8 + sumAmount +#Closetablerowdiv+ #Header9 + #Header10 + linedetails+  #Header9);
                batch.parmSubject(#Subject + PRid);
                batch.run();
            }

            purchReqTableExt.PaymentSent = NoYes::Yes;
            purchReqTableExt.update();
        }
        amount  = 0.0;
        ttsCommit;
    }
    catch (Exception::Error)
    {
        error("An Error occur while trying to send mail");
        ttsAbort;
    }

}

sending mail and create table in ax 2012

public static void sendMail(JournalForm       _journalForm)
{
    InventDim                                  inventDim;
    InventDimParm                          invDimParm;
    InventJournalTrans                     inventJournalTrans;
    EcoResProductParameters         ecoResProductParameters;
    str                                               itemonhand,availphysical;
    AlertUserInfo                            alertUserInfo;
    sysUserInfo                               sysUserInfo;

    SysEmailBatch   batch = new SysEmailBatch();
    #Define.AdminMailID("joseph.waititu@cic.co.ke")
    #define.Opentablerowdiv("<tr><td>")
    #define.Closetablediv("</td><td>")
    #define.Closetablerowdiv("</td></tr>")
    #define.Header1("<h3>Dear ")
    #define.Header2(",</h3><p>Below are the SKUs which have reached  minimum level.</p><table width= 50% border='2' style='border-collapse:collapse'><tr><th>Item Id</th><th>Name</th><th>On hand</th></tr>");
    #define.Header3("</table>")
    #define.Subject("Items Reached Minimum On Hand")

    try
    {
        select firstOnly InventLocationId from ecoResProductParameters;

        while select ItemId,sum(Qty),InventDimId from inventJournalTrans group by ItemId,InventDimId
                where inventJournalTrans.JournalId  == _journalForm.journalTable().JournalId
                          join InventLocationId from inventDim group by InventLocationId
                                where inventDim.InventDimId         ==  inventJournalTrans.InventDimId
                                                   && inventDim.InventLocationId   ==                  ecoResProductParameters.CICInventLocationId
        {
            inventDim.InventLocationId      = ecoResProductParameters.InventLocationId;
            inventDim                       = InventDim::findOrCreate(inventDim);
            invDimParm.initFromInventDim(InventDim::find(inventDim.inventDimId));

            if(inventSum::findSum(inventJournalTrans.ItemId,inventDim,invDimParm).AvailPhysical <= inventTable::find(inventJournalTrans.ItemId).MinimumStockLevel )
            {
                availphysical    = strFmt("%1",inventSum::findSum(inventJournalTrans.ItemId,inventDim,invDimParm).AvailPhysical);
                itemonhand      += strFmt(#Opentablerowdiv + inventJournalTrans.ItemId + #Closetablediv + InventTable::find(inventJournalTrans.ItemId).NameAlias + #Closetablediv + availphysical + #Closetablerowdiv);
            }
        }

        if(itemonhand)
        {
            while select Id,Email from alertUserInfo
                where alertUserInfo.MinimumStockLevel == NoYes::Yes
            {
                select Email from sysUserInfo
                    where sysUserInfo.Id == alertUserInfo.id;
                batch.parmSenderAddr(#AdminMailID);
                batch.parmEmailAddr(sysUserInfo.Email);
                batch.parmMessageBody(#Header1 + alertUserInfo.Id + #Header2 + itemonhand + #Header3);
                batch.parmSubject(#Subject);
                batch.run();
            }
        }
    }
    catch (Exception::Error)
    {
        error("An error occur while sending mail");
    }
}

Integration using ODBC connection in Ax 2012

    SqlStatementExecutePermission            perm;
    EOxegenDSNSetup                                EOxegenDSNSetup;
    EO2MembersCreationLog                     MembersCreationLog;
    LoginProperty                                        loginproperty;
    OdbcConnection                                    odbcconnection;
    Statement                                               statement;
    ResultSet                                                resultset;
    str                                                           myConnectionString,sql,ret,
                                                                   firstName,lastName ,othernames, surName,
                                                                   accountType,customerGroup,mobile,addresscity,
                                                                   addresscountry,addressline,addresscounty,postcode,
                                                                   accountgroup,gin,pin,govId,other,currency,
                                                                   gender,counter,email,status,processed,
                                                                   branchid,eo2customertype, beneficary, jobtitle,
                                                                  dob,integrated,eo2pmtype,partnerNumber, cRMCompany;
    str                                                          taxexempt;
    int64                                                      refrecord;



[SysEntryPointAttribute(false)]
public void processRecords()
{
    select firstOnly SystemDSN,DBUserName,DBPassword,
         SystemDSN,SetServer,SetDatabase from EOxegenDSNSetup;
    myConnectionString = strfmt("Dsn=%1;UID=%2;PWD=%3",EOxegenDSNSetup.SystemDSN,
                             EOxegenDSNSetup.DBUserName,
                             EOxegenDSNSetup.DBPassword);
    loginProperty = new LoginProperty();
    loginProperty.setDSN(EOxegenDSNSetup.SystemDSN);
    loginProperty.setServer(EOxegenDSNSetup.SetServer);
    loginProperty.setDatabase(EOxegenDSNSetup.SetDatabase);
    loginProperty.setOther(myConnectionString);
    odbcConnection = new ODBCConnection(loginProperty);
    if(odbcconnection)
    {
        odbcconnection.ttsbegin();
        sql = strFmt("select top 10 REFRECID, FIRSTNAME, LASTNAME, MIDDLENAME,"
                     +"EMAILADDRESS1, MOBILEPHONE, ADDRESS1_CITY, ADDRESS1_LINE2,"
                     +"ADDRESS1_COUNTRY, ADDRESS1_COUNTY, ADDRESS1_POSTCODE,"
                     +"Account_Group, CURRENCY, GENDER, GIN_OCCUPATION, UAP_PINNUMBER,"
                     +"GOVERNMENTID, UAP_OTHERNAME, STATUS, PROCESSED_TIME, UAP_BRANCHID,"
                     +"EO2_CUSTOMER_TYPE, BENEFICARY, JOBTITLE, DATEOFBIRTH, INTEGRATED,"
                     +"EO2_PM_TYPE,PARTNERNUMBER, CRMCompany from EO2_CUSTOMERS where PARTNERNUMBER = ''");
        perm= new SqlStatementExecutePermission(sql);
        perm.assert();
        statement = odbcconnection.createStatement();
        resultset = statement.executeQuery(sql);
        while(resultset.next())
        {
            refrecord                       = resultset.getInt64(1);
            firstName                     = resultset.getstring(2);
            surName                      = resultset.getstring(3);
            othernames                  = resultset.getstring(4);
            email                            = resultset.getstring(5);
            mobile                          = resultset.getstring(6);
            addresscity                   = resultset.getstring(7);
            addressline                    = resultset.getstring(8);
            addresscountry             = resultset.getstring(9);
            addresscounty               = resultset.getstring(10);
            accountgroup                = resultset.getstring(12);
            currency                       = resultset.getstring(13);
            gender                          = resultset.getstring(14);
            gin                               = resultset.getstring(15);
            pin                               = resultset.getstring(16);
            govId                           = resultset.getstring(17);
            other                            = resultset.getstring(18);
            status                           = resultset.getstring(19);
            processed                    = resultset.getstring(20);
            branchid                      = resultset.getstring(21);
            eo2customertype         = resultset.getstring(22);
            beneficary                   = resultset.getstring(23);
            jobtitle                        = resultset.getstring(24);
            dob                             = resultset.getstring(25);
            integrated                   = resultset.getstring(26);
            eo2pmtype                 = resultset.getstring(27);
            partnerNumber          = resultset.getstring(28);
            cRMCompany          = resultset.getstring(29);
            this.createNewCustomer();
        }
        resultset.close();
        statement.close();
        odbcconnection.ttscommit();
        info(strFmt("Successfully processed %1 records.",counter));
    }
    else
    {
        error("Failed to logon to the Database through ODBC");
    }
}
--------------------------------------------------------------------------------------------------------------------------
                                     second one
-------------------------------------------------------------------------------------------------------------------------
 
[SysEntryPointAttribute(false)]
public void processRecords()
{
    SqlStatementExecutePermission perm;
    EOxegenDSNSetup                          EOxegenDSNSetup;
    LoginProperty                                   loginProperty;
    OdbcConnection                               odbcConnection;
    Statement                                          statement;
    ResultSet                                           resultSet;
    str                                                       sql, myConnectionString;
    int                                                      counter;

    select firstOnly SystemDSN,DBUserName,DBPassword,SystemDSN,
        SetServer,SetDatabase from EOxegenDSNSetup;
    myConnectionString=strfmt("Dsn=%1;UID=%2;PWD=%3",EOxegenDSNSetup.SystemDSN,EOxegenDSNSetup.DBUserName,EOxegenDSNSetup.DBPassword);
    loginProperty = new LoginProperty();
    loginProperty.setDSN(EOxegenDSNSetup.SystemDSN);
    loginProperty.setServer(EOxegenDSNSetup.SetServer);
    loginProperty.setDatabase(EOxegenDSNSetup.SetDatabase);
    loginProperty.setOther(myConnectionString);
    odbcConnection = new ODBCConnection(loginProperty);

    if (odbcConnection)
    {
        sql = "SELECT * FROM EO2_CITY_MASTER;";
        perm = new SqlStatementExecutePermission(sql);
        perm.assert();
        statement = odbcConnection.createStatement();
        resultSet = statement.executeQuery(sql);
        while (resultSet.next())
        {
            info(strFmt('%1-%2',resultSet.getString(1),resultSet.getString(2)));
            counter++;
        }
        resultSet.close();
        statement.close();
        info(strFmt("Successfully processed %1 records.",counter));
    }
    else
    {
        error("Failed to log on to the database through ODBC.");
    }
}
-----------------------------------------------------------------------------------------------------------------------
                                     Get Country codes using ODBC
-----------------------------------------------------------------------------------------------------------------------
[SysEntryPointAttribute(false)]
public void processRecords()
{
    SqlStatementExecutePermission     perm;
    EOxegenDSNSetup                         EOxegenDSNSetup;
    LoginProperty                                  loginProperty;
    OdbcConnection                              odbcConnection;
    Statement                                         statement;
    ResultSet                                          resultSet;
    str                                                     sql, myConnectionString;
    int                                                    counter;

    select firstOnly SystemDSN,DBUserName,DBPassword,SystemDSN,
        SetServer,SetDatabase from cicEOxegenDSNSetup;
    myConnectionString=strfmt("Dsn=%1;UID=%2;PWD=%3",cicEOxegenDSNSetup.SystemDSN,cicEOxegenDSNSetup.DBUserName,cicEOxegenDSNSetup.DBPassword);
    loginProperty = new LoginProperty();
    loginProperty.setDSN(cicEOxegenDSNSetup.SystemDSN);
    loginProperty.setServer(cicEOxegenDSNSetup.SetServer);
    loginProperty.setDatabase(cicEOxegenDSNSetup.SetDatabase);
    loginProperty.setOther(myConnectionString);
    odbcConnection = new ODBCConnection(loginProperty);

    if (odbcConnection)
    {
        sql = "SELECT COUNTRY_CD ,COUNTRY_NAME FROM COUNTRY_CODES;";
        perm = new SqlStatementExecutePermission(sql);
        perm.assert();
        statement = odbcConnection.createStatement();
        resultSet = statement.executeQuery(sql);
        while (resultSet.next())
        {
            info(strFmt('%1-%2',resultSet.getString(1),resultSet.getString(2)));
            counter++;
        }
        resultSet.close();
        statement.close();
        info(strFmt("Successfully processed %1 records.",counter));
    }
    else
    {
        error("Failed to log on to the database through ODBC.");
    }
}



----------------------------------------------------------------------------------------------------------------------
              Update Customer
----------------------------------------------------------------------------------------------------------------------

public void updateCustomerAccount(RefRecId  refRecId, Custaccount accountnum)
{
    SqlStatementExecutePermission         fixedAssetTransferUpdate;
    Statement                                             statementTransferUpdate;
    ResultSet                                              resultSetTableTransferUpdate;
    OdbcConnection                                  odbcConnection3;
    str                                                         sql3;


    odbcConnection3 = new ODBCConnection(loginProperty);
    statementTransferUpdate = odbcConnection3.createStatement();
    sql3 = strFmt("UPDATE EO2_CUSTOMERS set  PARTNERNUMBER ='"+strfmt('%1',accountnum)+"' WHERE EO2_CUSTOMERS.REFRECID = '"+strfmt('%1',refRecId)+"'");
    fixedAssetTransferUpdate  = new SqlStatementExecutePermission(sql3);
    fixedAssetTransferUpdate.assert();
    statementTransferUpdate.executeUpdate(sql3);

    resultSetTableTransferUpdate = statementTransferUpdate.executeQuery(sql3);
    statementTransferUpdate.close();