SlideShare a Scribd company logo
1 of 43
Fabio Filardi
Dynamics AX Technical Architect
ffilardi@msbsgroup.com
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
OBJECTS AND CLASSES
   Microsoft Dynamics AX 2012


                          Topics

                             Classes
                             Method Access Control
                             Scoping and Parameters in X++
                             Method Types
                             Inheritance
                             Objects
                             Tables as Classes
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.
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
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
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.
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)
{
}
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
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()
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.
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;
}
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
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.
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
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
ACCESSING THE DATABASE
     Microsoft Dynamics AX 2012




                                  Topics

                                   Retrieving Data
                                   Data Manipulation
                                   Queries
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.
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;
}
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
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;
      }
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;
     }
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;
     }
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;
     }
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;
        }
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
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();}
     }
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;
     }
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();
     }
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";
     }
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();
     }
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";
     }
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
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.
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.
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
EXCEPTION HANDLING
   Microsoft Dynamics AX 2012




                          Topics

                           Exceptions
                           Try and Catch Statements
                           Throwing Exceptions
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.
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.
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.
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.
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;
          }
     }
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

More Related Content

What's hot

Dynamics ax 2012 development overview
Dynamics ax 2012 development overviewDynamics ax 2012 development overview
Dynamics ax 2012 development overviewAli Raza Zaidi
 
Developing ssrs-reports-for-dynamics-ax
Developing ssrs-reports-for-dynamics-axDeveloping ssrs-reports-for-dynamics-ax
Developing ssrs-reports-for-dynamics-axNicc Ngo
 
AX 2012: All About Lookups!
AX 2012: All About Lookups!AX 2012: All About Lookups!
AX 2012: All About Lookups!MAnasKhan
 
Optimization SQL Server for Dynamics AX 2012 R3
Optimization SQL Server for Dynamics AX 2012 R3Optimization SQL Server for Dynamics AX 2012 R3
Optimization SQL Server for Dynamics AX 2012 R3Juan Fabian
 
Deploying customizations across microsoft dynamics ax 2012 environments ax2012
Deploying customizations across microsoft dynamics ax 2012 environments ax2012Deploying customizations across microsoft dynamics ax 2012 environments ax2012
Deploying customizations across microsoft dynamics ax 2012 environments ax2012Prathamesh Joshi
 
Dynamics ax performance tuning
Dynamics ax performance tuningDynamics ax performance tuning
Dynamics ax performance tuningOutsourceAX
 
Developer's guide to customization
Developer's guide to customizationDeveloper's guide to customization
Developer's guide to customizationAhmed Farag
 
An Introduction to the Dynamics AX Application Integration Framework
An Introduction to the Dynamics AX Application Integration FrameworkAn Introduction to the Dynamics AX Application Integration Framework
An Introduction to the Dynamics AX Application Integration FrameworkFolio3-Dynamics-Services
 
Oracle XML Publisher / BI Publisher
Oracle XML Publisher / BI PublisherOracle XML Publisher / BI Publisher
Oracle XML Publisher / BI PublisherEdi Yanto
 
Oracle BI publisher intro
Oracle BI publisher introOracle BI publisher intro
Oracle BI publisher introAdil Arshad
 
18 Invaluable Lessons About ADF-JSF Interaction
18 Invaluable Lessons About ADF-JSF Interaction18 Invaluable Lessons About ADF-JSF Interaction
18 Invaluable Lessons About ADF-JSF InteractionSteven Davelaar
 
DAX and Power BI Training - 001 Overview
DAX and Power BI Training -  001 OverviewDAX and Power BI Training -  001 Overview
DAX and Power BI Training - 001 OverviewWill Harvey
 
Pitch-Deck-Collaborate-in-the-Cloud-with-Microsoft-365.pptx
Pitch-Deck-Collaborate-in-the-Cloud-with-Microsoft-365.pptxPitch-Deck-Collaborate-in-the-Cloud-with-Microsoft-365.pptx
Pitch-Deck-Collaborate-in-the-Cloud-with-Microsoft-365.pptxJibinChacko11
 
Integration with dynamics ax 2012
Integration with dynamics ax 2012Integration with dynamics ax 2012
Integration with dynamics ax 2012Ali Raza Zaidi
 
Active Directory Upgrade
Active Directory UpgradeActive Directory Upgrade
Active Directory UpgradeSpiffy
 
DAX and Power BI Training - 002 DAX Level 1 - 3
DAX and Power BI Training - 002 DAX Level 1 - 3DAX and Power BI Training - 002 DAX Level 1 - 3
DAX and Power BI Training - 002 DAX Level 1 - 3Will Harvey
 
AX 2012 R3 Installation Guide
AX 2012 R3 Installation GuideAX 2012 R3 Installation Guide
AX 2012 R3 Installation GuideBiswanath Dey
 

What's hot (20)

Dynamics ax 2012 development overview
Dynamics ax 2012 development overviewDynamics ax 2012 development overview
Dynamics ax 2012 development overview
 
Developing ssrs-reports-for-dynamics-ax
Developing ssrs-reports-for-dynamics-axDeveloping ssrs-reports-for-dynamics-ax
Developing ssrs-reports-for-dynamics-ax
 
Dynamics AX/ X++
Dynamics AX/ X++Dynamics AX/ X++
Dynamics AX/ X++
 
AX 2012: All About Lookups!
AX 2012: All About Lookups!AX 2012: All About Lookups!
AX 2012: All About Lookups!
 
Optimization SQL Server for Dynamics AX 2012 R3
Optimization SQL Server for Dynamics AX 2012 R3Optimization SQL Server for Dynamics AX 2012 R3
Optimization SQL Server for Dynamics AX 2012 R3
 
Deploying customizations across microsoft dynamics ax 2012 environments ax2012
Deploying customizations across microsoft dynamics ax 2012 environments ax2012Deploying customizations across microsoft dynamics ax 2012 environments ax2012
Deploying customizations across microsoft dynamics ax 2012 environments ax2012
 
Dynamics ax performance tuning
Dynamics ax performance tuningDynamics ax performance tuning
Dynamics ax performance tuning
 
Developer's guide to customization
Developer's guide to customizationDeveloper's guide to customization
Developer's guide to customization
 
An Introduction to the Dynamics AX Application Integration Framework
An Introduction to the Dynamics AX Application Integration FrameworkAn Introduction to the Dynamics AX Application Integration Framework
An Introduction to the Dynamics AX Application Integration Framework
 
Oracle XML Publisher / BI Publisher
Oracle XML Publisher / BI PublisherOracle XML Publisher / BI Publisher
Oracle XML Publisher / BI Publisher
 
Oracle BI publisher intro
Oracle BI publisher introOracle BI publisher intro
Oracle BI publisher intro
 
Abap Objects for BW
Abap Objects for BWAbap Objects for BW
Abap Objects for BW
 
18 Invaluable Lessons About ADF-JSF Interaction
18 Invaluable Lessons About ADF-JSF Interaction18 Invaluable Lessons About ADF-JSF Interaction
18 Invaluable Lessons About ADF-JSF Interaction
 
DAX and Power BI Training - 001 Overview
DAX and Power BI Training -  001 OverviewDAX and Power BI Training -  001 Overview
DAX and Power BI Training - 001 Overview
 
Security of hyperion planning
Security of hyperion planningSecurity of hyperion planning
Security of hyperion planning
 
Pitch-Deck-Collaborate-in-the-Cloud-with-Microsoft-365.pptx
Pitch-Deck-Collaborate-in-the-Cloud-with-Microsoft-365.pptxPitch-Deck-Collaborate-in-the-Cloud-with-Microsoft-365.pptx
Pitch-Deck-Collaborate-in-the-Cloud-with-Microsoft-365.pptx
 
Integration with dynamics ax 2012
Integration with dynamics ax 2012Integration with dynamics ax 2012
Integration with dynamics ax 2012
 
Active Directory Upgrade
Active Directory UpgradeActive Directory Upgrade
Active Directory Upgrade
 
DAX and Power BI Training - 002 DAX Level 1 - 3
DAX and Power BI Training - 002 DAX Level 1 - 3DAX and Power BI Training - 002 DAX Level 1 - 3
DAX and Power BI Training - 002 DAX Level 1 - 3
 
AX 2012 R3 Installation Guide
AX 2012 R3 Installation GuideAX 2012 R3 Installation Guide
AX 2012 R3 Installation Guide
 

Similar to Objects and Classes in Microsoft Dynamics AX 2012

Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3Ali Raza Zaidi
 
Object oriented basics
Object oriented basicsObject oriented basics
Object oriented basicsvamshimahi
 
Abap object-oriented-programming-tutorials
Abap object-oriented-programming-tutorialsAbap object-oriented-programming-tutorials
Abap object-oriented-programming-tutorialscesarmendez78
 
BIS08 Application Development - II
BIS08 Application Development - IIBIS08 Application Development - II
BIS08 Application Development - IIPrithwis Mukerjee
 
Beginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHPBeginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHPRick Ogden
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptxrani marri
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#SyedUmairAli9
 
Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1Synapseindiappsdevelopment
 
Objectorientedprogrammingmodel1
Objectorientedprogrammingmodel1Objectorientedprogrammingmodel1
Objectorientedprogrammingmodel1bharath yelugula
 
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad NicheTech Com. Solutions Pvt. Ltd.
 
Application package
Application packageApplication package
Application packageJAYAARC
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4dplunkett
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .NetGreg Sohl
 
chapter 5 Objectdesign.ppt
chapter 5 Objectdesign.pptchapter 5 Objectdesign.ppt
chapter 5 Objectdesign.pptTemesgenAzezew
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 

Similar to Objects and Classes in Microsoft Dynamics AX 2012 (20)

Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3
 
Object oriented basics
Object oriented basicsObject oriented basics
Object oriented basics
 
Abap object-oriented-programming-tutorials
Abap object-oriented-programming-tutorialsAbap object-oriented-programming-tutorials
Abap object-oriented-programming-tutorials
 
BIS08 Application Development - II
BIS08 Application Development - IIBIS08 Application Development - II
BIS08 Application Development - II
 
Beginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHPBeginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHP
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
 
C sharp chap5
C sharp chap5C sharp chap5
C sharp chap5
 
7494605
74946057494605
7494605
 
Class and object
Class and objectClass and object
Class and object
 
Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1
 
Objectorientedprogrammingmodel1
Objectorientedprogrammingmodel1Objectorientedprogrammingmodel1
Objectorientedprogrammingmodel1
 
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
 
Application package
Application packageApplication package
Application package
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
 
Hemajava
HemajavaHemajava
Hemajava
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .Net
 
Oops
OopsOops
Oops
 
chapter 5 Objectdesign.ppt
chapter 5 Objectdesign.pptchapter 5 Objectdesign.ppt
chapter 5 Objectdesign.ppt
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 

Recently uploaded

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 

Recently uploaded (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 

Objects and Classes in Microsoft Dynamics AX 2012

  • 1. Fabio Filardi Dynamics AX Technical Architect ffilardi@msbsgroup.com
  • 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