Sunday, June 14, 2015

Retail Product Hierarchy by item in AX 2012

// To Get Retail product hierarchy by Item in Job x++

static void  San_RetailItemHierarchy(Args _args)
{
    RecId                   localCatgory;
    RecId                   localHirarcghy;
    EcoResProductCategory   ecoResProdCategory;
    EcoResCategory          resCategory, loopresCategory;
    int                     i , level;
    ItemId                  _Itemid = "ItemNumber";
    Name                    Brand,Category,Grp,Division,SubGroup;
Name    BrandFN, CategoryFN,  DivisionFN,  GrpFN,  SubGroupFN;

    name cat [7];
    name catFName [7];

    ;
    for (i =1; i<= 7; i++)
    {
        cat[i] = "";
        catFname[i] = "";
    }
    ecoResProdCategory = EcoResProductCategory::findByItemIdCategoryHierarchyRole(_Itemid, EcoResCategoryNamedHierarchyRole::Retail);
    locCatgory =  ecoResProdCategory.Category;
    locHirarcghy = ecoResProdCategory.CategoryHierarchy;

    resCategory = EcoResCategory::find(locCatgory);
    level =  resCategory.Level;

    if (level > 2)
    {
    cat[level] = resCategory.Name;

    level --;

    for (i = level;  i > 2; i--)
    {
        loopCategory = resCategory.getParent();
        cat [i] = loopCategory.Name;
        catFName[i] =  EcoResCategoryTranslation::find(loopCategory.RecId, "en-us").FriendlyName;
        resCategory = loopCategory;
    }
    }
    Brand = cat[3];
    Category = cat [4];
    Division = cat [5];
    Grp = cat [6];
    SubGroup =cat  [7];

    BrandFN = catFName[3];
    CategoryFN =catFName[4];
    DivisionFN = catFName[5];
    GrpFN = catFName[6];
    SubGroupFN = catFName[7];
    info(strFmt("%1 \n Brand - %2 \n Category - %3 \n Division - %4 \n Group - %5 \n Sub group - %6",_Itemid,Brand,Category,Division,Grp,SubGroup));
 info(strFmt("%1 \n Brand - %2 \n Category - %3 \n Division - %4 \n Group - %5 \n Sub group - %6",_Itemid,BrandFN ,CategoryFN ,DivisionFN ,GrpFN ,SubGroupFN ));
 
}

Wednesday, April 29, 2015

Add new button in existing form AX

//  Add new button in existing form AX

private void San_addAboutButton()
{
FormActionPaneControl actionPane;
FormActionPaneTabControl actionPaneTab;
FormCommandButtonControl cmdAbout;
FormButtonGroupControl btngrp;
#define.taskAbout(259)
actionPane = this.design().controlNum(1);
if (!actionPane ||
!(actionPane is FormActionPaneControl) ||
actionPane.style() == ActionPaneStyle::Strip)
{
return;
}
actionPaneTab = actionPane.controlNum(1);
if (!actionPaneTab ||
!(actionPaneTab is FormActionPaneTabControl))
{
return;
}
btngrp = actionPaneTab.addControl(
FormControlType::ButtonGroup, 'ButtonGroup');
btngrp.caption("About");
cmdAbout = btngrp.addControl(
FormControlType::CommandButton, 'About');
cmdAbout.command(#taskAbout);
cmdAbout.imageLocation(SysImageLocation::EmbeddedResource);
cmdAbout.normalImage('412');
cmdAbout.big(NoYes::Yes);
cmdAbout.saveRecord(NoYes::No);
}

RUn Method

this.San_addAboutButton()

Form Creation through Code in ax .. For Dynamic Form Creation

// Form Creation through Code in ax .. For Dynamic Form Creation

static void DynamicFormAX(Args _args)
{
    DictTable                           dictTable;
    Form                                form;
    FormBuildDesign                     design;
    FormBuildDataSource                 dataSource;
    FormBuildActionPaneControl          actionPane;
    FormBuildActionPaneTabControl       actionPaneTab;
    FormBuildButtonGroupControl         buttonngroup1;
    FormBuildButtonGroupControl         buttonngroup2;
    FormBuildCommandButtonControl       cmdNew;
    FormBuildCommandButtonControl       cmdDel;  
    FormBuildMenuButtonControl          menubuttonPosting;
    FormBuildFunctionButtonControl      menuFuncbuttonPosting;
    FormBuildFunctionButtonControl      menuFuncbuttonForecast;
    FormBuildGridControl grid;
    FormBuildGroupControl grpBody;
    Args args;
    FormRun formRun;
    #Task
   
    dictTable = new DictTable(tableNum(CustGroup));
    form = new Form();
    form.name("CustGroupDynamic");
    dataSource = form.addDataSource(dictTable.name());
    dataSource.table(dictTable.id());
    design = form.addDesign('Design');
    design.caption("Customer groups");
    design.style(FormStyle::SimpleList);
    design.titleDatasource(dataSource.id());
    actionPane = design.addControl(FormControlType::ActionPane, 'ActionPane');
    actionPane.style(ActionPaneStyle::Strip);
    actionPaneTab = actionPane.addControl(FormControlType::ActionPaneTab, 'ActionPaneTab');
    buttonngroup1 = actionPaneTab.addControl(FormControlType::ButtonGroup, 'NewDeleteGroup');
    buttonngroup2 = actionPaneTab.addControl(FormControlType::ButtonGroup, 'ButtonGroup');
    cmdNew = buttonngroup1.addControl(FormControlType::CommandButton, 'NewButton');
    cmdNew.buttonDisplay(FormButtonDisplay::TextAndImageLeft);
    cmdNew.normalImage('11045');
    cmdNew.imageLocation(SysImageLocation::EmbeddedResource);
    cmdNew.primary(NoYes::Yes);
    cmdNew.command(#taskNew);
    cmdDel = buttonngroup1.addControl(FormControlType::CommandButton, 'NewButton');
    cmdDel.text("Delete");
    cmdDel.buttonDisplay(FormButtonDisplay::TextAndImageLeft);
    cmdDel.normalImage('10121');
    cmdDel.imageLocation(SysImageLocation::EmbeddedResource);
    cmdDel.saveRecord(NoYes::Yes);
    cmdDel.primary(NoYes::Yes);
    cmdDel.command(#taskDeleteRecord);
    /*menubuttonPosting = buttonngroup2.addControl(FormControlType::MenuButton, 'MenuButtonPosting');
    menubuttonPosting.helpText("Set up related data for the group.");
    menubuttonPosting.text("Setup");
    menuFuncbuttonPosting = menubuttonPosting.addControl(FormControlType::MenuFunctionButton, 'Posting');
    menuFuncbuttonPosting.text('Item posting');
    menuFuncbuttonPosting.saveRecord(NoYes::No);
    menuFuncbuttonPosting.dataSource(dataSource.id());
    menuFuncbuttonPosting.menuItemName(menuitemDisplayStr(InventPosting));
    menuFuncbuttonForecast = buttonngroup2.addControl(FormControlType::MenuFunctionButton, 'SalesForecast');
    menuFuncbuttonForecast.text('Forecast');
    menuFuncbuttonForecast.saveRecord(NoYes::No);
    menuFuncbuttonForecast.menuItemName(menuitemDisplayStr(ForecastSalesGroup));*/
    grpBody = design.addControl(FormControlType::Group, 'Body');
    grpBody.heightMode(FormHeight::ColumnHeight);
    grpBody.columnspace(0);
    grpBody.style(GroupStyle::BorderlessGridContainer);
    grid = grpBody.addControl(FormControlType::Grid, "Grid");
    grid.dataSource(dataSource.name());
    grid.widthMode(FormWidth::ColumnWidth);
    grid.heightMode(FormHeight::ColumnHeight);
    grid.addDataField(dataSource.id(), fieldNum(CustGroup,CustGroup));
    grid.addDataField(dataSource.id(), fieldNum(CustGroup,Name));
    grid.addDataField(dataSource.id(), fieldNum(CustGroup,PaymTermId));
    grid.addDataField(dataSource.id(), fieldnum(CustGroup,ClearingPeriod));
    grid.addDataField(dataSource.id(), fieldNum(CustGroup,BankCustPaymIdTable));
    grid.addDataField(dataSource.id(), fieldNum(CustGroup,TaxGroupId));
    args = new Args();
    args.object(form);
    formRun = classFactory.formRunClass(args);
    formRun.init();
    formRun.run();
    formRun.detach();
}

Get Default Dimensions value For Vend Cust Item

// Get Default Dimensions value For Vend Cust Item

static void San_GetDefaultDimensionsForVendCustItem(Args _args)
{
    VendTable                       vendTable;
    InventTable                     inventTable;
    CustTable                       custTable;
    DimensionAttributeValueSet      dimAttrValueSet;
    DimensionAttributeValueSetItem  dimAttrValueSetItem;
    DimensionAttributeValue         dimAttrValue;
    DimensionAttribute              dimAttr;
    Common                          dimensionValueEntity;
    ;
    //vendTable = VendTable::find('3008');
    //inventTable = InventTable::find('1001');
    custTable = CustTable::find('1102');
    //dimAttrValueSet = DimensionAttributeValueSet::find(vendTable.DefaultDimension);
    //dimAttrValueSet = DimensionAttributeValueSet::find(inventTable.DefaultDimension);
    dimAttrValueSet = DimensionAttributeValueSet::find(custTable.DefaultDimension);
    while select dimAttrValueSetItem
        where   dimAttrValueSetItem.DimensionAttributeValueSet   == dimAttrValueSet.RecId
    {
        dimAttrValue        = DimensionAttributeValue::find(dimAttrValueSetItem.DimensionAttributeValue);
        dimAttr             = DimensionAttribute::find(dimAttrValue.DimensionAttribute);
        dimensionValueEntity = DimensionDefaultingControllerBase::findBackingEntityInstance(curext(),dimAttr,dimAttrValue.EntityInstance);
        info(dimAttr.Name + ' ' + dimAttrValue.getValue());
    }
}

Thursday, March 19, 2015

Financial Dimension value in lookup

At times you'll be asked to bring the dimension values in lookup, which might be pretty difficult task.

Here in this post i have created a class using which you could easily bring the financial dimension values in lookup 

AX 2012
class DImensionLookupByName_Sa
{
}

-->>then create a method 

Public static client void lookupDimension(FormStringControl stringControl, Name dimensionName)
{
    Args                    args;
    FormRun                 lookupFormRun;
    DimensionAttribute      dimAttribute;

    if (_stringControl != null)
    {
        args = new Args();
        args.name(formStr(DimensionDefaultingLookup));
        args.lookupValue(_stringControl.text());
        args.caller(_stringControl);        
        dimAttribute = DimensionAttribute::findByName(_dimensionName);
        args.lookupField(dimAttribute.ValueAttribute);
        args.record(dimAttribute);        
        lookupFormRun = classfactory.formRunClass(args);
        lookupFormRun.init();
        _stringControl.performFormLookup(lookupFormRun);
    }
}



Here the two parameters that you are supposed to pass is the form control and the dimension's name which you wanna bring in the lookup..(say businessunit,costcenter,customcostcenter and so on.. )

so, 

create a form with a stringedit control and then , create the one line code in the lookup method 

DImensionLookupByName_Sa::lookupDimension(this,"Businessunit");

you will be able to see the dimension values of businessunit in the lookup.. 

or else, 

You could create a form with two stingedit controls say stringedit1 and stringedit2.

and .. in the stringedit1 use this in the lookup method.. 

{
   Query           query;

SysTableLookup  sysTableLookup;

super();

sysTableLookup = SysTableLookup::newParameters(tableNum(DimensionAttribute), this);

sysTableLookup.addLookupfield(fieldNum(DimensionAttribute, Name));

query = new Query();

query.addDataSource(tableNum(DimensionAttribute));

sysTableLookup.parmQuery(query);

sysTableLookup.performFormLookup();
}



This would bring all the dimensionattributes name in the lookup 

and then in the second field's lookup enter the following code

DImensionLookupByName_Sa::lookupDimension(this,stringedit1.text());

this would bring the values of the dimension selected in stringedit1.

Alternate Logic in D365FO X++:

public static void DimensionValueLookup(
        FormStringControl   _dimensionValueControl,
        Name                _localizedName,
        boolean             _promptErrorMessage = false)
    {
        Query                   query = new Query();
        SysTableLookup          sysTableLookup;
        QueryBuildDataSource    qbds;

        DimensionAttribute      dimensionAttribute;
        RecId                   dimensionAttributeId;
        DataAreaId              dataAreaId = curext();

        if (_localizedName)
        {
            dimensionAttribute      = DimensionAttribute::findByLocalizedName(_localizedName, false, currentUserLanguage());
            dimensionAttributeId    = dimensionAttribute.RecId;
        }

        if (dimensionAttributeId)
        {
            sysTableLookup = SysTableLookup::newParameters(DimensionCache::instance().dimensionAttributeBackingTable(dimensionAttributeId), _dimensionValueControl);

            sysTableLookup.addLookupfield(dimensionAttribute.ValueAttribute);
            LedgerDimensionTranslationLookupHelper::addLookupTranslation(sysTableLookup, dimensionAttributeId);
            sysTableLookup.addSelectionField(dimensionAttribute.NameAttribute);

            changeCompany(dataAreaId)
            {
                qbds = query.addDataSource(DimensionCache::instance().dimensionAttributeBackingTable(dimensionAttributeId));
                qbds.addOrderByField(DimensionCache::instance().dimensionAttributeValueField(dimensionAttributeId));
                DimensionAttribute::restrictQueryToCategorizedValues(qbds, dimensionAttributeId);
            }

            sysTableLookup.parmQuery(query);
            sysTableLookup.performFormLookup();
        }
        else if (_promptErrorMessage)
        {
            //Please choose a value for "Dimension type" first!
            checkFailed("@GLS100015");
        }
    }


or

public static void lookupDimensionValues(DimensionAttribute _dimensionAttribute, FormStringControl _formStringControl, CompanyId _companyId = curext(), DimensionLookupParameters _lookupParameters = null)
    {
        Args        args;
        FormRun     formRun;

        Debug::assert(_formStringControl != null);
        Debug::assert(_companyId != '');

        if (!_lookupParameters)
        {
            _lookupParameters = new DimensionLookupParameters();
        }

        if (_lookupParameters.parmFilterDate() == dateNull())
        {
            _lookupParameters.parmFilterDate(DateTimeUtil::getToday(DateTimeUtil::getUserPreferredTimeZone()));
        }

        changecompany(_companyId)
        {
            args = new Args();
            args.name(formStr(DimensionLookup));
            args.callerFormControl(_formStringControl);
            args.caller(_formStringControl.formRun());
            args.lookupValue(_formStringControl.text());

            args.lookupField(_dimensionAttribute.ValueAttribute);
            args.record(_dimensionAttribute);
            args.parmObject(_lookupParameters);

            formRun = classfactory.formRunClass(args);
            formRun.init();

            _formStringControl.performFormLookup(formRun);
        }
    }

Monday, March 16, 2015

Insert PO with multiple lines from excel

Just like PR if you want to create PO with multiple lines use this code snippet..

create an excel with 

Column 1 -> vend account 
Column 2 -> ItemID
Column 3 -> Quantity
Column 4 -> Price 
Column 5 -> Purchid

If you need multiple lines , create multiple excel rows with same PurchID


static void POEXCEL(Args _args)
{
    Dialog                  dialog;
    DialogField             dialogField;
    FilenameOpen            filename, Filename2;

    PO_temp                 potemp,potempline;
    PurchTable              purchtable;
    PurchLine               purchline;

    PurchFormLetter purchFormLetter;
    SysExcelApplication application;
    SysExcelWorkbooks workbooks;
    SysExcelWorkbook workbook;
    SysExcelWorksheets worksheets;
    SysExcelWorksheet worksheet;
    SysExcelCells cells;
    COMVariantType type;
    FileIOPermission        permission;
    int row = 0;
    str itemid,name,purchid;
    real price,qty;
     #File

     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 "";
    }


     //importing from excel
    dialog = new Dialog("Posting Payment Journal");
    dialogField = dialog.addField(ExtendedTypeStr("FilenameOpen"),"Source file");



    if (dialog.run())
   {
     filename = dialogField.value();
     permission = new fileIOpermission(filename,"RW");
     permission.assert();
     application = SysExcelApplication::construct();
     workbooks = application.workbooks();
     try
    {
        workbooks.open(filename);
    }
    catch (Exception::Error)
    {
        throw error("File not found");
    }
    workbook = workbooks.item(1);
    worksheets = workbook.worksheets();
    worksheet = worksheets.itemFromNum(1);
    cells = worksheet.cells();

       delete_from potemp;
         do
    {
    //Incrementing the row line to next Row
    row++;

    //row++;
    name        =  COMVariant2Str(cells.item(row,1).value());
    itemid      =  COMVariant2Str(cells.item(row,2).value());
    qty         =  cells.item(row,3).value().double();
    price       =  cells.item(row,4).value().double();
    purchid  =   COMVariant2Str(cells.item(row,5).value());

        potemp.Name       = name;
        potemp.ItemId     = itemid;
        potemp.PurchQty   = qty;
        potemp.PurchPrice = price;
        potemp.PurchId = purchid;
        potemp.insert();
                //row++;
            //name1 = COMVariant2Str(cells.item(j+1,1).value());

          type = cells.item(row+1, 1).value().variantType();

     }

       //info(strFmt("%1,%2",empId,salary));
      while (type != COMVariantType::VT_EMPTY);
      application.quit();
    }
    while select potemp group by potemp.PurchId,potemp.Name
    {
purchtable.initValue();
purchtable.PurchId = potemp.PurchId;
purchtable.OrderAccount = potemp.name;
purchtable.initFromVendTable();
//if (!purchtable.validateWrite())
//{
//throw Exception::Error;
//}
purchtable.insert();

    while select potempline where potempline.PurchId == potemp.PurchId
    {
        ttsBegin;
    purchLine.initFromPurchTable(purchTable);
    purchLine.ItemId = potempline.ItemId;
    purchLine.PurchQty = potempline.PurchQty;
    purchLine.PurchPrice = potempline.PurchPrice;
    purchLine.createLine(true, true, true, true, true, true);
    ttsCommit;
    purchLine.clear();
    }
    purchFormLetter = PurchFormLetter::construct(DocumentStatus::PurchaseOrder);
    purchFormLetter.update(purchTable, strFmt("Inv_%1", purchTable.PurchId));

    //Posting PO Invoice
    purchFormLetter = PurchFormLetter::construct(DocumentStatus::Invoice);
    purchFormLetter.update(purchTable, strFmt("Inv_%1", purchTable.PurchId));

    purchtable.clear();
    }
}

Import Purchase Requisition From Excel with multiple Lines

Here am giving the code to Import PR from excel and the same PR could have multiple lines, Create an excel sheet with columns like

column 1 -> name OF PR
column 2 -> Item ID
column 3 -> Quantity 
column 4 -> Price 
column 5 -> purchreqID

if you need multiple lines just create multiple rows with same purchreqID

and use the following code snippet..

static void PREXCEL(Args _args)
{
    Dialog                  dialog;
    DialogField             dialogField;
    FilenameOpen            filename, Filename2;
    PR_temp                 prtemp,prtemplines;

    SysExcelApplication application;
    SysExcelWorkbooks workbooks;
    SysExcelWorkbook workbook;
    SysExcelWorksheets worksheets;
    SysExcelWorksheet worksheet;
    SysExcelCells cells;
    COMVariantType type;
    PurchReqTable   purchReqTable;
    PurchReqLine    purchReqLine;
    ProjTable       projTable = projTable::find("10002");
    SalesLine       salesLine;// = SalesLine::findInventTransId("10002");
    FileIOPermission        permission;
    int row = 0;
    int j = 0;
    // if the excel has the header
    //parameters
    str itemid,name,purchreqid;
    real price,qty;


    #File

     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 "";
    }




    //importing from excel
    dialog = new Dialog("Posting Payment Journal");
    dialogField = dialog.addField(ExtendedTypeStr("FilenameOpen"),"Source file");





    if (dialog.run())
   {
     filename = dialogField.value();
     permission = new fileIOpermission(filename,"RW");
     permission.assert();
     application = SysExcelApplication::construct();
     workbooks = application.workbooks();
     try
    {
        workbooks.open(filename);
    }
    catch (Exception::Error)
    {
        throw error("File not found");
    }
    workbook = workbooks.item(1);
    worksheets = workbook.worksheets();
    worksheet = worksheets.itemFromNum(1);
    cells = worksheet.cells();
      //insert without class
   // vendTable = VendTable::find("3114");


delete_from prtemp;

     do
    {
    //Incrementing the row line to next Row
    row++;

    //row++;
    name        =  COMVariant2Str(cells.item(row,1).value());
    itemid      =  COMVariant2Str(cells.item(row,2).value());
    qty         =  cells.item(row,3).value().double();
    price       =  cells.item(row,4).value().double();
    purchreqid  =   COMVariant2Str(cells.item(row,5).value());

        prtemp.Name       = name;
        prtemp.ItemId     = itemid;
        prtemp.PurchQty   = qty;
        prtemp.PurchPrice = price;
        prtemp.PurchReqId = purchreqid;
        prtemp.insert();
                //row++;
            //name1 = COMVariant2Str(cells.item(j+1,1).value());

          type = cells.item(row+1, 1).value().variantType();

     }

       //info(strFmt("%1,%2",empId,salary));
      while (type != COMVariantType::VT_EMPTY);
      application.quit();

    }

     while select  prtemp group by prtemp.PurchReqId ,prtemp.Name
        {


    purchReqTable.clear();
    purchReqTable.initValue();
    purchReqTable.PurchReqId = prtemp.PurchReqId;
    purchReqTable.PurchReqName = prtemp.Name;
    purchReqTable.ProjId = projTable.ProjId;
    purchReqTable.ProjIdDataArea = projTable.dataAreaId;
    purchReqTable.insert();
            while select prtemplines where prtemplines.PurchReqId == prtemp.PurchReqId
            {


    purchReqLine.clear();
    purchReqLine.initValue();
    purchReqLine.initFromPurchReqTable(purchReqTable);
    purchReqLine.ItemId = prtemplines.ItemId;//salesLine.ItemId;
    salesLine = SalesLine::findInventTransId(prtemplines.ItemId);
    purchReqLine.InventDimId = salesLine.InventDimId;
    purchReqLine.PurchQty =  prtemplines.PurchQty;
    purchReqLine.PurchPrice = prtemplines.PurchPrice;

    //purchReqLine.ActivityNumber = 'AO-3456789';//salesLine.ActivityNumber;
    purchReqLine.BuyingLegalEntity = CompanyInfo::find().RecId;
    purchReqLine.InventDimIdDataArea = curext();//salesLine.dataAreaId;
    purchReqLine.initFromProjTable(projTable);
    purchReqLine.insert();
            }
        }

}

Thursday, February 5, 2015

To create a new employee.

As you could see in the client, the basic there are only five basic fields to create a new employee and the rest would be filled in thee next page,

Using this code snippet you could create those basic fields and hence a new employee would be created.

    CompanyInfo                             companyInfo;
    HcmEmploymentRecId                      newEmploymentRecId;
    ValidFromDateTime                       employmentStartDateTime;
    ValidToDateTime                         employmentEndDateTime;
    HcmWorker                               newHcmWorker;
    DirPerson                               dirPerson;
    DirPersonName                           dirPersonName;
    HcmEmploymentType                       hcmEmploymentType = HcmEmploymentType::Employee;
    NumberSeq                               numberSeqPersonnelNum;
    HcmPersonPrivateDetails                 HcmPersonPrivateDetails;
    //HcmEmployment                           hcmEmployment;
    HcmEmploymentType                         hcmEmployment;
    HcmWorkerTitle  hcmWorkerTitle;

    DirParty                        dirparty;
    DirPartyContactInfoView         contactView;
    HcmPersonDetails                persondetails;
    HcmPersonIdentificationNumber   hcmPersonIdentificationNumber;
 
    utcdatetime                     _validFrom = DateTimeUtil::utcNow();

    Struct              struct;
    container           ledgerDimension;
    DimensionDefault    DimensionDefault;
    int                 k;


    TransDate       HireDate,DOB;
    HcmPersonID     Employeecode;
    str             FirstName,Title,MobilePhone,email,MaritalStatus,NationalityCode,NationalityName,PaymentMode,MiddleName,LastName;

    str             DepartmentCode,DepartmentName,SubDivisionCode,SubDivisionName,DivisionCode,DivisionName ,SectorCode, SectorName;
    str             DesignationCode,DesignationName,SponsorCode,SponsorDesc,MOLNo,PASSPORTNUMBER,Gender,BloodGroup,ReligionCategory,EmployeeCategory,Emiratization;
    ;
    Employeecode    = "0005292";  
    FirstName       = "Aravind";
    MiddleName      = "";
    LastName        = "Swamy";
companyInfo = companyInfo::find();

    newHcmWorker = HcmWorker::findByPersonnelNumber(Employeecode);

    if(! newHcmWorker)
    {
        employmentStartDateTime = datetobeginUtcDateTime(HireDate, DateTimeUtil::getUserPreferredTimeZone());
        employmentEndDateTime   = DateTimeUtil::applyTimeZoneOffset(DateTimeUtil::maxValue(), DateTimeUtil::getUserPreferredTimeZone());

        dirPersonName.FirstName     = FirstName;
        dirPersonName.MiddleName    = Middlename;
        dirPersonName.LastName      = LastName;
        newHcmWorker = HcmWorker::find(HcmWorkerTransition::newCreateHcmWorker(dirPersonName
                                                                               , Employeecode
                                                                               , companyInfo.RecId
                                                                               , hcmEmploymentType
                                                                               , employmentStartDateTime
                                                                               , employmentEndDateTime));
    }
    else
    {

        dirPersonName               = DirPersonName::find(newHcmWorker.Person,true);
        dirPersonName.FirstName     = FirstName;
        dirPersonName.MiddleName    = Middlename;
        dirPersonName.LastName      = LastName;
        dirPersonName.update();
    }

Tuesday, February 3, 2015

Validation For contract parameter value at run time in ax 2012

// Validate Method For contract parameter value at run time in ax 2012

class ClassName implements SysOperationValidatable
{
    TransDate   fromdate;
    TransDate   ToDate;
}

public boolean validate()
{
    boolean             condition = true;

    if (!fromdate)
    {
        condition = checkFailed("From Date should be entered");
    }

    if (!ToDate)
    {
        condition = checkFailed("To Date should be entered");
    }

    if (condition && (fromDate > ToDate))
    {
        condition = checkFailed(strfmt("From Date should be less than or equal to To Date", date2StrUsr(fromDate, DateFlags::FormatAll), date2StrUsr(toDate, DateFlags::FormatAll)));
    }

    return condition;
}

Currency Converter through x++

// Currency Converter through x++

static void CurrencyConverter(Args _args)
{
    CurrencyExchangeHelper currencyExchangeHelper;
    CurrencyCode transCurrency = 'SAR';
    AmountCur amountCur = 500.00;
    AmountMst amountMST,amount;

    currencyExchangeHelper = CurrencyExchangeHelper::newExchangeDate(Ledger::current(),01\01\2014);
    amountMST = currencyExchangeHelper.calculateTransactionToAccounting(transCurrency, amountCur ,true);
    amount = currencyExchangeHelper.calculateCurrencyToCurrency("USD" ,transCurrency,amountCur,true);
    info(strFmt("%1",amountMST));
    info(strFmt("%1",amount));
 
    //ExchangeRateHelper  excRateHelper;
    //TransDate           todate = mkDate(01,12,2006);
    //CurrencyCode        transactionCur = "EUR";
    //CurrencyExchangeRate    exchangeRate;
    //;
    //excRateHelper = ExchangeRateHelper::newExchangeDate(Ledger::current(),transactionCur,todate);
    //exchangeRate = excRateHelper.getExchangeRate1();
    //info(num2str(exchangeRate/100,2,2,1,1));
}

Export label custom content

 GRID => Properties "Export Label" => "SalesReportMexico" To get download file with custom naming.