The document discusses objects and classes in Microsoft Dynamics AX 2012. It covers topics such as classes, methods, inheritance, objects, and tables as classes. It explains that a class defines the data and methods of objects constructed from that class. Methods can be public, protected, or private, and classes can inherit properties from parent classes. The document also provides examples of how to work with classes and objects in X++ code.
2. Microsoft Dynamics AX 2012
Development Introduction
Features
Architecture
Data Dictionary
User Interface
X++ Intro
X++ Control Statements
Objects and Classes
Accessing the Database
Exception Handling
3. OBJECTS AND CLASSES
Microsoft Dynamics AX 2012
Topics
Classes
Method Access Control
Scoping and Parameters in X++
Method Types
Inheritance
Objects
Tables as Classes
4. Objects and Classes
Microsoft Dynamics AX 2012
Classes
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.
A class is not an object. It can be thought of as a blueprint for different instances of an object.
It is possible for multiple instances of the object to exist, and for each instance to hold different values in
its variables, and therefore to run differently.
5. Objects and Classes
Microsoft Dynamics AX 2012
Classes
A class is constructed of members which can be variables or methods.
Variables are used to store the data for the class. They are specific to an object; every object
instantiated from the class declaration has its own copy of the variable. Such variables are known as
instance variables.
Methods are the functions that operate on the data and define the object's behavior. They are often
declared to operate on the instance variables of the class, and are known as instance methods.
Lab 3.1 - Create a New Class, pg. 3-4
6. Objects and Classes
Microsoft Dynamics AX 2012
Method Access Control
Methods in a class are always available to other methods in the class. However they should not always
be available to methods in other classes. To control access to a method, a methods modifier is placed in
the method definition.
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.
Lab 3.2 - Allow Access to Methods, pg. 3-6
7. Objects and Classes
Microsoft Dynamics AX 2012
Scoping and Parameters in X++
Scope is the area where an item is accessed.
Instance variables, declared in class declarations, can be accessed from any methods in the class, and
from methods in sub-classes that extend the class.
Local variables can be accessed only in the method in which they are defined.
Methods with Parameters
All methods in X++ have their own scope. To use data from a different scope, transfer the data into the
new scope using parameters.
A method can have one or more parameters. Within the scope of the method these parameters are
treated like local variables, initialized with the value from the parameter in the method-call.
8. Objects and Classes
Microsoft Dynamics AX 2012
Scoping and Parameters in X++
All parameters are passed by value, this means you cannot change the value of the original variable, but
only the local variable in the method, which is a copy of the original.
BEST PRACTICE: Method parameter names should always start with an underscore (_). Method
parameters should never be written to within the code, only read from.
private void methodWithParameters(str _parm1, int _parm2 = 1)
{
}
9. Objects and Classes
Microsoft Dynamics AX 2012
Scoping and Parameters in X++
Methods Returning Data
When you create a new method, it is declared with the keyword Void. The void (empty) specifies that
the method does not return a value.
You can enable a method to return a value, following two steps:
Replace the void with a primary type or a extended data type to specify the type of data to receive from
the method. Any kind of data can be returned including table buffers and class objects.
Write return followed by a specification of the data that you want to receive for any manipulation of the
data.
private str getStringValue()
{
str myTxt = "Text";
return myTxt;
}
Lab 3.4 - Use Method Parameters, pg. 3-13
10. Objects and Classes
Microsoft Dynamics AX 2012
Method Types
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.
static public void myStaticMethod()
{
}
myClass::myStaticMethod()
11. Objects and Classes
Microsoft Dynamics AX 2012
Method Types
Main Method
The main method is a static method and 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.
static void main(Args 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.
12. Objects and Classes
Microsoft Dynamics AX 2012
Method Types
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.
display itemName itemName()
{
InventTable inventTable;
select name from inventTable
where inventTable.itemId == this.itemId;
return inventTable.name;
}
13. Objects and Classes
Microsoft Dynamics AX 2012
Method Types
Referencing Object Methods
To refer to a method in the same class, use the keyword this.
Example: a class has a method called myMethod() and another called run(). The run() method calls the
myMethod() method:
public void run()
{
this.myMethod();
}
Lab 3.5 - Create a Run Method, pg. 3-15
14. Objects and Classes
Microsoft Dynamics AX 2012
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. Additional methods can be applied to the child
class, and inherited methods can be overridden. This means the child class is not always identical to the
parent class.
The advantage of inheritance in object-oriented programming is that code can be written one time and
be reused many times.
Declaration:
class Child extends Parent
{
}
Objects created from the Child:
Have at least the same methods and variables as the Parent.
Can have methods and variables that do not exist in the Parent.
Can have methods from the Parent that are overridden or altered, in the Child.
15. Objects and Classes
Microsoft Dynamics AX 2012
Objects
Objects are created at run-time using the classes defined in the AOT. To create an object from a class,
the class has to be instantiated.
Object instance methods can only be used when an object is instantiated from a specific class.
You can have multiple instances of a class, meaning, you can have the same code running multiple
times.
To execute a specific method from your object, use the reference variable followed by a "dot" operator
then the method name.
static void Job1(Args _args)
{
MyClass myClassObject;
;
myClassObject = new myClass();
myClassObject.myMethod();
}
Lab 3.3 - Instantiating a Class, pg. 3-10
16. Objects and Classes
Microsoft Dynamics AX 2012
Tables as Classes
A table can be considered an independent class used to address fields or methods defined on that
table.
Differences between tables and classes include the following:
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 directly. A method can only be referred to
using accessor methods.
Lab 3.6 - Create a Calculator Class, pg. 3-22
17. ACCESSING THE DATABASE
Microsoft Dynamics AX 2012
Topics
Retrieving Data
Data Manipulation
Queries
18. Accessing the Database
Microsoft Dynamics AX 2012
Retrieving Data
Microsoft Dynamics AX 2012 accesses data using select statements and queries.
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.
19. Accessing the Database
Microsoft Dynamics AX 2012
Retrieving Data
The following example shows code that selects a record from the Customer table where the customer
account number is 1102 (CEE company) and prints the customer name:
static void Job1(Args _args)
{
CustTable custTable;
;
select * from custTable
where custTable.AccountNum == "1102";
print custTable.name();
pause;
}
20. Accessing the Database
Microsoft Dynamics AX 2012
Retrieving Data Syntax Options Keyword
Find Options reverse
Select Statement Definition firstFast
firstOnly
select <find options>
<tablebuffer> or forUpdate
<[aggregate (field identifier) | fieldlist] from tablebuffer}> noFetch
<sorting options field identifier [direction]> Aggregate sum
<index clause (index)> avg
where <selection criteria> minof
<join clause join> maxof
count
Sorting Options order by
group by
Direction asc
desc
Index Clause index
index hint
Join Clause exists
notexists
outer
21. Accessing the Database
Microsoft Dynamics AX 2012
Retrieving Data
Field Lists
To perform a lookup on specific fields in a table, use a field list in the select statement.
select AccountNum, BankAccount, Currency
from CustTable
where CustTable.AccountNum =="4000";
Using While Select
The while select statement loops through many records fulfilling specific criteria in a table. Use this loop
to perform statements on each record.
while select accountNum, currency, creditMax from custTable
{
print custTable.AccountNum, " ", custTable.currency, " ", custTable.creditMax;
pause;
}
22. Accessing the Database
Microsoft Dynamics AX 2012
Retrieving Data
Using Ranges in Select Statements
A range can be set for records being selected. This range is specified in the where clause of the select
statement using relational operators.
while select custTable
where custTable.AccountNum > "4005" && custTable.AccountNum < "4017"
{
print custTable.AccountNum, " ", custTable.currency;
}
23. Accessing the Database
Microsoft Dynamics AX 2012
Retrieving Data
Sorting Options
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;
}
24. Accessing the Database
Microsoft Dynamics AX 2012
Retrieving Data
Order By
If an index does not exist on a table, you can create a temporary index using an order by clause in the
select statement. This lets you specify one or more table fields to sort the result.
while select custTable order by AccountNum desc
{
print custTable.AccountNum, " ", custTable.currency;
}
Group By
Use the group by clause to group selected records by field.
while select count(SalesId) from salesTable group by CustGroup
{
print salesTable.CustGroup,": ", salesTable.SalesId;
}
25. Accessing the Database
Microsoft Dynamics AX 2012
Retrieving Data
Joins
Use joins to link tables so they can return values together. By default, inner joins are created. The
following table describes the types of joins available: inner, outer, exists and notexists.
while select AccountNum from custTable
join custTrans
where (custTrans.AccountNum == custTable.AccountNum)
&& custTrans.AccountNum =="1103"
{
print custTable.accountNum, " ", custTrans.Voucher;
}
26. Accessing the Database
Microsoft Dynamics AX 2012
Retrieving Data
Cross-company Support
Microsoft Dynamics AX can have multiple companies in one data base. It is a common requirement to
retrieve data from many or all of these companies in a function.
This can be achieved in one select statement by using the crossCompany keyword.
If just the keyword is used, it will search all companies. You can also specify a container that defines
which companies to search.
static void Job1(Args _args)
{
container conCompanies = [ 'cee', 'ceu' ];
custTable custTable;
while select crossCompany : conCompanies custTable
{
print custTable.dataAreaId, " ", custTable.accountNum;
}
}
Lab 4.1 - Retrieving Data, pg. 4-10
27. Accessing the Database
Microsoft Dynamics AX 2012
Data Manipulation
Data manipulation in X++ refers to interactively using SQL commands. These commands include insert,
update and delete.
Insert
To create new records in the database, use the insert() method on the table.
The data is first set on the table buffer by assigning values to fields. The data is then committed to the
database by calling the insert() method.
static void Job1(Args _args)
{
custTable custTable;
custTable.accountNum = "1234";
custTable.Currency = "USD";
custTable.insert();}
}
28. Accessing the Database
Microsoft Dynamics AX 2012
Data Manipulation
Insert_Recordset
Insert_Recordset copies data from one or more tables in one call to the database.
This is much faster than selecting records individually and then inserting the new records in to the
table.
static void Job1(Args _args)
{
VendTable vendTable;
HcmWorker hcmWorker;
Insert_RecordSet VendTable (AccountNum, Party)
select PersonnelNumber, Person
from hcmWorker;
}
29. Accessing the Database
Microsoft Dynamics AX 2012
Data Manipulation
Update
The Update command modifies existing data in a table with the contents of a table buffer.
The record is first retrieved from the database using a select statement. The data is then modified by
assigning the new values to the fields in the table buffer.
The new values are then committed to the database using the update() method.
static void Job1(Args _args)
{
SalesTable salesTable;
select forupdate salesTable
where salesTable.CustAccount =="2001"
salesTable.SalesName ="New Enterprises";
salesTable.update();
}
30. Accessing the Database
Microsoft Dynamics AX 2012
Data Manipulation
Update_Recordset
The update_recordset command allows the manipulation of many records in one operation.
This command speeds up database processing because of fewer calls to the database.
static void Job1(Args _args)
{
SalesTable salesTable;
update_recordset salesTable
setting salesName = "New Enterprises"
where salesTable.custAccount =="2001";
}
31. Accessing the Database
Microsoft Dynamics AX 2012
Data Manipulation
Delete
The delete command deletes a complete record from the database that meets the condition of the
select statement.
The syntax of the delete command resembles update and insert.
static void Job1(Args _args)
{
CustTable custTable;
select forUpdate custTable
where custTable.accountnum =="2032";
custTable.delete();
}
32. Accessing the Database
Microsoft Dynamics AX 2012
Data Manipulation
Delete_from
The delete_from command removes multiple records from the database at one time. Similar to the
update_recordset command, delete_from consolidates many database calls into one operation, and
increases database performance.
static void Job1(Args _args)
{
CustTable custTable;
delete_from custTable
where custTable.Currency == "ABC";
}
33. Accessing the Database
Microsoft Dynamics AX 2012
Data Manipulation
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.
If the transaction terminates in the middle, the system should roll back to its state before the
transaction began.
The following keywords help in integrity checking:
ttsbegin
ttscommit
ttsabort
Nested ttsbegins and ttscommits are ignored in that a lock is held until the last ttscommit is reached.
However the system does keep track of the tts level. Each time a ttsbegin is called, the tts level
increases by one. Every ttscommit decreases the level by one.
Lab 4.2 - Update, pg. 4-15
34. Accessing the Database
Microsoft Dynamics AX 2012
Queries
Characteristics:
Query is an application object in the AOT;
Query performs the same function as the select
statements;
Queries provide more flexibility, especially when
sorting and specifying ranges;
Query allows more flexible to user when defining
which records are to be retrieved.
35. Accessing the Database
Microsoft Dynamics AX 2012
Queries
Executing a Query in X++
Queries can also be created and manipulated using X++. Two important classes when executing a query are:
Query and QueryRun.
The Query class does not "fetch" records, this is accomplished by using the QueryRun class. The Query class
provides the framework for the query whereas the QueryRun class starts this framework dynamically.
static void Job1(Args _args)
{
Query myQuery = new Query (QueryStr(CustTable));
QueryRun myQueryRun = new QueryRun (myQuery);
while (myQueryRun.next())
{
// code to execute here
}
}
NOTE: The QueryStr function validates that the element of type Query called CustTable exists in the AOT.
36. Accessing the Database
Microsoft Dynamics AX 2012
Queries
Building a Query in X++
Queries contain many important elements. There are two more classes to note before building a query:
QueryBuildDataSource
Data sources are what queries are built upon. They are arranged in a hierarchy and define the sequence in
which records are fetched from tables assigned to the data source.
QueryBuildRange
A QueryBuildRange object is embedded within a data source of a query and defines which records should
be selected from the data source. A QueryBuildRange is built upon a QueryBuildDataSource object.
Lab 4.3 - Create a Query Using X++, pg. 4-21
37. EXCEPTION HANDLING
Microsoft Dynamics AX 2012
Topics
Exceptions
Try and Catch Statements
Throwing Exceptions
38. Exception Handling
Microsoft Dynamics AX 2012
Exceptions
An exception is a situation where the flow of a program's execution is interrupted. Exceptions can occur
because of user input, setup, data, code, or installation problems.
Examples:
Printing to a printer that is not powered on
Accessing a file that does not exist
Updating a record that does not exist
Users need a clear indication of when exceptions occur so that they can resolve the problem or report it to
an administrator or systems developer, who can investigate what went wrong.
This feature allows developers to catch exceptions during program execution and control how the program
reacts to the exception.
39. Exception Handling
Microsoft Dynamics AX 2012
Exceptions
When these exceptions occur, the program must handle them.
For example, if the user requests a file that does not exist, the program might have to catch the
exception and create a new file.
All exception types can be caught, and it is the developer's responsibility to decide which exceptions
must be handled.
The exception type is identified using the system enum Exception. It is a system enum, and cannot be
modified or added new exception types.
40. Exception Handling
Microsoft Dynamics AX 2012
Exceptions
Exception Description
info Thrown when a message has been sent to the Infolog. Do not throw an info exception manually.
warning Thrown when something illegal, although nonfatal has occurred.
deadlock Thrown when there is a database deadlock because several transactions are waiting for one another.
error Thrown when a fatal problem has occurred and the transaction has stopped.
internal Thrown when Microsoft Dynamics AX encounters internal development problems at runtime.
break Thrown when the user presses Break or Ctrl+C during runtime.
DDEerror Thrown when a problem occurs in the Dynamic Data Exchange (DDE) system class.
sequence For internal use only.
numeric Thrown when a problem occurs during the use of any numerical function.
CLRError Thrown when a problem occurs during the use of the Common Language Runtime (CLR) functionality.
CodeAccessSecurity Thrown when a problem occurs during the use of CodeAccessPermission.demand.
UpdateConflict Thrown when a record being updated within a transaction that is using Optimistic Concurrency Control, and the
recVersion value of the record buffer and the database record are not equal. The transaction can be retried (use a
retry statement in the catch block).
UpdateConflict NotRecovered Thrown when a transaction using Optimistic Concurrency Control cannot be completed, and the code will not be
retried.
41. Exception Handling
Microsoft Dynamics AX 2012
Exceptions
Try and Catch Statements
try
{
// code with your business logic
}
catch (<Exception>)
{
// code to be executed if a exception was thrown
}
Try statements signify the start of a block of code that you want to control. Any exceptions that are thrown
in that block of code can be caught and handled in the associated Catch statements.
Catch statements define what code is executed when each exception is thrown. You do not have to define a
Catch statement for every possible exception. However, each Try statement must have at least one Catch
statement. It is also possible to define a Catch statement that is executed for any exception type.
Retry statements tell the system to go back to the Try statement and attempt to execute the code again.
42. Exception Handling
Microsoft Dynamics AX 2012
Exceptions
static void Job1(Args _args)
{
CustTable custTable;
Counter retryCount;
try
{
custTable.AccountNum = "0001";
custTable.CustGroup = "50";
custTable.insert();
}
catch (Exception::Error)
{
error("There was an error while inserting the record.");
}
catch (Exception::Deadlock)
{
retry;
}
}
43. Exception Handling
Microsoft Dynamics AX 2012
Exceptions
Throwing Exceptions : is used to throw an error that can be caught by a Catch statement:
static void Job1(Args _args)
{
CustTable custTable;
try
{
select custTable
where custTable.accountNum == "1019";
if (!custTable.RecId)
throw error("Customer does not exist");
}
catch (exception::error)
{
error ("Process was aborted");
}
}
Lab 5.1 - Handle an Exception, pg. 5-8