Saturday, 27 June 2015

Get the data from all companies in Microsoft Dynamics AX 2012

Now you can get the data from all the companies through query...using "cross company" keyword
Example:
select crosscompany accountNum from custTable;

Friday, 26 June 2015

Role-based security in Microsoft Dynamics AX [AX 2012]

Basics of Security Feature in AX:

In role-based security, access is not granted to individual users, only to security roles. Users are assigned to roles. A user who is assigned to a security role has access to the set of privileges that is associated with that role. A user who is not assigned to any role has no privileges.
                In Microsoft Dynamics AX, role-based security is aligned with the structure of the business. Users are assigned to security roles based on their responsibilities in the organization and their participation in business processes. The administrator grants access to the duties that users in a role perform, not to the program elements that users must use.
                Because rules can be set up for automatic role assignment, the administrator does not have to be involved every time that a user's responsibilities change. After security roles and rules have been set up, business managers can control day-to-day user access based on business data.


1. Security Roles
All users must be assigned to at least one security role in order to have access to Microsoft Dynamics AX. The security roles that are assigned to a user determine the duties that the user can perform and the parts of the user interface that the user can view.

2.Process Cycles:
A business process is a coordinated set of activities in which one or more participants consume, produce, and use economic resources to achieve organizational goals. Process cycles are used for organization only. The process cycles themselves cannot be assigned to roles.

3.Duties:
Duties correspond to parts of a business process. The administrator assigns duties to security roles. A duty can be assigned to more than one role.You can assign related duties to separate roles. These duties are said to be segregated. 

4. Privileges:
In the security model for Microsoft Dynamics AX, a privilege specifies the level of access that is required to perform a job. Privileges can be assigned directly to roles. However, for easier maintenance, it is  recommend that you assign only duties to roles.

5. Permissions:
Each function in Microsoft Dynamics AX, such as a form or a service, is accessed through an entry point. Menu items, web content items, and service operations are referred to collectively as entry points.In the security model for Microsoft Dynamics AX, permissions group the securable objects and access levels that are required to run a function. This includes any tables, fields, forms or server side methods that are accessed through the entry point.Only developers can create or modify permissions.Permissions may be Read,Write,View/Edit etc set on menu items.

Creating a simple SSRS report with UI Builder,Controller,contract and DP class in Microsft Dynamisc AX 2012

Here are the steps:

>> UI Builder Class:

1. Create a new class. Open AOT à Classes, Right Click on Classes and select New Class. Name it as SSRSTestUIBuilder.
2.Open the Class declaration by right clicking on it and selecting View code.
3.Write the following code: 
public class SSRSTestUIBuilder extends SrsReportDataContractUIBuilder
{

}

>> Contract Class:

4. Now create a new class called Contract Class. Example: TestContract()

[SysOperationContractProcessingAttribute(classStr(SSRSTestUIBuilder))] //Important Line which connects UI Builder and contract class.
public class TestContract()
{

}

5.In contract class add the parameter methods.
Example: 
public CustAccoutn parmAccountNum(CustAccount AccountNum _AccountNum )
{       
         AccountNum = _AccountNum ;      
         return AccountNum ;
}

Note : Based on the requirements add as much as parameters methods needed.


>> Controller Class:


6.Create a controller class.
Example: 
public class SSRSTestController extends SrsReportRunController
{
//define the required declarations
}

7. Create a main method and write the following code:
public static client void main(Args args)
 {
    //define the new object for controller class
    SSRSTestController ssrsTestController;
    ssrsTestController = new SSRSTestController();
    //pass the caller args to the controller
    ssrsTestController.parmArgs(args);
    //set the report name and report design to run
    ssrsTestController.parmReportName(ssrsReportStr(SSRSSessionQuery,Design));
     //execute the report
    ssrsTestController.startOperation();
 }

>> Back to UI-BUILDER:

8. Based on different scenarios, different methods are overridden as shown:

public void build()
{
    DialogGroup dlgGrp;   
     //get the current dialog
    Dialog      dlg = this.dialog();      

    //make required modifications to the dialog
    dlgGrp = dlg.addGroup('Dates'); 
    dlgGrp.columns(2);  
    dlg.addField(identifierStr(FromDate));
    dlg.addField(identifierStr(ToDate));   
       
    dlgGrp = dlg.addGroup('Customer'); 
    dlg.addField(identifierStr(CustAccount));   
}

also use this code in build method to bind data:

//get the report data contract object

contract = this.dataContractObject();
    
//associate dialog field with data contract method

this.addDialogField(methodStr(SSRSTestContract,parmCustAccount), contract);


9.Over-ride a lookup method:

public void lookupCustAccount(FormStringControl _formStringControl)
{   

    Query query = new Query();

    QueryBuildDataSource DS;  
  
    SysTableLookup sysTablelookup;

    //create a table lookup    

    sysTablelookup = SysTableLookup::newParameters(tableNum(CustTable),_formStringControl);

    sysTablelookup.addLookupfield(fieldNum(CustTable,AccoutNum));
    
    //create a query

    DS = query.addDataSource(tableNum(CustTable));

    DS.addRange(fieldNum(CustTable,AccoutnNum)).value('001');

    //assign the query and call lookup

    sysTablelookup.parmQuery(query);

    sysTablelookup.performFormLookup();
}


10.Now override the postBuild method:

public void postBuild()
{
    DialogField dlgCustGroup;
    
    super();
    
    //get the field to override by providing the data contract object and the associated 

attribute/method

    dlgCustGroup = this.bindInfo().getDialogField(this.dataContractObject(),

                methodStr(SSRSTestContract,parmCustAccoutn));

    //register the method we want to override

    dlgCustGroup.registerOverrideMethod(

          methodStr(FormStringControl, lookup),

          methodStr(SSRSTestUIBuilder,lookupCustAccount),this);    

}

>> RDP(Report data provider):

Now create a class called TestDemoDP class, note that the name of the class must end with 'DP'.

(i) class declaration:

public TestDemoDP ()
{
   # define the required variables
   TempTable     tmpTable;
}

(ii) getTemporaryTable(): Here you need to create a temporary table (Go to AOT create a table and name it ''TempTable' and set the Table Type property as 'TempDB')

public TempTable getTemporaryTable()
{
   select * from tmpTable;
   return tmpTable;
}

(iii) processReport():

public void processReport()
{
     //Define Contract method
     //write the business logic as per scenarios
     while select AccountNum from custTable
              where custTable.AccountNum == '001';
    {
        //insert into temp table
        tmpTable.AccountNum = custTable.AccountNum;
        tmpTable.insert()l
    }  

}

Now you are ready with the fully loaded SSRS report which contains UI-Builder,contract,controller,and DP class.

Note: After having created all these you need to create design in visual studio and connect these code there.For more information refer my earlier blogs on SSRS reports.








Wednesday, 24 June 2015

Accounting Cycle in Microsoft Dynamics AX 2012

As we know that organization operations such as purchases, sales should be recorded as transactions that credits/debits amounts from one accounts to others. The motto is to learn all the steps from the business operation till the financial statement. This flow is called the accounting cycle. These are the core responsibilities of an accountant person.
It can also be defined as the accounting cycle is the sequence of procedures used to keep track of what has happened in the business and to report the financial effect of those things. 
These are the things which occurs in accounting cycle:
1. Operations: Purchases/Sales occurs in  business.
2. Computerize/Record the purchase/sales: It is necessary to keep track of all things, so that accounting Dept has a record of all the information about sales and purchases that occurs in business.
3. Analyse: The most important step is to analyse the things.The goal is to write correct transactions.We need to analyse things such as “What happened?” , “What accounts will change?”(Asset, Liability, Owner’s Equity) , “How will they change?” (Will the accounts increase or decrease?) , "Debit or Credit?" (Debit is “good” for the company, Credit is “bad” for the company.).
4. Journalize: The main journal for an accountant is the General Journal. General Journal is used to write transactions to it.Accountant hold this responsibility.
5.Post: We need to post the transactions, because amounts are transferred from one account to another.
6.Trial Balance: A trail balance is a list of all accounts and their balances.checks the accounting equation: Assets = Liabilities + Owner’s Equity.
7.Adjustments: Adjustments are nothing but changes in any purchases or orders made or you can say that they are entries are made at the end of a period to track revenue and expenses.
8.Financial Statements: They are the Balance Sheet, Income Statement, and Cash Flow Statement.
9.Close: The accountant closes the transactions.The reason for the closing entries is to ensure that each revenue and expense account will begin the next accounting year with a zero balance.


Tuesday, 23 June 2015

Classes and Tables used in sales order process in Microsoft Dynamics AX 2012

  • Classes,Tables and Methods used to post the sales orders:
  1. SalesTableType and SaleslineType classes will get called while creating the orders.
  2. SalesFormLetter classes will be used to post the sales order at various document status(packing,invoice etc).
  3. SalesParm tables are used to prepare the data for posting.
  4. CustConfirmJourCustConfirmTrans - when a sales order gets confirmed
  5. CustPackingSlipJourCustPackingSlipTrans - when a packing slip is posted.
  6. CustInvoiceTable,CustInvoiceTrans - when an invoice is posted.



Import demo data in Microsoft Dynamics AX 2012

1.Download demo file and definition file. Extract and save these files in any folder on your local computer.

2.Return to Microsoft Dynamics AX. Make sure which company you want to import. Go to Administration> Periodic > Data export/import > Import. The Import options form opens.

3.In the File name field, enter the path to the downloaded demo file. Click OK.

Note : The process may take up to 10 minutes. When import is finished, the Infolog message appears stating that the file has been imported.That’s all! Our selected company has demo data.

Set a default company in Microsoft Dynamics AX 2012

1.Click the Microsoft Dynamics AX menu button and then click Tools > Options…
2.The Options form opens. On the General tab, find the Start company accounts field
and select AX company from the drop-down list. Close the form.

Creating a new company in Microsoft Dynamics AX 2012

1.Go to Administration Module >> Common Forms >> Company accounts. The Company form opens

2.Create a new record by pressing new button in action pane or CTRL+N. In the Company accounts field, type 'AX' and in the Name of company accounts field, type Demo AX Company.

3.Save the record by pressing CTRL+S.Good, now our new AX company is ready to work in.

How to override lookup in Microsoft Dynamics AX 2012

Here is the code
  • Method you need to define:
void DemoLookup(FormControl ctrl)
{
    SysTableLookup sysTableLookup = SysTableLookup::newParameters(tableNum(#TableName),ctrl);
    Query query = New Query();
    QueryBuildDataSource queryBuildDataSource = query.addDataSource(tableNum(#TableName));
    QueryBuildRange queryBuildRange;
    
    sysTableLookup.addLookupfield(fieldNum(#TableName, #FieldName));
    
    queryBuildRange = queryBuildDataSource.addRange(fieldNum(#TableName, #FieldName));
    queryBuildRange.value(queryValue(#Field Range);
    sysTableLookup.parmQuery(query);
    sysTableLookup.performFormLookup();
}

  • In the form override the lookup method:
public void lookup()
{
    element.SummaryProjectLookup(this);
}

Check if AOT object name is valid in Microsoft Dynamics AX 2012

TreeNode::isValidObjectName( ‘Object name’ );

SSRS Reporting Framework Terminologies in Microsoft Dynamics AX

As you all know, the reports in AX 2012 have moved to SSRS reporting, so MS has introduced a robust reporting framework wrapping over the basic SSRS reporting functionality. There are many terms used in reporting framework in AX that I will try and explain here:

1.Report Definition Language: RDL is an XML application primarily used with Microsoft SQL Server Reporting Services. RDL is usually written using Visual Studio. AX has Report Definition Language Contract classes that can generate and build the RDL for an AX SSRS report. This contract provides a weakly typed representation of parameters. It contains methods that can be used to get or set values. It also contains a map of parameter names and the SrsReportParameter class. The base class is SrsReportRdlDataContract.


2.Report Data Provider (RDP): A framework that helps in building, processing and rendering data to reports. Most of the reports require RDP classes that help in implementing business logic required to process data and provide data in readable, presentable and required formats design. The base class is SrsReportDataProvider. This class has two main sub classes, SrsReportDataProvderBase and SrsReportDataProviderPreProcess. We will discuss about these classes in future posts.

3.Report Data Contracts: The Report Data Contracts framework is used to provide and manage the parameters to an SSRS report. The report data contract contains all the other relevant instances like Report Data Provider contracts, print contracts, RDL contracts and query contracts that will be used by a report.
         
            3.1. Printing Contracts: The framework that manages report printing (to different mediums). The base class is SrsPrintDestinationSettings. There are other supporting contracts that are used for printing, we will discuss about them in future posts.

            3.2. Query Contracts: This framework manages the queries used to process report data. This framework is also responsible for providing dynamic filters (similar to our ‘Select” buttons on report dialogs that open the Query specification form to filter data on report queries).

4. Report Controllers: Report controllers control the report execution and dialog forms. Report controllers can be used to modify report dialogs, validate report parameters and other validations necessary before report execution. The base class is SrsReportRunController. Reports utilizing report controllers can only be used for printing data on client side. Reports controlled by controllers cannot be used in Enterprise Portals.

5. Report UI Builders: UI Builders are used to modify the report dialogs at run-time or to add additional parameters and write custom business logic to report dialogs. Ex: You want to perform some task based on data modified for one parameter, that affects other parameters or build a custom lookup etc (something that was provided by RunBaseReport framework class in previous versions. The base class is SrsReportDataContractUIBuilder.

These are some of the basic reporting terminologies that you will be using extensively for reporting in AX.

Thursday, 18 June 2015

Open a web url through x++ code/job in Microsoft Dynamics AX 2012

Now you can open a website/web url through x++ code/job: here it is folks >>>

    static void OpenWebUrl(Args _args)
    {
   
        Dialog      dialog;
        DialogField field;
   
        dialog = new Dialog("My Dialog");
        dialog.addText("Enter the web url you want to connect:");
        field = dialog.addField(extendedTypeStr(Name));
   
        if (dialog.run())
        {
            infolog.urlLookup(strFmt("http://%1",field.value()));
        }
    }

Example: you can enter: rgjdynamics.blogspot.com
    

Data Synchronization through x++ code in Microsoft Dynamics AX 2012

Normally when Data Synchronization is throwing an error or if you want to synchronize the database through x++ code here it is: 
It is a job you can run:
  
static void forceDataSyncronization(Args _args)
    {
        Dictionary             dict;
        int                    idx, lastIdx, totalTables;
        TableId                tableId;
        Application            application;
        SysOperationProgress   progress;
        StackBase              errorStack;
        ErrorTxt               errorTxt;
        ;
        application = new Application();
        dict = new Dictionary();
        totalTables = dict.tableCnt();
        progress = new SysOperationProgress();
        progress.setTotal(totalTables);
        progress.setCaption("@SYS90206");
        errorStack = new StackBase(Types::String);
   
        lastIdx = 0;
   
        if (Box::okCancel("Syncronization the database, It may take a long time?", DialogButton::Cancel) == DialogButton::Ok)
        {
            try
            {
                for (idx = lastIdx+1; idx <= totalTables; idx++)
                {
                    tableId = dict.tableCnt2Id(idx);
                    progress.setText(dict.tableName(tableId));
                    lastIdx = idx;
                    application.dbSynchronize(tableId, false, true, false);
                    progress.incCount();
                }
            }
            catch (Exception::Error)
            {
                errorTxt = strFmt("Error in table '%1' (%2)", tableId, dict.tableName(tableId));
                errorStack.push(errorTxt);
                retry;
            }
            setPrefix("@SYS86407");
            errorTxt = errorStack.pop();
            while (errorTxt)
            {
                error(errorTxt);
                errorTxt = errorStack.pop();
            }
            info('Sychrnonization is now done.');
        }
        else
        {
            info('Syncronization cancelled');
        }
    }

Get Current Company in Microsoft Dynamics AX 2012

Use this code to get the current company in ax 2012:

static void currentCompany(Args _arg)
{
   str curCompany;
   // Sets curCompany to the extension of the current company.
   curCompany= curExt();
    print "Current company is " + curCompany;
    pause;
    }
   

  

Export to Excel in Microsoft Dynamics AX 2012

Here is the code/job: Hope it helps

static void CreateExcel(Args _args)
    {
       SysExcelApplication  xlsApplication;
       SysExcelWorkBooks    xlsWorkBookCollection;
       SysExcelWorkBook     xlsWorkBook;
       SysExcelWorkSheets   xlsWorkSheetCollection;
       SysExcelWorkSheet    xlsWorkSheet;
       SysExcelRange        xlsRange;
       CustTable            custTable;
       int                  row = 1;
       str                  fileName;
   
       //Filename
       fileName = "D:\\test.xlsx";
       //Initialize Excel instance
       xlsApplication           = SysExcelApplication::construct();
       //Open Excel document
       //xlsApplication.visible(true);
       //Create Excel WorkBook and WorkSheet
       xlsWorkBookCollection    = xlsApplication.workbooks();
       xlsWorkBook              = xlsWorkBookCollection.add();
       xlsWorkSheetCollection   = xlsWorkBook.worksheets();
       xlsWorkSheet             = xlsWorkSheetCollection.itemFromNum(1);
       //Excel columns captions
       xlsWorkSheet.cells().item(row,1).value("Field name1");
       xlsWorkSheet.cells().item(row,2).value("FieldName2");
       row++;
       //Fill Excel with CustTable AccountNum and Name fields (only 20 records)
       while select #FieldName1,#FieldName2 from #tableName
       {
          if(row == 20)
            break;
          xlsWorkSheet.cells().item(row,1).value(#FieldName1);
          xlsWorkSheet.cells().item(row,2).value(#FieldName2 );
          row++;
       }
       //Check whether the document already exists
       if(WinApi::fileExists(fileName))
          WinApi::deleteFile(fileName);
       //Save Excel document
       //xlsWorkbook.saveAs(fileName);
       //Open Excel document
       xlsApplication.visible(true);
   
       //Close Excel
       //xlsApplication.quit();
       //xlsApplication.finalize();

    }

Method Types in Dynamics AX 2012 Classes

There are many different types of methods. Some of the more common types are:
  1. Static Methods
  2. Main Method 
  3. Display Methods
  4. Accessor Methods
1.Static Methods:
Static methods are attached to a class. However, they do not need that class to be instantiated to execute that method. They are not within the scope of the class, so any class variables are not available in a static method.
Static methods are declared static by using the Static method modifier.
Static methods are called using the class name followed by two colons (::) and then the methods name.
The following example shows a static method declaration, and a call to that static method.

static public void myStaticMethod()
{
}
myClass::myStaticMethod()

2. Main Method:
The main method is a static method that can be used to call a constuctor. It is special because its name is required to be "main". It is used by the system when the class is run directly from a menu item and it takes a parameter of type args. 
Args is a class that is used to pass parameters between objects, for instance, various parameters can be set on the properties on a menu item. When the menu item calls a class, the args class containing those property values is passed to the main method using the args parameter.

3. Display Methods
Display methods are used on forms. They are commonly created on the table, and can also be defined on the form. Display methods return a value that is displayed on the form or report. They are often used to display a calculation, or to look up a single field from another table. 
The following example shows how to display the item name on a form that displays data from a table containing the item id.

display itemNameitemName()
{
inventTableinventTable
select name from inventTable
where inventTable.itemId == this.itemId;
return inventTable.name;
}

The first line in this code is a comment to the compiler indicating that a Best

Practice deviation is considered and evaluated as reasonable. The deviation is
because a display method is able to return any data from any table or field in the system, and so the security implications should be considered.


4. Accessor Methods:
Accessor methods enable other elements to set or get the values of variables in a class and it is common that they do both. The following example accepts a value as a parameter, sets a class variable to this value and then returns the value. The parameter has a default value set to the class variable value, so if the method is called without a parameter, it returns the value of the class variable. If it is called with a value in the parameter, then the
class variable is set to this value.

publicstrmyName(str _myName = myName)
{
myName = _myName;
return myName;
}