Microsoft Dynamics AX 2012 - Development Introduction Training - Part 3/3


Published on

Microsoft Dynamics AX 2012 - Development Introduction Training - Part 3/3

Published in: Technology, Health & Medicine
  • Thanks @choanilax
    Are you sure you want to  Yes  No
    Your message goes here
  • nice work...
    Are you sure you want to  Yes  No
    Your message goes here
  • Thanks guys. @sergio_741, I did use the official training material (Dev I, II, III), and some MSDN articles as complement.

    Some useful links:

    Microsoft Dynamics AX architecture [AX 2012]

    AOS architecture [AX 2012]

    Model store architecture [AX 2012]

    What's New in Microsoft Dynamics AX 2012 for Developers [AX 2012]

    What's New: Services and AIF for Developers in Microsoft Dynamics AX 2012 [AX 2012]

    Are you sure you want to  Yes  No
    Your message goes here
  • excellent slides, thanks U
    can you tell me the bibliography (references)?
    Are you sure you want to  Yes  No
    Your message goes here
  • Excellent presentation. Good job guys.
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Microsoft Dynamics AX 2012 - Development Introduction Training - Part 3/3

  1. 1. Fabio FilardiDynamics AX Technical
  2. 2. Microsoft Dynamics AX 2012Development Introduction Features Architecture Data Dictionary User Interface X++ Intro X++ Control Statements Objects and Classes Accessing the Database Exception Handling
  3. 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. 4. Objects and ClassesMicrosoft Dynamics AX 2012ClassesA class is a software construct that defines the data (state) and methods (behavior) of the specificconcrete 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 inits variables, and therefore to run differently.
  5. 5. Objects and ClassesMicrosoft Dynamics AX 2012ClassesA 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 objects 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. 6. Objects and ClassesMicrosoft Dynamics AX 2012Method Access ControlMethods in a class are always available to other methods in the class. However they should not alwaysbe available to methods in other classes. To control access to a method, a methods modifier is placed inthe 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. 7. Objects and ClassesMicrosoft Dynamics AX 2012Scoping 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, andfrom methods in sub-classes that extend the class.Local variables can be accessed only in the method in which they are defined.Methods with ParametersAll methods in X++ have their own scope. To use data from a different scope, transfer the data into thenew scope using parameters.A method can have one or more parameters. Within the scope of the method these parameters aretreated like local variables, initialized with the value from the parameter in the method-call.
  8. 8. Objects and ClassesMicrosoft Dynamics AX 2012Scoping and Parameters in X++All parameters are passed by value, this means you cannot change the value of the original variable, butonly the local variable in the method, which is a copy of the original.BEST PRACTICE: Method parameter names should always start with an underscore (_). Methodparameters should never be written to within the code, only read from.private void methodWithParameters(str _parm1, int _parm2 = 1){}
  9. 9. Objects and ClassesMicrosoft Dynamics AX 2012Scoping and Parameters in X++Methods Returning DataWhen you create a new method, it is declared with the keyword Void. The void (empty) specifies thatthe 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 fromthe 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 thedata.private str getStringValue(){ str myTxt = "Text"; return myTxt;} Lab 3.4 - Use Method Parameters, pg. 3-13
  10. 10. Objects and ClassesMicrosoft Dynamics AX 2012Method TypesStatic MethodsStatic methods are attached to a class, however, they do not need that class to be instantiated toexecute 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. 11. Objects and ClassesMicrosoft Dynamics AX 2012Method TypesMain MethodThe 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 typeargs.static void main(Args args){}Args is a class that is used to pass parameters between objects, for instance, various parameters can beset on the properties on a menu item.When the menu item calls a class, the args class containing those property values is passed to the mainmethod using the args parameter.
  12. 12. Objects and ClassesMicrosoft Dynamics AX 2012Method TypesDisplay MethodsDisplay methods are used on forms. They are commonly created on the table, and can also be definedon the form.Display methods return a value that is displayed on the form or report. They are often used to display acalculation, 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;}
  13. 13. Objects and ClassesMicrosoft Dynamics AX 2012Method TypesReferencing Object MethodsTo 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 themyMethod() method:public void run(){ this.myMethod();} Lab 3.5 - Create a Run Method, pg. 3-15
  14. 14. Objects and ClassesMicrosoft Dynamics AX 2012InheritanceInheritance is a concept where one class can inherit all the methods and variables from another class. Achild class inherits the methods of the parent class. Additional methods can be applied to the childclass, and inherited methods can be overridden. This means the child class is not always identical to theparent class.The advantage of inheritance in object-oriented programming is that code can be written one time andbe 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. 15. Objects and ClassesMicrosoft Dynamics AX 2012ObjectsObjects 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 multipletimes.To execute a specific method from your object, use the reference variable followed by a "dot" operatorthen 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. 16. Objects and ClassesMicrosoft Dynamics AX 2012Tables as ClassesA table can be considered an independent class used to address fields or methods defined on thattable.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. 17. ACCESSING THE DATABASE Microsoft Dynamics AX 2012 Topics  Retrieving Data  Data Manipulation  Queries
  18. 18. Accessing the DatabaseMicrosoft Dynamics AX 2012Retrieving DataMicrosoft 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. 19. Accessing the DatabaseMicrosoft Dynamics AX 2012Retrieving DataThe following example shows code that selects a record from the Customer table where the customeraccount 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; pause;}
  20. 20. Accessing the DatabaseMicrosoft Dynamics AX 2012Retrieving Data Syntax Options Keyword Find Options reverseSelect Statement Definition firstFast firstOnlyselect <find options> <tablebuffer> or forUpdate <[aggregate (field identifier) | fieldlist] from tablebuffer}> noFetch <sorting options field identifier [direction]> Aggregate sum <index clause (index)> avgwhere <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. 21. Accessing the DatabaseMicrosoft Dynamics AX 2012Retrieving DataField ListsTo 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 SelectThe while select statement loops through many records fulfilling specific criteria in a table. Use this loopto perform statements on each record. while select accountNum, currency, creditMax from custTable { print custTable.AccountNum, " ", custTable.currency, " ", custTable.creditMax; pause; }
  22. 22. Accessing the DatabaseMicrosoft Dynamics AX 2012Retrieving DataUsing Ranges in Select StatementsA range can be set for records being selected. This range is specified in the where clause of the selectstatement using relational operators. while select custTable where custTable.AccountNum > "4005" && custTable.AccountNum < "4017" { print custTable.AccountNum, " ", custTable.currency; }
  23. 23. Accessing the DatabaseMicrosoft Dynamics AX 2012Retrieving DataSorting OptionsYou 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. 24. Accessing the DatabaseMicrosoft Dynamics AX 2012Retrieving DataOrder ByIf an index does not exist on a table, you can create a temporary index using an order by clause in theselect 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 ByUse 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. 25. Accessing the DatabaseMicrosoft Dynamics AX 2012Retrieving DataJoinsUse joins to link tables so they can return values together. By default, inner joins are created. Thefollowing 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. 26. Accessing the DatabaseMicrosoft Dynamics AX 2012Retrieving DataCross-company SupportMicrosoft Dynamics AX can have multiple companies in one data base. It is a common requirement toretrieve 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 defineswhich 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. 27. Accessing the DatabaseMicrosoft Dynamics AX 2012Data ManipulationData manipulation in X++ refers to interactively using SQL commands. These commands include insert,update and delete.InsertTo 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 thedatabase by calling the insert() method. static void Job1(Args _args) { custTable custTable; custTable.accountNum = "1234"; custTable.Currency = "USD"; custTable.insert();} }
  28. 28. Accessing the DatabaseMicrosoft Dynamics AX 2012Data ManipulationInsert_RecordsetInsert_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 thetable. static void Job1(Args _args) { VendTable vendTable; HcmWorker hcmWorker; Insert_RecordSet VendTable (AccountNum, Party) select PersonnelNumber, Person from hcmWorker; }
  29. 29. Accessing the DatabaseMicrosoft Dynamics AX 2012Data ManipulationUpdateThe 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 byassigning 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. 30. Accessing the DatabaseMicrosoft Dynamics AX 2012Data ManipulationUpdate_RecordsetThe 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. 31. Accessing the DatabaseMicrosoft Dynamics AX 2012Data ManipulationDeleteThe delete command deletes a complete record from the database that meets the condition of theselect 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. 32. Accessing the DatabaseMicrosoft Dynamics AX 2012Data ManipulationDelete_fromThe delete_from command removes multiple records from the database at one time. Similar to theupdate_recordset command, delete_from consolidates many database calls into one operation, andincreases database performance. static void Job1(Args _args) { CustTable custTable; delete_from custTable where custTable.Currency == "ABC"; }
  33. 33. Accessing the DatabaseMicrosoft Dynamics AX 2012Data ManipulationTransaction Integrity CheckingIt 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 thetransaction began.The following keywords help in integrity checking:  ttsbegin  ttscommit  ttsabortNested 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 levelincreases by one. Every ttscommit decreases the level by one. Lab 4.2 - Update, pg. 4-15
  34. 34. Accessing the DatabaseMicrosoft Dynamics AX 2012QueriesCharacteristics:  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. 35. Accessing the DatabaseMicrosoft Dynamics AX 2012QueriesExecuting 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 classprovides 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 ( { // code to execute here } }NOTE: The QueryStr function validates that the element of type Query called CustTable exists in the AOT.
  36. 36. Accessing the DatabaseMicrosoft Dynamics AX 2012QueriesBuilding a Query in X++Queries contain many important elements. There are two more classes to note before building a query: QueryBuildDataSourceData sources are what queries are built upon. They are arranged in a hierarchy and define the sequence inwhich records are fetched from tables assigned to the data source. QueryBuildRangeA QueryBuildRange object is embedded within a data source of a query and defines which records shouldbe 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. 37. EXCEPTION HANDLING Microsoft Dynamics AX 2012 Topics  Exceptions  Try and Catch Statements  Throwing Exceptions
  38. 38. Exception HandlingMicrosoft Dynamics AX 2012ExceptionsAn exception is a situation where the flow of a programs execution is interrupted. Exceptions can occurbecause 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 existUsers need a clear indication of when exceptions occur so that they can resolve the problem or report it toan administrator or systems developer, who can investigate what went wrong.This feature allows developers to catch exceptions during program execution and control how the programreacts to the exception.
  39. 39. Exception HandlingMicrosoft Dynamics AX 2012ExceptionsWhen 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 theexception and create a new file.All exception types can be caught, and it is the developers responsibility to decide which exceptionsmust be handled.The exception type is identified using the system enum Exception. It is a system enum, and cannot bemodified or added new exception types.
  40. 40. Exception HandlingMicrosoft Dynamics AX 2012ExceptionsException Descriptioninfo 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. 41. Exception HandlingMicrosoft Dynamics AX 2012ExceptionsTry 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 thrownin 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 aCatch statement for every possible exception. However, each Try statement must have at least one Catchstatement. 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. 42. Exception HandlingMicrosoft Dynamics AX 2012Exceptions 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. 43. Exception HandlingMicrosoft Dynamics AX 2012ExceptionsThrowing 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