Blog

Name is Anant Dubey and the intent to create this blog is to discuss the problems and issues that developer face in the dynamics AX development and to share the new things that come up with the new version of AX.

Friday, February 27, 2015

Developing a SSRS report using the Report Data Provider in Microsoft Dynamics AX 2012


NOTE : RDP based SSRS Reports are used when complex business logic cannot be achieved using AOT query.
Pre-requisites :
1.       Microsoft Dynamics AX 2012.
2.       Visual studio 2012
3.       SQL Server Reporting Services (SSRS) must be configured
4.       Reporting services extensions must be installed in Dynamics AX

Important Concepts:
> Report Data Provider (RDP) Class.
            Report Data Provider Class is an X++ class that is used to access and process data for a SSRS report. The RDP class processes the business logic based on a specified parameter and/or query and returns a dataset to the reporting services. In order to create a RDP class in AX, you have to extend that class with SRSReportDataProviderBase. This tells AX that this class will be used by reporting services to process the data.
Two important attributes are used in RDP classes:
1. SRSReportQueryAttribute: specifies which AOT query will be used in this report. If the RDP class uses an AOT query to process data, define this attribute at the beginning of the class.
2. SRSReportParameterAttribute: defines the data contract class that will be used by this report to prompt for parameter values. If the RDP class contains any parameters this define this attribute at the beginning of the class.
Both the attributes are optional. If the report does not use any query or does not want any parameter to filter report data, these attributes do not need to be used.
>> Data Contract Class
A data contract class is an X++ class which contains parm methods with the DataMemberAttribute defined at the beginning of the method. This class is used to define one or more parameters that will be used in a SSRS report.
>>> Table
An AX table is used as the dataset to store data for the report. The RDP class processes the data and stores it in the table which is then used by a SSRS report to render data.
A table can be a temporary table (InMemory or TempDB) or a regular table, but it is Microsoft best practice to use a temporary table.
The type of temporary table is based upon the performance considerations. InMemory temporary table is used when the data set is small, while TempDB is normally used for larger datasets to improve performance.
X++ provides support for data contract serialization through the following attributes.
·         DataContractAttribute – This attribute is applied to an X++ class and specifies that the class can be used as a data contract (that it should be serialized).
·         DataMemberAttribute – This attribute is applied to a parm method on an X++ data contract class and specifies that the data member should be serialized. The attribute can be applied to public and instance methods, as long as the method uses a get/set pattern that contains one optional parameter. The data type of the return type and the parameter should be the same. For example, [DataMemberAttribute] Int parmXX(int _x = x)

Scenario:
As part of this tutorial, the report will print a list of customers and their invoiced sales order counts.
Steps:
> First of all, create a temporary table. Open AOT > Date Dictionary > Tables.
> Right Click on Tables and create a new Table called CustReportRDPDemoTmp.
                                               
> Set the TableType property to InMemory. This will define the table as a temporary table.
                                   
> Expand the CustReportRDPDemoTmp table node and add the following fields in the table:
> The final table should look like the following:
                                   
> Now create a RDP class. Go to Classes and create a new class called CustReportRDPDemoDP by right clicking on Classes and selecting New Class. It is a best practice to suffix the RDP class name with DP .
                                   
> Open the Class declaration by right clicking on it and selecting View code.
                                   
> Now write the following code:
class CustReportRDPDemoDP extends SRSReportDataProviderBase
{
//Temporary table buffer
CustReportRDPDemoTmp custReportRDPDemoTmp;
}
> Add a new method and name it getCustReportRDPDemoTmp. This method is mandatory because reporting services uses this method to get the table buffer containing the processed data. The SRSReportDataSetAttribute attribute is used to indicate the temporary table name and also tells the reporting services to use this method to retrieve the processed data.
> Write the following code in the method:
[SRSReportDataSetAttribute(tablestr('CustReportRDPDemoTmp'))]
public CustReportRDPDemoTmp getCustReportRDPDemoTmp()
{
//select data from table buffer
select * from custReportRDPDemoTmp;
//return the buffer
return custReportRDPDemoTmp;
}
> Add a new method and name it processReport. This method contains the business logic and is called by reporting services to generate data.
> This method will query customer details and fill the temporary table buffer. Write the following code in the method:
///<summary>
/// Processes the SQL Server Reporting Services report business logic
/// </summary>
/// <remarks>
/// This method provides the ability to write the report business logic. This method will be called by
/// SSRS at runtime. The method should compute data and populate the data tables that will be returned
/// to SSRS.
/// </remarks>
public void processReport()
{
CustTable custTable;
SalesTable salesTable;
//select all customers
while select * from custTable
{
//clear the temporary table
custReportRDPDemoTmp.clear();
//assign customer account and name
custReportRDPDemoTmp.CustAccount = custTable.AccountNum;
custReportRDPDemoTmp.Name = custTable.name();
//select count of invoiced sales order of customer
select count(RecId) from salesTable
where salesTable.CustAccount == custTable.AccountNum
&& salesTable.SalesStatus == SalesStatus::Invoiced;
custReportRDPDemoTmp.SalesOrderInvoiceCount = int642int(salesTable.RecId);
//insert in temporary table buffer
custReportRDPDemoTmp.insert();
}
}
> Now create a new report. Since the development of a SSRS report is done in Visual studio, we first need to create a new project in Visual studio.
> Open Visual studio. Go to File > New > Project
> In the Installed templates section select Microsoft Dynamics AX and then select Report Model in the right pane. Name the project RDPBasedDemo and press Ok.

> A new project will be created as shown below.
                                               
> Now add a new report in the project by right clicking on the project RDPBasedDemo >Add > Report.
> A report will be added to the project with the name Report1. Rename the report RDPBasedDemo.
> Now double click the report to open it.
                                               
> The description of the individual node is given below:
a. Datasets: Datasets retrieve data from RDP class. It acts as a bridge between AX and the SSRS report. Only the fields added in the datasets can be used in a report.
b. Designs: It defines the layout of the report.
c. Images: It contains the images that you want to display in the SSRS report.
d. Data Methods: It contains the business logic which can then be used in the report.
e. Parameters: It is used to apply filtering to the data in a report. All the parameters defined in the data contract class are automatically added here when the RDP class is defined in the datasets.
> Now you will want to create a new Dataset by right clicking Datasets > Add Dataset. Name it CustDetail.
                                   
> Select the CustDetail dataset and open the properties window. Set the Data Source Type to Report Data Provider. Then select the Query field. An ellipse button appears. Click it to open a dialog box.
                                   
> This dialog box lists all the RDP classes present in the AOT. Select CustReportRDPDemoDP and press Next.
           
> Select the fields to be displayed in the report and press OK. Only the fields selected in this dialog box can be shown in the report.
           
> There are two types of designs that can be created in a SSRS report:
a. Auto design: Visual studio automatically creates a design based on the dataset provided. Auto design is the preferred method because it is easy and usually fulfills the majority scenarios.
b. Precision Design: This is used when you need custom placement of fields or the layout of the report is too complex.
> In this demo we will use Auto Design. Now right click the Designs node>Add >Auto Design. A new design is added. Rename it Design. It is recommended that you set the name of the Design to either ‘Design‘ or ‘Report‘.
           
> Now drag the CustDetail form to the Datasets node and drop it on the Design node. A table will be created which contain all the fields present in the data set. These fields will appear in the same order as in the report. So if you want to arrange the fields, right click the field and select either ‘move up’ or ‘move down’.
> The final design should look like the following:
                                   
> Now we have to define the layout of the report. Visual studio provides built in templates. Select the Design and open the properties window. Select ReportLayoutStyleTemplate in the LayoutTemplate field. Give a suitable title to the report.
                       
> Select CustDetailTable under the Design node and open the properties window. Select TableStyleAlternatingRowsTemplate in the Style Template field.
           
> The report is now completed and can be viewed. To preview the report, select the Design node, right click it and select preview.
                       
> Select the Report tab. The report will appear as shown below:

> To view this report from AX, Add the report to AOT and create an Output menu item and set the appropriate Properties. For further details on creating SSRS reporting, refer to our previous article ‘Developing SSRS report using Query‘.
















Get worker's mobile no, email and website in ax 2012

Get worker's mobile no, email and website in ax 2012

static void NamewithDetail(Args _args)
{
    HcmWorker                   hcmWorker;
    DirPerson                   dirPerson;
    DirPartyTable               dirPartyTable;
    LogisticsElectronicAddress  logisticsElectronicAddress;
    ;

    select dirPartyTable where dirPartyTable.NameAlias == "<Worker Name>"
        join logisticsElectronicAddress where logisticsElectronicAddress.RecId == dirPartyTable.PrimaryContactEmail;
        info(strFmt("%1, %2, %3, %4, %5, %6",dirPartyTable.NameAlias,logisticsElectronicAddress.Locator,dirPartyTable.primaryPhone(),dirPartyTable.primaryEmail(),dirPartyTable.primaryFax(),dirPartyTable.primaryURL()));
}

Get item's id, brand, size and category in ax 2012

static void FilterRecord(Args _args)
{
    EcoResProductCategory   ecoResProductCategory;
    EcoResProduct           ecoResProduct;
    InventTable             inventTable;
    InventTableModule       inventTableModule;
    EcoResCategory          ecoResCategory;
    S3_ItemMasterPurchase   S3_ItemMasterPurchaseloc,S3_ItemMasterPurchaselocal;
    int                     a;
    int64                   ecoresrecid,ecoresprodrecid;
    real                    mrp;
    boolean                 ret;


      while select ecoResProduct
        join inventTable where inventTable.Product == ecoResProduct.RecId //&& inventTable.PrimaryVendorId == "<Vendor Name>"
        join ecoResProductCategory where ecoResProductCategory.Product == ecoResProduct.RecId
        join ecoResCategory where ecoResCategory.RecId == ecoResProductCategory.Category
    {

        if(/*inventTable.StandardInventSizeId == "200x300" && inventTable.StandardConfigId == "BASIC"  &&*/ ecoResCategory.Name == "Durashield"/* && inventTable.PrimaryVendorId == "SOBER CERAMICS"*/)
       // {
            // ecoresrecid = ecoResCategory.RecId;
            info(strFmt("%1,%2",inventtable.ItemId,inventtable.StandardConfigId));
           }
   }
}
         

Get amount in words in ax 2012

Get amount in words in ax 2012

static void amount2words(Args _args)
{
    real amount = 1011.05;
    int numOfPennies = frac(amount)*100 mod 100;
    int test = real2int(round(amount,0));
    int paise;
    int numOfTenths;
    str 20 ones[19], tenths[9], hundreds, thousands, lakhs, crores, millions, billions;
    str 40 textpaise;
    int tmpnumofpennies;
    int temp;
    str 200 returntxt;

    int checkPower(int _test, int _power)
    {
    int numOfPower;

    if (_test >= _power)
    {
    numOfPower = _test DIV _power;
    if (numOfPower >= 100)
    {
    temp = numOfPower DIV 100;
    returntxt = returntxt + ' ' + ones[temp] + ' ' + hundreds;
    numOfPower = numOfPower MOD 100;
    }
    if (numOfPower >= 20)
    {
    temp = numOfPower DIV 10;
    returntxt = returntxt + ' ' + tenths[temp];
    numOfPower = numOfPower MOD 10;
    }
    if (numOfPower >= 1)
    {
    returntxt = returntxt + ' ' + ones[numOfPower];
    numOfPower = numOfPower MOD 10;
    }
    switch(_power)
    {
    case 1000000000 :
    {
    returntxt = returntxt + ' ' + billions;
    _test = _test MOD 1000000000;
    break;
    }
    case 10000000 :
    {
    returntxt = returntxt + ' ' + crores;
    _test = _test MOD 10000000;
    break;
    }
    case 100000 :
    {
    returntxt = returntxt + ' ' + lakhs;
    _test = _test MOD 100000;
    break;
    }
    case 1000 :
    {
    returntxt = returntxt + ' ' + thousands;
    _test = _test MOD 1000;
    break;
    }
    case 100 :
    {
    returntxt = returntxt + ' ' + hundreds;
    _test = _test MOD 100;
    break;
    }
    }
    }
    return _test;
    }

    ones[1] = "@SYS26620";
    ones[2] = "@SYS26621";
    ones[3] = "@SYS26622";
    ones[4] = "@SYS26626";
    ones[5] = "@SYS26627";
    ones[6] = "@SYS26628";
    ones[7] = "@SYS26629";
    ones[8] = "@SYS26630";
    ones[9] = "@SYS26631";
    ones[10] = "@SYS26632";
    ones[11] = "@SYS26633";
    ones[12] = "@SYS26634";
    ones[13] = "@SYS26635";
    ones[14] = "@SYS26636";
    ones[15] = "@SYS26637";
    ones[16] = "@SYS26638";
    ones[17] = "@SYS26639";
    ones[18] = "@SYS26640";
    ones[19] = "@SYS26641";

    tenths[1] = 'Not used';
    tenths[2] = "@SYS26643";
    tenths[3] = "@SYS26644";
    tenths[4] = "@SYS26645";
    tenths[5] = "@SYS26646";
    tenths[6] = "@SYS26647";
    tenths[7] = "@SYS26648";
    tenths[8] = "@SYS26649";
    tenths[9] = "@SYS26650";

    hundreds = "@SYS26651";
    thousands = "@SYS26652";
    lakhs = "Lakh";
    crores = "Crore";
    millions = "@SYS26653";
    billions = "@SYS26654";
    test = checkPower(test, 1000000000);
    test = checkPower(test, 10000000);
    test = checkPower(test, 100000);
    test = checkPower(test, 1000);
    test = checkPower(test, 100);

    if (test >= 20)
    {
    numOfTenths = test DIV 10;
    returntxt = returntxt + ' ' + tenths[numofTenths];
    numOfTenths = numOfTenths MOD 10;
    test = test MOD 10;
    }
    if (test >= 1)
    {
    numOfTenths = test;
    returntxt = returntxt + ' ' + ones[numOfTenths];
    }
    if (numOfPennies)
    {
    returntxt = returntxt + ' ' + "@SYS5534" +"\n\n";
    }
    paise=numofPennies;
    if(paise)
    {
    if(paise >=20)
    {
    numofTenths= paise DIV 10;
    returntxt=returntxt + ' '+tenths[numofTenths];
    numofTenths = numofTenths MOD 10;
    paise=paise MOD 10;
    }
    if(paise >=1)
    {
    numOfTenths=paise;
    returntxt=returntxt+ ' '+ones[numOfTenths];
    }
    returntxt=returntxt+" Paise";
    }

    info(strFmt("%1",returntxt + " Only"));
}

Get Vendor Id based on Vender's Name in ax 2012

static void VendorId(Args _args)
{
    VendTable       VendTableloc;
    DirPartyTable   DirPartyTableloc;
    str a;

    select DirPartyTableloc join VendTableloc where DirPartyTableloc.Name == "Test" && VendTableloc.Party == DirPartyTableloc.RecId;

    a = VendTableloc.AccountNum;

   info(strfmt("%1",a));
}

How to track item's address in ax 2012

static void S3_TrackItemsAddress(Args _args)
{
    VendTable               vendTable;
    str                     description, address, city;
    InventTable             inventTable;
    DirPartyTable           DirPartyTableloc;
    ;

select inventTable where inventTable.ItemId == salesline.ItemId;
        select DirPartyTableloc
        join vendTable where DirPartyTableloc.Name == inventTable.PrimaryVendorId &&
             vendTable.Party == DirPartyTableloc.RecId;

        vendTable   = VendTable::find(vendTable.AccountNum);
        description = DirParty::primaryPostalAddress(vendTable.Party).displayLocationDescription();
     
        address     = DirParty::primaryPostalAddress(vendTable.Party).Address;

        city        = DirParty::primaryPostalAddress(vendTable.Party).City;

    info(strFmt("%1,%2, %3", description,city, address));
}

Thursday, January 1, 2015

Importing a General Journal using Data Import/Export Framework in AX 2012 R3

Importing a General Journal using Data Import/Export Framework in AX 2012 R3
Here is a tutorial on how to configure Dynamics AX 2012 to import a general journal from a CSV file. The steps below are using Contoso demo data.

  1. Create a new folder on the root of the C: Drive and name it “DIEF”:
  2. Navigate to Data import export framework | Setup | Data import export framework parameters. Click “Browse” next to “Shared working directory” and select the “DIEF” folder we created. Once selected, click “Validate”.
  3. Close the “Data import export framework parameters” form.
  4. Go to Data import export framework | Setup | Source data formats. Enter “GLJOURNAL” for the “Source name” and “Type” = “File. In the parameters on the right side, enter “File format” = “Delimited”, “First row header” = TRUE, “Row delimiter” = “{CR}{LF}”, “Column delimiter” = “Comma {,}”, “Text Qualifier” = “*”, and “Role separator” = “;”. Click “Application”, and then select “CostCenter”, “Department”, and “ExpensePurpose”. Enter “CostCenter-Department-ExpensePurpose” for the “Dimension format” value.

  5. Go to Data import export framework | Setup | Target entities. Click “New” and enter “Entity type” = “Entity”, “Entity” = “Custom”, “Entity name” = “GLJOURNAL”, “Staging table” = “DMFLedgerJournalEntity”, “Entity class” = “DMFLedgerBalanceEntityClass”, and “Target entity” = “DMFLedgerJournalTransEntity”. Close the “Target entites” form.
  6. Go to Data import export framework | Common | Processing group. Type “GLJOURNAL” for the “Group name”, Ctrl+S to save, and click “Entities”. 
  7. On the “Select entities for processing group” form, enter “GLJOURNAL” for both the “Entity name” and the “Source data format”. Click “Generate source file”.
  8. On the “Wizard” form, click “Next”. For the “Display data” fields, select the following and put them in the following sequence: JournalName, JournalNum, LineNum, CurrencyCode, TransDate, Voucher, AccountType, LedgerDimension, AmountCurDebit, AmountCurCredit, OffsetAccountType, OffsetLedgerDimension. Click “Generate sample file”.
  9. A .txt file should open, and save it to the root of the C: drive.
  10. Click “Finish” on the “Wizard” form. Close the “Select entities for processing group” form. Close the “Processing group” form.
  11. Go to General ledger | Setup | General ledger parameters. Click “Number sequences”. Right-click “Gene_10” next to “Journal batch number” and click “View details”.
  12. Click “Edit”, copy the format. To copy click the “General” fast tab and note the “Next” value, in my case format is “INMF-00441”.

  13. Close the “Number sequences” form and the “General ledger parameters” form.
  14. Navigate to General ledger | Setup | Journals | Journal names. Select “GenJn” and right-click the “Acco_18” next to “Voucher series”, and then click “View details”.
  15. On the “Number sequences” form, click “Edit”. copy the number sequence format as copied earlier. In my case format is, “VN00000038”.
  16. Close all forms.
  17. Open Excel. Click File | Open. Navigate to the C: drive and select the “GLJOURNAL.txt” file (You may need to change the drop menu to “All Files (*.*)”)
  18. On the “Text Import Wizard” form, click “Delimited” and click “Next”. Check the box for “Comma” and click “Finish”.
  19. In line 2, enter the following values for each header:
  1. JournalName = GenJn
  2. JournalNum = INMF-00441(Value from step 12)
  3. LineNum = 1
  4. CurrencyCode = USD
  5. TransDate = 01/01/2015
  6. Voucher = VN00000038 (Value from step 16)
  7. AccountType = Ledger
  8. LedgerDimension = 110180-OU_1-OU_3566-Training "Or" 110110-022-001
  9. AmountCurDebit = 10
  10. OffsetAccountType = Ledger
  11. OffsetLedgerDimension = 110101-OU_1-OU_3566-Training "Or" 110120-022-001
  • Click File | Save As. Click “CSV (Comma delimited)” for the “Save as type” drop-menu.
  • Close Excel.
  • Go to Data import export framework | Common | Processing group. Select the line for “GLJOURNAL” and click “Entities”.
  • Click the folder icon next to “Sample file path”, and select the .csv file from step 20. Click “Generate source mapping”. Close the infolog.
  • Close the “Select entities for processing group” form.
  • On the “Processing group” form, select the line for “GLJOURNAL” and click “Get staging data”.
  • A form for “Create a job ID for the staging data job” should open and populate with a “Job ID”. Click “OK”.
  • On the “Staging data execution” form, click “Preview”. Verify the columns are correct, and then click “Run”.
  • Close the infolog.
  • On the “Processing group” form, click “Copy data to target”. Select the “Job ID” created earlier, and click “OK”. On the “Target data execution” form, click “Run”, then click “OK”.
  • Close the Infolog.
  • Go to General ledger | Journals | General journal. Locate the imported journal, and click “Lines”.
  • Notice the values imported properly, and click Post | Post. The journal posts successfully.
reference: https://community.dynamics.com/ax/b/axsupport/archive/2014/07/17/importing-a-general-journal-using-data-import-export-framework-ax-2012.aspx