Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 127

Microsoft Dynamics Ax

2012 Development
Overview
Ali Raza Zaidi
MVP (Dynamics Ax)
Advisory Software
Engineer At Systems
Limited.

Agenda
Dynamics AX 2012 Features and
History Modules
Dynamics AX Development Pattern
Dynamics Ax 2012 Navigation and
layout overview.
Dynamics Ax architecture
Overview of X++
Short Introduction to AIF
Q&A
2

What is ERP.
Enterprise resource planning(ERP) is a
business management softwareusually a
suite of integrated applicationsthat a
company can use to collect, store, manage
and interpret data from many business
activities, including:
Product planning, cost and development
Manufacturing or service delivery
Marketing and sales
Inventory management
Shipping and payment

Dynamics AX 2012
Completely integrated ERP solution
One business logic, one database
Easily recognize the dependencies of
business activities
Rich functionality

State-of-the-art technology
Layer technology
Integrated Development environment
Three-tier architecture

Suitable for midsize and large


organizations

Feature and Modules

Dynamics AX
Dynamics AX
Dynamics AX
Dynamics AX
Accounting
Dynamics AX
Dynamics AX
Dynamics AX
Dynamics AX
Dynamics AX
Dynamics AX
Dynamics AX

Financial Management
Requisitions and Purchase Orders
Expense Management
Project Management and Project
Supply Chain Management
Inventory Management and Warehousing
Sales Orders
Service Management
Production and Manufacturing
Fixed Assets
CRM and Sales and Marketing

The history of Microsoft Dynamics


AX
More then 25 years in Business application
Invocation.
Original Name Axapta purchase of the
Danish company Navision A/S
First Version March 1998 as Axapta 1.0
Purchase by Microsoft in 2002 Release
version 3.0
2006 Version 4.0
2008 Version Dynamics Ax 2009.
2011 Version Dynamics Ax 2012
2012 Version Dynamics Ax 2012 R1.
2013 Version Dynamics Ax 2012 R2.

Development Patterns In
Dynamics Ax 2012

Development patterns are the building blocks of any business


application, and they fall into the following categories:

Customization

Alteration
Extension
Enhancement

Integration

SSIS
BizTalk

External application module development


Custom dedicated applications development
Report development

Enterprise Portal Web application development

Customization
Customization is the development pattern in which you create
new functionality by altering, extending, or enhancing the
functionality in the shipped product.

Alteration to the base functionality are achieved by


changing the metadata and source code of the base
application.

Extension to functionality are achieved by incrementally


increasing base functionality by adding to the source code in
the business logic of the base application.

Enhancement to the application are achieved by adding


new functionality originally unavailable in the base
application. Typically, an enhancement is larger in scope than
an alteration or extension.

Integration
Integration is the development
pattern that involves enabling existing
applications (not written exclusively
for Microsoft Dynamics AX) to interact
and work with Microsoft Dynamics AX
across process boundaries.

External application
module development

Custom dedicated application development (e.g.


Custom Mobile app, Custom Module development)
Report development (e.g. Out of the box report)
Enterprise Portal web application development (New
page to enter the employee time sheet)

Dynamics Ax 2012 Clients


Navigational Overview.

Navigation

6/7/15

13

Client Workspace

Role Center
Role center is user page, appear on
opening at Dynamics Ax. The role
center is depending on rights and role
of user. Role center provide
dashboards, which helps to user to
monitor their roles. This information
include transaction data, alerts, links
and common tasks that are associated
with users role.
6/7/15

16

Footer Text

6/7/15

17

Footer Text

6/7/15

18

Area Page
Area page is the main page of Every

Module.
This area page have link to, List page,
Journal, Reports, Setup table list, Inquiries
and Periodic page.
By Default 20 area page exists for dynamics
Ax.
Each Area page focus on one complete
module or area, for example Account
receivable, Account payable, cost
accounting and Administration.
Footer Text

6/7/15

19

Footer Text

6/7/15

20

Common or list page.


These links leads you to list page of
any Entities in that module. For
example in Account receivable module
contains customer list page. Through
list page user is able to Navigate
every part of data related to that
entity.

Footer Text

6/7/15

21

Footer Text

6/7/15

22

Detail From:
Detail forms are primary way to create
or update entities in Dynamics Ax like
customer Vendor, worker and
products. These detail forms can be
open by click on list page. By default
these pages are open in read only
mode. You have to click edit button to
open in detail page.

Footer Text

6/7/15

23

Footer Text

6/7/15

24

Transaction detail Forms.


Transaction detail forms are forms
that are used to create, update
transaction in Microsoft Dynamics Ax.
Transaction is business event that
occurs with in company that needs to
be recorded in ERP system.
Transaction detail forms have to
divided two parts one is Line view and
Header view.
Footer Text

6/7/15

25

Line View
This shows a few header level fields
which are required for transaction.
This default view and items are added
here.

Footer Text

6/7/15

26

Header View:
This contains all most all fields at
header view. Most of fields have
default values and did not modify
here.

Footer Text

6/7/15

27

Periodic:
All those page which will periodically
access by user

Footer Text

6/7/15

28

Journal:
These pages link to all related which
have some functional or finance
related journal

Footer Text

6/7/15

29

Dynamics Ax Architecture
and Layers

Three-Tier Architecture

The client application


allows users to connect to
the server to access
business logic and use the
data in the database.
The server runs the
application business logic.
The database stores the
data.

The following image describes a typical system architecture that includes other
components of the Microsoft technology stack:

Presentation tier (clients and external


applications)

A client provides an interface to Microsoft Dynamics AX data


and functionality. An external application is integrated with
Microsoft Dynamics AX to programmatically integrate
functionality or exchange data.
The Windows client for Microsoft Dynamics AX is a native 32bit program that provides a rich user interface.
Supported web browsers provide access to Microsoft
Dynamics AX functionality and data through Enterprise
Portal.
External applications interact with Microsoft Dynamics AX via
services and Application Integration Framework (AIF).
Services and AIF provide an extensible framework for XMLbased scenarios for enterprise application integration (EAI),
business-to-business (B2B), and service-oriented architecture
(SOA).

Application tier
Active Directory domain controller
Application Object Server
Enterprise Portal
Enterprise Search
Reporting
Analytics
Services and Application Integration
Framework (AIF)
Help server

Application Object Server

Application Object Server (AOS) controls communication


among Microsoft Dynamics AX clients, databases, and
applications. AOS also hosts Microsoft Dynamics AX services
and the workflow system. You can deploy AOS on a single
computer or create a load-balanced cluster of multiple AOS
instances. AOS is a Windows service that requires a Windows
Server operating system. For the current hardware and
software requirements for Microsoft Dynamics AX, see
thesystem requirementsdocument that is available from the
Microsoft Download Center.
AOS uses libraries from the Microsoft.NET Framework version
4, such as Windows Communication Foundation and Windows
Workflow Foundation.

Data tier

Microsoft Dynamics AX requires several database


components.
The Microsoft Dynamics AX database
Thebusiness databaseis a Microsoft SQL Server database
that stores transaction and reference data. This database is
functionally equivalent to the principal database in Microsoft
Dynamics AX 4.0 and Microsoft Dynamics AX 2009.

The model store

Themodel storedatabase stores all application elements for


Microsoft Dynamics AX. These elements include
customizations. Information about layers and models is an
integral part of the store. AOS has access to the model store,
handles layer flattening, and provides model data to all the
Microsoft Dynamics AX subsystems. These subsystems
include the subsystems for form rendering, report rendering,
and X++ code. The model store replaces the Microsoft
Dynamics AX Object Data (AOD) files that were used in
earlier versions of Microsoft Dynamics AX.

Baseline model store


The baseline model store holds model
store tables for the earlier version of
the metadata and is used only during
upgrade. The baseline model store is
like the old folder in earlier versions of
Microsoft Dynamics AX.

Client /AOS communication

Development
Environments
Morphx IDE

X++ language code is written here.


Drag and Drop.
Code written forms, Classes and logic

written here

Visual Studio.
Any Manage Code will be written here
Report Customization and Development.
Remote Debugging Tools.
Application Explorer (Read Only ).

Microsoft Dynamics AX 2012 Layered


Architecture
The method used by Microsoft Dynamics AX 2012 to
separate and control the updates and modifications made in
the application is known as "layering.
Layers are a hierarchy of levels in the application
The standard application is never overwritten

Layer

Description

USR

The user layer is for user modifications, such as reports.

CUS

The customer layer is for modifications that are specific to a company.

VAR

Value Added Resellers (VAR) can make modifications or new developments


to the VAR layer as specified by the customers or as a strategy of creating
an industry specific solution.

ISV

When an Independent Software Vendor (ISV) creates their own solution,


their modifications are saved in the ISV layer.

SLN

The solution layer is used by distributors to implement vertical partner


solutions.

FPK

The FPK layer is an application object patch layer reserved by Microsoft for
future patching or other updates. For more information, seePatch Layers.

GLS

When the application is modified to match country or region specific legal


demands, these modifications are saved in the GLS layer.

SYS

The standard application is implemented at the lowest level, the SYS layer.
The application objects in the standard application can never be deleted

Models
A model is a logical grouping of
elements within a layer.
Models help in situations where
multiple ISV solutions or projects must
operate together.
An element can exist in exactly one
model in a layer.
New models are easy to create in the
MorphX IDE and are applied when
modifying or adding objects in the

AXUtil create /model:"My Model" /Layer:USR


AXUtil export /model:"My Model"
/file:MyModel.axmodel
signtool sign /f mycertprivate.pfx /p
password MyModel.axmodel
AXUtil import /file:SomeModel.axmodel

DATA DICTIONARY
Topics
Application Object Tree
Labels
Table Structure and Components
Views
Maps
Base Enums
Extended Data Types
Table Collections:
Projects

Application Object Tree (AOT)

The Application Object Tree (AOT)


is a tree view of all the application
objects within
Microsoft Dynamics AX 2012.
Viewing Repository
The AOT contains everything
needed to customize the look and
functionality of a
Microsoft Dynamics AX 2012 application.

Label Files
system which systematizes all the labels (for buttons, forms,
dialog boxes, and more) for a specific language in one file; a
label file
A label is the text that appears in the user interface.
Create New Label File: Tools > Development Tools > Label >
Label File Wizard.

Table Structure and Components


Tables: Tables store data in the system. They are organized in
fields. These are assigned to different data types,
depending
on the type of data they hold. Data is entered,
edited, and
deleted through forms. Tables are discussed in
more detail later in the section.
Creating a Table:
1. Create a table.
2. Create extended data types.
3. Add fields to the table.
Drag relevant extended data types to the
Fields node of the relevant table.
4. Create relations on extended data types.
5. Create indexes.

Table Structure and Components


Indexes :
An index is a table-specific database structure that speeds the
retrieval of rows from a table. Indexes are used to improve
the performance of data retrieval and occasionally to ensure
the existence of unique records. It's up to the databasespecific query optimizer to use available indexes to facilitate
efficient data retrieval.
The indexes in the Microsoft Dynamics AX 2012 table
definition are the physical indexes that exist on the tables in
the database.
There are two types of indexes:
Unique
Non-Unique

Table Structure and Components


Whether an index is unique is defined by the
index'sAllowDuplicatesproperty. When this property is set to
No, a unique index is created. The database uses the unique
index to ensure that no duplicate key values occur. The
database prevents you from inserting records with duplicate key
values by rejecting the insert
Setting the index'sAllowDuplicatesproperty to Yes creates a
non-unique index. These indexes allow you to enter duplicate
values for the indexed fields and are used for performance
reasons.
System Index
Microsoft Dynamics AX requires a unique index on each table so
if there are no indexes on a table or all the indexes are disabled,
a system index is automatically created. The system index is
created on the RecId and DataAreaId fields if the DataAreaId
field exists. Otherwise the system index is created on the RecId
field. You can see system indexes in the database but they

Table Structure and


Components

Relations:
Relations are a method that helps
secure business rules to enforce
existing properties between field
values existing in different tables. This
is known as referential integrity.

DATA
DICTIONARY(Contd.)

Data Types Primitive and Extended


Microsoft Dynamics AX 2012 has built in primitive and extended
data types associated with the information in the database.
Primitive Data Types

Extended Data Types


Extended Data types can inherit either from primitive types or
other Extended Data Types, which enables properties to be
inherited.

Delete Actions: Microsoft Dynamics AX 2012 uses a category of


methods called Delete Actions to govern how data is
handled when a deletion event occurs in a parent
tableRelations.
Methods:
Microsoft Dynamics AX 2012 uses methods within the table
node to perform a variety of functions such as contact
person and currency name lookup.

DATA
DICTIONARY(Contd.)
View
A view is an X++ SQLselectstatement that is given a name that is reusable in
other X++ SQL statements. Theselectstatement of the view can reference one
table, or it can join tables. Also, a view can reference other views, or a mix of
views and tables. A view can also reference maps.
Developers are encouraged to consider using an AOTqueryelement as the
source of data for their view.
Views are specified atAOT>Data Dictionary>Views.

DATA
Base Enums : Base enums are a list of literals. They can be
DICTIONARY(Contd.)
used
throughout the development environment in MorphX.

Table Types
Regular Table.
In memory Tables.
Less then 128k remain in memory
ISAM Index sequential Access Method
Does not map on any physical table.
Initiate only when first insert occur, and

remains until the table buffer remains.


Index only when copied from regular
table.

TempDB
Stored Sql Servers TempDB.

TempDb
Tables Created in SQL Server TempDb.
Can bejoined.
Can be either per company or global.
Can haveforeign keycolumns.
Can have methods, but cannot
override.
AOT Queries can be used TempDb as
source.
Transaction support.

TempDb limitations
Cannot use theTable browser form.
Can not be part of Table collection.

Projects:
Projects organize new or customized application objects.
Think of a Project as a reference folder for related objects.
Advantage of Projects is the ability to save a project's
contents and state separately for each user by using Private
Projects.

Macros :

With the macro capabilities in X++, you can define and use
constants and perform conditional compilation. Macros are
unstructured because they are not defined in the X++ syntax.
Macros are handled before the source code is compiled. You can
add macros anywhere you write source code: in methods and in
class declarations.

Jobs & Static Query

The jobs node on the application object tree contains small X ++ programs that are
executed as batch jobs.
They are useful when developing and testing new functionality for Microsoft Dynamics
AX 2012.
Queries ask questions about
data stored in a database.
The information selected by a
query can be used as the
basis for a form, auto report.

X++ OVERVIEW

X++ is the programming language used in MorphX IDE.


X++ resembles other popular languages such as C# and
Java.
X++ includes many integrated SQL commands;
X++ is object-oriented language and provides a clean and
efficient object-based development platform.
Data Aware Includes keywords such as firstFast,
forceSelectOrder, and forUpdate, as well as a database
query syntax application aware client, server,
changecompany, and display

Code Editor
Jobs
Compiler
The Debugger
Compare

Development Tools(Contd.)

Reverse Engineering
Simplify collection
Extract relationships
Integrate and view collections
in Microsoft Office Visio as UML
diagrams

Naming conventions
Naming conventions contribute to consistency and to
making
the application easier to understand.
{business area name} + {business area description} +
{action performed (for classes) or type of contents (for
tables)}
Examples:

CustJournalPrintOutInvoice
PriceDiscAdmDelete
PriceDiscAdmSearch
PriceDiscAdmName
PriceDiscAdmTrans

Comments
Single line //
Block comments /* */
To do comments TODO. To do comments appear in the compilers
Tasks tab page.
/// <summary>
/// This is an XML comment with tags to distinguish
sections.
/// </summary>

X++ CONTROL STATEMENTS


Data Type

Declaration
Keyword

Description/Example

String

str

any string

Integer

int

2356

Real

Real

3.14

Date

date

24\11\2010

Enum

Must be declared
as a Base Enum
first

Enum values are represented


internally as Integers.

Boolean

boolean

True/False

Time

timeOfDay

15:23:08

utcDateTime

utcDateTime

9/28/2008
07:11:02 am

Guid

guid

Global Unique Identifier, a


reference number which is unique
in any context

Int64

Int64

A large integer, represent by 64


bits.

X++ CONTROL STATEMENTS(Contd.)


Composite Date Types

Variable Declaration:
dataType
variableIdentifier;
Array Declaration:
real
realUnlimtedArray[];
real
realLimitedArray[10];

// Unlimited index values


// maximum of 10 values

X++ CONTROL STATEMENTS(Contd.)


Containers:
A variable that can contain different types and values of simple and extended data types,
including arrays and other container variables. Classes cannot be put into containers.
container
c;
int i, j;
str txt;
;
c = [10, 20, "test"];
print conPeek(c, 3);
[i,j,txt] = c;

// the container is declared

// the container has 3 values set


// the third element is printed
// Variables being set

Containers There are many functions that manipulate


container
conPeek: Returns the value being held in a specific position
in the container.
conDel: Removes a value from a specific position in the
container.
conNull: Returns an empty container.
conFind: Finds the position in the container that a certain
value is being held (if found).
conIns: Inserts a value into a specific position in the
container.
conPoke: Replaces the value in a specific position in the
container with a new value.
conLen: Returns the number of elements in the container.

X++ CONTROL STATEMENTS(Contd.)


Operators:
a) Assignment operators
Operator

Term

Description

Becomes
equal to

Assigns the expression on the right


of the equal sign to the variable on
the left.

+=

Increments the variable on the left


by the value on the right.

++

Increments the variable on the left


by 1.

-=

Decrements the variable on the left


by the value on the right.

--

Decrements the variable on the left


by 1.

X++ CONTROL STATEMENTS(Contd.)


Operators:
b) Arithmetic operators

X++ CONTROL STATEMENTS(Contd.)


Operators:
c) Relational operators

X++ CONTROL STATEMENTS(Contd.)


Operator Precedence:

X++ CONTROL STATEMENTS(Contd.)


Conditional Statements
a) If Statement

Code syntex is just like c#, c++


if (condition)
{
//if true these statements are executed }
else
{
//if false these statements are executed }

X++ CONTROL STATEMENTS(Contd.)


Conditional Statements
b) Switch statement
switch (expression)
{
case 'Choice1': Statement1;
Statement2;
break;
case 'Choice2': Statement3;
break;
case 'Choice3': Statement4;
Statement5;
Statement6;
break;
default : DefaultStatement;
}

X++ CONTROL STATEMENTS(Contd.)


Conditional Statements
c) Ternary Operator
condition ? statement1 : statement2;

X++ CONTROL STATEMENTS(Contd.)


Loops
a) while loop

while (condition)
{
//statement;
}

X++ CONTROL STATEMENTS(Contd.)


Loops
b) Do...while statement
do
{
//statement;
}
while (condition);

X++ CONTROL STATEMENTS(Contd.)


Loops
c) For loop
for ( initial value ; condition ; increment)
{
//statement;
}

X++ CONTROL STATEMENTS(Contd.)


Built-in functions:
Built-in functions can be used anywhere in X++ code.
These functions can be typed manually or accessed by using the context (right-click)
menu in the code editor and selecting List Built-in Functions, or by pressing Shift+F4.
Example
str letters;
;
letters ="ABCDEFG";
print subStr(letters, 2, 4);
print subStr(letters, 5, -3);
Result :
BCDE
CDE

X++ CONTROL STATEMENTS(Contd.)

Communication Tools:
Communicating with the end-user
Main types of communication are the following:
Forms and reports which are used for input and output
of larger amounts of data
Print commands, infologs and dialog boxes which are
generally used for specific data input and output

X++ CONTROL STATEMENTS(Contd.)


Communication Tools:
The print command
print "This is a test message.";
pause;

X++ CONTROL STATEMENTS(Contd.)


Communication Tools:
Infolog
Infolog is the most common method of communicating to
the user information about how a process has been
executed.
Boxes can output a message to a user, but sometimes
multiple messages are generated during processing.
Usage Example:
Info ("This is an info infolog");

X++ CONTROL STATEMENTS(Contd.)


Communication Tools:
Boxes
Boxes display brief messages to application users.
There are many different box types and each has their own box
method.
Methods in the box class take the following parameters
The main text
The title bar text
Help text
Example
box::info('Main Text', 'Title', 'This is the help text');

X++ CONTROL STATEMENTS(Contd.)


Communication Tools:
Dialog
Dialog boxes are a simplified type of form in Microsoft Dynamics AX.
They are generated from the Dialog class.
Example
static void Simple_Dialog(Args _args)
{
dialog dialog;
dialogGroup dialogGroup;
dialogField dialogField;
;
dialog = new Dialog("Simple Dialog");
dialogGroup = dialog.addGroup("Customer");
dialogField = dialog.addField(extendedTypeStr(custAccount));
if (dialog.run())
{
print dialogField.value();
pause;
}
}

CLASSES AND OBJECTS


A class is a software construct that defines the data (state)
and methods (behavior) of the specific concrete objects
that are subsequently constructed from that class.
How to create a Class
1. Open the AOT.
2. Locate the Classes node.
3. Right-click the Classes node and select New Class in the context
menu. The new class looks as shown below.
4. A new class named Class1 is created and contains one node: the
classDeclaration node. It is empty by default.
5. Double-click the classDeclaration node.
6. Enter the declarations between the two { } braces.
7. Right-click on the class and select New Method.
8. Rename the method.
9. Type code between the two { } braces.

Method Access
There are three modifiers available:
Public allows the method to be called
from any code in the application.
Protected allows the method to be
called only by methods in the same
class or subclasses of the class in
which the method is defined.
Private allows the method to be
called only by methods in the same
class in which the method is defined.

CLASSES AND OBJECTS


Inheritance:
Inheritance is a concept where one class can inherit all the
methods and variables from another class. A child class
inherits the methods of the parent class.
Syntax:
class Child extends Parent
{
}
multiple inheritance is not support. Use interfaces and/or
composition instead.

CLASSES AND OBJECTS


Method Types:
a) Static Methods
)

Static methods are methods that are attached to a class, but 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 void myStaticMethod() { }
myClass::myStaticMethod()

Main Method
It is used by the system when the class is run directly from a
menu item and it takes a parameter of type args.
static void main(Args args){}Args
is a class that is used to pass parameters between objects, for
instance, various parameters can beset 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.

Display Methods
Display methods are used on forms and in reports. Display
methods return a value.
display itemName itemName() {
inventTable
inventTable
;
select name from inventTable
where inventTable.itemId == this.itemId;
return inventTable.name;
}

CLASSES AND OBJECTS


Method Types:
d) Accessor
Accessor methods enable other elements to set or get the
values of variables in a class. It is common that they do
both.
str myName(str _myName = myName)
{
;
myName = _myName;
return myName;
}

CLASSES AND OBJECTS


Tables as Classes
A place for a table buffer is automatically assigned in a
table in classes the new method is used.
Fields in tables are public; they can be referred to from
everywhere. Fields in tables can be referred to
directly;
for example, in a report, whereas variables in a method
can only be referred to using access or methods.

ACCESSING THE DATABASE


In Dynamics Ax 2012
Retrieve data from the database using a select statement
Table Buffers:
A table buffer is declared like a variable the table name is
specified in the declaration.
A table buffer stores complete records in a variable.
Select Statements:
Select statements are used to retrieve data from a
database.
The pure select statement returns records to a table buffer.

ACCESSING THE DATABASE


(Contd.)
Select
static void Q1_Select1(Args _args)
{
CustTable CustTable;
;
select * from CustTable
where CustTable.AccountNum == 'BRMF-000001';
print CustTable.address();
pause;
}

// To Loop Records
while select AccountNum, Name, Address
from CustTable
{
print CustTable.AccountNum+ ": " + CustTable.Name + ": " +
CustTable.Address;
}
pause;

Sort
You can sort data retrieved from the database in many ways.
This includes:

Using existing indexes on the tables.

Using the order by clause in a select statement.

Using the group by clause in a select statement.

while select custTable index AccountIdx


{ print custTable.AccountNum, " ",
custTable.currency; }

Inner join
CustTable custTable;
DirPartyTable partyTable;
while select custTable
join partyTable
where custTable.party==
partyTable.RecId
{
info (custTable.AccountNum + " "
+partyTable.Name);
}

Exist
while select * from custTable
order by AccountNum

exists join * from salesTable


where
(custTable.AccountNum==salesTable.
CustAccount)

notExists
CustTable custTable;
CustBankAccount custBankaccount;
;
while select AccountNum from custTable order by
AccountNum
notexists join * from custBankaccount where
(custTable.AccountNum==custBankaccount.AccountNum
&& custTable.BankAccount == custBankaccount.AccountID
)
{
info( custTable.AccountNum);
}

outer
while select AccountNum from
custTable order by AccountNum
outer join * from salesTable

where salesTable.CustAccount
== custTable.AccountNum

{ info( custTable.AccountNum+ "


, " + salesTable.SalesId) ;}

Count
CustTable xCT;
int64 iCountRows; ;
Select COUNT(RecID) from xCT;
iCountRows = xCT.RecID;

ACCESSING THE DATABASE


(Contd.)
Transaction Integrity Checking
It is important to ensure the integrity of all transactions
within the system. When a transaction begins, to ensure
data consistency, it must finish completely with predictable
results.
The following keywords help in integrity checking:
ttsbegin Indicates the beginning of the transaction.
ttscommit Indicates the successful end of a
transaction. This ensures the transaction performed
as intended upon completion.
ttsabort Used as an exception to abort and roll back
a
transaction to the state before the ttsbegin.

ACCESSING THE DATABASE


(Contd.)
Create
static void Q13_Insert(Args _args)
{
CustTable CustTable;
;
CustTable.AccountNum = "supposedAccount1";
CustTable.Name = "SupposedName1";
CustTable.insert();
info("Inserted");
}

ACCESSING THE DATABASE


(Contd.)
Update:
static void Q14_Update(Args _args)
{
SalesTable SalesTable;
;
ttsbegin;
while select forupdate SalesTable
where SalesTable.CustAccount == "1102"
{
SalesTable.SalesName = "aaaaa";
SalesTable.update();
info("Updated Successfully");
}
ttscommit;
}

SalesTable SalesTable;
;
update_recordset SalesTable
setting salesName = "Update RecordSet",
DeliveryStreet = "New Address"
where SalesTable.CustAccount == "1102 ;
info("Updated Successfully via RecordSet");

ACCESSING THE DATABASE


(Contd.)
Delete
static void Q16_Delete(Args _args)
{
CustTable CustTable;
;
ttsbegin;
select forupdate CustTable
where CustTable.AccountNum == "supposedAccount1";
CustTable.delete();
info("Deleted");
ttscommit;
}
CustTable CustTable;
;
while select forupdate CustTable
where CustTable.AccountNum == "4018"
delete_from CustTable
where CustTable.AccountNum == "4018";

ACCESSING THE DATABASE


(Contd.)
Queries:
A query is an application object in the AOT
A query performs the same function as the select
statements, but is a better option as it allows for more
flexible user interaction when defining which records are to
be retrieved.
Queries Using X++:
Queries can also be created and manipulated using X++.
There are a number of classes available that you can use to
achieve this.
Two important classes when executing a query are:
Query()

The Query() class provides the framework for the query

QueryRun()

QueryRun() class starts this framework dynamically.

ACCESSING THE DATABASE


(Contd.)
Queries Using X++:
static void Q20_ViaXPlusPlus(Args _args)
{
Query query;
QueryBuildDataSource qbds;
QueryBuildRange qbr;
QueryRun queryrun;
CustTable CustTable;
;
query = new Query();
qbds = query.addDataSource(TableNum(CustTable));
qbr = qbds.addRange(FieldNum(CustTable,AccountNum));
qbr.value('1101');
qbds.addSortField(FieldNum(CustTable,AccountNum));
queryrun = new QueryRun(query);
while(queryrun.next())
{
CustTable = queryrun.get(TableNum(CustTable));
Print CustTable.AccountNum + ": " + CustTable.Name;
}
Pause;
}

ACCESSING THE DATABASE


(Contd.)
Accessing data from Different Companies:
static void Q10_CrossCompanies1(Args _args)
{
Container ConComapnies = ['cee','ceu'];
CustTable CustTable;
;
while select crossCompany : ConComapnies CustTable
{
Print CustTable.Name;
}
pause;
}

EXCEPTION HANDLING
Exception:
When code is running, errors can occur due to user input,
setup, data, code, or installation problems.
Users need a clear indication of when errors occur so they
can resolve the problem or report it to an administrator or
systems developer, who can investigate what went wrong.

EXCEPTION HANDLING
Exception Example:
static void Exception3(Args _args)
{
CustTable custTable;
;
try
{
custTable.AccountNum = '54299';
custTable.CustGroup = '50';
custTable.Address = 'Lahore Pakistan';
if(!custTable.validateWrite())
throw error("1. Record Failed during Validation.");
custTable.insert();
info("2. Record saved in database successfully, while passing validation");
}
catch(Exception::Error)
{
error("3. There was an error, while inserting the record.");
}
}

Short introduction to AIF


Framework

Usually we have to communicate with


external systems with Dynamics Ax.
In many business Scenario, Data is
imported from other application or
export form Dynamics Ax to external
system.
For Data Export or import Microsoft
provide AIF or application Integration
Framework.

What can we do with Dynamics AX Aif


Services.
Encapsulate the Business Logic.
Communicate with external systems.

Encapsulate the Business


logic:
With the help of Microsoft Dynamics
Ax services framework, we can
encapsulate required business logic.
For example we can create sales
order, purchase order, Create
Customers, vendors. These custom
business logic will be publish as web
service through the Application
Integration Framework (AIF). AIF also
participate in any Service Oriented
architecture (SOA).

Communicate with external systems.


Microsoft Dynamics AX Application
Integration Framework (AIF) enables
companies to integrate and
communicate with other systems
(External Systems). This
communication is based on external
business processes and partners
through the exchange of XML over
various transport media.
AIF enables Dynamics Ax to integrate
Business to business or application to
application scenario.

Types of services
Query service
Custom Service
Document Service.

Query Service
Publishes service operations that
allow execution of existing (static) or
ad hoc queries from service clients
and returns results in the form of
generic .NET datasets.

Custom Service
X++ method can be expose as service
Custom service artifacts
Service implementation class A class that
implements the business logic and exposes it
through X++ methods.
Service contract Service-related metadata (no
code). The most important service metadata
consists of the service operations that are
published to external service applications, and a
reference to the X++ service implementation class
that implements these service operations.
One or more data contracts X++ classes that
represent the complex parameter types used for
service operations. Data contracts are not needed
for primitive data types.

Document services

document services stems from the reality that


businesses need to exchange business
documents, such as sales orders and invoices Axd
documents:
API document-centeric application interface. For
example sales order service include create sales
order, read order, Update order.
Useful in those scenario when, validation is
extremely important, Response time is not critical,
even not important.

Document service
artifacts

Service contract Service-related


metadata (no code) that is stored in
the AOT nodes under the Services
node.
Service implementation An X++
class that derives from
AifDocumentService and implements
the service operations that are
published through the service contract
custCustomerService Class for
customer

Axd<Document> class An X++


class that derives from AxdBase.
Axd<Document> classes coordinate
cross-table validation and cross-table
defaulting. There is one
Axd<Document> class for each
document service. For example,
AxdCustomer is the Axd<Document>
class for customer. The AxdBase class,
among others, implements code for
XML serialization.

Data object An X++ class that


represents a parameter type and
serves as a data contract. The
parameter types that the Create New
Document Service Wizard generates
derive from AifDocument and
represent business documents. For
example, custCustomer is the data
object that is created for the
custCustomerService.

Learning resources and


references

http://technet.microsoft.com/enus/library/gg852966.aspx
Book, Inside Dynamics Ax 2012

Question and Answer.

You might also like