Tuesday, 29 November 2016

AX 2012: Create a Batch Job through SysOperation Framework

How to extract Inventory on-hand through batch job

In this post we’ll learn how to create a very basic custom Batch job using SysOperation framework. We’ll use the base controller class SysOperationServiceController and develop a custom service operation class to achieve the goal.
Requirement:
To create a Batch job to extract inventory on-hand and insert records into a custom table IDT_InventOnhandExtractionTMP.
Project overview:

The project shows how simple yet powerful the SysOperation framework is for developing custom batch jobs as opposed to RunBase framework since the minimum development needed to create a fully functional batch job is to create a custom service operation class defining a single method giving the implementation for the batch operation to be performed.
Development steps:
1. Create a service operation class IDT_InventOnhandExtractionService having the following class declaration:

2. Create sub-methods in the class giving a suitable name like initFrom.... having the following definition:



3. Create a new method in the class giving a suitable name like processData having the following definition:

[ SysEntryPointAttribute(false) ]
public void processData()
{
    InventTable             inventTable;
    InventSum               inventSum;
    InventDim               inventDim;
    InventDimId             inventDimId = "AllBlank";
    //SysTableBrowser         sysTableBrowser = new SysTableBrowser();

    //Determines the runtime
    if (xSession::isCLRSession())
    {
        info('Running in a CLR session.');
    }
    else
    {
        info('Running in an interpreter session.');

        //Determines the tier
        if (isRunningOnServer())
        {
            info('Running on the AOS.');
        }
        else
        {
            info('Running on the Client.');
        }
    }

    delete_from inventOnhandExtractionTMPExt
        where inventOnhandExtractionTMPExt.ItemDataAreaId == curext();

    //inventOnhandExtractionTMP.clear();
    while select ItemId,Closed,ClosedQty,InventDimId,PhysicalInvent from inventSum
        join ItemId,NameAlias,dataAreaId,Product from inventTable
            where inventSum.ItemId      == inventTable.ItemId
            &&    inventSum.Closed      == NoYes::No
            &&    inventSum.ClosedQty   == NoYes::No
            &&    inventSum.PhysicalInvent > 0
            &&    inventTable.NameAlias != "Obsolete"
            &&    inventTable.NameAlias != "Use to Depletion"
    {
        ttsBegin;
        inventOnhandExtractionTMP.ItemId                = inventSum.ItemId;
        inventOnhandExtractionTMP.NameAlias             = inventTable.NameAlias;
        inventOnhandExtractionTMP.ItemName              = inventTable.itemName();
        inventOnhandExtractionTMP.ItemDataAreaId        = inventTable.dataAreaId;
        inventOnhandExtractionTMP.PhysicalInvent        = inventSum.PhysicalInvent;

        inventDim = InventDim::find(inventSum.InventDimId);
        inventOnhandExtractionTMP.InventSiteId          = inventDim.InventSiteId;
        inventOnhandExtractionTMP.InventLocationId      = inventDim.InventLocationId;
        inventOnhandExtractionTMP.wmsLocationId         = inventDim.wMSLocationId;
        inventOnhandExtractionTMP.InventBatchId         = inventDim.inventBatchId;

        this.initFromInventItemGroupItem(inventSum);
        this.initFromInventTableModule(inventSum);
        this.initFromInventBatch(inventSum, inventOnhandExtractionTMP.InventBatchId);

        inventOnhandExtractionTMP.insert();
        ttsCommit;
        //counter++;
    }
    //sysTableBrowser.run(tableNum(IDT_MaterialExtractionTMP));
}

4. Create a new Action type menu item IDT_InventOnhandExtractionService pointing to SysOperationServiceController.
5. Set the parameters of the action menu item to the service operation just created, IDT_InventOnhandExtractionService.processData.

6. Compile the service operation class and generate incremental CIL.
7.Click on the action menu item to run the batch job. Check the Batch processing checkbox to run the job in CLR runtime which is the batch server execution environment.


8. Click System administration > Inquiries > Batch jobs to view the status of the job. You may also click on the Log button to view the messages written to infolog during the job execution.

Happy DAXing...

SSRS Report header (Company name, Page number and current date & time)

How to display company name, Page number and current (print) date & time in SSRS header.

expression for Company name:

=Microsoft.Dynamics.Framework.Reports.DataMethodUtility.GetFullCompanyNameForUser(Parameters!AX_CompanyName.Value, Parameters!AX_UserContext.Value)

Expression for page number

=System.String.Format(Labels!@SYS182565, Globals!PageNumber & space(2) & Labels!@sys26401 & space(2) & Globals!TotalPages)

Expression for Print date & time.

=Microsoft.Dynamics.Framework.Reports.DataMethodUtility.ConvertUtcToAxUserTimeZoneForUser(Parameters!AX_CompanyName.Value, Paraemeters!AX_UserContext.Value, System.DateTime.UtcNow, "d", Parameters!AX_RenderingCulture.Value) & vbCrLf & Microsoft.Dynamics.Framework.Reports.DataMethodUtility.ConvertUtcToAxUserTimeZoneForUser(Parameters!AX_CompanyName.Value, Parameters!AX_UserContext.Value, System.DateTime.UtcNow, "t", Parameters!AX_RenderingCulture.Value)


Happy DAXing....

Tuesday, 18 October 2016

Select Statement Examples [AX 2012]

All of the following examples use the CustTable.

General Examples

The following X++ job shows several small examples of how you can use the select statement.
static void SelectRecordExamples3Job(Args _args)
{
    CustTable custTable;  // As of AX 2012.

    // A customer is found and returned in custTable
    select * from custTable;
    info("A: " + custTable.AccountNum);

    // A customer with account number > "100" is found
    select * from custTable
        where custTable.AccountNum > "100";
    info("B: " + custTable.AccountNum);

    // Customer with the lowest account number > "100" found:
    select * 
        from custTable 
            order by accountNum
                where custTable.AccountNum > "100";
    info("C1: " + custTable.AccountNum);

    // The next customer is read
    next custTable;
    info("C2: " + custTable.AccountNum);

    // Customer with higest account number
    // (greater than 100) found: Fourth Coffee
    select * 
        from custTable 
            order by accountNum desc
                where custTable.accountNum > "100";
    info("D1: " + custTable.AccountNum);
    
    // The next record is read (DESC): Fabrikam, Inc.
    next custTable; 
    info("D2: " + custTable.AccountNum);

    // Customer with highest account number found: Fourth Coffee
    select reverse custTable 
        order by accountNum;
    info("E: " + custTable.AccountNum);

    // Customer with "lowest" name and account number
    // in the interval 100 to 1000 is found. This is Coho Winery.
    select * 
        from custTable 
            order by DlvMode
                where custTable.accountNum > "100"
                    && custTable.accountNum < "1000";
    info("F: " + custTable.AccountNum);

    // The count select returns the number of customers.
    select count(AccountNum) 
        from custTable;
    // Prints the result of the count
    info(strFmt("G: %1 = Count of AccountNums", custTable.accountNum));

    // Returns the average credit max for non-blocked customers.
    select avg(CreditMax) 
        from custTable
            where custTable.blocked == CustVendorBlocked::No;
    // Prints the result of the avg
    info(strFmt("H: %1 = Average CreditMax", custTable.CreditMax));
}
/*** Display from infolog:
Message (02:00:34 pm)
A: 4000
B: 4000
C1: 4000
C2: 4001
D1: 4507
D2: 4506
E: 4507
F: 
G: 29 = Count of AccountNums
H: 103.45 = Average CreditMax
***/

Join Sample

This X++ code sample shows how an inner join can be performed as part of an SQL select statement.
The sample also shows an order by clause that has each field qualified by a table name. This enables you to control how the retrieved records are sorted by using only one order by clause.
static void SelectJoin22Job(Args _args)
{
    CustTable xrecCustTable;
    CashDisc xrecCashDisc;
    struct sut4;

    sut4 = new struct("str AccountNum; str CashDisc; str Description");

    while select firstOnly10 *
        from xrecCustTable
            order by xrecCashDisc.Description
                join xrecCashDisc
                    where xrecCustTable.CashDisc ==
                        xrecCashDisc.CashDiscCode
                        && xrecCashDisc.Description LIKE "*Days*"
    {
        sut4.value("AccountNum", xrecCustTable.AccountNum );
        sut4.value("CashDisc", xrecCashDisc.CashDiscCode );
        sut4.value("Description", xrecCashDisc.Description );

        info(sut4.toString());
    }
/*********  Actual Infolog output
Message (02:29:37 pm)
(AccountNum:"1101"; CashDisc:"0.5%D10"; Description:"0.5% 10 days")
(AccountNum:"4001"; CashDisc:"0.5%D10"; Description:"0.5% 10 days")
(AccountNum:"1102"; CashDisc:"0.5%D30"; Description:"0.5% 30 days")
(AccountNum:"1201"; CashDisc:"0.5%D30"; Description:"0.5% 30 days")
(AccountNum:"2211"; CashDisc:"0.5%D30"; Description:"0.5% 30 days")
(AccountNum:"1202"; CashDisc:"1%D15"; Description:"1% 15 days")
(AccountNum:"1203"; CashDisc:"1%D07"; Description:"1% 7 days")
(AccountNum:"2212"; CashDisc:"1%D07"; Description:"1% 7 days")
(AccountNum:"2213"; CashDisc:"1%D07"; Description:"1% 7 days")
(AccountNum:"2214"; CashDisc:"1%D07"; Description:"1% 7 days")
*********/
}

Group By and Order By

This X++ code sample shows that the fields in the group by clause can be qualified with a table name. There can be multiple group by clauses instead of just one. The fields can be qualified by table name in only one group by clause. Use of table name qualifiers is recommended.
The order by clause follows the same syntax patterns that group by follows. If provided, both clauses must appear after the join (or from) clause, and both must appear before the where clause that might exist on the same join. It is recommended that all group by and order by and whereclauses appear immediately after the last join clause.
static void SelectGroupBy66Job(Args _args)
{
    CustTable xrecCustTable;
    CashDisc xrecCashDisc;
    struct sut4;

    sut4 = new struct("str AccountNum_Count; str CashDisc; str Description");

    while select
        count(AccountNum)
        from xrecCustTable
            order by xrecCashDisc.Description
                join xrecCashDisc
        group by
            xrecCashDisc.CashDiscCode
                    where xrecCustTable.CashDisc ==
                        xrecCashDisc.CashDiscCode
                        && xrecCashDisc.Description LIKE "*Days*"
    {
        sut4.value("AccountNum_Count", xrecCustTable.AccountNum );
        sut4.value("CashDisc", xrecCashDisc.CashDiscCode );
        sut4.value("Description", xrecCashDisc.Description );

        info(sut4.toString());
    }
/*********  Actual Infolog output
Message (02:45:26 pm)
(AccountNum_Count:"2"; CashDisc:"0.5%D10"; Description:"")
(AccountNum_Count:"3"; CashDisc:"0.5%D30"; Description:"")
(AccountNum_Count:"4"; CashDisc:"1%D07"; Description:"")
(AccountNum_Count:"1"; CashDisc:"1%D15"; Description:"")
(AccountNum_Count:"1"; CashDisc:"2%D30"; Description:"")
(AccountNum_Count:"1"; CashDisc:"3%D10"; Description:"")
*********/
}

This X++ code sample shows how to count number of records in a table through an SQL select statement. I don't want to use while loop.
static void recordCountInInventTable(Args _args)
{
    InventTable     inventTable;
    
    select count(RecId) from inventTable
        where inventTable.NameAlias != "Obsolete"
        &&    inventTable.NameAlias != "Use to Depletion"
        &&    inventTable.FSProductApprovalStatus == FSProductApprovalStatus::Approved;
    //return inventTable.RecId;
    info(strFmt('%1', inventTable.RecId));
}

Or

/// <summary> /// Get resource poool count. /// </summary> /// <returns> /// resource pool count. /// </returns> protected int getResourcePoolCount() { select count(Rank) from resourceTable where resourceTable.UserSession == _userSession && resourceTable.ResourceSet == ProjResourceSet::Pool;
return resourceTable.Rank; }

Happy DAXing...

How to Open a table in AX 2012 through X++ code

Opening the table from x++ code

This code helps you to open the any Table from X++ code. Here is an example for SalesTable, just copy and paste this into a job you will get the table.

static void TableBrowser(Args _args)
{
     SysTableBrowser sysTableBrowser = new SysTableBrowser();

    //Browse the SalesTable table
   sysTableBrowser.run(tablenum(SalesTable ));
}



How to open a form by using AX code

In the shortest example, all it takes is one line of code.

new MenuFunction(MenuItemDisplayStr(CustTable),MenuItemType::Display).run();

The above code will open the CustTable form. That's all it takes, it's that simple.
Now if you want to supply some arguments to the opening form, this is also possible with the optional args parameter.
Like this for example:

static void OpenFormByCodeA()
{ Args args = new Args();
 
args.record(CustTable::find('ABC'));
new MenuFunction(MenuItemDisplayStr(CustTable),MenuItemType::Display).run(Args);
}

This code will open the CustTable form and filter out the customer with accountnumber ABC.
Use the args methods like parm and parmEnum to provide your target form with more data.

If you want even more control on opening the form from code, this is also possible.
This next example gives the same result as the previous one.

static void OpenFormByCodeB()
FormRun formRun;
Args args = new Args();

args.name(formstr(CustTable));
args.record(CustTable::find('ABC'));

formRun = ClassFactory.formRunClass(args);
formRun.init();
formRun.run();
formRun.wait();
}


Now if we tweak this a little bit, we can add our code
Like this:

static void OpenFormByCodeB()
Object formRun;
Args args = new Args();

args.name(formstr(CustTable));
args.record(CustTable::find('ABC'));

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

formRun.yourmethodgoeshere(); /* !!

formRun.run();
formRun.wait();
}

Happy DAXing...

How to Open a table in AX 2012 through X++ code

Opening the table from x++ code

This code helps you to open the any Table from X++ code. Here is an example for SalesTable, just copy and paste this into a job you will get the table.

static void TableBrowser(Args _args)
{
     SysTableBrowser sysTableBrowser = new SysTableBrowser();

    //Browse the SalesTable table
   sysTableBrowser.run(tablenum(SalesTable ));
}



How to open a form by using AX code

In the shortest example, all it takes is one line of code.

new MenuFunction(MenuItemDisplayStr(CustTable),MenuItemType::Display).run();

The above code will open the CustTable form. That's all it takes, it's that simple.
Now if you want to supply some arguments to the opening form, this is also possible with the optional args parameter.
Like this for example:

static void OpenFormByCodeA()
{ Args args = new Args();
 
args.record(CustTable::find('ABC'));
new MenuFunction(MenuItemDisplayStr(CustTable),MenuItemType::Display).run(Args);
}

This code will open the CustTable form and filter out the customer with accountnumber ABC.
Use the args methods like parm and parmEnum to provide your target form with more data.

If you want even more control on opening the form from code, this is also possible.
This next example gives the same result as the previous one.

static void OpenFormByCodeB()
FormRun formRun;
Args args = new Args();

args.name(formstr(CustTable));
args.record(CustTable::find('ABC'));

formRun = ClassFactory.formRunClass(args);
formRun.init();
formRun.run();
formRun.wait();
}


Now if we tweak this a little bit, we can add our code
Like this:

static void OpenFormByCodeB()
Object formRun;
Args args = new Args();

args.name(formstr(CustTable));
args.record(CustTable::find('ABC'));

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

formRun.yourmethodgoeshere(); /* !!

formRun.run();
formRun.wait();
}

Happy DAXing...

Friday, 14 October 2016

Export Obsolete Material from AX to Excel

static void ExportObsoluteItemIntoExcel(Args _args)
{

EcoResProduct ecoResProduct;
 
//EcoResProductMaster ecoResProductMaster;


InventTable inventTable;

SysExcelApplication application;

SysExcelWorkbooks workbooks;

SysExcelWorkbook workbook;

SysExcelWorksheets worksheets;

SysExcelWorksheet worksheet;

SysExcelCells cells;

SysExcelCell cell;

SysExcelFont font;

int row = 1;


application = SysExcelApplication::construct();

workbooks = application.workbooks();

workbook = workbooks.add();

worksheets = workbook.worksheets();

worksheet = worksheets.itemFromNum(1);

cells = worksheet.cells(); 
cells.range('A:A').numberFormat('@');

// Setting Header values

/*cell = cells.item(1, 1);

cell.value("Item number");

font = cell.font();

font.bold(true);*/

cells.item(1, 1).value("Item number");

cells.item(1, 1).font().bold(true);

cells.item(1, 2).value("Search name");

cells.item(1, 2).font().bold(true);

cells.item(1, 3).value("Item name");

cells.item(1, 3).font().bold(true);

while select ecoResProduct

where ecoResProduct.SearchName == "Obsolete"

|| ecoResProduct.SearchName == "Use to Depletion"
{
row++;
/*cell = cells.item(row, 1);
cell.value(ecoResProduct.DisplayProductNumber);*/ cells.item(row, 1).value(ecoResProduct.DisplayProductNumber);

cells.item(row, 2).value(ecoResProduct.SearchName);

cells.item(row, 3).value(ecoResProduct.productName());
}application.visible(true);
}

Friday, 22 July 2016

To add the AOS service account to the debug group

Microsoft Dynamics AX Debugging Users group

Hi,
Here we will talk about Debugging users group issue.
Suppose, if you are working with a new instance in a new machine and once you do debugging you will get an error "The X++ debugger works only for users who are in the 'Microsoft Dynamics AX Debugging users' local group of windows. Get added to the group, then login again to the windows."
For fixing this issue, we need to do some kind of setup. which are as:

  1. From the Start menu, point to All Programs, click Administrative Tools, click Computer Management, and then click Local Users and Groups.
  2. In Local Users and Groups, double-click Groups, right-click Microsoft Dynamics AX Debugging Users and click Add to Group.

Detailed:

If you see this when you expected to see the debugger:


  1. Go to Control Panel -> System and Security -> Administrative tools -> Computer Management
    (To find it quickly, press the windows key on the keyboard and start typing “Computer Management”)
  2. Click on Local Users and Groups -> Groups. In the middle pane, Click on “Microsoft Dynamics AX Debugging Users”.
  3. Click on the Add button. (Users that are already added are displayed in the members block. Mine are blacked out for privacy.)
  4. In the dialog, enter the name of the user you want to add to the Microsoft Dynamics AX Debugging Users group and click on OK.
  5. Sign out and back into the Windows account.
It is possible that only the admin has rights to add users to the Microsoft Dynamics AX Debugging Users group. In that case you will have to log in with the admin account or ask the administrator to complete these steps for you.

Happy DAXing...

How to Convert Ledger dimension into Default dimension

Display Main account from LedgerDimension and convert Ledgerdimension into Defaultdimension:

Hi,
Here We will talk, how to display MainAccountId from LedgerDimension and second, how to convert LedgerDimension into DefaultDimension so that we can display financial dimensions separately....
Code will be like:
Example-1: Suppose we need to display MainAccountId from Purchase requisition detail form/Purchase requisition lines/ Financials/ Distribution amounts (AccountingDistribution table) to Purchase requisition line grid (PurchReqLine table) then code will be like...

//created by v-vimsin on 18th July 2016
//BP deviation documented
display public MainAccountNum MSDisplayLedgerDim()
{
    PurchReqTable           purchReqTableLoc;
    AccountingDistribution  accountingDistributionLoc;

    purchReqTableLoc = PurchReqTable::find(this.PurchReqTable);

    select RecId,SourceDocumentHeader,SourceDocumentLine,LedgerDimension from accountingDistributionLoc
        where  purchReqTableLoc.SourceDocumentHeader    == accountingDistributionLoc.SourceDocumentHeader
            && this.SourceDocumentLine                  == accountingDistributionLoc.SourceDocumentLine;

    return MainAccount::find(DimensionStorage::getMainAccountIdFromLedgerDimension(accountingDistributionLoc.LedgerDimension)).MainAccountId;

}


Example-1: Suppose we need to display Cost center from Purchase requisition detail form/Purchase requisition lines/ Financials/ Distribution amounts (AccountingDistribution table) to Purchase requisition line grid (PurchReqLine table) then we will convert LedgerDimension to DefaultDimension first and then return Cost center. Code will be like...

//created by v-vimsin on 18th July 2016
//BP deviation documented
display public DimensionValue MSDisplayCostCenter()
{
    PurchReqTable                   purchReqTableLoc;
    DimensionDefault                defaultdimension;
    AccountingDistribution          accountingDistributionLoc;
    DimensionAttribute              DimensionAttributeLoc;
    DimensionAttributeValue         DimensionAttributeValueLoc;
    DimensionAttributeValueSetItem  DimAttrValueSetItemLoc;

    purchReqTableLoc = PurchReqTable::find(this.PurchReqTable);

    select RecId,SourceDocumentHeader,SourceDocumentLine,LedgerDimension from accountingDistributionLoc
        where  purchReqTableLoc.SourceDocumentHeader    == accountingDistributionLoc.SourceDocumentHeader
            && this.SourceDocumentLine                  == accountingDistributionLoc.SourceDocumentLine;

    defaultdimension =  Dimensionstorage::GetDefaultDimensionfromLedgerDimension(accountingDistributionLoc.LedgerDimension);

    select RecId,Name from DimensionAttributeLoc
        join RecId,DimensionAttribute from DimensionAttributeValueLoc
        join DimAttrValueSetItemLoc
            where DimensionAttributeValueLoc.DimensionAttribute == DimensionAttributeLoc.RecId
                && DimAttrValueSetItemLoc.DimensionAttributeValue == DimensionAttributeValueLoc.RecId
                && DimAttrValueSetItemLoc.DimensionAttributeValueSet == defaultdimension
                && DimensionAttributeLoc.Name == "@SYS343410";
    return DimAttrValueSetItemLoc.DisplayValue;
}


For this time that's it.

Happy DAXing....

Monday, 20 June 2016

How to update SID, Network domain and Network alias after restoring new DB in AX

Issue "Failed to logon to Microsoft Dynamics AX" after restoring demo/ other network domain data into SQL 

Here, We will discuss about the issue "Failed to logon to Microsoft Dynamics AX". 
Generally when we install new AOS then "MicrosoftDynamicsAX" is our default database and after synchronization/compilation we can access our AOS instance. After completing this approach we need data to start practice or work. 
So I would recommend to create new database (suppose "MsDyDemo") in your SSMS instead of overwriting over your default DB. What I mean to say, don't touch your default database (MicrosoftDynamicsAX). Now restore demo data or other network domain's data into your newly created database "MsDyDemo" and go to: Administrative tools/Microsoft Dynamics AX 2012 Server Configuration/Database connection (tab). Select "MsDyDemo" under Database name drop down and restart AOS services. Once AOS services is running then you need to access Ms Dy AX but you will get info message "Failed to logon to Microsoft Dynamics AX" in case your system domain and restored DB domain are different.

Here, for fixing this issue we need to change SID, Network domain and Alias from restored DB "MsDyDemo" so first select your default DB "MicrosoftDynamicsAX" and run SQL query 
select * from USERINFO
execute this query and select user- "Admin". Copy SID, Network domain from Admin user and save in separate Note pad or Word document. 



Now select and expand database "MsDyDemo", expand tables and select dbo.UserInfo. Right click on table dbo.UserInfo and select "Edit Top 200 Rows". 

Select User- Admin and update SID, Network domain values from Note pad or Word document (the values which we copied from default DB) and give your current user account name under NetworkAlias. Save the changes and run AOS with admin credential. Once AX gets open then go to: Systemadministration/Common/Users/Users/Import other user accounts.

I hope I cleared the concept.

Happy DAXing..... 

Update SID through SQL query

Update SID after restoring DB into AX

UPDATE USERINFO SET SID = '', NETWORKALIAS = '', NETWORKDOMAIN = '', NAME = ''


UPDATE SYSBCPROXYUSERACCOUNT SET SID = '', NETWORKALIAS = '', NETWORKDOMAIN = ''


UPDATE SYSUSERINFO SET SQMUSERGUID = '00000000-0000-0000-0000-000000000000'


DELETE FROM SYSSERVERCONFIG
DELETE FROM SYSSERVERSESSIONS
DELETE FROM SYSCLIENTSESSIONS
DELETE FROM SRSSERVERS
DELETE FROM BATCHSERVERCONFIG
DELETE FROM BATCHSERVERGROUP
DELETE FROM SYSUSERLOG
DELETE FROM BICONFIGURATION
DELETE FROM BIANALYSISSERVER
DELETE FROM SMMPHONEPARAMETERS
DELETE FROM EPGlobalParameters
DELETE FROM EPWebSiteParameters