Search This Blog

Thursday, July 26, 2012

Data Migration Framework for AX2012 was released.


Data Migration Framework beta for AX2012  was released.

Please go through about this in the following link and you can download the setup


Tuesday, July 24, 2012

Import Ax2012 Routes from CSV

We are importing route  from CSV.
We are dealing with the following tables for importing routes.

 RouteTable; RouteVersion,  Route,   RouteOpr .

For any item there must be only one RouteVersion record per item.So before importing we have to find whether routeversion exists or not.

There is 1:1 relation between RouteTable and RouteVersion records during the import.

If the RouteVersion record exists, then the RouteTable record must exist as well and we should not be created.

Class declaration


class krishh_ImportRoute 
{
    //Define your csv file column name with positions
    #define.RouteTable_Name_ColumnNum(1)
    #define.RouteVersion_ItemId_ColumnNum(2)
    #define.Route_OprId_ColumnNum(3)
    #define.Route_OprNum_ColumnNum(4)
    #define.Route_OprNumNext_ColumnNum(5)
    #define.RouteOpr_ProcessTime_ColumnNum(6)
    #define.RouteOpr_RouteGroupId_ColumnNum(7)
    #define.RouteOpr_RouteType_ColumnNum(8)
    #define.RouteOpr_SetupTime_ColumnNum(9)
    #define.RouteOpr_ToHours_ColumnNum(10)
    #define.RouteOpr_WrkCtrIdCost_ColumnNum(11)
    #define.WrkCtrActivityResourceRequirement_WrkCtrId_ColumnNum(12)

    RouteTable      routeTable;
    RouteVersion    routeVersion;
    Route           route;
    RouteOpr        routeOpr;
    ItemId          itemIdRouteVersion;
    NumberSeq       numberSeq;
}
// execute the route imports here container is the values that we read from CSV file.

public void run(container _item)
{
    ttsBegin;
    this.initRouteVersion(_item);
    this.createRouteTable(_item);
    this.createRoute(_item);
    this.createRouteOpr(_item);
    this.createWrkCtrActivity(_item);
    ttsCommit;
}
protected void new()
{
    ;
    numberSeq       =   RouteTable::numberSeq(false,true);
}

protected void initRouteVersion(container _conLine)
{
    itemIdRouteVersion  =   conPeek(_conLine,
                                              #RouteVersion_ItemId_ColumnNum);

    // There must be only one RouteVersion record per item
    select firstOnly routeVersion
        where routeVersion.ItemId == itemIdRouteVersion;
}
protected void createRouteTable(container _conLine)
{
    ;
    if(routeVersion.RecId)
    {
        routeTable  =   RouteTable::find(routeVersion.RouteId);
        // There is always 1:1 relation betwean RouteTable and RouteVersion records during the import.
        // If the RouteVersion record exists, then the RouteTable record must exist as well and should not be created.
        return;
    }
    // If it is a new route, then update the last one.
    if(routeTable.RecId     &&
       !routeVersion.RecId)
    {
        this.updateLastRoute();
    }
    routeTable.clear();
    routeTable.initValue();
    routeTable.CheckRoute   =   NoYes::Yes;
    // Approved
    routeTable.Approved     =   NoYes::Yes;
    // Approver
    routeTable.Approver     =   "krishh"
    // Name
    routeTable.Name         =   conPeek(_conLine,
                                                  #RouteTable_Name_ColumnNum);
    // RouteId
    routeTable.RouteId      =   numberSeq.num();
    routeTable.insert();
}
protected void createRouteVersion(container _conLine)
{
    InventDim           inventDim;

    if(routeVersion.RecId)
    {
        return;
    }
    routeVersion.clear();
    routeVersion.initValue();
    // Active
    routeVersion.Active         =   NoYes::Yes;
    // Approved
    routeVersion.Approved       =   NoYes::Yes;
    // Approver
    routeVersion.Approver       =   "Krishh";
    // FromDate
    routeVersion.FromDate       =   dateNull();
    // ItemId
    routeVersion.ItemId         =   itemIdRouteVersion;
    // RouteId
    routeVersion.RouteId        =   routeTable.RouteId;
    // InventDimId
    inventDim.clear();
    inventDim.InventSiteId      =   InventTable::find(routeVersion.ItemId).inventInventSiteId();
    routeVersion.InventDimId    =   InventDim::findOrCreate(inventDim).inventDimId;
    routeVersion.insert();
}


protected void createRoute(container _conLine)
{
   Route routeFieldList;
   ;
   route.clear();
   route.initValue();
   route.RouteId = routeTable.RouteId;
   route.OprId =Conpeek(_conLine,#Route_OprId_ColumnNum);
   route.OprNum = Conpeek(_conLine,#Route_OprNum_ColumnNum);
   route.OprNumNext = Conpeek(_conLine,#Route_OprNumNext_ColumnNum);

   select RecId from routeFieldList where routeFieldList.RouteId == route.RouteId &&                routeFieldList.OprNum == route.OprNum && routeFieldList.OprPriority == route.OprPriority;

        if(routeFieldList.RecId)         {

              // Do not create if it already exists.
                     return;          }
   route.insert();
}


protected void createRouteOpr(container _conLine)
{
    ;
    routeOpr.clear();

    routeOpr.initValue();

    routeOpr.WrkCtrIdCost   =  Conpeek(_conLine,
                                                  #RouteOpr_WrkCtrIdCost_ColumnNum);

    routeOpr.initFromWrkCtrId(routeOpr.WrkCtrIdCost);
    routeOpr.ProcessTime    =   str2num( Conpeek (_conLine,
                                                  #RouteOpr_ProcessTime_ColumnNum));
    routeOpr.RouteGroupId   =    Conpeek (_conLine,
                                                  #RouteOpr_RouteGroupId_ColumnNum);
    routeOpr.RouteType      =    Conpeek (_conLine,
                                                  #RouteOpr_RouteType_ColumnNum) == "Standard" ?
    RouteOprType::Standard : RouteOprType::Vendor;
    routeOpr.SetupTime      =   str2num( Conpeek (_conLine
                                                                          , #RouteOpr_SetupTime_ColumnNum));
    routeOpr.ToHours        =   Conpeek (_conLine,
                                                  #RouteOpr_ToHours_ColumnNum);

    routeOpr.OprId          =   route.OprId;

    routeOpr.ItemCode       =   TableGroupAll::Table;
    routeOpr.ItemRelation   =   routeVersion.ItemId;
    routeOpr.RouteCode      =   RouteAll::Route;
    routeOpr.RouteRelation  =   route.RouteId;
    routeOpr.SiteId         =   routeVersion.inventSiteId();
    if(RouteOpr::exist(routeOpr.OprId,
                       routeOpr.ItemCode,
                       routeOpr.ItemRelation,
                       routeOpr.ConfigId,
                       routeOpr.RouteCode,
                       routeOpr.RouteRelation,
                       routeOpr.SiteId))
    {
        return;
    }
    routeOpr.insert();
}


protected void createWrkCtrActivity(container _conLine)
{
    WrkCtrActivityRequirement           wrkCtrActivityRequirement;
    WrkCtrActivityResourceRequirement   wrkCtrActivityResourceRequirement;
    ;
    wrkCtrActivityRequirement.clear();

    wrkCtrActivityRequirement.ActivityRequirementSet    =   routeOpr.activityRequirementSet().RecId;

    wrkCtrActivityRequirement.RelationshipType          =   WrkCtrActivityRequirementType::Resource;
    wrkCtrActivityRequirement.UsedForJobScheduling      =   NoYes::Yes;

    wrkCtrActivityRequirement.insert();


    wrkCtrActivityResourceRequirement.clear();

    wrkCtrActivityResourceRequirement.setActivityRequirement(wrkCtrActivityRequirement.RecId);

    wrkCtrActivityResourceRequirement.ResourceDataAreaId    =   curExt2dataareaid(tableNum(WrkCtrTable));
    wrkCtrActivityResourceRequirement.WrkCtrId              =  Conpeek(_conLine,
                                                                                  #WrkCtrActivityResourceRequirement_WrkCtrId_ColumnNum);

    wrkCtrActivityResourceRequirement.insert();
}


protected void updateLastRoute()
{
    if(routeTable.RecId)
    {
        routeTable.updateRoute(false);
    }
}










Wednesday, July 18, 2012

Ax2012 Table Keys.

We are going to see the concept of keys on Tables in Ax2012.
These all following keys that we are going though appears in the AOT Table properties window.

Primary Key
The primary key is usually the type of key that other tables, called child tables, refer to when a foreign key field in those other tables need a relational identifier.
When we create a new table in AX2012 the Primary key was enforced by an index that has one field, this field should be unique, by default the primary key is based on Recid field. This is represented as surrogateKey in the table properties primary index.
By default the CreateRecIdIndex property was true and ClusterIndex as surrogateKey.


The ClusterIndex value is given to the underlying Microsoft SQL Server database system as a performance tuning choice. This choice generally controls the physical sequence in which the records are stored in the underlying database.


ReplacementKey
This key is used to define the replacement fields to display in your design when you referred  to some relation using the Recid.
for ex:-
Table B is referring to Table A where the TableB have the Refrecid from Table A, but when you open the form for TableB We cant show the Recid of the TableA in the Presentation,So whatever the field that you want to display, you will define one index on TableA with the fields that you want to show and and index alternateKey property to Yes. define the Replacement key property for the table A as this index.


If a ReplacementKey is chosen, its fields can appear on forms to helpfully identify each record.The ReplacementKey should be a set of fields that represent the natural key.


In AX2012 Relation represents a foreign key.


In Ax2012 we will use different Terms that used to describe the keys, These terms we wont see anywhere in AX physically in property names.


Foriegn Key-In Microsoft Dynamics AX, an AOT node under MyTable > Relations represents a foreign key. 
natural key-A key whose value has meaning to people. Most replacement keys are natural keys.(ReplacementKey).
unique key-this applies to primary keys and to alternate keys. It does not apply to foreign keys. This term emphasizes that all values for a given key must be unique within one table. All fields in a unique key must be not-nullable.

Thursday, July 12, 2012

Perform Lookup on RealEdit Control in AX2012

Lookup for RealEdit Control in Ax2012

we cant build the lookup for RealEdit control by using SysLookup functionality for that we have to customize the SysTableLookup class method performFormLookup()
Add the case for switch for handling the FormRealControl.
FormRealControl     callingRealControl;


 case classNum(FormRealControl):
            callingRealControl = callingControl;
            callingRealControl.performFormLookup(this.formRun());
            break;

Monday, July 9, 2012

AX2012 Import Vendors from CSV using VENDVendTableService part2

To use this class method I have created all parmmethods in this class where i am using all those fields in this method to create vendor.
Before seeing this post please read the post That i posted earlier for creating the vendors.

http://krishhdax.blogspot.dk/2012/03/ax2012-import-vendors-from-csv-using.html

This post is just upgrade of my earlier logic to create vendor,multiple contacts informations.


public static void CreateVendor()
{

    VendVendTableService                        vendVendTableService;
    VendVendTable                               vendVendTable;
    VendVendTable_VendTable                     vendTable;
    VendVendTable_DirPartyPostalAddressView     adresss;
    VendVendTable_DirPartyTable_DirOrganiza1    dirPartyTable;
    VendVendTable_DirPartyContactInfoView       contactInfoPhone, contactInfoFax, contactInfoEmail,
                                                                             contactInfoWeb;
    VendVendTable_OrganizationName              organizationName;

    DirContactPersonsService                    dirContactPersonsService;
    DirContactPersons                           dirContactPersons;
    DirContactPersons_ContactPerson             dirContactPersons_ContactPerson;
    DirContactPersons_Person                    dirContactPersons_Person;
    DirContactPersons_PersonName                dirContactPersons_PersonName;

    TaxVATNumTable                              taxVATNumTable;
    LogisticsLocationRole                       logisticsLocationRole =
    LogisticsLocationRole::findBytype(LogisticsLocationRoleType::Business);

    AifDimensionAttributeValueSet               aifDimensionAttributeValueSet;
    AifDimensionAttributeValue                  aifDimensionAttributeValue;

    AifEntityKeyList                            aifEntityKeyList, aifEntityKeyList_DirContactPerson;

    str                                         fName, mName, lName;
    ;

    vendVendTableService = vendVendTableService::construct();

    vendVendTable = new VendVendTable();
    vendTable = vendVendTable.createVendTable().addNew();

    vendTable.parmAccountNum(vendorAccount);
    vendTable.parmItemBuyerGroupId(buyerGroup);
 
    vendTable.parmVendGroup(credGroup);
    vendTable.parmCurrency(currency);
    vendTable.parmName(name);
    vendTable.parmVATNum(vATNum);
    vendTable.parmPaymTermId(PaymTerms);
 
   //This is validated and not found in Ax so update vendor after create or leave empty
    vendTable.parmInvoiceAccount(InvoiceAccount);
    vendTable.parmDlvTerm(deliveryTerms);

    // Create dimension
    if (defDimProject)
    {
        if (!aifDimensionAttributeValueSet)
        {
            aifDimensionAttributeValueSet   = vendTable.createDefaultDimension();
            aifDimensionAttributeValue      = aifDimensionAttributeValueSet.createValues().addNew();
        }
        else
        {
            aifDimensionAttributeValue = aifDimensionAttributeValueSet.parmValues().addNew();
        }

        aifDimensionAttributeValue.parmName("Project");
        aifDimensionAttributeValue.parmValue(defDimProject);
    }

    if (defDimDepartment)
    {
        if (!aifDimensionAttributeValueSet)
        {
            aifDimensionAttributeValueSet   = vendTable.createDefaultDimension();
            aifDimensionAttributeValue      = aifDimensionAttributeValueSet.createValues().addNew();
        }
        else
        {
            aifDimensionAttributeValue = aifDimensionAttributeValueSet.parmValues().addNew();
        }

        aifDimensionAttributeValue.parmName("Department");
        aifDimensionAttributeValue.parmValue(defDimDepartment);
    }


    if (vATNum && !TaxVATNumTable::exist(vendTable.parmVATNum(), countryRegionId))
    {
        taxVATNumTable.VATNum = vendTable.parmVATNum();
        taxVATNumTable.CountryRegionId = countryRegionId;
        taxVATNumTable.insert();
    }



    dirPartyTable = new VendVendTable_DirPartyTable_DirOrganiza1();
    vendTable.createDirPartyTable().add(dirPartyTable);
    dirPartyTable.parmLanguageId(language);

    organizationName = dirPartyTable.createOrganizationName().addNew();
    organizationName.parmName(name);

    adresss = dirPartyTable.createDirPartyPostalAddressView().addNew();
    adresss.parmCity(city);
    adresss.parmCountryRegionId(countryRegionId);
    adresss.parmStreet(street);
    adresss.parmZipCode(zipCode);
    adresss.parmRoles(logisticsLocationRole.Name);

    contactInfoPhone = dirPartyTable.createDirPartyContactInfoView().addNew();
    contactInfoPhone.parmLocationName(name);
    contactInfoPhone.parmIsPrimary(NoYes::Yes);
    contactInfoPhone.parmLocator(phone);
    contactInfoPhone.parmType(LogisticsElectronicAddressMethodType::Phone);
    contactInfoPhone.parmRoles(logisticsLocationRole.Name);
    contactInfoPhone.parmIsLocationOwner(1);


    contactInfoFax = dirPartyTable.parmDirPartyContactInfoView().addNew();
    contactInfoFax.parmLocationName(name);
    contactInfoFax.parmIsPrimary(NoYes::Yes);
    contactInfoFax.parmLocator(fax);
    contactInfoFax.parmType(LogisticsElectronicAddressMethodType::Fax);
    contactInfoFax.parmRoles(logisticsLocationRole.Name);
    contactInfoFax.parmIsLocationOwner(1);

    contactInfoEmail = dirPartyTable.parmDirPartyContactInfoView().addNew();
    contactInfoEmail.parmLocationName(name);
    contactInfoEmail.parmIsPrimary(NoYes::Yes);
    contactInfoEmail.parmLocator(email);
    contactInfoEmail.parmType(LogisticsElectronicAddressMethodType::Email);
    contactInfoEmail.parmRoles(logisticsLocationRole.Name);
    contactInfoEmail.parmIsLocationOwner(1);

    contactInfoWeb = dirPartyTable.parmDirPartyContactInfoView().addNew();
    contactInfoWeb.parmLocationName(name);
    contactInfoWeb.parmIsPrimary(NoYes::Yes);
    contactInfoWeb.parmLocator(web);
    contactInfoWeb.parmType(LogisticsElectronicAddressMethodType::URL);
    contactInfoWeb.parmRoles(logisticsLocationRole.Name);
    contactInfoWeb.parmIsLocationOwner(1);

    aifEntityKeyList = vendVendTableService.create(vendVendTable);


    dirContactPersonsService        = DirContactPersonsService::construct();
    dirContactPersons               = new DirContactPersons();

    if (contactId)
    {
        dirContactPersons_ContactPerson = dirContactPersons.createContactPerson().addNew();
        dirContactPersons_ContactPerson.parmContactForPartyVendAccount(vendorAccount);

        dirContactPersons_Person        = dirContactPersons_ContactPerson.createPerson().addNew();
        dirContactPersons_Person.parmNameAlias(contactId);

        dirContactPersons_PersonName    = dirContactPersons_Person.createPersonName().addNew();
        [fName, mName, lName]           = DirPerson::splitNameParts(contactId);
        dirContactPersons_PersonName.parmFirstName(fName);
        dirContactPersons_PersonName.parmMiddleName(mName);
        dirContactPersons_PersonName.parmLastName(lName);

        aifEntityKeyList_DirContactPerson = dirContactPersonsService.create(dirContactPersons);
    }

  }

Friday, July 6, 2012

AX2012 Import BOM from CSV


Sample code used to import BOM lines from CSV


//Create the BomTable
protected void createBOMTable(container _conLine)
{
    BOMId           bomId;
    BOMTable        bomTable;
    InventTable     inventTable;
 
  bomId       =   this.getLineValue(_conLine,
                                      #BOMTable_BomId_ColumnNum);

    bomTable    =   BOMTable::find(bomId,
                                   true);

    if(bomTable.RecId)
    {
        axBOMTable = AxBOMTable::newBOMTable(bomTable);

        // Avoid update for better performance.
        return;
    }
    else
    {
        axBOMTable = AxBOMTable::construct();
    }

    // BOMId
    axBOMTable.parmBOMId(bomId);

    // Name
    axBOMTable.parmName(this.getLineValue(_conLine,
                                           #BOMTable_Name_ColumnNum));

    inventTable =   InventTable::find(axBOMTable.parmBOMId());

    // ItemGroupId
    axBOMTable.parmItemGroupId(inventTable.itemGroupId());

    // SiteId
    axBOMTable.parmSiteId(inventTable.inventInventSiteId());

 
    // Approver
    AxBOMTable.parmApprover(gnDTDestAxBOM.parmApprover());

    // Approved
    axBOMTable.parmApproved(NoYes::Yes);

    axBOMTable.save();
}

// create the BOM

protected void createBOM(container _conLine)
{
    BOMId   bomId;
    ItemId  itemId;
    LineNum lineNum;

    BOM     bom;

    bomId   =   axBOMTable.parmBOMId();

    itemId  =   this.getLineValue(_conLine,
                                  #BOM_ItemId_ColumnNum);

    lineNum =   this.getLineValue(_conLine,
                                  #BOM_LineNum_ColumnNum);

    select firstOnly forupdate bom
        where   bom.BOMId   ==  bomId   &&
                bom.ItemId  ==  itemId  &&
                bom.LineNum ==  lineNum;

    if(bom.RecId)
    {
        axBOM = AxBOM::newBOM(bom);

        // Avoid update for better performance.
        return;
    }
    else
    {
        axBOM = AxBOM::construct();
    }

    // LineNum
    axBOM.parmLineNum(lineNum);

    // BOMType
    axBOM.parmBOMType(this.getLineValue(_conLine,
                                        #BOM_BOMType_ColumnNum));

    // BOMConsump
    axBOM.parmBOMConsump(this.getLineValue(_conLine,
                                           #BOM_BOMConsump_ColumnNum));

    // ItemId
    axBOM.parmItemId(itemId);

    // BOMQty
    axBOM.parmBOMQty(this.getLineValue(_conLine,
                                       #BOM_BOMQty_ColumnNum));

    // RoundUpQty
    axBOM.parmRoundUpQty(this.getLineValue(_conLine,
                                           #BOM_RoundUpQty_ColumnNum));

    // Position
    axBOM.parmPosition(this.getLineValue(_conLine,
                                         #BOM_Position_ColumnNum));

    // UnitId
    axBOM.parmUnitId(this.getLineValue(_conLine,
                                       #BOM_UnitId_ColumnNum));

    // BOMId
    axBOM.parmBOMId(bomId);

    // BOMQtySerie
    axBOM.parmBOMQtySerie(1);

    // ProdFlushingPrincip
    axBOM.parmProdFlushingPrincip(ProdFlushingPrincipBOM::Blank);

    axBOM.save();
}

// Create the BOM Version

protected void createBOMVersion(container _conLine)
{
    ItemId              itemId;
    BOMId               bomId;
    BOMVersionActive    active;
    FromQty             fromQty;
 

    BOMVersion          bomVersion;

    itemId      =   this.getLineValue(_conLine,
                                      #BOMVersion_ItemId_ColumnNum);

    bomId       =   axBOMTable.parmBOMId();

    active      =   NoYes::Yes;

    fromQty     =   1;

    bomVersion  =   BOMVersion::find(itemId,
                                     bomId,
                                     active,
                                     dateNull(),
                                     dateNull(),
                                     fromQty,
                                     true);

    if(bomVersion.RecId)
    {
        axBOMVersion = AxBOMVersion::newBOMVersion(bomVersion);

        // Avoid update for better performance.
        return;
    }
    else
    {
        axBOMVersion = AxBOMVersion::construct();
    }

    // ItemId
    axBOMVersion.parmItemId(itemId);
    axBOMVersion.parmInventDimId(bomVersion.InventDimId);

    // BOMId
    axBOMVersion.parmBOMId(bomId);

    // Name
    axBOMVersion.parmName(axBOMTable.parmName());

    // Active
    axBOMVersion.parmActive(active);

    // FromQty
    axBOMVersion.parmFromQty(fromQty);

    // Approver
    axBOMVersion.parmApprover(GNDTDestAxBOM.parmApprover());

    // Approved
    axBOMVersion.parmApproved(NoYes::Yes);

    axBOMVersion.save();
}

public void run()
{

    this.createBOMTable(container);
    this.createBOM( container );
    this.createBOMVersion( container );

}


AX2012 Import Items from CSV-part 2.


This was the continuation of my earlier post for importing items from CSV.
Please refer post before going into this code.


http://krishhdax.blogspot.dk/2012/05/ax2012-import-items-from-csv-file.html

MACROS that I was using for this code.

 #Define.InventTable_ItemId_ColumnNum(1)
    #Define.InventTable_PrimaryVendorId_ColumnNum(2)
    #Define.InventTable_NetWeight_ColumnNum(3)
    #Define.InventTable_UnitVolume_ColumnNum(4)
    #Define.InventTable_BOMUnitId_ColumnNum(5)
    #Define.InventTable_AltItemId_ColumnNum(6)
    #Define.InventTable_Intracode_ColumnNum(7)
    #Define.InventTable_ABCRevenue_ColumnNum(8)
    #Define.InventTable_NameAlias_ColumnNum(9)
    #Define.InventTable_ProdGroupId_ColumnNum(10)
    #Define.InventTable_SerialNumGroupId_ColumnNum(11)
    #Define.InventTable_ItemBuyerGroupId_ColumnNum(12)
    #Define.InventTable_DefaultDimension_ColumnNum(13)
    #Define.InventTable_PmfProductType_ColumnNum(14)
 
    #Define.InventItemLocation_ItemId_ColumnNum(24)
    #Define.InventItemGroupItem_ItemId_ColumnNum(25)
    #Define.InventItemGroupItem_ItemGroupId_ColumnNum(26)
    #Define.InventModelGroupItem_ModelGroupId_ColumnNum(27)
    #Define.InventModelGroupItem_ItemId_ColumnNum(28)
    #Define.EcoResProductTranslation_Description_ColumnNum(29)
    #Define.EcoResProductTranslation_Name_ColumnNum(30)
    #Define.InventItemPurchSetup_ItemId_ColumnNum(31)
    #Define.InventItemPurchSetup_MultipleQty_ColumnNum(32)
    #Define.InventItemPurchSetup_LowestQty_ColumnNum(33)
    #Define.InventItemPurchSetup_HighestQty_ColumnNum(34)
    #Define.InventItemPurchSetup_LeadTime_ColumnNum(35)
    #Define.InventItemPurchSetup_CalendarDays_ColumnNum(36)
    #Define.InventItemPurchSetup_Stopped_ColumnNum(37)
    #Define.InventItemInventSetup_ItemId_ColumnNum(38)
    #Define.InventItemInventSetup_MultipleQty_ColumnNum(39)
    #Define.InventItemInventSetup_LowestQty_ColumnNum(40)
    #Define.InventItemInventSetup_HighestQty_ColumnNum(41)
    #Define.InventItemInventSetup_StandardQty_ColumnNum(42)
    #Define.InventItemInventSetup_Stopped_ColumnNum(43)
    #Define.InventItemSalesSetup_Stopped_ColumnNum(44)
    #Define.InventItemSetupSupplyType_DefaultOrderType_ColumnNum(45)
    #Define.InventItemSetupSupplyType_ItemId_ColumnNum(46)
    #Define.InventTableModulePurch_ItemId_ColumnNum(47)
    #Define.InventTableModulePurch_UnitId_ColumnNum(48)
    #Define.InventTableModuleSales_ItemId_ColumnNum(49)
    #Define.InventTableModuleSales_UnitId_ColumnNum(50)
    #Define.InventTableModuleInvent_ItemId_ColumnNum(51)
    #Define.InventTableModuleInvent_UnitId_ColumnNum(52)
    #Define.EcoResStorageDimensionGroupItem_ItemId_ColumnNum(53)
    #Define.EcoResStorageDimensionGroupItem_StorageDimensionGroup_ColumnNum(54)
    #Define.EcoResTrackingDimensionGroupItem_ItemId_ColumnNum(55)
    #Define.EcoResTrackingDimensionGroupItem_TrackingDimensionGroup_ColumnNum(56)
    #Define.ReqItemTable_ItemId_ColumnNum(57)
    #Define.ReqItemTable_MaxInventOnHand_ColumnNum(58)
    #Define.ReqItemTable_MinInventOnHand_ColumnNum(59)
    #Define.ReqItemTable_ReqGroupId_ColumnNum(60)
    #Define.ReqItemTable_LeadTimeProduction_ColumnNum(61)


// this method is used to find  and create the dimension values if not not found.

RecId findCreateDimension(str _project, str _department, str _sapProductCode = "", str _item = "", str _vendor="", str _customer="",str _orginizationvalue)
{
    RecId                               ret;

    DimensionAttributeValueSetStorage   dimStorage;
    DimensionAttributeValue             dimensionAttributeValue;
    DimensionAttribute                  dimensionAttribute;
    ;

    if (_project || _department || _sapProductCode || _item || _vendor || _customer)
    {
        dimStorage              = new DimensionAttributeValueSetStorage();

        if (_project)
        {
            dimensionAttribute      = AxdDimensionUtil::validateFinancialDimension("project");
            dimensionAttributeValue = AxdDimensionUtil::validateFinancialDimensionValue(dimensionAttribute, _project);
            dimStorage.addItem(dimensionAttributeValue);
        }

        if (_department)
        {
            dimensionAttribute      = AxdDimensionUtil::validateFinancialDimension("Department");
            dimensionAttributeValue = AxdDimensionUtil::validateFinancialDimensionValue(dimensionAttribute, _department);
            dimStorage.addItem(dimensionAttributeValue);

           
            if( _orginizationvalue )
            {
                dimensionAttribute      = AxdDimensionUtil::validateFinancialDimension("Organization");
                dimensionAttributeValue = AxdDimensionUtil::validateFinancialDimensionValue(dimensionAttribute,  _orginizationvalue );
                dimStorage.addItem(dimensionAttributeValue);
            }
        }

        if (_sapProductCode)
        {
            dimensionAttribute      = AxdDimensionUtil::validateFinancialDimension("SAPProductCode");
            dimensionAttributeValue = AxdDimensionUtil::validateFinancialDimensionValue(dimensionAttribute, _sapProductCode);
            dimStorage.addItem(dimensionAttributeValue);
        }

        if (_item)
        {
            dimensionAttribute      = AxdDimensionUtil::validateFinancialDimension("Item");
            dimensionAttributeValue = AxdDimensionUtil::validateFinancialDimensionValue(dimensionAttribute, _item);
            dimStorage.addItem(dimensionAttributeValue);
        }

        if (_vendor)
        {
            dimensionAttribute      = AxdDimensionUtil::validateFinancialDimension("Vendor");
            dimensionAttributeValue = AxdDimensionUtil::validateFinancialDimensionValue(dimensionAttribute, _vendor);
            dimStorage.addItem(dimensionAttributeValue);
        }

        if (_customer)
        {
            dimensionAttribute      = AxdDimensionUtil::validateFinancialDimension("Customer");
            dimensionAttributeValue = AxdDimensionUtil::validateFinancialDimensionValue(dimensionAttribute, _customer);
            dimStorage.addItem(dimensionAttributeValue);
        }

        ret = dimStorage.save();
    }
    return ret;
}


protected void createInventTable(container _conLine)
{
    ItemId  itemId;
    InventTable inventTable;
    InventItemGroupItem inventItemGroupItem;
    InventDimGroupSetup inventDimGroupSetup;
    InventDim           inventDim;
    inventDim           inventDim_InventSiteId, inventDim_InventLocationId;
    #Define.DefaultInventSiteId("Melb")
    #Define.DefaultInventLocationId("Kilda")
    ;


    itemId  =   this.getLineValue(_conLine,#InventTable_ItemId_ColumnNum);
    inventTable= InventTable::find(itemId);
    if(!inventTable)
    {
        ecoResDistictProduct.clear();
        ecoResDistictProduct.initValue();
        ecoResDistictProduct.DisplayProductNumber=itemId;
        ecoResDistictProduct.ProductType=ecoResProductType::Item;
        ecoResDistictProduct.SearchName=this.getLineValue(_conLine,#InventTable_NameAlias_ColumnNum);

        ecoResDistictProduct.insert();

        //Product Translation
        axProductTranslation=AxEcoResProductTranslation::construct();
        axProductTranslation.parmDescription(this.getLineValue(_conLine,#EcoResProductTranslation_Description_ColumnNum));
        axProductTranslation.parmName(this.getLineValue(_conLine,#EcoResProductTranslation_Name_ColumnNum));
        axProductTranslation.parmLanguageId(CompanyInfo::languageId());
        axProductTranslation.parmProduct(ecoResDistictProduct.RecId);

        axProductTranslation.save();


        axInventTable=axInventTable::construct();
        axInventTable.parmItemId(this.getLineValue(_conLine,#InventTable_ItemId_ColumnNum));
        axInventTable.parmItemType(ItemType::Item);

        axInventTable.parmPrimaryVendorId(this.getLineValue(_conLine,#InventTable_PrimaryVendorId_ColumnNum));
        axInventTable.parmNetWeight(dtSource.convertStr2Num(this.getLineValue(_conLine, #InventTable_NetWeight_ColumnNum)));
        axInventTable.parmProduct(ecoResDistictProduct.RecId);

        axInventTable.parmUnitVolume(dtSource.convertStr2Num(this.getLineValue(_conLine,#InventTable_UnitVolume_ColumnNum)));

        axInventTable.parmUseAltItemId(ItemNumAlternative::Never);
        axInventTable.parmAltItemId(this.getLineValue(_conLine,#InventTable_AltItemId_ColumnNum));
        axInventTable.parmIntracode(this.getLineValue(_conLine,#InventTable_Intracode_ColumnNum));
        axInventTable.parmABCRevenue(str2enum(ABC, this.getLineValue(_conLine,#InventTable_ABCRevenue_ColumnNum)));
        axInventTable.parmNameAlias(this.getLineValue(_conLine,#InventTable_NameAlias_ColumnNum));
       
        axInventTable.parmBOMUnitId(this.getLineValue(_conLine,#InventTable_BOMUnitId_ColumnNum));
        axInventTable.parmProdGroupId(this.getLineValue(_conLine,#InventTable_ProdGroupId_ColumnNum));
        axInventTable.parmSerialNumGroupId(this.getLineValue(_conLine,#InventTable_SerialNumGroupId_ColumnNum));
        axInventTable.parmItemBuyerGroupId(this.getLineValue(_conLine,#InventTable_ItemBuyerGroupId_ColumnNum));
        axInventTable.parmPmfProductType(this.getLineValue(_conLine,#InventTable_PmfProductType_ColumnNum) == "Yes" ? PmfProductType::BOM : PmfProductType::None);
       

        //InventTableModulePurch
        axInventTableModulePurch = AxInventTableModule::construct();
        axInventTableModulePurch.axInventTable(axInventTable);
        axInventTableModulePurch.parmItemId(this.getLineValue(_conLine, #InventTableModulePurch_ItemId_ColumnNum));
        axInventTableModulePurch.parmModuleType(ModuleInventPurchSales::Purch);
        axInventTableModulePurch.parmUnitId(this.getLineValue(_conLine, #InventTableModulePurch_UnitId_ColumnNum));
        axInventTable.axInventTableModule_Purch(axInventTableModulePurch);

        //InventTableModuleSales
        axInventTableModuleSales = AxInventTableModule::construct();
        axInventTableModuleSales.axInventTable(axInventTable);
        axInventTableModuleSales.parmItemId(this.getLineValue(_conLine, #InventTableModuleSales_ItemId_ColumnNum));
        axInventTableModuleSales.parmModuleType(ModuleInventPurchSales::Sales);
        axInventTableModuleSales.parmUnitId(this.getLineValue(_conLine, #InventTableModuleSales_UnitId_ColumnNum));
        axInventTable.axInventTableModule_Sales(axInventTableModuleSales);

        //InventTableModuleInvent
        axInventTableModuleInvent = AxInventTableModule::construct();
        axInventTableModuleInvent.axInventTable(axInventTable);
        axInventTableModuleInvent.parmItemId(this.getLineValue(_conLine, #InventTableModuleInvent_ItemId_ColumnNum));
        axInventTableModuleInvent.parmModuleType(ModuleInventPurchSales::Invent);
        axInventTableModuleInvent.parmUnitId(this.getLineValue(_conLine, #InventTableModuleInvent_UnitId_ColumnNum));
        axInventTable.axInventTableModule_Invent(axInventTableModuleInvent);

        //EcoResTrackingDimensionGroupItem
        axEcoResTrackingDimensionGroupItem = AxEcoResTrackingDimensionGroupItem::construct();
        axEcoResTrackingDimensionGroupItem.axInventTable(axInventTable);
        axEcoResTrackingDimensionGroupItem.parmItemDataAreaId(axInventTable.inventTable().dataAreaId);
        axEcoResTrackingDimensionGroupItem.parmItemId(itemId);
        axEcoResTrackingDimensionGroupItem.parmTrackingDimensionGroup(EcoResTrackingDimensionGroup::findByDimensionGroupName(this.getLineValue(_conLine, #EcoResTrackingDimensionGroupItem_TrackingDimensionGroup_ColumnNum)).RecId);
        axInventTable.axEcoResTrackingDimensionGroupItem(axEcoResTrackingDimensionGroupItem);

        //EcoResTrackingDimensionGroupItem
        axEcoResStorageDimensionGroupItem = AxEcoResStorageDimensionGroupItem::construct();
        axEcoResStorageDimensionGroupItem.axInventTable(axInventTable);
        axEcoResStorageDimensionGroupItem.parmItemDataAreaId(axInventTable.inventTable().dataAreaId);
        axEcoResStorageDimensionGroupItem.parmItemId(itemId);
        axEcoResStorageDimensionGroupItem.parmStorageDimensionGroup(EcoResStorageDimensionGroup::findByDimensionGroupName(this.getLineValue(_conLine, #EcoResStorageDimensionGroupItem_StorageDimensionGroup_ColumnNum)).RecId);
        axInventTable.axEcoResStorageDimensionGroupItem(axEcoResStorageDimensionGroupItem);

        axInventTable.save();

 

        //EcoResTrackingDimensionGroupProduct
        axEcoResTrackingDimensionGroupProduct = AxEcoResTrackingDimensionGroupProduct::construct();
        axEcoResTrackingDimensionGroupProduct.parmProduct(ecoResProduct.RecId);
        axEcoResTrackingDimensionGroupProduct.parmTrackingDimensionGroup(EcoResTrackingDimensionGroup::findByDimensionGroupName(this.getLineValue(_conLine, #EcoResTrackingDimensionGroupItem_TrackingDimensionGroup_ColumnNum)).RecId);
        axEcoResTrackingDimensionGroupProduct.save();

        //EcoResStorageDimensionGroupProduct
        axEcoResStorageDimensionGroupProduct = AxEcoResStorageDimensionGroupProduct::construct();
        axEcoResStorageDimensionGroupProduct.parmProduct(ecoResProduct.RecId);
        axEcoResStorageDimensionGroupProduct.parmStorageDimensionGroup(EcoResStorageDimensionGroup::findByDimensionGroupName(this.getLineValue(_conLine, #EcoResStorageDimensionGroupItem_StorageDimensionGroup_ColumnNum)).RecId);
        axEcoResStorageDimensionGroupProduct.save();

// creating the Dimension values
        axInventTable.parmDefaultDimension(
            findCreateDimension(""
                , ""
                , this.getLineValue(_conLine, #InventTable_DefaultDimension_ColumnNum)
                , this.getLineValue(_conLine, #InventTable_ItemId_ColumnNum)));

        axInventTable.save();

        inventDim_InventSiteId.clear();
        inventDim_InventSiteId.InventSiteId = #DefaultInventSiteId;
        inventDim_InventSiteId = InventDim::findOrCreate(inventDim_InventSiteId);

        inventDim_InventLocationId.clear();
        inventDim_InventLocationId.InventLocationId = #DefaultInventlocationId;
        inventDim_InventLocationId = InventDim::findOrCreate(inventDim_InventLocationId);

        //InventItemInventSetup
        axInventItemInventSetup = AxInventItemInventSetup::newInventItemInventSetup(InventItemInventSetup::findDefault(itemId, true));
        axInventItemInventSetup.axInventTable(axInventTable);
        axInventItemInventSetup.parmInventDimIdDefault(inventDim_InventSiteId.InventDimId);
        axInventItemInventSetup.parmLowestQty(dtSource.convertStr2Num(this.getLineValue(_conLine, #InventItemInventSetup_LowestQty_ColumnNum)));
        axInventItemInventSetup.parmHighestQty(dtSource.convertStr2Num(this.getLineValue(_conLine, #InventItemInventSetup_HighestQty_ColumnNum)));
        axInventItemInventSetup.parmStandardQty(dtSource.convertStr2Num(this.getLineValue(_conLine, #InventItemInventSetup_StandardQty_ColumnNum)));
        axInventItemInventSetup.parmMultipleQty(dtSource.convertStr2Num(this.getLineValue(_conLine, #InventItemInventSetup_MultipleQty_ColumnNum)));
        axInventItemInventSetup.parmStopped(str2enum(noYes, this.getLineValue(_conLine, #InventItemInventSetup_Stopped_ColumnNum)));
        axInventItemInventSetup.save();

        axInventItemInventSetup = AxInventItemInventSetup::construct();
        axInventItemInventSetup.axInventTable(axInventTable);
        axInventItemInventSetup.parmItemId(itemId);
        axInventItemInventSetup.parmInventDimId(inventDim_InventSiteId.inventDimId);
        axInventItemInventSetup.parmInventDimIdDefault(inventDim_InventLocationId.InventDimId);
        axInventItemInventSetup.save();

        //InventPurchSetup
        axInventItemPurchSetup  = axInventItemPurchSetup::newInventItemPurchSetup(InventItemPurchSetup::findDefault(itemId, true));
        axInventItemPurchSetup.axInventTable(axInventTable);
        axInventItemPurchSetup.parmInventDimIdDefault(inventDim_InventSiteId.InventDimId);
        axInventItemPurchSetup.parmMultipleQty(dtSource.convertStr2Num(this.getLineValue(_conLine, #InventItemPurchSetup_MultipleQty_ColumnNum)));
        axInventItemPurchSetup.parmLowestQty(dtSource.convertStr2Num(this.getLineValue(_conLine, #InventItemPurchSetup_LowestQty_ColumnNum)));
        axInventItemPurchSetup.parmHighestQty(dtSource.convertStr2Num(this.getLineValue(_conLine, #InventItemPurchSetup_HighestQty_ColumnNum)));
        axInventItemPurchSetup.parmLeadTime(dtSource.convertStr2Num(this.getLineValue(_conLine, #InventItemPurchSetup_LeadTime_ColumnNum)));
        axInventItemPurchSetup.parmCalendarDays(str2enum(CalendarDays, this.getLineValue(_conLine, #InventItemPurchSetup_CalendarDays_ColumnNum)));
        axInventItemPurchSetup.parmStopped(str2enum(noYes, this.getLineValue(_conLine, #InventItemPurchSetup_Stopped_ColumnNum)));
        axInventItemPurchSetup.save();

        axInventItemPurchSetup = AxInventItemPurchSetup::construct();
        axInventItemPurchSetup.axInventTable(axInventTable);
        axInventItemPurchSetup.parmItemId(itemId);
        axInventItemPurchSetup.parmInventDimId(inventDim_InventSiteId.inventDimId);
        axInventItemPurchSetup.parmInventDimIdDefault(inventDim_InventLocationId.InventDimId);
        axInventItemPurchSetup.save();

        //InventItemSalesSetup
        axInventItemSalesSetup  = AxInventItemSalesSetup::newInventItemSalesSetup(InventItemSalesSetup::findDefault(itemId, true));
        axInventItemSalesSetup.axInventTable(axInventTable);
        axInventItemSalesSetup.parmInventDimIdDefault(inventDim_InventSiteId.InventDimId);
        axInventItemSalesSetup.parmStopped(str2enum(noYes, this.getLineValue(_conLine, #InventItemSalesSetup_Stopped_ColumnNum)));
        axInventItemSalesSetup.save();

        axInventItemSalesSetup = AxInventItemSalesSetup::construct();
        axInventItemSalesSetup.axInventTable(axInventTable);
        axInventItemSalesSetup.parmItemId(itemId);
        axInventItemSalesSetup.parmInventDimId(inventDim_InventSiteId.inventDimId);
        axInventItemSalesSetup.parmInventDimIdDefault(inventDim_InventLocationId.InventDimId);
        axInventItemSalesSetup.save();

        //InventGroup Item
        axInventGroupItem=AxInventItemGroupItem::construct();
        axInventGroupItem.parmItemId(itemId);
        axInventGroupItem.parmItemGroupId(this.getLineValue(_conLine,#InventItemGroupItem_ItemGroupId_ColumnNum));
        axInventGroupItem.parmItemGroupDataAreaId(curext());
        axInventGroupItem.parmItemDataAreaId(curext());
        axInventGroupItem.save();

        //InventModelGroupItem
        axInventModelGroupItem=AxInventModelGroupItem::construct();
        axInventModelGroupItem.parmItemId(itemId);
        axInventModelGroupItem.parmModelGroupId(this.getLineValue(_conLine,#InventModelGroupItem_ModelGroupId_ColumnNum));
        axInventModelGroupItem.parmModelGroupDataAreaId(curext());
        axInventModelGroupItem.parmItemDataAreaId(curext());
        axInventModelGroupItem.save();


        //InventItemSetupSupplyType
        inventItemSetupSupplyType.clear();
        inventItemSetupSupplyType.initValue();
        inventItemSetupSupplyType.ItemId=itemId;
        inventItemSetupSupplyType.ItemDataAreaId=curext();
        inventItemSetupSupplyType.DefaultOrderType  = this.getLineValue(_conLine, #InventItemSetupSupplyType_DefaultOrderType_ColumnNum) == "Indkøbsvare" ? ReqPOType::Purch : ReqPOType::Production;
        inventItemSetupSupplyType.insert();


        //ReqItemTable
        inventDimGroupSetup = InventDimGroupSetup::newInventTable(axInventTable.inventTable());
        inventDim.initFromInventTable(axInventTable.inventTable());
        inventDim.clearNotCovPrDim(inventDimGroupSetup);
        inventDim.InventSiteId      = #DefaultInventSiteId;
        inventDim.InventLocationId  = #DefaultInventLocationId;

        reqItemTable.clear();
        reqItemTable.initValue();
        reqItemTable.initFromInventTable(axInventTable.inventTable());
        reqItemTable.ItemId             = this.getLineValue(_conLine, #ReqItemTable_ItemId_ColumnNum);
        reqItemTable.MaxInventOnhand    = dtSource.convertStr2Num(this.getLineValue(_conLine, #ReqItemTable_MaxInventOnHand_ColumnNum));
        reqItemTable.MinInventOnhand    = dtSource.convertStr2Num(this.getLineValue(_conLine, #ReqItemTable_MinInventOnHand_ColumnNum));
        reqItemTable.ReqGroupId         = this.getLineValue(_conLine, #ReqItemTable_ReqGroupId_ColumnNum);
        reqItemTable.CalendarDaysProduction = NoYes::Yes;
        reqItemTable.LeadTimeProduction     = dtSource.convertStr2Num(this.getLineValue(_conLine, #ReqItemTable_LeadTimeProduction_ColumnNum));
        reqItemTable.LeadTimeProductionActive = reqItemTable.LeadTimeProduction ? NoYes::Yes : NoYes::No;
        reqItemTable.CovInventDimId         = InventDim::findOrCreate(inventDim).InventDimId;
        reqItemTable.insert();
     
    }

}

Copy Map


This code is just you can add into global and you can use int any where in your logics for creating map from another map

static Map CopyMap(Map _mapFrom, Map _mapTo)
{
    MapEnumerator   mapEnumerator;
    ;
    if (_mapFrom && _mapTo)
    {
        mapEnumerator = _mapFrom.getEnumerator();
        while (mapEnumerator.moveNext())
        {
            if (_mapTo.exists(mapEnumerator.currentKey()))
            {
                _mapTo.insert(mapEnumerator.currentKey(), _mapTo.lookup(mapEnumerator.currentKey()) + mapEnumerator.currentValue());
            }
            else
            {
                _mapTo.insert(mapEnumerator.currentKey(), mapEnumerator.currentValue());
            }
        }
    }
    else
    {
        if (!_mapTo)
        {
            _mapTo = _mapFrom;
        }
    }

    return _mapTo;
}

Import Financial Ledger Budget in AX2012 using BudgetTransactionService

Import Financial Ledger Budget using BudgetTransactionService


class budgetTransactionLine 
{
    BudgetModelId                       budgetModelId;
    DialogField                         dlgBudgetModelId;

    #Define.Name(1)
    #Define.Date(2)
    #Define.FinancialAccount(3)
    #Define.Amount(4)
    #Define.budgetCode(5)
 

    DimensionHierarchyId                accountStructureHierarchy;
    DialogField                         dlgAccountStructureHierarchy;

    BudgetTransactionService            budgetTransactionService;
    BudgetTransaction                   budgetTransaction;
    BudgetTransaction_BudgetTransHeader budgetTransaction_BudgetTransHeader;

    #define.CurrentVersion(1)
    #localmacro.CurrentList
        budgetModelId
        , budgetCode
        , accountStructureHierarchy
    #endmacro
}

// add the dialog field to which account hierarchy we have to import,what was the model

public Object dialog(Dialog _dialog)
{
    ;
    _dialog = super(_dialog);

    _dialog.addGroup("Budgeting");
    dlgAccountStructureHierarchy    = _dialog.addFieldValue(extendedTypeStr(DimensionHierarchyId), accountStructureHierarchy , "@SYS310383");
    dlgBudgetModelId                = _dialog.addFieldValue(extendedTypeStr(BudgetModelId), budgetModelId);
     return _dialog;
}


public boolean getFromDialog()
{
    boolean ret;

    ret = super();

    budgetModelId               = dlgBudgetModelId.value();

    accountStructureHierarchy   = dlgAccountStructureHierarchy.value();

    return ret;
}


public void createBudgetTransactionLine(
    TransDate                               _transDate
    , MainAccountNum                        _mainAccountNum
    , AmountCur                             _amountCur
    , str                                   _department
    , BudgetModelId                         _budgetModelId = budgetModelId )
{
    BudgetTransaction_BudgetTransLine   budgetTransaction_BudgetTransLine;

    AifBudgetAccount                    aifBudgetAccount;
    AifDimensionAttributeValue          aifDimensionAttributeValue;
    ;

    if (!budgetTransactionService)
    {
        budgetTransactionService                = BudgetTransactionService::construct();

        budgetTransaction                       = new budgetTransaction();

        budgetTransaction_BudgetTransHeader     = budgetTransaction.createBudgetTransHeader().addNew();
        budgetTransaction_BudgetTransHeader.parmBudgetModelId(budgetModelId);
        budgetTransaction_BudgetTransLine       = budgetTransaction_BudgetTransHeader.createBudgetTransLine().addNew();
    }
    else
    {
        budgetTransaction_BudgetTransLine       = budgetTransaction_BudgetTransHeader.parmBudgetTransLine().addNew();
    }

    budgetTransaction_BudgetTransLine.parmDate(_transDate);
    budgetTransaction_BudgetTransLine.parmTransactionCurrencyAmount(_amountCur);

// assigning the Financial dimensions for that main account and department.

    if (_mainAccountNum)
    {
        if (!aifBudgetAccount)
        {
            aifBudgetAccount   = budgetTransaction_BudgetTransLine.createLedgerDimension();
            aifBudgetAccount.parmAccountStructure(DimensionHierarchy::find(accountStructureHierarchy).Name);
            aifBudgetAccount.parmDisplayValue("1");//Will be changed by system to wright display value

            aifDimensionAttributeValue   = aifBudgetAccount.createValues().addNew();
        }
        else
        {
            aifDimensionAttributeValue = aifBudgetAccount.parmValues().addNew();
        }

        aifDimensionAttributeValue.parmName("Mainaccount");
        aifDimensionAttributeValue.parmValue(_mainAccountNum);
    }

    if (_department)
    {
        if (!aifBudgetAccount)
        {
            aifBudgetAccount   = budgetTransaction_BudgetTransLine.createLedgerDimension();
            aifBudgetAccount.parmAccountStructure(DimensionHierarchy::find(accountStructureHierarchy).Name);
            aifBudgetAccount.parmDisplayValue("2");//Will be changed by system to wright display value

            aifDimensionAttributeValue   = aifBudgetAccount.createValues().addNew();
        }
        else
        {
            aifDimensionAttributeValue = aifBudgetAccount.parmValues().addNew();
        }

        aifDimensionAttributeValue.parmName("Department");
        aifDimensionAttributeValue.parmValue(_department);

// this will creates the lines
      BudgetTransactionService.create(budgetTransaction);
    }



// before this you have to read from the CSV and get the container from that read.
//If you want to see how to read from CSV sample you can check my previous posts how to get the container from csv file
 http://krishhdax.blogspot.dk/2012/03/ax2012-import-ledger-journal-trans-from.html

public void run()
{
 this.
createBudgetTransactionLine(


        str2date((conPeek(_item, #Dato))
        , conPeek(_item, #Finanskonto)
        , str2num((conPeek(_item, #Beloeb))
       
 );


}






Thursday, July 5, 2012

AX2012 CU3 Update Released


Cumulative Update 3 for Microsoft Dynamics AX 2012

Cumulative Update 3 (CU3) contains hotfixes for Microsoft Dynamics AX 2012 that were fixed since the release of Microsoft Dynamics AX 2012. This cumulative update is applicable for both Microsoft Dynamics AX 2012 (6.0.947.0) and Microsoft Dynamics AX 2012 Feature Pack 1 (6.0.1108.0).

Note The build number of this cumulative update package is 6.0.1108.670.

This cumulative update includes all fixes that are described in Cumulative Update 2 and in Cumulative Update 1 for Microsoft Dynamics AX 2012.
For more information about Cumulative Update 2 for Microsoft Dynamics AX 2012, click the following article number to view the article in the Microsoft Knowledge Base:
2606916  Cumulative Update 2 for Microsoft Dynamics AX 2012
For more information about Cumulative Update 1 for Microsoft Dynamics AX 2012, click the following article number to view the article in the Microsoft Knowledge Base:
2579565  Cumulative Update 1 for Microsoft Dynamics AX 2012

If you have partner source access then you can go through the fixes that was available in this CU3 update

Tuesday, July 3, 2012

AX2012 Create SSRS Report using Data Provides Classes

Create the SSRS Report in AX2012 using Report Data Provider (RDP) functionality.

RDP implments the standard MVC(Model View Controller) design pattern.
In this post I am building one report which is used in the production packing list report for production module.

What is MVC?

  • Model-view-controller (MVC) is a pattern used to isolate business logic from the user interface.
  • Model: Responsible for retrieving data and for business logic, this can included queries, data methods, or other classes that are designed to retrieve data.
  • View: Responsible for the User Interface, this can also be thought of as the design for the report.
  • Controller: Orchestrates the flow between Model and View



For this Report I am creating the Query,Contract,Controller,DataProvider classes in below.
In this I used lot of my custom fields that we created and used in the functionality

I am extending this functionality with adding builder class to the contract and adding the logic to lookup the data for the contract parmmethods.

for this I am writing the class which extending the SysOperationAutomaticUIBuilder.


TmpTable- ProdPackingSlipDetailsTmp
Query Name-ProdPackList
Contract class-ProdPacklistContract
Controller class-ProdPackListController Extends SRSReportRunController
Data ProvideClass-ProdPacklistDP Extends SRSReportDataProvidePreProcess
SSRS Report-ProdPackList

Starting with Query-Build the Query as the following data sources with the fields and relations.



Create the TMP table as below fields and properties of the table




define Properties of the table mainly createTransactionID=Yes
















Create the Contract  Class first,
This class is used to create parm methods for the reports, So if you have any parameters that you want to pass to report then create parm methods for those as datamembers.

for ex.-

[    DataMemberAttribute('UseQuantity')]
public ProdBOMJournalQty parmUseQuantity(ProdBOMJournalQty _useQuantity = useQuantity)
{
    useQuantity = _useQuantity;
    return useQuantity;
}


In my report I am using Query and adding two parm fields.
I am adding the contract processing through my builder with the following attribute of my contract class.

[DataContractAttribute,
SysOperationContractProcessingAttribute(classstr(ProdPackListUIBuilder)) ]
public class ProdPacklistContract
{
SalesId salesId;
LineNum lineNum
}

[    DataMemberAttribute('SalesId')]
public SalesId parmSalesId(SalesId _salesId=salesId)
{
salesId=_salesId;
return salesId;
}

[ DataMemberAttribute('LineNum')]
public LineNum parmLineNum(LineNum _lineNum=LineNum)
{
 lineNum=_lineNum;
return lineNum;
}

Create Controller class which extends SrsReportRunController

/// <summary>
///    The <c>ProdPackListController</c> class is the controller class for <c>ProdPackList</c> SSRS report.
/// </summary>
public class ProdPackListController extends SrsReportRunController
{
}
Create the Main method where you have to define the reportname and design and this was the method which will calls the report to exectue...starting point of the report.

public static void main(Args _args)
{
    SrsReportRunController    controller = new  ProdPackListController  ();
    controller.parmReportName("ProdPackList.Report");
    controller.parmArgs(_args);
    controller.startOperation();
}



Override the method preRunModifyContract method


protected void preRunModifyContract()
{
    GNProdPacklistContract    contract;
    contract = this.parmReportContract().parmRdpContract() as GNProdPacklistContract;
}


if you want to handle the record count and no records then you can over ride this method and you can handle the no records warnings.
protected container preRunValidate()

{
    // This report is only containing dynamic filters and via testing it's been determined
    // that on warm box it performs under 10 seconds with a 500 records and under 10 minutes
    // with 50000 records. The rest of the contract parameters just define layout and UI, so
    // no additional filtering on those needs to be done in this method.
    // The granularity of the query is determined by the join of ProdJournalBOM and ProdBOM tables.
    #define.ErrorLimit(50000)
    #define.WarningLimit(500)

    container               validateResult;
    Query                   firstQuery = this.getFirstQuery();
    int                     rowCount = QueryRun::getQueryRowCount(firstQuery, #ErrorLimit + 1);

    if (rowCount > #ErrorLimit)
    {
        validateResult = [SrsReportPreRunState::Error];
    }
    else if (rowCount > #WarningLimit)
    {
        validateResult = [SrsReportPreRunState::Warning];
    }
    else if(rowCount <=0)
    {
       // validateResult = [SrsReportPreRunState::Error];
         throw error("No records available for the Selected criteria");
    }
    else
    {
        validateResult = super();
    }

    return validateResult;
}


if you want to pass the values for the report before promting to user for input you can override this method
prePromptModifyContract

In my case I am overriding to pass the value and ranges for my query before showing the dialog to user.


/// <summary>
///    Sets query ranges based on the caller.
/// </summary>
/// <exception cref="M:Exception::Error">
///    The method is called from a invalid path.
/// </exception>
protected void prePromptModifyContract()
{
    QueryBuildRange         queryBuildRangeSerial;
    QueryBuildRange         queryBuildRangeProd,qbrTransStatus;

    QueryBuildDataSource    queryBuildDataSource,queryBuildDataSource1,queryBuildDataSource2;
    ProdTable               localProdTable;
    Query                   query;
    // get the report query
    query                   = this.parmReportContract().parmQueryContracts().lookup(this.getFirstQueryContractKey());

    queryBuildDataSource    = SysQuery::findOrCreateDataSource(query, tableNum(ProdTable));
    queryBuildDataSource1   = SysQuery::findOrCreateDataSource(query, tableNum(InventDim));
    queryBuildDataSource2   = SysQuery::findOrCreateDataSource(query, tableNum(InventTrans));

    queryBuildRangeProd     = SysQuery::findOrCreateRange(queryBuildDataSource, fieldNum(ProdTable,ProdId));
    queryBuildRangeSerial   = SysQuery::findOrCreateRange(queryBuildDataSource1, fieldNum(InventDim,inventSerialId));
    qbrTransStatus          = SysQuery::findOrCreateRange(queryBuildDataSource2, fieldNum(InventTrans,StatusReceipt));
    qbrTransStatus.value(queryValue(StatusReceipt::Received));

    if (this.parmArgs().dataset() ==  tableNum(ProdTable))
    {
        localProdTable = this.parmArgs().record();
        queryBuildRangeProd.value(queryValue(localProdTable.ProdId));
        this.parmShowDialog(true);
    }
    else if ((this.parmArgs().menuItemName() == menuitemOutputStr(ProdPacklist)) && (this.parmArgs().dataset() ==0))
    {
        this.parmShowDialog(true);
    }
    else
    {
        throw error(strFmt("Packing list can only printed from Production",funcName()));
    }

}


Create DataProvider class which extends SrsReportDataProviderPreProcess
In My report I am using the Barcode setup functionality for printing the serial numbers aswell.


[
    SRSReportQueryAttribute(queryStr(ProdPackList)),
    SRSReportParameterAttribute(classStr(ProdPacklistContract))
]
class ProdPacklistDP extends SrsReportDataProviderPreProcess
{

    boolean                     showQuery;

    boolean                     firstPage;
    ProdTable                   prodTable;
    ProdId                      prodId;

    CompanyInfo                 companyInfo;

    ProdBOM                     prodBOM;
    InventDim                   inventDim;

   ProdPackingSlipDetailsTmp prodPackingSlipDetailsTmp;
    BarcodeSetup                barCodeSetup;
    BarcodeSetupId  barcodeSetupId;
    Barcode         barcode;
}


Create the method which return the tmp table object

[
    SRSReportDataSetAttribute(tableStr('ProdPackingSlipDetailsTmp'))
]
public ProdPackingSlipDetailsTmp getProdPacklistDetailsTmp()
{
    select prodPackingSlipDetailsTmp;
    return prodPackingSlipDetailsTmp;
}

override the method ProcessReport where you will write the business logic to fill into thetmp table

/// <summary>
///    Processes the report business logic.
/// </summary>
/// <remarks>
///    Calls the sub methods to insert data into the temporary table.
/// </remarks>
[SysEntryPointAttribute(false)]
public void processReport()
{
    QueryRun                queryRun;
     ProdPacklistContract contract       = this.parmDataContract() as  ProdPacklistContract ;
    // Set the userconnection to use on table.
    // This is required to ensure that createdTransactionId of inserted record is different than default
           transaction.
    prodPackingSlipDetailsTmp.setConnection(this.parmUserConnection());
    this.init();
    this.setupBarcode();
    queryRun                        = new QueryRun(this.parmQuery());
    while (queryRun.next())
    {
        prodTable       = queryRun.get(tableNum(ProdTable));
        inventDim       = queryRun.get(tableNum(InventDim));
        prodId          = prodTable.ProdId;
        if(prodTable.InventRefType==InventRefType::Sales)
        {
           this.insertHeader();
           this.insertDetails(prodId,inventDim.inventSerialId);
        }
    }
}


private void init()
{
    companyInfo = CompanyInfo::find();
    firstPage   = true;
}





//BP Deviation documented
protected BarCodeString barcode(str _SerialNumber)
{
    str jobId = strupr(_SerialNumber);

    if (barcodeSetup.validateBarcode(jobId))
    {
        barcode.string(true, jobId);
        barcode.encode();
    }
    else
    {
        throw(error(strfmt("@SYS41409", barcode.barcodeType(), jobId)));
    }
    return barcode.barcodeStr();
}


/// <summary>
/// Initialize barcode settings.
/// </summary>
protected void setupBarcode()
{
    barcodeSetupId = JmgParameters::find().getBarcodeSetupId();
    barcodeSetup = BarcodeSetup::find(barcodeSetupId);
    barcode = barcodeSetup.barcode();
}

// assigns the data into header information first

private void insertHeader()
{
    prodPackingSlipDetailsTmp.clear();
    prodPackingSlipDetailsTmp.initValue();
    prodPackingSlipDetailsTmp.SalesId=prodTable.InventRefId;
    prodPackingSlipDetailsTmp.SerialNumber=inventDim.inventSerialId;


    prodPackingSlipDetailsTmp.ProdItemId                = prodTable.ItemId;
    prodPackingSlipDetailsTmp.Description               = prodTable.Name;
    prodPackingSlipDetailsTmp.Customer                  = SalesTable::find(prodPackingSlipDetailsTmp.SalesId).CustAccount;


    prodPackingSlipDetailsTmp.initValue();
    prodPackingSlipDetailsTmp.barcodeSetupId=barCodeSetup.barcodeSetupId;
    prodPackingSlipDetailsTmp.barcodeType=barCodeSetup.barcodeType;
    prodPackingSlipDetailsTmp.fontName=barCodeSetup.fontName;
    prodPackingSlipDetailsTmp.fontSize=barCodeSetup.fontSize;
    prodPackingSlipDetailsTmp.maximumLength=barCodeSetup.maximumLength;
    prodPackingSlipDetailsTmp.minimumLength=barCodeSetup.minimumLength;
    prodPackingSlipDetailsTmp.SerialNumberBarCode=this.barcode(inventDim.inventSerialId);
}


private void insertDetails(ProdId _prodId,InventSerialId _inventSerialId)
{
    SMAServiceObjectTable smaServiceObjectTable;
    SMAServiceBOMTable    smaServiceBOMTable;
    ProdBOM               prodBOMTable;

    while select prodBOMTable order by InventTransId asc
        where prodBOMTable.ProdId==_prodId
    {
        if(InventTable::Find(prodBOMTable.ItemId).PrintItemProduction)
        {
            prodPackingSlipDetailsTmp.ItemId=prodBOMTable.ItemId;
            prodPackingSlipDetailsTmp.Qty=prodBOMTable.BOMQty;
            prodPackingSlipDetailsTmp.Name=prodBOMTable.itemName();
            if(prodBOMTable.SerialnoControlled())
            {
                select TemplateBOMId,ServiceObjectId from smaServiceObjectTable
                    where smaServiceObjectTable.InventSerialId==_inventSerialId
                    && smaServiceObjectTable.ReferenceId==_prodId
                    && smaServiceObjectTable.ReferenceCategory==InventTransType::Production
                join InventSerialId from smaServiceBOMTable where
                    smaServiceBOMTable.ItemId==prodBOMTable.ItemId
                    && smaServiceBOMTable.ObjectId==smaServiceObjectTable.ServiceObjectId
                    && smaServiceBOMTable.ServiceBOMId==smaServiceObjectTable.TemplateBOMId;

                prodPackingSlipDetailsTmp.SerialNo=smaServiceBOMTable.InventSerialId;
            }
            prodPackingSlipDetailsTmp.SalesFormNotes=FormLetterRemarks::find(companyInfo.LanguageId,FormTextType::ProductionPackingList).Txt;
            prodPackingSlipDetailsTmp.insert();
            prodPackingSlipDetailsTmp.SerialNo="";
        }
    }
}

Builder class

public class ProdPackListUIBuilder extends SysOperationAutomaticUIBuilder
        {
            DialogField dialogSalesId;
            DialogField dialogSalesLine;
            SalesId  salesId;
            LineNum  lineNum;
            ProdPacklistContract prodPacklistContract;
            ProdPackListController packListcontroller;
            QueryRun queryRun;
            Query baseQuery;
            ProdTable prodTable;
        }
       public void build()
        {
            FormBuildGroupControl grp;
       
            Dialog      dialogLocal = this.dialog();
            ;
            prodPacklistContract = this.dataContractObject();
            if(this.validateCaller())
            {
                dialogLocal.addGroup("Sales");
                this.addDialogField(methodStr(ProdPacklistContract,parmSalesId), prodPacklistContract);
                this.addDialogField(methodStr(ProdPacklistContract,parmSalesLine), prodPacklistContract);
            }
       }

        public SysOperationController controller()
        {
            SysOperationController ret;
            ret = super();
            packListcontroller=ret;
            return ret;
        }

        private str getFirstQuery()
        {
              // this will just return the first contract key in the Map
            Map queryContracts =packListcontroller.parmReportContract().parmQueryContracts();
            MapEnumerator mapEnum;
            str firstQueryKey;
            if(queryContracts)
            {
                mapEnum = queryContracts.getEnumerator();
                if(mapEnum.moveNext())
                {
                    firstQueryKey = mapEnum.currentKey();
                }
            }
            return firstQueryKey;
        }
        public void getFromDialog()
        {
            prodPacklistContract = this.dataContractObject();
            if(this.validateCaller())
            {
                salesId=dialogSalesId.value();
                LineNum=dialogSalesLine.value();
                this.validateData(salesId,LineNum);
            }
            super();
        }

        public void initializeFields()
        {
            prodPacklistContract = this.dataContractObject();
        }

        private void initquery()
        {
baseQuery=packListcontroller.parmReportContract().parmQueryContracts().lookup(this.getFirstQuery());
            QueryRun=new QueryRun(baseQuery);
            while (queryRun.next())
            {
                prodTable=queryRun.get(tableNum(ProdTable));
                if(prodTable)
                    break;
            }
        }
        public void lookupSalesId(FormStringControl _control)
        {
            Query query = new Query();
            SysTableLookup sysTablelookup;
            sysTablelookup =SysTableLookup::newParameters(tableNum(SalesTable),_control);
            sysTablelookup.addLookupfield(fieldNum(SalesTable,SalesId));
            sysTablelookup.addLookupfield(fieldnum(SalesTable,CustAccount));
            sysTablelookup.addLookupMethod(tableMethodStr(SalesTable,customerName));
       
            query.addDataSource(tableNum(SalesTable));
            if(ProdTable.InventRefType==InventRefType::Sales)
            {
                query.dataSourceTable(tableNum(SalesTable)).addRange(fieldNum(SalesTable, SalesId)).value(queryValue(ProdTable.InventRefId));
            }
            sysTablelookup.parmQuery(query);
            sysTablelookup.performFormLookup();
        }
        public void lookupSalesLine(FormStringControl _control)
        {
            Query query = new Query();
            SysTableLookup sysTablelookup;
            sysTablelookup =SysTableLookup::newParameters(tableNum(SalesLine),_control);
            sysTablelookup.addLookupfield(fieldnum(SalesLine,LineNum));
            sysTablelookup.addLookupfield(fieldnum(SalesLine,Itemid));
            sysTablelookup.addLookupfield(fieldNum(SalesLine,SalesId));
            query.addDataSource(tableNum(SalesLine));
            query.dataSourceTable(tableNum(SalesLine)).addRange(fieldNum(SalesLine, SalesId)).value(dialogSalesId.value());
            query.dataSourceTable(tableNum(SalesLine)).addRange(fieldNum(SalesLine, ItemId)).value(queryValue(prodTable.ItemId));
            if(prodTable.InventRefType==InventRefType::Sales)
            {
                query.dataSourceTable(tableNum(SalesLine)).addRange(fieldNum(SalesLine, InventtransId)).value(queryValue(prodTable.InventRefTransId));
            }
       
            sysTablelookup.parmQuery(query);
            sysTablelookup.performFormLookup();
        }

//Override the postbuild function to bind the lookups for the fields.
        public void postBuild()
        {
            super();
            if(this.validateCaller())
            {
                prodPacklistContract=this.dataContractObject();
                this.initquery();
                // From binding info, get the dialog field for racecode attribute and add button
                dialogSalesId = this.bindInfo().getDialogField(
                                     this.dataContractObject(),
                                     methodStr(ProdPacklistContract,parmSalesId));
                if (dialogSalesId)
                {
                    dialogSalesId.lookupButton(2);
                }
                dialogSalesId.value(" ");
       
                // register override method for lookup cust Group
                dialogSalesId.registerOverrideMethod(methodStr(FormStringControl, lookup), methodStr(ProdPackListUIBuilder, lookupSalesId), this);
                // register override method for modified
                dialogSalesId.registerOverrideMethod(methodStr(FormStringControl, modified), methodStr(ProdPackListUIBuilder, SalesIdModified), this);
       
                //binding info for customer drop down
                dialogSalesLine = this.bindInfo().getDialogField(this.dataContractObject(),
                                     methodStr(ProdPacklistContract,parmSalesLine));
                dialogSalesLine.value(" ");
                // register override method for lookup customer
                dialogSalesLine.registerOverrideMethod(methodStr(FormStringControl, lookup), methodStr(ProdPackListUIBuilder, lookupSalesLine), this);
       
                if (dialogSalesLine)
                {
                    dialogSalesLine.lookupButton(2);
                }
                if(ProdTable.InventRefType==InventRefType::Sales)
                {
                    dialogSalesId.value(prodTable.InventRefId);
                    dialogSalesLine.value(SalesLine::findInventTransId(prodTable.InventRefTransId).LineNum);
                    prodPacklistContract.parmSalesId(prodTable.InventRefId);
                    prodPacklistContract.parmSalesLine(SalesLine::findInventTransId(prodTable.InventRefTransId).LineNum);
                    dialogSalesId.enabled(false);
                    dialogSalesLine.enabled(false);
                }
                if(prodTable.RecId==0)
                {
                    throw error(strFmt("please select valid production order"));
                }
            }
            else
            {
                    prodPacklistContract.parmSalesId("");
           }
        }
// if the salesId is modified we have to load the sales lines 
        public boolean SalesIdModified(FormStringControl _control)
        {
            dialogSalesId.value(_control.valueStr());
            dialogSalesLine.value('');
            return true;
        }
        private boolean validateCaller()
        {
            if((packListcontroller.parmArgs().menuItemName() == menuitemOutputStr(ProdPacklist)) && (packListcontroller.parmArgs().dataset() ==0))
                return false;
            else
                return true;
        }

        private void validateData(SalesId _salesId,LineNum _lineNum)
        {
            boolean ret=true;
            SalesLine salesLine;
            if(this.validateCaller())
            {
                    if(_salesId=="")
                        throw error(strFmt("this production is not linked to sales %1",prodTable.ProdId));
       
                    if(_lineNum==0)
                        throw error(strFmt("this production is not linked to sales %1 ",_salesId,prodTable.ProdId));
                    if(ret)
                    {
                        salesLine= SalesLine::find(_salesId,_lineNum);
                        if(salesLine && salesline.ItemId != prodTable.ItemId)
                        {
                            throw error(strFmt("this production is not linked to sales %1 ,%2",salesLine.ItemId,prodTable.ItemId));
                        }
                    }
            }
        }
     
 This was the new functionality for the adding the lookups for the fields using builder class.



After creation of all the classes above mentioned then we have to create the report,
Open .netDevelopment enviorment and create project and select Microsoft Dynamics AX from the Left pane and select the ReportModel Project from the list of project and give your project name and click ok.

















select the project and right click and click add and select report.














It will create the new report as follow.Right click on report and select properties and give the name as ProdPackList.













Select DataSets and right click and click AddDataset and provide the DatasetName and select the dataset that you created and right click and properties.








click on Query it will opens the dialog with the DataProvider classes,in that select the DataProvider class that we built and click next. It will opens the fields selection window where we will select the list of fields that required to show in the report
















based on your requirements you can select or deselect the fields and click on. Now the dataset with the fields are ready for the report.
Now you can drag and drop that dataset on to the designs node, It will generate auomatic design for those fields.
If you want to design your own format then create new precision Design by right click on the designnode and  add precisionDesign and change that design name as we mentioned in the controller class main method(Report).

I Created the Precision design as follows.









This is how my report looks like above.