Friday, May 23, 2014

Job Code to Test Dp class (Process report) input from Contract Class...

// Job Code to Test Dp class from input Contract Class... Testing... And change a Temp table to Regular table while testing in job

static void DPClassTest(Args _args)
{
    //initialize contract
    CustContract cont = new    CustContract();
    CustDP        dp  = new     CustDP();
    //fill the contract
    cont.parmRecId(5637144576);
    //pass the contract
    dp.parmDataContract(cont);
    //fill the table
    dp.processReport();
}

Wednesday, May 21, 2014

Job to Create N number of companys and import the data in it.


//Job to Create N number of companys and import the data in it.

static void CreateCompanies(Args _args)
{
DataArea dataarea;
counter i;
CompanyDomainList companyDomainList;
CompanyDomainList cCompanyDomainList;
sysdataImport sysDataimport;
Application gappl = new Application();
filename filename;
;
filename = "D:\\Computer\\0";

for(i=1 ; i<301 ; i++)
{
DataArea.clear();
DataArea.Id = 'C' + int2str(i);
DataArea.name = 'Company' + int2str(i);
DataArea.insert();
xDataArea::insertPost(dataArea);

while select * from companyDomainList where companyDomainList.CompanyId == DataArea.Id
{
select firstonly cCompanyDomainList
where cCompanyDomainList.CompanyId == DataArea.Id &&
cCompanyDomainList.DomainId == companyDomainList.DomainId;

if (!cCompanyDomainList)
{
cCompanyDomainList.data(companyDomainList.data());
cCompanyDomainList.CompanyId = DataArea.Id;
cCompanyDomainList.insert();
}

//create the default company
gappl.setDefaultCompany(DataArea.Id,false);
syssecurity::reload(false);
InfoLog.navPane().loadStartupButtons();
Infolog.navPane().refreshFavorites(infolog.navPane().selectedFavoriteGroup(),xInfo::currentWorkspaceNum());

sysDataImport = new sysDataImport();
sysDataImport.parmDropCompany(true);
sysdataimport.parmDeleteTables(connull());
sysDataImport.parmSilent(true);
sysdataImport.parmFilename(filename);
sysDataImport.parmServerAccess(Noyes::Yes);
sysdataImport.run(false);
//sysDataImport::importFile("D:\\MyShare\\Data\\5.0SP1\\ExtendedData\\40ExtendedData1380.dat",FileType::Binary);
}

if(i==14 || i==25 || i==40 || i==60 || i==75 || i== 90 || i== 110 || i== 130 ||
i==150 || i==170 || i==190 || i==220 || i==240 || i==270)
infolog.clearBrowser();

}
}

AX Job to export Security Key to CSV file.

//AX Job to export Security Key to CSV file.
Error ...

static void AOTGetProperty(Args _args)
{
 #aot #properties Boolean writeFile;
Boolean infoDebug;
CommaIo outFile;
TreeNode tn = TreeNode::findNode(#SecurityKeysPath);
str securityKeysName;
str securityKeyID, Property;
int sID; str errMsg; ;
infoDebug = false;
// ***OPTION*** View InfoLog Output (true / false) writeFile = true;
// ***OPTION*** Export results to CSV file (true / false) errMsg = "";
 //"--- NOT DEFINED ---";
//C:\Users\m.a.gudidevuni\Documents outFile = new AsciiIo("C:\\GTA\\SecurityKey.CSV","W");
outFile.outFieldDelimiter("\r\n");
outFile.outRecordDelimiter("\r");
tn = tn.AOTfirstChild();
while (tn)
{
securityKeysName = findProperty(tn.AOTgetProperties(), #PropertyName);
securityKeyID = findProperty(tn.AOTgetProperties(),#PropertyId);
sID = tn.applObjectId();
if(infoDebug)
{
info(strfmt('SecurityKeysName %1 with ID : %2',securityKeysName,sID));
}
if(writeFile)
{
 outFile.write(securityKeysName + " , " + strReplace(int2str(sID),",",""));
}
// info(strfmt('SecurityKeysName %1 with ID : %2',securityKeysName,sID));
// Property = tn.AOTgetProperties();
// info(strfmt('%1', findProperty(Property, 'ID')));
// info (strfmt( // 'SecurityKeysName %1 has the ID property specified as %2', // securityKeysName, securityKeyID));
tn = tn.AOTnextSibling();
}
}

Tree node to Excel file:

Tree node to Excel file:

static void CreateExcelTreeNode(Args _args)


{



SysExcelApplication xlsApplication;

SysExcelWorkBooks xlsWorkBookCollection;

SysExcelWorkBook xlsWorkBook;

SysExcelWorkSheets xlsWorkSheetCollection;

SysExcelWorkSheet xlsWorkSheet;

SysExcelRange xlsRange;

AsciiIO tmpfile;

Filename tmpfilename;

FileIOPermission permission;

TreeNode treeNode;

TreeNode treeNodeTables;

#File

#AOT

int row = 1;

str fileName;

;



treeNodeTables = TreeNode::findNode(#SecurityKeysPath);



// Name of the Excel document.



fileName = "C:\\test.xsl";



// Excel open and initialize.



xlsApplication = SysExcelApplication::construct();

xlsApplication.visible(true); //Generate new Excel worksheet.

xlsWorkBookCollection = xlsApplication.workbooks();

xlsWorkBook = xlsWorkBookCollection.add();

xlsWorkSheetCollection = xlsWorkBook.worksheets();

xlsWorkSheet = xlsWorkSheetCollection.itemFromNum(1);

// Write headlines cells in the worksheet.

xlsWorkSheet.cells().item(row,1).value('Name'); xlsWorkSheet.cells().item(row,2).value('ID');

row++;

// first table

treeNode = treeNodeTables.AOTfirstChild();

// Excel worksheet with fill data (Excel fill-cells).

while (treeNode != null)

{

xlsWorkSheet.cells().item(row,1).value(treeNode.AOTname()); xlsWorkSheet.cells().item(row,2).value(treeNode.applObjectId());

row++; // next table

treeNode = treeNode.AOTnextSibling();

}

// Check whether the document already exists.

if(WinApi::fileExists(fileName))

{

WinApi::deleteFile(fileName);

}

// Excel document store.

xlsWorkbook.saveAs(fileName);

//Close Excel.

xlsApplication.quit(); xlsApplication.finalize();

}

Resolving Ctrl+F5 Error on creation of Item Master while edit and update in Master data in AX2012:

Resolving Ctrl+F5  Error on creation of Item Master while edit and update in Master data in AX2012:

 FormRun         formRun;
    FormObjectSet   formObjSet;
    int             i;
    InventTable     linventTable;

    // refresh and reread inventTable datasource if exists in form
    if (this.isFormDataSource())
    {
        formRun = this.dataSource().formRun();
        for (i=1; i<= formRun.dataSourceCount(); i++)
        {
            if (formRun.dataSource(i).cursor() is InventTable)
            {
                formObjSet = formRun.dataSource(i);
                linventTable = formObjSet.cursor() as InventTable;
                break;
            }
        }
        if (!linventTable)
        {
            linventTable = InventTable::find(this.ItemId, true);
        }
        if (linventTable)
        {
            if (formObjSet)
            {
                formObjSet.refresh();
                formObjSet.reread();
            }
        }
    }

AOS Server name from Job

// AOS Server name from Job
static void getServerNameForCurrentSession(Args _args)
 {
   sysClientSessions cliSessions;
   sysServerSessions svrSessions;
   ;
   select svrSessions
     exists join cliSessions
       where cliSessions.SessionId == sessionID()
         && cliSessions.ServerID == svrSessions.ServerId;
   info(substr(svrSessions.AOSId, 1, strfind(svrSessions.AOSId, '@', 1, strlen(svrSessions.AOSId))-1));
 }

Friday, May 16, 2014

Get Count of Lines from Header table record

// To Get Count of Line from Header  table

    real a,b;
    int64 cnt;

    a = RfqDisc.realValue();
    select count(RecId) from  PurchRFQCaseLine where PurchRFQCaseLine.RFQCaseId == PurchRFQCaseTable.RFQCaseId;
    cnt = PurchRFQCaseLine.RecId;
    b = a/cnt;
    while select PurchRFQCaseLine
                where PurchRFQCaseLine.RFQCaseId == PurchRFQCaseTable.RFQCaseId
    {
            PurchRFQCaseLine.LineDisc = b;
            PurchRFQCaseLine.update();

    }

    PurchRFQCaseLine_ds.reread();
    PurchRFQCaseLine_ds.research();
    PurchRFQCaseLine_ds.refresh();


Thursday, May 15, 2014

Class ID and Number get through X++

// Class ID and Number get through X++

static void classIdNUmGetExample(Args _args)
{
    int i,j;
    WorkTimeCheck w; // class
    ;
    i = classIdGet(w);
    print "Class ID for object is " + int2Str(i);
   

    j = classNum(PurchTableForm); //class name
    print "Class NUm for object is " + int2Str(j);
    print j;
    pause;
}

Remove Space Bar and special Chaarcter while typing in Text field

// Remov Space Bar while typing in Text field

public void textChange()
{
    str text;
    int len;
    text = TextFIeld.valueStr();
    len = strLen(text);
 
    super();
    if(strLen(text) > 0)
    {      
        if(strnFind(text, " ",1,len) >= 0)
        {
            strdel(text,len-1,1);
            TextFIeld.text(text);
        }
    }
}

Currency Exchange through X++

Amount        costInCurrency;
currencyExchangeHelper = CurrencyExchangeHelper::construct();

    costInCurrency  = currencyExchangeHelper.calculateCurrencyToCurrency("USD" ,costingLine.CurrencyCode,costingLine.Cost,false);

Get Inventory Dimension From ItemID ... Site,warehouse,Config,Dimid

// Get Inventory Dimension From ItemID ... Site,warehouse,Config,Dimid

static void GetInventoryDimensions(Args _args)
{
    InventTable                 inventTable = inventTable::find('1005');
    InventItemOrderSetupType    setupType   = InventItemOrderSetupType::Invent;
    InventDim                   inventDim;
    ;

    inventDim.InventSiteId = inventTable.inventItemOrderSetupMap(setupType).inventSiteId(inventDim.InventSiteId, inventTable);
    inventDim.InventLocationId  = inventTable.inventItemOrderSetupMap(setupType,
                                                                      InventDim::findOrCreate(inventDim).InventDimId)
                                                                      .inventLocationId(inventDim.InventLocationId,
                                                                                        inventTable,
                                                                                        inventDim.InventSiteId);

    inventDim.ConfigId = inventTable.StandardConfigId;
    inventDim = InventDim::findOrCreate(inventDim);

    info(strFmt('Invent Dim. Id: %1', inventDim.inventDimId));
    info(strFmt('Site Id: %1', inventDim.InventSiteId));
    info(strFmt('Warehouse Id: %1', inventDim.InventLocationId));
}

Getting Dimension Values from LedgerDimension in Ax 2012

// Getting Dimension Values from LedgerDimension in Ax 2012

static void getDimensionValueFromLedgerDimension(Args _args)
{
DimensionAttribute                          dimensionAttributeTable;
DimensionAttributeValueGroupStatus          dimAttrValueGroupStatusTable;
DimensionAttributeValueGroupCombination     dimAttrValueGroupComboTable;
DimensionAttributeValueGroup                dimAttrValueGroupTable;
DimensionAttributeLevelValue                dimAttrLevelValueTable;
DimensionAttributeValue                     dimAttrValueTable;
DimensionAttrValueCOAOverride               dimAttrValueCOAOverrideTable;
DimensionAttrValueLedgerOverride            dimAttrValueLedgerOverrideTable;
DimensionFinancialTag                       dimensionFinancialTagTable;
InventPosting                               inventPostingTable;
DimensionValue                              Dimension1, Dimension2, Dimension3;
MainAccountNum                              LedgerAccount;
RecId                                       LedgerRecId, dimCombinationId;
dimCombinationId    = 5637144728; // for example here i gave a valid ledgerdimension
// find MainAccountId from LedgerDimension
LedgerAccount       = MainAccount::findByLedgerDimension(dimCombinationId).MainAccountId;
LedgerRecId         = Ledger::findLedgerRecIdByLegalEntity(CompanyInfo::findDataArea(curext()).RecId);
Dimension1 = “”;
Dimension2 = “”;
Dimension3 = “”;
while select Ordinal from dimAttrValueGroupComboTable order by Ordinal
where dimAttrValueGroupComboTable.DimensionAttributeValueCombination == dimCombinationId
join dimAttrValueGroupTable
where dimAttrValueGroupTable.RecId == dimAttrValueGroupComboTable.DimensionAttributeValueGroup
outer join dimAttrValueGroupStatusTable
where dimAttrValueGroupStatusTable.DimensionAttributeValueGroup == dimAttrValueGroupTable.RecId
join dimAttrLevelValueTable
where dimAttrLevelValueTable.DimensionAttributeValueGroup == dimAttrValueGroupTable.RecId
join pessimisticLock IsSuspended, IsTotal, ActiveFrom, ActiveTo, DimensionAttribute, RecId, EntityInstance from dimAttrValueTable
where dimAttrValueTable.RecId == dimAttrLevelValueTable.DimensionAttributeValue
outer join pessimisticLock IsSuspended, ActiveFrom, ActiveTo, RecId from dimAttrValueCOAOverrideTable
where dimAttrValueCOAOverrideTable.DimensionAttributeValue == dimAttrValueTable.RecId && dimAttrValueCOAOverrideTable.ChartOfAccounts == LedgerChartOfAccounts::current()
outer join pessimisticLock IsSuspended, ActiveFrom, ActiveTo, RecId from dimAttrValueLedgerOverrideTable
where dimAttrValueLedgerOverrideTable.DimensionAttributeValue == dimAttrValueTable.RecId && dimAttrValueLedgerOverrideTable.Ledger == LedgerRecId
{
dimensionFinancialTagTable = null;
select * from dimensionFinancialTagTable
where dimensionFinancialTagTable.RecId == dimAttrValueTable.EntityInstance
join dimensionAttributeTable
where dimensionAttributeTable.RecId == dimAttrValueTable.DimensionAttribute;
if (dimensionAttributeTable.Name == ‘Department’)
{
Dimension1 = dimensionFinancialTagTable.Value;
}
if (dimensionAttributeTable.Name == ‘CostCenter’)
{
Dimension2 = dimensionFinancialTagTable.Value;
}
if (dimensionAttributeTable.Name == ‘Purpose’)
{
Dimension3 = dimensionFinancialTagTable.Value;
}
}
info(strFmt(“%1     %2      %3?,Dimension1,Dimension2,Dimension3));
}

Getting Individual Dimension Combination Values–Dimension Storage class in ax 2012

//Getting Individual Dimension Combination Values–Dimension Storage class in ax 2012

static void getDimensionCombinationValues(Args _args)
{
    // DimensionAttributeValueCombination stores the combinations of dimension values
    // Any tables that uses dimension  combinations for main account and dimensions
    // Has a reference to this table’s recid
    DimensionAttributeValueCombination  dimAttrValueComb;
    //GeneralJournalAccountEntry is one such tables that refrences DimensionAttributeValueCombination
    GeneralJournalAccountEntry          gjAccEntry;
    // Class Dimension storage is used to store and manipulate the values of combination
    DimensionStorage        dimensionStorage;
    // Class DimensionStorageSegment will get specfic segments based on hierarchies
    DimensionStorageSegment segment;
    int                     segmentCount, segmentIndex;
    int                     hierarchyCount, hierarchyIndex;
    str                     segmentName, segmentDescription;
    SysDim                  segmentValue;
    ;

    //Get one record for demo purpose
    gjAccEntry = GeneralJournalAccountEntry::find(5637765403);

    setPrefix("Dimension values fetching");
    //Fetch the Value combination record
    dimAttrValueComb = DimensionAttributeValueCombination::find(gjAccEntry.LedgerDimension);
    setPrefix("Breakup for " + dimAttrValueComb.DisplayValue);

    // Get dimension storage
    dimensionStorage = DimensionStorage::findById(gjAccEntry.LedgerDimension);
    if (dimensionStorage == null)
    {
        throw error("@SYS83964");
    }

    // Get hierarchy count
    hierarchyCount = dimensionStorage.hierarchyCount();
    //Loop through hierarchies to get individual segments
    for(hierarchyIndex = 1; hierarchyIndex <= hierarchyCount; hierarchyIndex++)
    {
        setPrefix(strFmt("Hierarchy: %1", DimensionHierarchy::find(dimensionStorage.getHierarchyId(hierarchyIndex)).Name));
        //Get segment count for hierarchy
        segmentCount = dimensionStorage.segmentCountForHierarchy(hierarchyIndex);

        //Loop through segments and display required values
        for (segmentIndex = 1; segmentIndex <= segmentCount; segmentIndex++)
        {
            // Get segment
            segment = dimensionStorage.getSegmentForHierarchy(hierarchyIndex, segmentIndex);

            // Get the segment information
            if (segment.parmDimensionAttributeValueId() != 0)
            {
                // Get segment name
                segmentName = DimensionAttribute::find(DimensionAttributeValue::find(segment.parmDimensionAttributeValueId()).DimensionAttribute).Name;
                //Get segment value (id of the dimension)
                segmentValue        = segment.parmDisplayValue();
                //Get segment value name (Description for dimension)
                segmentDescription  = segment.getName();
                info(strFmt("%1: %2, %3", segmentName, segmentValue, segmentDescription));
            }
        }
    }
}

Get Default Dimensions value For Vend Customer Item in ax 2012 through X++

// 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());
    }
}

Inventory OnHand Get through X++

real a;
    InventDimParm inventDimParm;
    inventDimParm.initFromInventDim(InventDim::find("00000492_069"));
    a =InventSumDatePhysicalDim::onHandQty(today(),"1001",InventDim::find("00000492_069"),inventDimParm);
    info(strfmt("%1",a));

Copy data from one dropped table to another

// Copy data from one dropped table to another
static void EmployeeDetailsCopyTableData(Args _args)
{
    EmployeeDetails      employeeDetails; // Table From Copying
    CopyOfEmployeeDetails copyOfEmployeeDetails; // Duplicated Table want to copy data from base table
    ;

    ttsBegin;
    // Clear the data from the copy table
    delete_from copyOfEmployeeDetails;

    while select employeeDetails
    {
        buf2Buf(employeeDetails, copyOfEmployeeDetails);
        copyOfEmployeeDetails.insert();
    }
 
    ttsCommit;
}

Position test in ax

//  Position test

static void PositionTest(Args _args)
{
    HierarchyPosition   hierarchyPosition;
    container           workerHirerchy;
    int                 i;
    int64               posi;
    str                 name;
    HcmWorker         worker;



    delete_from hierarchyPosition;
    RecursionPosition::postion(curUserId());
    while select hierarchyPosition //where currency.CurrencyCode like "E*"
    {
        workerHirerchy += hierarchyPosition.Position;
    }

    for(i=1;i<=conLen(workerHirerchy);i++)
    {
        posi = conPeek(workerHirerchy, i);
        worker = HcmWorker::find(posi);
        name   = strFmt("%1 ",worker.name());
        info(name);

    }
}

Journal Creation Method in Class

// Journal Creation Method in Class

private void JournalCreation( System.Data.SqlClient.SqlDataReader   dr1)
{

    NumberSequenceTable                 numberSequenceTable;

    Voucher                             voucher;
    Amount                              amountCurDebit,amountCurCredit;

    AxLedgerJournalTrans                trans  = new AxLedgerJournalTrans();
    AxLedgerJournalTable                header ;//= new AxLedgerJournalTable();

    str                                 description;
    str                                 Agreement,Category,Department,Division,Employee,ProductManagers,Project,Publisher,Region,Salesmen;

    DimensionStorage                    DimensionStorage;
    LedgerJournalNameId                 LedgerJournalNameId;
    CurrencyCode                        currencycode;
    TransDate                           TransDate = today();

    LedgerAccountContract               ledgerAccountContract,OffledgerAccountContract;
    MainAccountNum                      mainAccount;
    mainAccountNum                      OffmainAccount ;
    DimensionAttributeValueContract     attributeValueContract;

    LedgerJournalCheckPost              ledgerJournalCheckPost;

    ;

    ttsBegin;

    header = new AxLedgerJournalTable();
    LedgerJournalNameId = "GenJrn";
    header.parmJournalName(LedgerJournalNameId);

    header.save();

    numberSequenceTable = NumberSequenceTable::find(LedgerJournalName::find(LedgerJournalNameId).NumberSequenceTable);

    voucher =  NumberSeq::newGetVoucherFromId(numberSequenceTable.RecId).voucher();

    mainAccount     = dr1.get_Item('Account');
    OffmainAccount  = dr1.get_Item('OffsetAccount');

    amountCurDebit  = dr1.get_Item('Debit');
    amountCurCredit = dr1.get_Item('Credit');

    description  = dr1.get_Item('Txt');
    currencycode = dr1.get_Item('Currency');

    Employee        = dr1.get_Item('Dimension1');
    ProductManagers = dr1.get_Item('Dimension2');
    Project         = dr1.get_Item('Dimension3');
    Publisher       = dr1.get_Item('Dimension4');
    Region          = dr1.get_Item('Dimension5');

    trans.parmJournalNum(header.ledgerJournalTable().JournalNum);

    //AccountNum
    ledgerAccountContract = new LedgerAccountContract();
    ledgerAccountContract.parmValues(new List(Types::Class));

    ledgerAccountContract.parmMainAccount(mainAccount);
    if (Employee)
    {
        attributeValueContract = new DimensionAttributeValueContract();
        attributeValueContract.parmName("Employee");
        attributeValueContract.parmValue(Employee);

        ledgerAccountContract.parmValues().addEnd(attributeValueContract);
    }
    if (ProductManagers)
    {
        attributeValueContract = new DimensionAttributeValueContract();
        attributeValueContract.parmName("ProductManagers");
        attributeValueContract.parmValue(ProductManagers);

        ledgerAccountContract.parmValues().addEnd(attributeValueContract);
    }
    if (Project)
    {
        attributeValueContract = new DimensionAttributeValueContract();
        attributeValueContract.parmName("Project");
        attributeValueContract.parmValue(Project);

        ledgerAccountContract.parmValues().addEnd(attributeValueContract);
    }
    if (Publisher)
    {
        attributeValueContract = new DimensionAttributeValueContract();
        attributeValueContract.parmName("Publisher");
        attributeValueContract.parmValue(Publisher);

        ledgerAccountContract.parmValues().addEnd(attributeValueContract);
    }
    if (Region)
    {
        attributeValueContract = new DimensionAttributeValueContract();
        attributeValueContract.parmName("Region");
        attributeValueContract.parmValue(Region);

        ledgerAccountContract.parmValues().addEnd(attributeValueContract);
    }

    dimensionStorage = DimensionServiceProvider::buildDimensionStorageForLedgerAccount(ledgerAccountContract);

    trans.parmLedgerDimension(dimensionStorage.save());
    //-------------------------------------
    //OffsetAccount
    OffledgerAccountContract = new LedgerAccountContract();
    OffledgerAccountContract.parmValues(new List(Types::Class));
    Employee        = dr1.get_Item('Dimension1');
    ProductManagers = dr1.get_Item('Dimension2');
    Project         = dr1.get_Item('Dimension3');
    Publisher       = dr1.get_Item('Dimension4');
    Region          = dr1.get_Item('Dimension5');

    OffledgerAccountContract.parmMainAccount(OffmainAccount);
    if (Employee)
    {
        attributeValueContract = new DimensionAttributeValueContract();
        attributeValueContract.parmName("Employee");
        attributeValueContract.parmValue(Employee);

        OffledgerAccountContract.parmValues().addEnd(attributeValueContract);
    }
    if (ProductManagers)
    {
        attributeValueContract = new DimensionAttributeValueContract();
        attributeValueContract.parmName("ProductManagers");
        attributeValueContract.parmValue(ProductManagers);

        OffledgerAccountContract.parmValues().addEnd(attributeValueContract);
    }
    if (Project)
    {
        attributeValueContract = new DimensionAttributeValueContract();
        attributeValueContract.parmName("Project");
        attributeValueContract.parmValue(Project);

        OffledgerAccountContract.parmValues().addEnd(attributeValueContract);
    }
    if (Publisher)
    {
        attributeValueContract = new DimensionAttributeValueContract();
        attributeValueContract.parmName("Publisher");
        attributeValueContract.parmValue(Publisher);

        OffledgerAccountContract.parmValues().addEnd(attributeValueContract);
    }
    if (Region)
    {
        attributeValueContract = new DimensionAttributeValueContract();
        attributeValueContract.parmName("Region");
        attributeValueContract.parmValue(Region);

        OffledgerAccountContract.parmValues().addEnd(attributeValueContract);
    }

    dimensionStorage = DimensionServiceProvider::buildDimensionStorageForLedgerAccount(OffledgerAccountContract);

    trans.parmOffsetLedgerDimension(dimensionStorage.save());
    //------------------------------------
    trans.parmTxt(description);

    trans.parmDocumentDate(today());
    trans.parmTransDate(today());

    trans.parmAmountCurDebit(AmountCurDebit);

    trans.parmAmountCurCredit(AmountCurCredit) ;

    trans.parmCompany(curext());
    trans.parmCurrencyCode(currencycode);
    trans.parmVoucher(voucher);
    trans.parmExchRate(1);
    trans.currentRecord().insert();

    trans.save();

    //ledgerJournalCheckPost= ledgerJournalCheckPost::newLedgerJournalTable(header.ledgerJournalTable(),NoYes::Yes);
    //ledgerJournalCheckPost.run();

    info(header.ledgerJournalTable().JournalNum);

    ttsCommit;

}

Copy Markup charges while posting purchase invoice using X++

 Copy Markup charges while posting purchase invoice using X++ Class: Important: Code logic is just for Reference.  New class => Duplicate...