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, true, false);
     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();
}