Friday, December 30, 2016

Restriction of updation when modifying field value in Header(Purchase/Sales)

//Restriction of updation when modifying field value in Header(Purchase/Sales)'

Requirement: Need to restrict Warehouse updation from Header to line level

SalesPurchTableToLineUpdatePrompt - Dialog(method)
intiailize variable in method
update = false;
code:
Standard: line num -51
if (salesPurchTableToLineField.parmTableToLineUpdate() == TradeTable2LineUpdate::Prompt)
{
                refreshable = true;
Replace with :
if (salesPurchTableToLineField.parmTableToLineUpdate() == TradeTable2LineUpdate::Prompt
&& salesPurchTableToLineField.parmFieldId() != fieldNum("Field id "))
{
update = true;
refreshable = true;
}

Code:
Standard: Line Num(97)
return dialog;
Replace with:
if(update)
{
return dialog;
}
else
{
return null;   
}
//Related class list
//Common for purch and Sales
SalesPurchTableToLineUpdatePrompt
SalesPurchTableToLineField
SalesPurchTableToLineParametersForm
//Purchase
PurchTable2LineField
PurchTable2LineParametersForm
PurchTable2LineUpdate
PurchTable2LineUpdatePrompt
//Sales
SalesTable2LineField
SalesTable2LineParametersForm
SalesTable2LineUpdate
SalesTable2LineUpdatePrompt

Validate Email Id in ax 2012

static boolean validateEmail(str _email)
{
    str emailAddressFilter = @"^[^@]+@[^@]+\.[^@]+$";
    System.Text.RegularExpressions.Regex regEx;
    System.Text.RegularExpressions.Match regMatch;
    str email;
    List emailAddresses;
    ListEnumerator enum;
    boolean retVal;
    regEx = new System.Text.RegularExpressions.Regex(emailAddressFilter);
    emailAddresses = SysEmailDistributor::splitEmail(_email);
    enum = emailAddresses.getEnumerator();
    while(enum.moveNext())
    {
        email = enum.current();
        if (email)
        {
            regMatch = regEx.Match(email);
            retVal = regMatch.get_Success();
        }
        else
            retVal = false;
        if(!retVal)
            break;
    }
    return retVal;
}

Rounding in SSRS Expression based on count of Decimal place ax 2012

=iif(Fields!RoundingDecimals.value=0,FormatNumber(Fields!Fieldname.Value,3),FormatNumber(Fields!FieldName.value,fields!RoundingDecimals.Value))

Save and get last value object in ax 2012

xSysLastvalue::getLast(this);

Get Trial Balance report by Query Ax 2012

static void CheckGLEntry(Args _args)
{
    GeneralJournalEntry                 generalJournalEntry;
    GeneralJournalAccountEntry          generalJournalAccountEntry;
    FiscalCalendarPeriod                fiscalCalendarPeriod;
    TransDate             _startDate = mkDate(31,12,2015);
    TransDate             _endDate = mkDate(31,12,2016);
    Fcc_BIData          bidata;
    DimensionAttributeValueCombination  dimValueCombi;
    MainAccount     mainAccount;
    MainAccountCategory mainAccountCategory;
    DimensionAttributeLevelValueAllView dimAllviewchk;
    //Find Dimension value - function
    Description255 getDimensionValue(RecId  _recId,Name _DimensionName)
    {
        DimensionAttributeLevelValueAllView dimAllview;
        DimensionAttribute          dimAttr;
        ;
        dimAllview.clear();
        select firstOnly dimAllview
            where dimAllview.ValueCombinationRecId == _recId
                join dimAttr
                    where dimAttr.RecId == dimAllview.DimensionAttribute
                            && dimAttr.Name == _DimensionName;
        return dimAllview.DisplayValue;
    }
    //Get Voucher type
    Fcc_BIType  GetBIType(Voucher   _Voucher,Name   _LE)
    {
        Fcc_BIType  Fcc_BIType;
        ;
        changeCompany(_LE)
        {
            if(_Voucher && CustTrans::findByVoucher(_Voucher))
            {
                return Fcc_BIType::Cust;
            }
            else if(_Voucher && VendTrans::findByVoucher(_Voucher))
            {
                return Fcc_BIType::Vend;
            }
            else
            {
                return Fcc_BIType::Ledger;
            }
        }
    }
    //Get Account num Cust/Vend
    AccountNum  GetAccountNumBI(Voucher   _Voucher,Name _LE)
    {
        ;
        changeCompany(_LE)
        {
            if(_Voucher && CustTrans::findByVoucher(_Voucher))
            {
                return CustTrans::findByVoucher(_Voucher).AccountNum;
            }
            else if(_Voucher && VendTrans::findByVoucher(_Voucher))
            {
                return VendTrans::findByVoucher(_Voucher).AccountNum;
            }
            else
            {
                return "";
            }
        }
    }
    //End
    ;
    delete_from bidata;
    while select generalJournalAccountEntry
            //where generalJournalAccountEntry.LedgerAccount like  mainAccount.MainAccountId //For other than expenses and sales Account category
        join generalJournalEntry  order by AccountingDate Asc
            where generalJournalEntry.RecId == generalJournalAccountEntry.GeneralJournalEntry
                    && generalJournalEntry.AccountingDate >= _startDate
                        && generalJournalEntry.AccountingDate <= _endDate
                            && generalJournalEntry.SubledgerVoucherDataAreaId != ""
                            //&& generalJournalEntry.Ledger == Ledger::current()
        join dimAllviewchk
            where dimAllviewchk.ValueCombinationRecId == generalJournalAccountEntry.LedgerDimension
                    && dimAllviewchk.DimensionAttribute == DimensionAttribute::findByName("MainAccount",false).RecId
            join mainAccount
                where  mainAccount.MainAccountId == dimAllviewchk.DisplayValue
                            && mainAccount.MainAccountId != "9999999"
                    join mainAccountCategory
                        where mainAccountCategory.AccountCategoryRef == mainAccount.AccountCategoryRef
                                && (mainAccountCategory.AccountCategory == "INCOME" ||
                                    mainAccountCategory.AccountCategory == "MTCOGS" ||
                                    mainAccountCategory.AccountCategory == "SRCOGS" ||
                                    mainAccountCategory.AccountCategory == "EMPEXP" ||
                                    mainAccountCategory.AccountCategory == "RENTEX" ||
                                    mainAccountCategory.AccountCategory == "OTHEXP" ||
                                    mainAccountCategory.AccountCategory == "DEPEXP"
                                    )
    {
        bidata.clear();
        select dimValueCombi
            where dimValueCombi.DisplayValue == generalJournalAccountEntry.LedgerAccount;
        bidata.MainAccountNum = getDimensionValue(dimValueCombi.RecId,"MainAccount");
        bidata.MainAccountName = MainAccount::findByMainAccountId(bidata.MainAccountNum).Name;
        bidata.AccountCatgeory = MainAccountCategory::findAccountCategoryRef(MainAccount::findByMainAccountId(bidata.MainAccountNum).AccountCategoryRef).AccountCategory;
        bidata.Opening = 0;//num2str(_amount,8,3,0,0,)
        if(generalJournalAccountEntry.IsCredit == NoYes::Yes)
        {
            bidata.Credit = generalJournalAccountEntry.AccountingCurrencyAmount *-1; //For summary AmountCredit
            bidata.Debit = 0; //For summary Amount Debit
        }
        else
        {
            bidata.Credit = 0;
            bidata.Debit = generalJournalAccountEntry.AccountingCurrencyAmount; //For summary Amount Debit
        }
        bidata.Closing = bidata.Debit - bidata.Credit; //For summary endingbalacne
        bidata.TransDate = generalJournalEntry.AccountingDate;
        bidata.month = mthOfYr(generalJournalEntry.AccountingDate);
        bidata.Year = year(generalJournalEntry.AccountingDate);
        bidata.BU = getDimensionValue(dimValueCombi.RecId,"BusinessUnit");
        bidata.Dept = getDimensionValue(dimValueCombi.RecId,"Department");
        bidata.Project = getDimensionValue(dimValueCombi.RecId,"Project");
        bidata.Worker = getDimensionValue(dimValueCombi.RecId,"Worker");
        bidata.LegalEntity = getDimensionValue(dimValueCombi.RecId,"LegalEntity");
        bidata.DateAreaVoucher  = curext();
        bidata.SubledgerVoucher = generalJournalEntry.SubledgerVoucher;
        bidata.Fcc_BIType = GetBIType(generalJournalEntry.SubledgerVoucher,curext());
        bidata.AccountNum = GetAccountNumBI(generalJournalEntry.SubledgerVoucher,curext());
        bidata.insert();
    }
    info("Data got refreshed");
}

Get Lastest Purchase price of an item ax 2012

private Price GetLatestPurchPrice(ItemId _item)
{
    InventItemPrice invItemprice;
    ;
    select firstOnly invItemprice order by RecId desc
        where invItemprice.ItemId == _item
            && invItemprice.PriceType == CostingVersionPriceType::Purch
                && invItemprice.CostingType == InventItemCostingType::Last;
   
    return  invItemprice.Price;
}

SQL Store Procedure sample

ALTER PROCEDURE Proc_Test
       -- Add the parameters for the stored procedure here
       @name varchar(50),
       @trns_dt datetime
AS
BEGIN
       -- SET NOCOUNT ON added to prevent extra result sets from
       -- interfering with SELECT statements.
       SET NOCOUNT ON;
    -- Insert statements for procedure here
       SELECT * from AdventureWorks2012.Sales.SalesOrderDetail D
       print @name
       --where convert(varchar(10),D.ModifiedDate,120)=convert(varchar(10),@trns_dt,120)
END
GO
--Select getdate()
--Select convert(varchar(10),GETDATE(),105)

Connecting SQL Store procedure from VS with parameter Ax 2012

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace SangeetDemo
{
    public partial class Form1 : Form
    {
        SqlConnection con;
        SqlCommand command;
        string sqlcon = @"Server=Sangeeth-PC\DEV01;Database=AdventureWorks2012;User ID=sa; Password=1234";
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            con = new SqlConnection();
            con.ConnectionString = sqlcon;
            try
            {
                con.Open();
                command = new SqlCommand();
                command.Connection = con;
                command.CommandText = "Proc_Test";
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.AddWithValue("@name", "abc");
                command.Parameters.AddWithValue("@trns_dt", DateTime.UtcNow);
                SqlDataReader reader = command.ExecuteReader();
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        MessageBox.Show(reader["SalesOrderID"].ToString());
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
    }
}

Deploy SSRS Report in X++ ax 2012

static void DeploySSRSreportsAx2012(Args _args)
{
    #AOT   
    TreeNodeIterator        reportIterator = TreeNode::findNode(#SSRSReportsPath).AOTiterator();
    SRSReportManager        srsReportManager = new SRSReportManager();
    SSRSReportConceptNode   ssrsReportConceptNode;
   
    if (!reportIterator)
        return;
   
    ssrsReportConceptNode = reportIterator.next();
    while (ssrsReportConceptNode)
    {
        try
        {
            srsReportManager.deploymentStart();
            srsReportManager.deployReport(ssrsReportConceptNode);
            srsReportManager.deploymentEnd();
        }
        catch
        {
            exceptionTextFallThrough();
        }
       
        ssrsReportConceptNode = reportIterator.next();
    }
}

Wednesday, November 30, 2016

Fixed Asset Posting Profile/Disposal (Sold/Scrap) Upload in ax 2012

//Upload FA posting profile ax 2012
//FA PP
static void ImportAssetPP(Args _args)
{
    CommaTextIO                 csvFile;
    container                   readCon;
    counter                     icount,inserted;
    Dialog                      dialog;
    DialogField                 dfFileName,dfFAName;
    FileName                    fileName;
    AssetLedger                 assetLedger;
    AssetLedgerAccounts         asseteLedgerAccounts;
    AssetTransType              AssetTransType;
    TableGroupAll               TableGroupAll;
     #File
    //Function to creation Ledger dimension
    LedgerDimensionDefaultAccount CreateLedgerDimension(MainAccountNum  _Account)
    {
        return DimensionStorage::getDefaultAccount(MainAccount::findByMainAccountId(_Account).RecId);
    }
    ;
    //Template
    //1)Account Type,2)Value Model,3)Grouping,4)FA Number/Group,5)Main Accounts,6)Offset Account
    dialog = new Dialog("Pick CSV file for upload");
    dfFileName = dialog.addField(extendedTypeStr("FilenameOpen"));
    dfFAName = dialog.addField(extendedTypeStr("AssetPostingProfile"));
    dialog.filenameLookupFilter(["All files", #AllFiles]);
    if (dialog.run())
    {
        if(dfFAName.value() == "")
        {
            throw warning("Select any one of Asset POsting profile");
        }
        assetLedger = AssetLedger::find(dfFAName.value(),false);
        csvFile = new CommaTextIo(dfFileName.value(), 'r');
        csvFile.inFieldDelimiter(',');
        readCon = csvFile.read();
        ttsBegin;
        while(csvFile.status() == IO_Status::OK)
        {
            readCon = csvFile.read();
            if(readCon)
            {
                asseteLedgerAccounts.clear();
                asseteLedgerAccounts.BookId                 = conPeek(readCon,2);
                asseteLedgerAccounts.AccountCode            = str2enum(TableGroupAll,conPeek(readCon,3));
                asseteLedgerAccounts.PostingProfile         = assetLedger.PostingProfile;
                asseteLedgerAccounts.TransType              = str2enum(AssetTransType,conpeek(readCon,1));
                asseteLedgerAccounts.AccountRelation        = conPeek(readCon,4);
                asseteLedgerAccounts.LedgerDimension        = CreateLedgerDimension(any2str(conPeek(readCon,5)));
                asseteLedgerAccounts.OffsetLedgerDimension  = CreateLedgerDimension(any2str(conPeek(readCon,6)));                              
                asseteLedgerAccounts.insert();
                icount++;
            }
        }
        ttsCommit;
    }
    info("Import COmpleted");
}
//FA disposal
static void ImportAssetPPDisposal(Args _args)
{
    CommaTextIO                 csvFile;
    container                   readCon;
    counter                     icount,inserted;
    Dialog                      dialog;
    DialogField                 dfFileName,dfFAName,dfSoldScarp;
    FileName                    fileName;
    AssetDisposalParameters     disposalParameters;
    AssetLedger                 assetLedger;
    AssetLedgerAccounts         asseteLedgerAccounts;
    AssetPostValue              AssetPostValue;
    TableGroupAll               TableGroupAll;
    AssetSoldScrap              AssetSoldScrap;
    FormStringControl   control,Control1;
     #File
    //Function to creation Ledger dimension
    LedgerDimensionDefaultAccount CreateLedgerDimension(MainAccountNum  _Account)
    {
       return DimensionStorage::getDefaultAccount(MainAccount::findByMainAccountId(_Account).RecId);
    }
    ;
    //Template
    //1)Account Type,2)Value Model,3)Grouping,4)FA Number/Group,5)Main Accounts,6)Offset Account
    dialog = new Dialog("Pick CSV file for upload");
    dfFileName = dialog.addField(extendedTypeStr("FilenameOpen"));
    dfFAName = dialog.addField(extendedTypeStr("AssetPostingProfile"));
    control1 = dfFAName.fieldControl();
    control1.mandatory(true);
    dfSoldScarp = dialog.addField(enumStr(AssetSoldScrap));
    control = dfSoldScarp.fieldControl();
    control.mandatory(true);
    dialog.filenameLookupFilter(["All files", #AllFiles]);
    if (dialog.run())
    {
        if(dfFAName.value() == "")
        {
            throw warning("Select any one of Asset POsting profile");
        }
        assetLedger = AssetLedger::find(dfFAName.value(),false);
        csvFile = new CommaTextIo(dfFileName.value(), 'r');
        csvFile.inFieldDelimiter(',');
        readCon = csvFile.read();
        ttsBegin;
        while(csvFile.status() == IO_Status::OK)
        {
            readCon = csvFile.read();
            if(readCon)
            {
                disposalParameters.clear();
                disposalParameters.BookId                 = conPeek(readCon,2);
                disposalParameters.SoldScrap              = str2enum(AssetSoldScrap,dfSoldScarp.Value());
                disposalParameters.AssetCode              = str2enum(TableGroupAll,conPeek(readCon,3));
                disposalParameters.PostingProfile         = assetLedger.PostingProfile;
                disposalParameters.PostValue              = str2enum(AssetPostValue,conpeek(readCon,1));
                disposalParameters.AssetRelation          = conPeek(readCon,4);
                disposalParameters.LedgerDimension        = CreateLedgerDimension(any2str(conPeek(readCon,5)));
                disposalParameters.OffsetLedgerDimension  = CreateLedgerDimension(any2str(conPeek(readCon,6)));                              
                disposalParameters.ValueType              = AssetPostType::All;
                disposalParameters.insert();
                icount++;
            }
        }
        ttsCommit;
    }
    info("Import COmpleted");
}

Inventory Posting  Profile Upload in ax 2012

//Inventory Posting Profile ax 2012

1) Inventory Sales Posting Profile data
//Format 1.ItemgroupId,2.SOIssue,3.SOConsumption,4.SORevenue
static void ImportSalesPosting(Args _args)
{
    SysExcelApplication     application;
    SysExcelWorkbooks       workbooks;
    SysExcelWorkbook        workbook;
    SysExcelWorksheets      worksheets;
    SysExcelWorksheet       worksheet;
    SysExcelCells           cells;
    COMVariantType          type;
    int                     row = 2;
    InventPosting           inventPosting;
    ItemGroupId             itemGroupId;
    MainAccountNum          salesOrderIssue, salesOrderConsumption, salesOrderRevenue;
    ;
    application =   SysExcelApplication::construct();
    workbooks   =   application.workbooks();
    try
    {
        workbooks.open(@"filename");
    }
    catch(Exception::Error)
    {
        throw error("File not found");
    }
    workbook = workbooks.item(1);
    worksheets = workbook.worksheets();
    worksheet = worksheets.itemFromNum(1);
    cells = worksheet.cells();
    try
    {
        ttsBegin;
        do
        {
            itemGroupId = cells.item(row, 1).value().bStr();
            salesOrderIssue = cells.item(row, 3).value().bStr();
            salesOrderConsumption = cells.item(row, 4).value().bStr();
            salesOrderRevenue = cells.item(row, 5).value().bStr();

            if (salesOrderIssue)
            {
                try
                {
                    // sales issue
                    inventPosting.InventAccountType = InventAccountType::SalesIssue;
                    inventPosting.ItemCode = InventPostingItemCode::GroupId;
                    inventPosting.ItemRelation = itemGroupId;
                    inventPosting.CostCode = TableGroupAll::All;
                    inventPosting.LedgerDimension = DimensionStorage::getDefaultAccount(MainAccount::findByMainAccountId(salesOrderIssue).RecId);
                    inventPosting.insert();
                }
                catch
                {
                    info(strFmt("Error: Item group: %1, Account: %2", itemGroupId, salesOrderIssue));
                }
            }
            if (salesOrderConsumption)
            {
                try
                {
                    // sales order consumption
                    inventPosting.InventAccountType = InventAccountType::SalesConsump;
                    inventPosting.ItemCode = InventPostingItemCode::GroupId;
                    inventPosting.ItemRelation = itemGroupId;
                    inventPosting.CostCode = TableGroupAll::All;
                    inventPosting.LedgerDimension = DimensionStorage::getDefaultAccount(MainAccount::findByMainAccountId(salesOrderConsumption).RecId);
                    inventPosting.insert();
                }
                catch
                {
                    info(strFmt("Error: Item group: %1, Account: %2", itemGroupId, salesOrderConsumption));
                }
            }
            if (salesOrderRevenue)
            {
                try
                {
                    // sales order revenue
                    inventPosting.InventAccountType = InventAccountType::SalesRevenue;
                    inventPosting.ItemCode = InventPostingItemCode::GroupId;
                    inventPosting.ItemRelation = itemGroupId;
                    inventPosting.CostCode = TableGroupAll::All;
                    inventPosting.LedgerDimension = DimensionStorage::getDefaultAccount(MainAccount::findByMainAccountId(salesOrderRevenue).RecId);
                    inventPosting.insert();
                }
                catch
                {
                    info(strFmt("Error: Item group: %1, Account: %2", itemGroupId, salesOrderRevenue));
                }
            }
            row ++;
            type = cells.item(row, 1).value().variantType();
        }
        while (type != COMVariantType::VT_EMPTY);
        ttsCommit;
    }
    catch
    {
        application.quit();
        throw error(strFmt("%1 Line Error", row));
    }
    application.quit();
    info("Import completed");
}
2) Inventory Purchase Posting  Profile Data
//Format 1.ItemgroupId,2.prodReciptAcc,3.PurchExpUnInvoicedAcc,4.PurchInvReceiptAcc,5.PurchExpProdAcc,6.purchAccrualAcc
static void ImportPurchasePosting(Args _args)
{
    SysExcelApplication     application;
    SysExcelWorkbooks       workbooks;
    SysExcelWorkbook        workbook;
    SysExcelWorksheets      worksheets;
    SysExcelWorksheet       worksheet;
    SysExcelCells           cells;
    COMVariantType          type;
    int                     row = 2;
    InventPosting           inventPosting;
    ItemGroupId             itemGroupId;
    MainAccountNum          productReceiptAccount, purchaseExpenditureUnInvoicedAccount, purchaseInventoryReceiptAccount,    purchaseExpenditureProductAccount,    purchaseAccrualAccount;
    ;
    application =   SysExcelApplication::construct();
    workbooks   =   application.workbooks();
    try
    {
        workbooks.open(@"filename");
    }
    catch(Exception::Error)
    {
        throw error("File not found");
    }
    workbook = workbooks.item(1);
    worksheets = workbook.worksheets();
    worksheet = worksheets.itemFromNum(1);
    cells = worksheet.cells();
    try
    {
        ttsBegin;
        do
        {
            itemGroupId = cells.item(row, 1).value().bStr();
            productReceiptAccount = cells.item(row, 3).value().bStr();
            purchaseExpenditureUnInvoicedAccount = cells.item(row, 4).value().bStr();
            purchaseInventoryReceiptAccount = cells.item(row, 5).value().bStr();
            purchaseExpenditureProductAccount = cells.item(row, 6).value().bStr();
            purchaseAccrualAccount = cells.item(row, 7).value().bStr();
            if (productReceiptAccount)
            {
                try
                {
                    // product receipt
                    inventPosting.InventAccountType = InventAccountType::PurchPackingSlip;
                    inventPosting.ItemCode = InventPostingItemCode::GroupId;
                    inventPosting.ItemRelation = itemGroupId;
                    inventPosting.CostCode = TableGroupAll::All;
                    inventPosting.LedgerDimension = DimensionStorage::getDefaultAccount(MainAccount::findByMainAccountId(productReceiptAccount).RecId);
                    inventPosting.insert();
                }
                catch
                {
                    info(strFmt("Error: Item group: %1, Account: %2", itemGroupId, productReceiptAccount));
                }
            }
            if (purchaseExpenditureUnInvoicedAccount)
            {
                try
                {
                    // purchase expenditure unInvoiced
                    inventPosting.InventAccountType = InventAccountType::PurchPackingSlipOffsetAccount;
                    inventPosting.ItemCode = InventPostingItemCode::GroupId;
                    inventPosting.ItemRelation = itemGroupId;
                    inventPosting.CostCode = TableGroupAll::All;
                    inventPosting.LedgerDimension = DimensionStorage::getDefaultAccount(MainAccount::findByMainAccountId(purchaseExpenditureUnInvoicedAccount).RecId);
                    inventPosting.insert();
                }
                catch
                {
                    info(strFmt("Error: Item group: %1, Account: %2", itemGroupId, purchaseExpenditureUnInvoicedAccount));
                }
            }
            if (purchaseInventoryReceiptAccount)
            {
                try
                {
                    // purchase inventory receipt
                    inventPosting.InventAccountType = InventAccountType::PurchReceipt;
                    inventPosting.ItemCode = InventPostingItemCode::GroupId;
                    inventPosting.ItemRelation = itemGroupId;
                    inventPosting.CostCode = TableGroupAll::All;
                    inventPosting.LedgerDimension = DimensionStorage::getDefaultAccount(MainAccount::findByMainAccountId(purchaseInventoryReceiptAccount).RecId);
                    inventPosting.insert();
                }
                catch
                {
                    info(strFmt("Error: Item group: %1, Account: %2", itemGroupId, purchaseInventoryReceiptAccount));
                }
            }
            if (purchaseExpenditureProductAccount)
            {
                try
                {
                    // purchase expenditure product
                    inventPosting.InventAccountType = InventAccountType::PurchConsump;
                    inventPosting.ItemCode = InventPostingItemCode::GroupId;
                    inventPosting.ItemRelation = itemGroupId;
                    inventPosting.CostCode = TableGroupAll::All;
                    inventPosting.LedgerDimension = DimensionStorage::getDefaultAccount(MainAccount::findByMainAccountId(purchaseExpenditureProductAccount).RecId);
                    inventPosting.insert();
                }
                catch
                {
                    info(strFmt("Error: Item group: %1, Account: %2", itemGroupId, purchaseExpenditureProductAccount));
                }
            }
            if (purchaseExpenditureProductAccount)
            {
                try
                {
                    // purchase accrual
                    inventPosting.InventAccountType = InventAccountType::PurchPackingSlipPurchaseOffsetAccount;
                    inventPosting.ItemCode = InventPostingItemCode::GroupId;
                    inventPosting.ItemRelation = itemGroupId;
                    inventPosting.CostCode = TableGroupAll::All;
                    inventPosting.LedgerDimension = DimensionStorage::getDefaultAccount(MainAccount::findByMainAccountId(purchaseExpenditureProductAccount).RecId);
                    inventPosting.insert();
                }
                catch
                {
                    info(strFmt("Error: Item group: %1, Account: %2", itemGroupId, purchaseExpenditureProductAccount));
                }
            }
            row ++;
            type = cells.item(row, 1).value().variantType();
        }
        while (type != COMVariantType::VT_EMPTY);
        ttsCommit;
    }
    catch
    {
        application.quit();
        throw error(strFmt("%1 Line Error", row));
    }
    application.quit();
    info("Import completed");
}
3) //Inventory Invent posting ProfileData
static void ImportInventoryPosting(Args _args)
{
    SysExcelApplication     application;
    SysExcelWorkbooks       workbooks;
    SysExcelWorkbook        workbook;
    SysExcelWorksheets      worksheets;
    SysExcelWorksheet       worksheet;
    SysExcelCells           cells;
    COMVariantType          type;
    int                     row = 2;
    InventPosting           inventPosting;
    ItemGroupId             itemGroupId;
    MainAccountNum          inventoryIssueAccount, inventoryLossAccount, inventoryReceiptAccount, inventoryProfitAccount;
    ;
    application =   SysExcelApplication::construct();
    workbooks   =   application.workbooks();
    try
    {
        workbooks.open(@"filename");
    }
    catch(Exception::Error)
    {
        throw error("File not found");
    }
    workbook = workbooks.item(1);
    worksheets = workbook.worksheets();
    worksheet = worksheets.itemFromNum(1);
    cells = worksheet.cells();
    try
    {
        ttsBegin;
        do
        {
            itemGroupId = cells.item(row, 1).value().bStr();
            inventoryIssueAccount = cells.item(row, 3).value().bStr();
            inventoryIssueAccount = strReplace(inventoryIssueAccount, "~", "");
            inventoryLossAccount = cells.item(row, 4).value().bStr();
            inventoryLossAccount = strReplace(inventoryLossAccount, "~", "");
            inventoryReceiptAccount = cells.item(row, 5).value().bStr();
            inventoryReceiptAccount = strReplace(inventoryReceiptAccount, "~", "");
            inventoryProfitAccount = cells.item(row, 6).value().bStr();
            inventoryProfitAccount = strReplace(inventoryProfitAccount, "~", "");
            if (inventoryIssueAccount)
            {
                try
                {
                    // inventory issue
                    inventPosting.InventAccountType = InventAccountType::InventIssue;
                    inventPosting.ItemCode = InventPostingItemCode::GroupId;
                    inventPosting.ItemRelation = itemGroupId;
                    inventPosting.CostCode = TableGroupAll::All;
                    inventPosting.LedgerDimension = DimensionStorage::getDefaultAccount(MainAccount::findByMainAccountId(inventoryIssueAccount).RecId);
                    inventPosting.insert();
                }
                catch
                {
                    info(strFmt("Error: Item group: %1, Account: %2", itemGroupId, inventoryIssueAccount));
                }
            }
            if (inventoryLossAccount)
            {
                try
                {
                    // inventory loss
                    inventPosting.InventAccountType = InventAccountType::InventLoss;
                    inventPosting.ItemCode = InventPostingItemCode::GroupId;
                    inventPosting.ItemRelation = itemGroupId;
                    inventPosting.CostCode = TableGroupAll::All;
                    inventPosting.LedgerDimension = DimensionStorage::getDefaultAccount(MainAccount::findByMainAccountId(inventoryLossAccount).RecId);
                    inventPosting.insert();
                }
                catch
                {
                    info(strFmt("Error: Item group: %1, Account: %2", itemGroupId, inventoryLossAccount));
                }
            }
            if (inventoryReceiptAccount)
            {
                try
                {
                    // inventory receipt
                    inventPosting.InventAccountType = InventAccountType::InventReceipt;
                    inventPosting.ItemCode = InventPostingItemCode::GroupId;
                    inventPosting.ItemRelation = itemGroupId;
                    inventPosting.CostCode = TableGroupAll::All;
                    inventPosting.LedgerDimension = DimensionStorage::getDefaultAccount(MainAccount::findByMainAccountId(inventoryReceiptAccount).RecId);
                    inventPosting.insert();
                }
                catch
                {
                    info(strFmt("Error: Item group: %1, Account: %2", itemGroupId, inventoryReceiptAccount));
                }
            }
            if (inventoryProfitAccount)
            {
                try
                {
                    // inventory profit
                    inventPosting.InventAccountType = InventAccountType::InventProfit;
                    inventPosting.ItemCode = InventPostingItemCode::GroupId;
                    inventPosting.ItemRelation = itemGroupId;
                    inventPosting.CostCode = TableGroupAll::All;
                    inventPosting.LedgerDimension = DimensionStorage::getDefaultAccount(MainAccount::findByMainAccountId(inventoryProfitAccount).RecId);
                    inventPosting.insert();
                }
                catch
                {
                    info(strFmt("Error: Item group: %1, Account: %2", itemGroupId, inventoryProfitAccount));
                }
            }
            row ++;
            type = cells.item(row, 1).value().variantType();
        }
        while (type != COMVariantType::VT_EMPTY);
        ttsCommit;
    }
    catch
    {
        application.quit();
        throw error(strFmt("%1 Line Error", row));
    }
    application.quit();
    info("Import completed");
}

Vendor/Customer-Opening,Closing,Transaction AmountCur,AmountMST in Summary Balance

//VendorCustomer-Opening,Closing,AmountCur,AmountMST in Summary Balance

 vendTable.openBalanceCur(fromDate,toDate,assessmentDate,_CurrencyCode); //for Acc cur Mst
 CustTable.openBalanceCur(fromDate,toDate,assessmentDate,_CurrencyCode);
static void VendCustBalanceCheck(Args _args)
{
    VendTable     vendTableSummary; 
    TmpCustVendTrans    tmpCustVendTrans;
    ;
   while select vendTableSummary
    {
        tmpCustVendTrans.setTmpData(TmpCustVendTrans::vendTransBalanceCurrency(vendTableSummary.AccountNum,True));
           
        while select tmpCustVendTrans
        {
            info(strFmt("%1,%2,%3,%4,%5",vendTableSummary.AccountNum,tmpCustVendTrans.CurrencyCode,
                                         vendTableSummary.openBalanceCur(dateNull(),today()-1,today(),tmpCustVendTrans.CurrencyCode),
                                         tmpCustVendTrans.AmountCur,
                                         (vendTableSummary.openBalanceCur(dateNull(),today()-1,today(),tmpCustVendTrans.CurrencyCode)) -
                                                tmpCustVendTrans.AmountCur));
        }
    }
}

Clear marking in ax 2012 Invent Trans

//Clear marking in ax 2012 Invent Trans

public void clearMarking()
{
//this == inventTrans
    this.MarkingRefInventTransOrigin    = 0;
}

Set Default value in ax Contract class

//Set Default value in ax Contract class
ContractClass implements SysOperationInitializable
Method : initialize

AX Security Development Tool Reference

http://kaya-consulting.com/tips-on-ax-2012-security-development-tool-part-1/
http://kaya-consulting.com/tips-on-ax-2012-security-development-tool-part-2/
http://kaya-consulting.com/tips-on-ax-2012-security-development-tool-part-3/
http://kaya-consulting.com/tips-on-ax-2012-security-development-tool-part-4/
http://kaya-consulting.com/tips-on-ax-2012-security-development-tool-part-5/
http://kaya-consulting.com/tips-on-ax-2012-security-development-tool-part-6/
http://kaya-consulting.com/security-development-tool-part-7/

Get Aging bucket in ax 2012

//Get Aging bucket in ax 2012

static void Fcc_CheckBucketSplitUp(Args _args)
{
    CustVendReportName       _agingPeriodDefinition = "3";
    TransDate                _zeroDate = today();
    QueryRun                    queryRun;
    QueryBuildDataSource        qbds;
    TmpStatPer                  tmpStat;
    TransDate                   datePointer;
    StatRepIntervalLine         statRepIntervalLine;
    StatRepInterval             statRepInterval;
    RecordInsertList            recordInsertList;
    int                         bucket;
    ForwardBackwardPrinting     direction;
    Fcc_inventoryAgingPeriodScaleTmp    agingPeriodTmp;
    int i;
    Query                       query = new Query();
    TmpStatPer                  tmpStatPer = TmpStatPer::createDefName(_agingPeriodDefinition,_zeroDate); // Need to modify if aging bucket table is customize means..Table TmpStatPer Method CreateDefName for Newly created table

    void addLine(TransDate _transDate, str _description,  ItemAgingIndicator _indicator, int _bucketNumber)
    {
        agingPeriodTmp.TransDate            = _transDate;
        agingPeriodTmp.BucketDescription    = _description;
        agingPeriodTmp.AgingIndicator       = _indicator;
        agingPeriodTmp.BucketNumber         = _bucketNumber;
        recordInsertList.add(agingPeriodTmp);
    }
    delete_from agingPeriodTmp;
    direction = (select PrintDirection from statRepInterval where statRepInterval.Name == _agingPeriodDefinition).PrintDirection;
    qbds = query.addDataSource(tableNum(TmpStatPer));
    recordInsertList = new RecordInsertList(tableNum(Fcc_InventoryAgingPeriodScaleTmp), true, true, true, false, true, agingPeriodTmp);
    switch (direction)
    {
        case ForwardBackwardPrinting::Forward:
            qbds.addSortField(fieldNum(TmpStatPer, StartDate), SortOrder::Ascending);
            bucket = 1;
            break;
        case ForwardBackwardPrinting::Backward:
            qbds.addSortField(fieldNum(TmpStatPer, StartDate), SortOrder::Descending);
            bucket = int642int((select count(RecId) from statRepIntervalLine where statRepIntervalLine.Name == _agingPeriodDefinition).RecId);
            break;
    }
    queryRun = new QueryRun(query);
    queryRun.setCursor(tmpStatPer);
    while (queryRun.next())
    {
        tmpStat = queryRun.getNo(1) as TmpStatPer;
        if (tmpStat.StartDate == dateNull())
        {
            addLine(tmpStat.StartDate, tmpStat.Description, tmpStat.InvoiceQty, bucket);
            addLine(tmpStat.EndDate, tmpStat.Description, tmpStat.InvoiceQty, bucket);
        }
        if (tmpStat.StartDate != dateNull() && tmpStat.EndDate != dateMax())
        {
            for (datePointer = tmpStat.StartDate; datePointer <= tmpStat.EndDate; datePointer++)
            {
                // means that if we order buckets in aging period definition ASC from the past to future - each bucket will have a corresponding int, to be used afterwards as bucket number.
                addLine(datePointer, tmpStat.Description, tmpStat.InvoiceQty, bucket);
            }
        }
        if (tmpStat.EndDate == dateMax())
        {
            addLine(tmpStat.StartDate, tmpStat.Description, tmpStat.InvoiceQty, bucket);
            addLine(tmpStat.EndDate, tmpStat.Description, tmpStat.InvoiceQty, bucket);
        }
        if (direction == ForwardBackwardPrinting::Forward)
        {
            bucket++;
        }
        else
        {
            bucket--;
        }
    }
    recordInsertList.insertDatabase();
    //Deletion and updation of aging bucket
    ttsBegin;
    for(i=1;i<=6;i++)
    {
        agingPeriodTmp.clear();
        select forUpdate agingPeriodTmp order by RecId Asc
            where agingPeriodTmp.BucketNumber == i;
        if(agingPeriodTmp)
        {
            agingPeriodTmp.Updated = NoYes::Yes;
            agingPeriodTmp.Update();
        }
        agingPeriodTmp.clear();
        select forUpdate agingPeriodTmp order by RecId Desc
            where agingPeriodTmp.BucketNumber == i;
        if(agingPeriodTmp)
        {
            agingPeriodTmp.Updated = NoYes::Yes;
            agingPeriodTmp.Update();
        }
    }
    delete_from agingPeriodTmp where agingPeriodTmp.Updated == NoYes::No;
    ttsCommit;
}

Getting Aging date by days,Month,year,Qr in ax 2012

//Getting Aging date by days,Month,year,Qr in ax 2012

TransDate startDate(TransDate initDate = systemDateGet())
{
    Futures                 futures;
    recId                   calendarRecId = CompanyInfo::fiscalCalendarRecId();
    ;
    switch(this.IntervalType)
    {
        case PerDayWeekMthQtYr::Period:
            return FiscalCalendars::findPeriodStartDateByDateWithIndex(calendarRecId,initDate,this.Qty+1);
        case PerDayWeekMthQtYr::Day :
            futures = new Futures(initDate,
                                 (this.Qty+1),
                                 PeriodUnit::Day);
            return futures.next();
        case PerDayWeekMthQtYr::Week:
            futures = new Futures(dateStartWk(initDate),
                                 (this.Qty   * 7 +7),
                                 PeriodUnit::Day);
            return futures.next();
        case PerDayWeekMthQtYr::Month:
            futures = new Futures(dateStartMth(initDate),
                                 (this.Qty+1),
                                 PeriodUnit::Month);
            return futures.next();
        case PerDayWeekMthQtYr::Quarter:
            futures = new Futures(dateStartQtr(initDate),
                                 (this.Qty * 3 +3),
                                 PeriodUnit::Month);
            return futures.next();
        case PerDayWeekMthQtYr::Year:
            futures = new Futures(dateStartYr(initDate),
                                 (this.Qty+1),
                                 PeriodUnit::Year);
            return futures.next();
        case PerDayWeekMthQtYr::Unlimited:
            return dateNull();
    }
    return dateNull();
}

Hiding Parameter in UI builder ax 2012 from Controller class caller

//Hiding Parameter in UI builder ax 2012 based on Controller caller class


if (this.controller().parmArgs().menuitemName() == #yourMenuItemName)
     {
           grp.visible(false);
     }

Get Table Properties in ax 2012

//Get Table Properties in ax 2012

static void TableProperties(Args _args)
{
    DictTable       dictTable;
    DictField       dictField;
    int             i, cnt;
 
    dictTable = new DictTable(tableNum(CustTrans));
    cnt = dictTable.fieldCnt();
    for (i= 1; i<=cnt;i++)
    {
        dictField = new DictField(tableNum(CustTrans),dictTable.fieldCnt2Id(i));
        if (dictField.mandatory())
        {
            info (strFmt("Field %1 is mandatory.",dictField.label()));
        }
    }
   
}

Tuesday, October 18, 2016

Record Lock in SQL

//Record Lock in SQL
select cmd,* from sys.sysprocesses
where blocked > 0

exec sp_lock
exec sp_who
exec sp_who2

select
  object_name(resource_associated_entity_id) as 'TableName' ,*
from
  sys.dm_tran_locks
where resource_type = 'OBJECT'
  and resource_database_id = DB_ID()
SELECT
     blocking_session_id AS BlockingSessionID,
     session_id AS VictimSessionID,
    
     (SELECT [text] FROM sys.sysprocesses
      CROSS APPLY sys.dm_exec_sql_text([sql_handle])
      WHERE spid = blocking_session_id) AS BlockingQuery,
    
     [text] AS VictimQuery,
     wait_time/1000 AS WaitDurationSecond,
     wait_type AS WaitType,
     percent_complete AS BlockingQueryCompletePercent
FROM sys.dm_exec_requests
CROSS APPLY sys.dm_exec_sql_text([sql_handle])
WHERE blocking_session_id > 0

http://shahnawazdba06.blogspot.com/2016/05/find-table-which-has-row-lock.html

Monday, September 12, 2016

New Customize Scripts Method for AX Develper in ax 2012

//New Customize Sys Develper Method in ax 2012

//Adding new method in Scripts method in ax Development window
Image :

//Class-> xppsource
 New method -> Find (Ex)

public Source findMethod(TableName _tableName)
{
    str method;
    DictTable dictTable;
    DictIndex dictIndex;
    DictField dictField;
    FieldName fieldName;
    DictType dictType;
    DictEnum dictEnum;
    int fieldCount;
    int i;
    container fields1;
    container fields2;
    container fields3;
    IdentifierName varName;
    IdentifierName varType;
    ;
    method = 'public static %1 find' + '(%2, boolean _forUpdate = false)%5' + '{%5' + ' %1 table;%5' +  '%5' + ' if (%3)%5' +
            ' {%5' +' if (_forUpdate)%5' + ' table.selectForUpdate(_forUpdate);%5' + '%5' + ' select firstOnly table%5' + ' where %4;%5' +
            ' }%5' + ' return table;%5' + '}';
    dictTable = new DictTable(tableName2id(_tableName));
    dictIndex = dictTable.indexObject(
    dictTable.replacementKey() ?
    dictTable.replacementKey() :
    dictTable.primaryIndex());
    if (dictIndex)
    {
        fieldCount = dictIndex.numberOfFields();
        for (i = 1; i <= fieldCount; i++)
        {
            dictField = new dictField(
            dictTable.id(),
            dictIndex.field(i));
            fieldName = dictField.name();
            varName = '_' + strLwr(subStr(fieldName,1,1)) +
            subStr(fieldName,2,strLen(fieldName)-1);
            if (dictField.typeId())
            {
                dictType = new DictType(dictField.typeId());
                varType = dictType.name();
            }
            else if (dictField.enumId())
            {
                dictEnum = new DictEnum(dictField.enumId());
                varType = dictEnum.name();
            }
            else
            {
                throw error(strfmt("Field '%1' type is not defined",fieldName));
            }
            fields1 += strFmt('%1 %2',varType,varName);
            fields2 += varName;
            fields3 += strFmt('table.%1 == %2',fieldName,varName);
        }
    }
    source = strFmt(method,_tableName,con2Str(fields1,', '),con2Str(fields2, ' && '),con2Str(fields3, #newLine + strRep(' ', 14) + '&& '),#newLine);
    return source;
}


// Class->EditorScrpts
public void template_method_find(Editor _editor)
{
    TreeNode objNode;
    xppSource xpp;
    Source template;
    objNode = EditorScripts::getApplObjectNode(_editor);
    if (!objNode)
    {
        return;
    }
    _editor.gotoLine(1);
    _editor.firstLine();
    while (_editor.moreLines())
    {
        _editor.deleteLines(1);
        _editor.nextLine();
    }
    xpp = new xppSource();
    template = xpp.findMethod(objNode.AOTname());
    _editor.insertLines(template);
}

//Class->EditorScripts->Method(isApplicableMethod)
case methodStr(EditorScripts, template_method_find):
            return (_aotNode && _aotNode.treeNodeType().id() == #NT_DBTABLE);


//Final Output in Ax development Workspace

Image:


Enjoy...

Upload data from Excel in D365FO X++

 Action Menu Item: SAN_UploadExcelData Object type: Class Object: <Controller class name> Label: <> Class: Controller class clas...