Tuesday, 15 September 2015

Get list of AOT elements(objects) through code in Dynamics AX 2012

How to get list of AOT elements(objects) through code in Dynamics AX ?
Here  is the code:
UtilElements    UtilElementsLocal;
  
while select * from UtilElementsLocal
    where UtilElementsLocal.recordType == UtilElementType::ExtendedType
    && UtilElementsLocal.utilLevel == global::currentAOLayer() 
{
      info(UtilElementsLocal.name) ;
}

How to GAC a DLL when any changes are made in AX 2012

Gac a DLL, when any changes are made in the DLL? 

1. Open Visual studio x64 Win 64 Command prompt----> as administrator.
2. Command : gacutil -i <path-of-dll-with-name> (i-install, u-uninstall).

Ex: gacutil -i C:\Users\Administrator\Desktop\Demo.dll

Thursday, 13 August 2015

Creating a service AIF in Microsoft Dynamics AX 2012

1    1.Create a new service in Services node.
2.       Go the properties of that service node and set the service class that you are intended to.
3.       Now drag and drop the required methods in the operations group of the service node.
4.       Create a new Service Group and add the created service into this group.
5.       Now right click on the newly created service group and deploy it!.
6.       Go to the AX rich client and go to the System Administration module and Click on Service and           Application Integration Framework >> Inbound ports >> refresh the list and you will find your           service here >> now select your service and click “Activate”.

Monday, 3 August 2015

Export a shared/private project through x++ code in Microsoft Dynamics AX 2012

static void exportingtoxpos(Args _args)
{
TreeNode treeNode;
FileIoPermission perm;
#define.ExportFile(@"D:\TestProject.xpo")
#define.ExportMode("w")

perm = new FileIoPermission(#ExportFile, #ExportMode);
if (perm == null)
  {
        return;
  }

perm.assert();

treeNode = TreeNode::findNode(@"\Projects\private\SSRSReports"); //path of project either private                                                                                                                     or shared and project name
if (treeNode != null)
  {
      // BP deviation documented.
      treeNode.treeNodeExport(#ExportFile);
  }

CodeAccessPermission::revertAssert();
}

Tuesday, 28 July 2015

SQL server Reporting Services (SSRS) Architecture for AX 2012


1. User requesta a report :

A menu item in the Microsoft Dynamics AX client may be bound to a report for Reporting Services. After a user clicks the menu item, a parameters form is displayed to the user. The user enters parameters to filter the data that is displayed on the report.
The Microsoft Dynamics AX client then requests the report from an instance of Reporting Services. The request includes the parameters that the user entered.

2.Reporting Services receives the request and requests the report data from the Microsoft Dynamics AX server.

Reporting Services receives the request and examines the report. The report is stored as an .rdl file. The .rdl file indicates the report’s data source. The data source may be a Microsoft Dynamics AX query, a report data provider class, or an external data source that is accessed through report data methods.
If a Microsoft Dynamics AX data source is used for the report, Reporting Services uses the Microsoft Dynamics AX data extension to retrieve the data.

Reporting Services then requests metadata about the data source from Microsoft Dynamics AX. Then Reporting Services requests the data for the report.

3.The Microsoft Dynamics AX server receives the request and sends the report data back to Reporting Services.
The Microsoft Dynamics AX services examine the query in the Application Object Tree (AOT) to return the requested metadata. The services also run the query to generate the data for the report.

Microsoft Dynamics AX then returns the metadata and data to Reporting Services.

4.Reporting Services renders the report and sends it to the Microsoft Dynamics AX client.
The Microsoft Dynamics AX customization extension formats the report. The customization extension uses metadata to provide automatic formatting of data and can affect the positioning and layout of elements on the report.
Reporting Services then renders the report into a visual representation and sends that representation to the Microsoft Dynamics AX client.

5.The report is displayed to the user.
The Microsoft Dynamics AX client displays the report to the user in the report viewer control.

Friday, 24 July 2015

Stages of Reports in Microsoft Dynamics AX 2012


Report definition
The report definition file (.rdl) stored on a report server. 

Compiled report and intermediate report format
The report that uses evaluated expressions, parameters and parameter properties evaluated.

Snapshot or Report History
A snapshot is the set of report data at a specific point in time plus the intermediate format that 
contains report layout information.

Processed report
A fully processed report that contains both data and layout information.

Rendered report
A fully processed report is sent to a report renderer to combine the data and layout on each page of the targeted rendering format. Rendering extensions are customizable and extensible.

Exported report

An exported report is a fully paged report saved in a specific file format. Export formats depend on installed rendering extensions and can be customized. By default, export formats include Excel, Word, XML, PDF, TIFF, and CSV.

Type of Reports in Microsoft Dynamics AX 2012

Drilldown reports

Drilldown reports must retrieve all possible data that can be shown in the report. For reports that use large amounts of data, consider drillthrough reports instead.

Subreports

A subreport is a report item that you add to a report as a layout element. A subreport points to a different report and displays inside the body of a main report as an subreport instance.


Main/detail reports and drillthrough reports

A main/detail report solution includes a main report that displays summary information with hyperlinks to one or more reports that display detailed information.

Linked reports

A linked report is a report server item that contains a pointer to the report definition but has its own set of report properties and settings. These include security, parameters, location, subscriptions, and schedules.

History reports

Report history is a collection of report snapshots. You can use report history to maintain a record of a report over time.

Cached reports

A cached report is a saved copy of a compiled report and report data. Cached reports are used to improve performance by reducing the number of processing requests to the report processor and by reducing the time that is required to retrieve large report datasets.

Snapshots

A report snapshot is a report that contains layout information and query results that were retrieved at a specific point in time.

Model reports and Clickthrough reports

(i) Report model :A report model is a user-friendly description of an underlying database, with pre-established data relationships and auto-generated queries. Report models can be used as data sources for reports created in Report Designer and Report Builder.

(ii)Clickthrough report : A clickthrough report is a report that displays related data from a report model when you click the interactive data contained in the model-based report. Clickthrough reports are autogenerated.

Saved reports

A saved report is a report definition (.rdl) file. A report definition can be saved locally or uploaded to a report server.

Published reports

A published report is a report server item that you publish to a report server from a Reporting Services tool.
  

Upgraded reports

An upgraded report is a published report definition that is converted to a newer schema when a report server is upgraded from one version of Reporting Services to a later version. The original report definition is preserved. The report is upgraded in memory, compiled, and the compiled version is saved internally.

Wednesday, 15 July 2015

X++ CODE TO READ WORD DOCUMENT into AX 2012

Below is the job to read text from Word document to AX 2012

static void ReadFromWord(Args _args)
{     
    str         document = "D:\\Demo Edition.doc"; //path were the word document is situated
    COM         wordApplication;
    COM         wordDocuments;
    COM         wordDoc;
    COM         range;
    TextBuffer  txtBuff = new TextBuffer();

    // Create instance of Word application
    wordApplication = new COM("Word.Application");

    // Get documents property
    wordDocuments = wordApplication.Documents();

    // Add document that you want to read
    wordDoc = wordDocuments.add(document);
    range = wordDoc.range();

    txtBuff .setText(range.text());

    // to replace carriage return with newline char
    txtBuff .replace('\r', '\n');   
   
    info(txtBuff .getText());
}

Debug Ax Code in Visual Studio in Microsoft Dynamics AX 2012

The steps involved in in debugging AX code through Visual Studio :

Step 1

Make sure AOS Service runs on account which you logged in. 

Step 2:

Open visual studio and click on AX Application explorer (Shortcut Ctrl + D)AOT opens and you can browse nodes as you used to do in Dynamics AX.Open the object which you want to debug and insert breakpoint.

Step 3:

Then in Visual studio, Click on Debug->Attach process


Note: As shown in above image, First make sure two check boxes at bottom are marked.Then only you can find and able to select AX32Serv.exe (AOS)  process and click on attach button.

Step 4:

You done with setting up visual studio to debug code running in CIL.
Now restrart process in Dynamics AX which you want to debug and you can find Visual studio debugger opened for you.

List of paper sizes in Microsoft Dynamics AX 2012

Below is the job to get the list of paper sizes in Dynamics AX    


Thursday, 9 July 2015

Virtual Company in Microsoft Dynamics AX 2012

Dynamics Ax stores data as per company in tables. But there might be occasions when you want to share data across companies, like country, state, zip codes data. This sharing of data is achieved by creating a virtual company and storing data in this virtual company. 

The only purpose of virtual company is to share data across companies, you cannot log into this virtual company.

There is a property on Ax tables called "SaveDataPerCompany", you can use this property to save data globally in Ax. To share data set this property to "No".





Virtual Company setup:

Step 1: Create Table Collection


Decide the tables you want to share and create a table collection for these functionally related tables. For example; if you want to share Global Address Book across companies then you can utilize the existing table collection "DirPartyCollection".


Note: To create a table collection, go to AOT\Data Dictionary\Table Collections and on right click select "New Table Collection", then just drag your required tables in this collection.

Step 2: Create Virtual Company, configure/attach normal companies and table collection

Create a virtual company that will hold the shared data for normal companies.
Note: You should be Ax administrator.
  1. Go to Administration -- Setup -- Virtual company accounts, and create a virtual company.

  2. Decide which companies needs to share data and attach those normal companies with this virtual company.

  3. Attach the table collection with this virtual company.

Your Ax client will re-start and you are done with setting up the virtual company account.

Note: Now, when you have virtual company in place, all new data will be saved in this virtual company. Only companies attached to the virtual company can use this shared data. All other companies which are not attached will work normally, these companies will continue to read/write data as per company bases.

Import data from Excel into AX in Microsoft Dynamics AX 2012

static void mynamescopyfromexcel(Args _args)
{
SysExcelApplication application;
SysExcelWorkbooks workbooks;

SysExcelWorkbook workbook;
SysExcelWorksheets worksheets;
SysExcelWorksheet worksheet;
SysExcelCells cells;
COMVariantType type;
Name name;
FileName filename;
testTable  mynames;

int row = 1 ;

str lastname;
str firstname;
int salary;

application = SysExcelApplication::construct();
workbooks = application.workbooks();
//specify the file path that you want to read
filename = @"C:\Location\Name.xlsx";
 
try
{
    workbooks.open(filename);
}
catch (Exception::Error)
{
    throw error("File cannot be opened.");
}

    workbook = workbooks.item(1);
    worksheets = workbook.worksheets();
    worksheet = worksheets.itemFromNum(1);
    cells = worksheet.cells();

do
{
    row++;
    firstname = cells.item(row, 1).value().bStr();
    lastname = cells.item(row, 2).value().bStr();
    mynames.clear();
    mynames.Fname = firstname;
    mynames.Lname = lastname;
    mynames.insert();

    info("Data inserted succesfully");

    type = cells.item(row+1, 1).value().variantType();
}

while (type != COMVariantType::VT_EMPTY);
application.quit();
}

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