Ax2012 Enus Devii 02

download Ax2012 Enus Devii 02

of 42

Transcript of Ax2012 Enus Devii 02

  • 8/11/2019 Ax2012 Enus Devii 02

    1/42

    Chapter 2: X++ Control Statements

    2-1

    CHAPTER 2: X++ CONTROL STATEMENTS

    Objectives

    The objectives are:

    Declare and use extended data types for variables.

    Use the various operators available in X++.

    Control program flow using conditional statements in X++.

    Repetitively call the same blocks of code by using Loop statements.

    Use standard functions that are built in to the application.

    Use output commands to display data and messages to the user.

    Introduction

    This course explains how to use control statements in X++. These statements

    control the logic flow in the program. This course also describes how to use some

    built-in functions in Microsoft Dynamics AX to communicate with the end-user.

    Scenario

    Isaac, the Systems Developer, is implementing a project that requires a

    modification to code. He has been asked to become familiar with the typical

    statements in X++ used to control program flow, and to communicate with the

    user.

  • 8/11/2019 Ax2012 Enus Devii 02

    2/42

    Development II in Microsoft DynamicsAX 2012

    2-2

    Introduction to Variables

    Variables hold data when a block of code executes. Variables all have scope.

    Scope is the area where the variable can be accessed. Some different types of

    scope include:

    Scope Description

    Global (to a class) These are variables defined in the classDeclaration

    of a class.

    Local (to a method) These are variables defined in a method of a class.

    Local (to an embedded

    function)

    These are variables defined in a function embedded

    in a method of a class.

    Use the type of variable that matches the type of data that you want to store. You

    can name the variable, as long as you do not use names the system already uses,

    such as commands or keywords. A list of reserved words is located in the

    Developer Helpunder the "Keywords" lesson.

    BEST PRACTICE: Do not use names like string1. Always give a variable a

    meaningful name so its use is easier to identify when reading the code.

    Declaration

    All variables must be declared before use. When a variable is declared, a small

    amount of memory is reserved. The syntax of the declaration is the same,

    whether it is a simple variable or an object variable.

    You cannot mix variable declarations with other X++ statements. Variables mustbe declared before the statements.

    There are two rules to use when declaring variables:

    Declare all variables before anything else in the code.

    Use a semicolon after each declaration.

    You might want a variable to have a value other than the default when thevariable is declared. X++ supports initialization of variables in the Declaration

    statement. Initialization is performed by adding the assignment-statement to the

    variable declaration. For example:

    int a = 10; // a is assigned the value 10

    Simple Data Types

    X++ implements primitive data types that can be used to declare variables in

    X++ code. You can also create Extended Data Types on the basis of primitive

    types; this is discussed in theDevelopment I in Microsoft Dynamics 2012course.

  • 8/11/2019 Ax2012 Enus Devii 02

    3/42

    Chapter 2: X++ Control Statements

    2-3

    The following table provides an overview of the simple data types available in

    Microsoft Dynamics AX:

    Data Type Description Example Declaration

    Keyword

    String A string is a number ofcharacters. X++ supports several

    types of strings: Left aligned,

    right aligned, fixed length or not

    fixed length. The maximum

    length of a string is 999

    characters.

    Name str

    Integer An integer, also named a natural

    figure, is a number without a

    decimal point.

    1090 int

    Real Reals, also named decimals, are

    numbers with a decimal point.

    3.14 real

    Date The date type contains day,

    month, and year.

    10\29\1978 date

    UTC

    DateTime

    Contains year, month, day, hour,

    minute and second.

    9/28/2008

    07:11:02 am

    utcDateTim

    e

    Enum Enum values are represented

    internally as integers. The first

    literal has the number 0, the next

    number 1, the next number 2,

    and so on. You can use enums as

    integers in expressions.

    NoYes Must be

    declared as

    a Base

    Enum first

    Boolean Booleans can only contain the

    values false and true. The enum

    values false and true are

    predefined in X++ and

    recognized by the compiler.

    TRUE boolean

    Time Contains hours, minutes, and

    seconds. To declare a time, use

    the system type timeOfDay.

    15:23:08 timeOfDay

    GUID Global Unique Identifier

    (GUID) is a reference number

    which is unique in any context.

    {3F2504E0-

    4F89-11D3-

    9A0C-0305E82C3

    301}

    guid

    Int64 A large integer, represented by

    64 bits.

    5637144579 Int64

  • 8/11/2019 Ax2012 Enus Devii 02

    4/42

    Development II in Microsoft DynamicsAX 2012

    2-4

    The simple variable declaration is frequently used.

    The syntax for the simple variable declaration is as follows:

    dataType variableIdentifier;

    The data type can be any of the data types in X++. Here are some examples:

    int integerVariable;

    real realVariable;

    str unboundStringVariable;

    str 30 boundStringVariable; // max of 30 chars

    date dateVariable;

    boolean booleanVariable;

    When declaring a variable, you can also declare them as an extended data type.

    This is a good practice because it can highlight errors in code at compile time

    when a variable is used incorrectly.

    It is common to name the variable the same as the extended data type, when

    possible.

    custAccount custAccount;

    transDate transDate;

    amountMST amountDebit, amountCredit;

    Initializing Variables

    The following statements show how to declare the variables for use later in the

    code. You can declare several variables of the same type with different names.

    You can also assign a value to the variable when you declare it or later in the

    code.

    int counter, toCount;

    int fromCount = 1;

  • 8/11/2019 Ax2012 Enus Devii 02

    5/42

    Chapter 2: X++ Control Statements

    2-5

    Composite Data Types

    In addition to the simple data types, you can use composite data types when

    declaring variables.

    The following composite data types are available:

    Data type Description

    Array An array is a list of items with the same data type and the

    same name; only the index differs.

    Container A container is a dynamic list of items that can contain

    primitive data types and some composite data types.

    Classes A class is a type definition that describes both variablesand methods for instances (objects) of the class.

    Tables All tables defined in the database (in the data dictionary)

    can be handled as class definitions.

    Arrays

    Arrays can be declared by adding brackets ( [ ] ).

    You can set the maximum number of array elements by putting the number in the

    brackets.

    Array values can be set by specifying the index when assigning the value.

    real realUnlimtedArray[]; // Unlimited index values

    real realLimitedArray[10]; // maximum of 10 values

    realLimitedArray[2] = 3.142;

    Containers

    A container variable can contain different types and values of simple and

    extended data types, including arrays and other container variables. Classes

    cannot be put into containers.

    There are many functions that manipulate container variables. The following

    functions are available:

    Function Description

    conPeek Returns the value being held in a specific position in thecontainer.

    conDel Removes a value from a specific position in the container.

    conNull Returns an empty container.

  • 8/11/2019 Ax2012 Enus Devii 02

    6/42

    Development II in Microsoft DynamicsAX 2012

    2-6

    Function Description

    conFind Finds the position in the container that a certain value is

    being held (if found).

    conIns Inserts a value into a specific position in the container.

    conPoke Replaces the value being held in a specific position in thecontainer, with a new value.

    conLen Returns the number of elements in the container.

    The following examples have a container variable that contains four values,

    including three different data types.

    container c; // the container is declared

    int i, j;

    str txt;

    c = [10, 20, "test"]; // the container has 3 values set

    print conPeek(c, 3); // the third element is printed[i,j,txt] = c; // other variables are set from the

    container

    Operators

    Operators are used to manipulate variable and field values and to control the

    logical program flow based on the values in variables and fields. The following

    types of operators are available.

    Assignment operators modify the contents of a variable or field.

    Arithmetic operators perform mathematical operations on the valuesin a variable or field.

    Relational operators evaluate how two values relate to one anotherand return either True or False according to the result.

    Assignment Operators

    Assignment operators modify the contents of a variable or field. The following

    table defines available operators.

    Operator Description

    = Assigns the expression on the right of the equal sign to the

    variable on the left.

    += Increments the variable on the left by the value on the right.

    ++ Increments the variable on the left by one.

    -= Decrements the variable on the left by the value on the right.

    -- Decrements the variable on the left by one.

  • 8/11/2019 Ax2012 Enus Devii 02

    7/42

    Chapter 2: X++ Control Statements

    2-7

    Arithmetic Operators

    Arithmetic operators perform calculations in X++. Arithmetic operators are used

    like relational operators except for '~, ++, --, +=, and -='. The following table

    defines available arithmetic operators:

    Operator Term Description

    + Plus Adds expression1 to expression2.

    - Minus Subtracts expression2 from expression1.

    * Multiply Multiplies expression1 with expression2.

    / Divide Divides expression1 with expression2.

    DIV Integer

    division

    Performs an integer division of expression1

    with expression2.

    MOD Integer

    remainder

    Returns the rest of an integer division of

    expression1 with expression2.

    ~ Not Unary operator: performs a binary not-

    operation.

    & Binary

    And

    Performs a binary and-operation on expression1

    and expression2.

    ^ Binary

    XOR

    Performs a binary XOR-operation on

    expression1 and expression2.

    | Binary Or Performs a binary or-operation on expression1

    and expression2.

    > Right shift Performs expression2 right shift (a division by

    two) on expression1.

    ? Ternary

    operator

    Takes three expressions: expression1 ?

    expression2 : expression3. If expression1 is

    true, expression2 is returned otherwise

    expression3 is returned.

    The following are some examples of these arithmetic operators. For all examples,

    the variable 'i' is an integer.

    Evaluated Expression Return Value

    i++; Increments the i variable by one.

    i--; Decrements the i variable by one.

    i += 2; Increments the i variable by two every time.

    i -= 3; Decrements the i variable by three every time.

    i = 3

  • 8/11/2019 Ax2012 Enus Devii 02

    8/42

    Development II in Microsoft DynamicsAX 2012

    2-8

    Evaluated Expression Return Value

    i = 24 >> 2 i = 6 (i = 24/2/2)

    i = 80 DIV 13 i = 6 (6 is the largest number that 13 can be

    multiplied by, where the result is less than or

    equal to 80. In this case, 6*13 = 78, remainder

    2)

    i = 80 MOD 13 i = 2 (2 is the remainder after dividing 80 by

    13)

    NOTE: View more examples of arithmetic operators in the "X++ Online Help

    Guide."

    Relational Operators

    Relational operators, except for '!', are placed between two expressions. The

    following table defines available relational operators:

    Operator Term Description

    == equal Returns true if both expressions are equal.

    >= greater than

    or equal

    Returns true if expression1 is greater than or

    equal to expression2.

    greater than Returns true if expression1 is greater than

    expression2.

    < less than Returns true if expression1 is less than

    expression2.

    != not equal Returns true if expression1 differs from (not

    equal to) expression2.

    && and Returns true if both expression1 and

    expression2 are true.

    || or Returns true if expression1 or expression2 or

    both are true.

    ! not A unary operator. Negates the expression.

    Returns true if the expression is false, and false

    if the expression is true.

    like like Returns true if expression1 is like expression2.

    This can use * as a wildcard for zero or more

    characters and ? as wildcard for one character.

  • 8/11/2019 Ax2012 Enus Devii 02

    9/42

    Chapter 2: X++ Control Statements

    2-9

    The following are examples using relational operators and their return values:

    Evaluated Expression Return Value

    'abcdef' like 'abc*' TRUE: the * is equal to any string of characters.

    'abcdef' like 'abc?' FALSE: the ? is equivalent to one character.

    9 != 10 TRUE: these values are not equal to one

    another.

    (10 > 9) && (11 9) TRUE: the first expression returns true.

    Operator Precedence

    You can use X++ to create complex statements using multiple operators when

    data types on all parts of the statements are equivalent. When multiple operators

    are used in one statement, precedence for the operators must be in place for

    statement evaluation. The following table lists the precedence for operators. Thehighest precedence is at the beginning of the table; precedence gets lower as you

    move down the table.

    Operator Type Operator Syntax

    postfix operators [] . (params) expr++ expr--

    unary operators ++expr --expr +expr -expr ~ !

    creation new (type)expr

    multiplicative * /

    additive + -relational < > =

    equality == !=

    bitwise AND &

    shift >

    bitwise exclusive OR ^

    bitwise inclusive OR |

    logical operators (AND, OR) && ||

    conditional ? :assignment = += -=

  • 8/11/2019 Ax2012 Enus Devii 02

    10/42

    Development II in Microsoft DynamicsAX 2012

    2-10

    Conditional Statements

    Conditional statements in programming define conditions under which certain

    functions are performed. Conditional statements use logical expressions that are

    evaluated and return a value of either trueor false. There are three primary

    conditional statements:

    Ifstatement

    Switchstatement

    Ternaryoperators

    All these statements are evaluated using operators.

    If

    The ifstatement is the simplest control statement. It checks whether a condition

    is true or false. If the condition is satisfied, all the code within the braces '{}' is

    executed. The syntax for an ifstatement is as follows:

    if (condition)

    {

    //if true these statements are executed

    }

    The following is an example of an ifstatement. If the variable a is greater than

    10, the value of a will be printed to the screen.

    if (a > 10)

    {

    print a;}

    The following is an example of an ifstatement using multiple expressions toevaluate the condition.

    if((a < 5) || (a > 10))

    {

    print a;

    }

  • 8/11/2019 Ax2012 Enus Devii 02

    11/42

    Chapter 2: X++ Control Statements

    2-11

    If...else

    An ifstatement checks for only one possibility and ignores all other conditions.

    An ifelsestatement checks one condition and if true, the block of code is

    executed. Otherwise, an alternative statement is executed. The syntax for an

    ifelse statement is as follows:

    if (condition)

    {

    //if true these statements are executed

    }

    else

    {

    //if false these statements are executed

    }

    int i = 12;

    int j = 10;

    int max;

    if (i > j)

    {

    max = i;

    }

    else

    {

    max = j;

    }

    The previous conditional formulas allow for only two alternative outcomes. A

    program might have to check more than two alternatives. To check for multiplealternatives, you can use an ifelse...ifstatement. The syntax for this statement

    is as follows:

    if (condition1)

    {

    //statement1

    }

    else

    {

    if (condition2)

    {

    //statement2

    }else

    {

    //statement3

    }

    }

  • 8/11/2019 Ax2012 Enus Devii 02

    12/42

    Development II in Microsoft DynamicsAX 2012

    2-12

    The system checks condition 1 first, and if satisfied, statement1 is executed. If

    the condition 1 is not satisfied, it moves to condition2. If condition2 is satisfied,

    statement2 is executed. If condition2 is not satisfied, then statement3 executes.

    You can use as many conditions as necessary.

    You might need to have a condition in a condition. You can do this using nested

    if statements.

    A mathematics teacher uses the following criteria to determine who passes or

    fails the class:

    Pass the final exam

    Pass the homework sections

    Check the logic in the following order:

    1. If the student has failed the exam, then the student fails the course.

    2. If the student has passed the exam, then check the student'shomework sections.

    3. If the student has passed the exam and the homework sections, thestudent passes the course.

    4. Otherwise, the student fails.

    boolean passExam = true;

    boolean passHomeWork = false;

    str studentStatus;

    if (passExam == true)

    {

    if (passHomeWork == true)

    {studentStatus = "Passed";

    }

    else

    {

    studentStatus = "Failed";

    }

    }

    else

    {

    studentStatus = "Failed";

    }

    Ternary Operator

    This conditional statement behaves exactly like an ifelse statement. The main

    reason to use the ternary operator is convenience in coding. Its syntax is as

    follows:

    condition ? statement1 : statement2;

  • 8/11/2019 Ax2012 Enus Devii 02

    13/42

    Chapter 2: X++ Control Statements

    2-13

    The condition is checked first and if true, statement1 is executed, if false,

    statement2 is executed. However, the two expressions following the question

    mark (?) must be of the same data type.

    This example using the ternary operator, is equivalent in logic and results to the

    previous example using the if...else statement.

    int i = 12;

    int j = 10;

    int max;

    max = i > j ? i : j;

    Switch

    A switchstatement acts as a multi-branch control statement that defines an

    expression and whose result leads to a specific program execution. The switch

    statement considers the result and executes code, depending on possible

    outcomes of the expression. These are known as cases. Each of these cases islisted in the body of the statement.

    Following the colon after each case are statements that execute if the expression

    satisfies the case. There can be any number of statements following a case in a

    switchstatement. The body of a switchstatement is enclosed in braces '{}'. The

    following shows the syntax for a switchstatement:

    switch (expression)

    {

    case 'Choice1':

    Statement1;

    Statement2;

    break;

    case 'Choice2':

    Statement3;

    break;

    case 'Choice3':

    Statement4;

    Statement5;

    Statement6;

    break;

    default : DefaultStatement;

    }

    The break;statement tells the program to leave the switchstatement and

    continue immediately after the switch. This can also be used elsewhere in X++

    coding. The defaultcase executes if the result of the expression does not match

    any of the cases. Using the default case is optional.

  • 8/11/2019 Ax2012 Enus Devii 02

    14/42

    Development II in Microsoft DynamicsAX 2012

    2-14

    The following example compares a switchstatement with an ifelsestatement.

    For these examples, students receive a score from a test. The score must have a

    corresponding letter grade. The scores can only be 90, 80, 70, and so on.

    int score = 80;

    str grade;str message;

    switch (score)

    {

    case 90 : grade = "A";

    message = "Excellent";

    break;

    case 80 : grade = "B";

    message = "Good";

    break;

    case 70 : grade = "C";

    message = "Average";

    break;

    case 60 : grade = "D";

    message = "Poor";

    break;

    default : grade = "Failed!";

    message = "You need to study more!" ;

    }

    This example produces the same result as the previous example, but uses if...else

    statements instead of the case statement. Note the number of lines of code and

    the ease of reading the code in each case.

    int score = 80;

    str grade;

    if (score == 90)

    {

    grade = "A";

    }

    else

    {

    if (score == 80)

    {

    grade = "B";

    }

    else

    {

    if (score == 70){

    grade = "C";

    }

    else

    {

  • 8/11/2019 Ax2012 Enus Devii 02

    15/42

    Chapter 2: X++ Control Statements

    2-15

    if (score == 60)

    {

    grade = "D";

    }

    else

    {

    grade = "Failed!";

    }

    }

    }

    }

    As illustrated on the previous page, the switchstatement simplifies the code and

    makes the program flow more efficiently. Another advantage of using a switch

    statement is allocating multiple results of the expression to one outcome or case.

    The following example shows the use of multiple expressions in a switch

    statement.

    str color = "red";

    str colortype;

    switch (color)

    {

    case "red", "yellow", "blue" :

    colortype = "Primary Color";

    break;

    case "purple", "green", "orange" :

    colortype = "Secondary Color";

    break;

    default : colortype ="Neither Primary or Secondary";

    }

  • 8/11/2019 Ax2012 Enus Devii 02

    16/42

    Development II in Microsoft DynamicsAX 2012

    2-16

    This example produces the same result as the previous example, but uses if...else

    statements instead of the case statement. Note the number of lines of code and

    the ease of reading the code in each case.

    str color = "red";

    str colortype;

    if ((color =="red")

    || (color =="yellow")

    || (color =="blue"))

    {

    colortype ="Primary Color";

    }

    else

    {

    if ((color =="purple")

    || (color =="green"')

    || (color =="orange"))

    {

    colortype ="Secondary Color";

    }

    else

    {

    colortype ="Neither Primary or Secondary color"

    }

    }

    Loops

    Repetitive statements, also known as loops, conditionally control data input and

    output. There are three main loops in X++:

    Whileloop

    Do whileloop

    Forstatement

    While

    The whileloop evaluates a condition and executes statements, depending on

    whether the condition is satisfied. The loop continues to check the condition, and

    as long as the condition is true, it continues to execute the statements. As soon as

    the condition becomes false, the statement is exited. The syntax is as follows:

    while (condition)

    {

    //statement;

    }

  • 8/11/2019 Ax2012 Enus Devii 02

    17/42

    Chapter 2: X++ Control Statements

    2-17

    This is a simple whilestatement that counts from 1 to 5.

    int counter = 1;

    while (counter

  • 8/11/2019 Ax2012 Enus Devii 02

    18/42

    Development II in Microsoft DynamicsAX 2012

    2-18

    For

    The forstatement uses an incrementing counter variable, and a condition, to

    determine the how long it will continue to loop. The parameters in a for

    statement include three elements:

    The initial value of the variable.

    The condition under which the loop will continue.

    The amount the variable is increased or decreased by.

    The syntax can be defined as follows:

    for ( initial value ; condition ; increment)

    {

    //statement;

    }

    Forloops are frequently used when navigating through an array. The followingis an example of how to use a forloop to print each element of a string array

    called 'abc' that contains 10 strings:

    for (counter = 1; counter

  • 8/11/2019 Ax2012 Enus Devii 02

    19/42

    Chapter 2: X++ Control Statements

    2-19

    The continuestatement ignores the rest of the current loop and continues to

    control the loop. The following example uses a forloop with the continue

    statement to control which values print to the screen. The loop executes the print

    statement for values = 8.

    int counter;

    for (counter=1;counter 3 && counter < 8)

    {

    continue;

    }

    print counter;

    }

    pause;

    Result:

    1

    2

    3

    8

    9

    10

  • 8/11/2019 Ax2012 Enus Devii 02

    20/42

    Development II in Microsoft DynamicsAX 2012

    2-20

    Lab 2.1 - Create a Times Table Using a While Loop

    Scenario

    Isaac has been asked to demonstrate the use of a whilestatement by printing out

    the multiplication table for 2.

    Challenge Yourself!

    1. Create a job that prints the multiplication table for 2 using a whilestatement.

    2. Have the list contain all even numbers up to 50.

    3. Use a 'counter' variable to increment every time.

    Step by Step

    1. Open the AOT.2. Right-click the Jobsnode and select New Job.

    3. Rename the job.

    4. Add the following code.

    int counter = 1;

    while (counter

  • 8/11/2019 Ax2012 Enus Devii 02

    21/42

    Chapter 2: X++ Control Statements

    2-21

    Lab 2.2 - Create a Times Table Using a Do...while Loop

    Scenario

    Isaac has been asked to demonstrate the use of a do...whilestatement by printing

    out the multiplication table for 2.

    Challenge Yourself!

    1. Create a job that prints the multiplication table for 2 using ado...whilestatement.

    2. Have the list contain all even numbers up to 50.

    3. Use a 'counter' variable to increment every time.

    Step by Step

    1. Open the AOT.2. Right-click the Jobsnode and select New Job.

    3. Rename the job.

    4. Add the following code.

    int counter = 1;

    do

    {

    print counter * 2;

    counter++;

    }

    while(counter

  • 8/11/2019 Ax2012 Enus Devii 02

    22/42

    Development II in Microsoft DynamicsAX 2012

    2-22

    Lab 2.3 - Create a Times Table Using a for Statement

    Scenario

    Isaac has been asked to demonstrate the use of a forstatement by printing out the

    multiplication table for 2.

    Challenge Yourself!

    1. Create a job that prints the multiplication table for 2 using a forstatement.

    2. Have the list contain all even numbers up to 50.

    3. Use a 'counter' variable to increment every time.

    Step by Step

    1. Open the AOT.2. Right-click the Jobsnode and select New Job.

    3. Rename the job.

    4. Add the following code.

    int counter;

    for(counter = 1; counter

  • 8/11/2019 Ax2012 Enus Devii 02

    23/42

    Chapter 2: X++ Control Statements

    2-23

    Built-in Functions

    Microsoft Dynamics AX contains many built-in functions to help in X++

    development. These functions perform mathematical operations, convert data

    types, return system values, and so on.

    Built-in functions can be used anywhere in X++ code. These functions can be

    typed manually or accessed by using the context (right-click) menu in the Code

    Editor and selecting List Built-in Functions,or by pressing Shift+F4.

    FIGURE 2.1 BUILT-IN FUNCTIONS LISTING

    To use a function, click it. The function is placed in the code where the pointer is

    located.

    This example uses a function that returns a subset of a string variable. The syntax

    for the function is as follows:

    str subStr(str text, int position, int number);

    The following table describes the components of the function:

    Component Description

    str substr Specifies the return type of the function (string) and the

    name of the function (subStr).

    str text The original text string.

    int position Indicates the position where the sub-string starts.

    int number Designates how many characters are included in the sub-

    string.

    str letters;

    letters = "ABCDEFG";

    print subStr(letters, 2, 4);

    print subStr(letters, 5, -3);

    pause;

    Result in the message window:

    BCDE

    CDE

    The negative number causes the characters to be selected backward from the

    position.

  • 8/11/2019 Ax2012 Enus Devii 02

    24/42

    Development II in Microsoft DynamicsAX 2012

    2-24

    Communication Tools

    Communicating with the end-user is important and critical for an application to

    run correctly. The main types of communication include:

    Forms and reports used for input and output of larger amounts ofdata.

    Print statements, Infologs and dialog boxes generally used forspecific data input and output.

    This lesson discusses how to use the print statement, create dialog boxes and

    Infologs. Forms and reports are covered in more detail in the next development

    course.

    Print...Pause

    When the compiler reaches a printstatement, it returns whatever value or

    variable value that immediately follows the printsyntax. The following is anexample of the printstatement:

    print "This is a test message.";

    pause;

    The pauseline freezes the output text on the screen after the code runs so that it

    is easier to read. The pausestatement causes a message box to pop up. It lets the

    user continue or end code execution.

    The printstatement should not be used within the actual application business

    logic. It is used only as a programmers tool to display data or values while

    developing and debugging code.

    Boxes

    Boxes display brief messages to application users. There are many box types and

    each has their own box method.

    Methods in the box class take the following parameters:

    The main text

    The title bar text

    Help text

    The following is an example of an information box and how the parameters are

    used:

    Box::info("Main Text", "Title", "This is the help text");

  • 8/11/2019 Ax2012 Enus Devii 02

    25/42

  • 8/11/2019 Ax2012 Enus Devii 02

    26/42

    Development II in Microsoft DynamicsAX 2012

    2-26

    The resultingbox is shown on the display.

    FIGURE 2.4 YES/NO BOX EXAMPLE

    Notice the additional required parameterDialogButton::Yes. This parameter

    specifies a default button. Notice on the YesNobox that the Yesbutton is

    selected as the default.

    The following is an example of how X++ accepts user input and executes

    statements based on this input:

    DialogButton dialogButton;

    dialogButton= Box::yesNo("Choose Yes or No",DialogButton::Yes, "Yes No Box Example");

    if (dialogButton == DialogButton::Yes){

    print "You chose Yes";

    pause;}else if (dialogButton == DialogButton::No)

    {print "You chose No";

    pause;}

    The boxfunction returns a value of the enum DialogButtonthat can be used to

    determine which option the user chooses.

    Infolog

    The Infolog is the most common method used to communicate with the user

    about how a process is executed. Boxes can output a message to a user. However,

    sometimes multiple messages are generated during processing. Infologs are more

    suited to handle multiple messages; there are three types of messages:

    Message type Description

    Information Important information that does not require any action.

    Warning Warning when a critical situation occurs.

    Error When a fatal error occurs and a user must take action

  • 8/11/2019 Ax2012 Enus Devii 02

    27/42

    Chapter 2: X++ Control Statements

    2-27

    The following table contains Infolog icons and a description of each method.

    FIGURE 2.5 INFOLOG ICONS

    Several methods exist to invoke the Infolog system.

    The easiest way is to use the info (text)function. This adds the text to the Infolog

    system. Any text that is added to the Infolog is displayed when the program

    returns to a state of waiting for user input. This is typically at the end of a

    process.

    info("This is an info infolog");

    The following figure shows the resulting output.

    FIGURE 2.6 EXAMPLE INFOLOG BOX

    Creating warning or error Infolog messages resemble the example shown

    previously in this lesson. The only part of the syntax that changes is the word infront of the parentheses. The following example shows the syntax for warning

    and error Infologs:

    warning("Infolog text");

    error("Infolog text");

  • 8/11/2019 Ax2012 Enus Devii 02

    28/42

    Development II in Microsoft DynamicsAX 2012

    2-28

    The following figure shows the error Infolog message.

    FIGURE 2.7 EXAMPLE INFOLOG BOX

    The Infolog system is used mostly to display multiple messages at the same time,

    in tree form. The following figure shows an example of multiple messages in tree

    form.

    FIGURE 2.8 INFOLOG TREE

    The setPrefix()function sets the label for the heading of the Infolog tree. In the

    example, it specifies the label, 'Infolog Tree'. The following example shows the

    syntax of this method:

    setPrefix("Infolog Tree");

  • 8/11/2019 Ax2012 Enus Devii 02

    29/42

    Chapter 2: X++ Control Statements

    2-29

    The following figure shows how adding calls to setPrefix()adds multiple levels

    to the Infolog tree. The level will continue while the method the setPrefix()

    statement is called in remains in scope.

    FIGURE 2.9 MULTILEVEL INFOLOG

    BEST PRACTICE: Use labels when possible for the text of these Infolog

    messages and the SetPrefix function.

    Dialog Boxes

    Dialog boxes are a simplified type of form in Microsoft Dynamics AX, and theyare generated from the Dialog class. They create a dialog with the user where the

    user can input values. Dialog boxes are not used in complex scenarios; forms are

    the preferred method in complex situations. All dialog boxes have a standardized

    form that contains an OK/Canceloption.

    NOTE: The Dialog class described here is a different concept then the Dialog

    Form Template available as a context-menu option on the Form node in the

    AOT. This topic describes creating Dialog forms using X++ code.

  • 8/11/2019 Ax2012 Enus Devii 02

    30/42

    Development II in Microsoft DynamicsAX 2012

    2-30

    The following is an example of the OK/Canceldialog box.

    FIGURE 2.10 SIMPLE DIALOG BOX

    The following example displays the dialog box and prints the value entered to the

    screen.

    static void Simple_Dialog(Args _args){

    dialog dialog;

    dialogGroup dialogGroup;dialogField dialogField;

    dialog = new Dialog("Simple Dialog");dialogGroup = dialog.addGroup("Customer");

    dialogField =dialog.addField(extendedTypeStr(custAccount));

    if (dialog.run())

    {print dialogField.value();

    pause;}

    }

    The dialog.run()method returns trueif OKis clicked, andfalseif Cancelis

    clicked.

  • 8/11/2019 Ax2012 Enus Devii 02

    31/42

  • 8/11/2019 Ax2012 Enus Devii 02

    32/42

    Development II in Microsoft DynamicsAX 2012

    2-32

    Lab 2.5 - Create an Infolog Tree

    Scenario

    Isaac has been asked to create an Infolog Tree that has an Info message, a

    Warning message and an Error message.

    Challenge Yourself!

    Create a tree of Infolog messages using a job in Microsoft Dynamics AX. The

    tree should have a root node which states: "This is the Infolog Tree lab." The tree

    should contain at least one of each type of message (Info, Warning and Error).

    Step by Step

    1. Open the AOT.

    2. Right-click the Jobsnode and select New Job.

    3. Rename the job.

    4. Add the following code.

    setPrefix("This is the Infolog Tree lab");

    info("Info message");

    warning("Warning message");

    error("Error message");

    5. Compile the code (press F7or click the Compilebutton in thetoolbar).

    6. Run the job (press F5or click the Gobutton in the toolbar).

  • 8/11/2019 Ax2012 Enus Devii 02

    33/42

    Chapter 2: X++ Control Statements

    2-33

    Lab 2.6 - Create a Dialog Box

    Scenario

    Isaac has been asked to create a dialog box that will prompt the user to enter a

    customer account number and a sales order ID.

    Challenge Yourself!

    Create a dialog box that lets the user select a customer account number and a

    sales order ID. Once the user clicks OK, show the values of each selection using

    the Infolog.

    Step by Step

    1. Open the AOT.

    2. Right-click the Jobsnode and select New Job.

    3. Rename the job.

    4. Add the following code.

    Dialog dialog;

    DialogGroup dialogGroup;

    DialogField dialogFieldCustAccount;

    DialogField dialogFieldSalesId;

    dialog = new Dialog("Simple Dialog");

    dialogGroup = dialog.addGroup("Customer");

    dialogFieldCustAccount =

    dialog.addField(extendedTypeStr(CustAccount));

    dialogFieldSalesId =dialog.addField(extendedTypeStr(SalesId));

    if(dialog.run())

    {

    info(dialogFieldCustAccount.value());

    info(dialogFieldSalesId.value());

    }

    5. Compile the code (press F7or click the Compilebutton in thetoolbar).

    6. Run the job (press F5or click the Gobutton in the toolbar).

  • 8/11/2019 Ax2012 Enus Devii 02

    34/42

    Development II in Microsoft DynamicsAX 2012

    2-34

    Lab 2.7 - Use X++ Control Statements

    Scenario

    Isaac has been asked to create a job that will ask the user if he or she wants to

    display his or her date of birth. If the user chooses Yes, the system should print

    the user's name and date of birth. If the user chooses No, the system should only

    print the user's name.

    Challenge Yourself!

    Create a dialog for the user that determines, based on input, what appears on a

    screen.

    1. Create a new job in the AOT and declare and initialize aDialogButtonobject variable and a containerdata type variable.

    2. The three elements of the container are your first name, last name,

    and birth date.3. The Dialogbutton should be a Yes Nobox with the text "Do you

    want to display your birth date?" with Yesbeing the default button.

    4. If Yesis clicked -first name, last name, and birth date appear.

    5. If Nois clicked -only first and last name appear.

    Step by Step

    1. Open the AOT.

    2. Right-click the Jobsnode and select New Job.

    3. Rename the job.

    4. Add the following code.

    DialogButton dialogButton;

    container nameAndDOB;

    nameAndDOB = ["John","Doe",mkDate(28,9,71)];

    dialogButton = Box::yesNo("Do you want to see the

    birthdate?", DialogButton::Yes);

    if (dialogButton == DialogButton::Yes)

    {

    Box::info(strFmt("%1 %2, %3", conPeek(nameAndDOB,1),

    conPeek(nameAndDOB,2), date2str(conPeek(nameAndDOB,3),-1,-

    1,-1,-1,-1,-1)));

    }

    else

    {

    Box::info(strFmt("%1 %2",conPeek(nameAndDOB,1),

    conPeek(nameAndDOB,2)));

    }

  • 8/11/2019 Ax2012 Enus Devii 02

    35/42

    Chapter 2: X++ Control Statements

    2-35

    5. Compile the code (press F7or click the Compilebutton in thetoolbar).

    6. Run the job (press F5or click the Gobutton in the toolbar).

    Note the use of mkDate and strfmt functions. MkDate ("make date") returns a

    date from the parameters day, month and year. Strfmt ("string format") inserts

    any type of value into a string.

  • 8/11/2019 Ax2012 Enus Devii 02

    36/42

    Development II in Microsoft DynamicsAX 2012

    2-36

    Summary

    This course introduced three conditional statements and three repetitive

    statements. Depending on whether the conditions are true, different commands

    can be executed.

    This course also showed how the built-in functions can help when writing X++

    code to perform mathematical operations, convert data types and so on.

    Additionally, to communicate with the end-user, this course showed how to use

    the Print Statement, the Box Class, the Infolog System and the Dialog Box.

  • 8/11/2019 Ax2012 Enus Devii 02

    37/42

    Chapter 2: X++ Control Statements

    2-37

    Test Your Knowledge

    Test your knowledge with the following questions.

    1. What are the three primary types of conditional statements in X++?

    2. Which arithmetic operator would you use to output the remainder whendividing 83 by 10 and what would the syntax be?

    3. What is the main difference between using a whilestatement and ado...whilestatement?

  • 8/11/2019 Ax2012 Enus Devii 02

    38/42

    Development II in Microsoft DynamicsAX 2012

    2-38

    4. What is the function 'mthName' used for? What is its syntax? Give anexample using this function.

    5. What is the syntax for the three types of messages in an Infolog?

  • 8/11/2019 Ax2012 Enus Devii 02

    39/42

    Chapter 2: X++ Control Statements

    2-39

    Quick Interaction: Lessons Learned

    Take a moment and write down three key points you have learned from this

    chapter

    1.

    2.

    3.

  • 8/11/2019 Ax2012 Enus Devii 02

    40/42

    Development II in Microsoft DynamicsAX 2012

    2-40

    Solutions

    Test Your Knowledge

    1. What are the three primary types of conditional statements in X++?

    MODEL ANSWER:

    A. If Statement: This statement checks whether a condition is true or false.

    If the statement is true, all the code in the braces '{}' is executed. There are

    other versions of the If statement including an Ifelse, or a nested If

    statement.

    B. Switch Statement: This is a multi-branch control statement that defines a

    condition and whose result determines the code that is executed. A switch

    statement has multiple cases and for each case there are listed statements that

    will be executed if that case satisfies the condition.

    C. Ternary Operator: This control structure acts as an Ifelse statement. It

    is primarily used because it is much more convenient to code than writing out

    an Ifelse statement.

    2. Which arithmetic operator would you use to output the remainder whendividing 83 by 10 and what would the syntax be?

    MODEL ANSWER:

    MOD

    83 Mod 10

    3. What is the main difference between using a whilestatement and ado...whilestatement?

    MODEL ANSWER:

    The main difference between a While statement and a Do...While statement

    is that the condition is evaluated after the statements are executed in a

    Do...While statement. Therefore a Do...While statement always runs at least

    one time.

  • 8/11/2019 Ax2012 Enus Devii 02

    41/42

    Chapter 2: X++ Control Statements

    2-41

    4. What is the function 'mthName' used for? What is its syntax? Give anexample using this function.

    MODEL ANSWER:

    'mthName' is used to return the month name based on the number specifying

    the month. Its syntax is as follows:str mthName (int month);

    Example

    mthname(1); //returns "January"

    5. What is the syntax for the three types of messages in an Infolog?

    MODEL ANSWER:

    info ('Infolog text');

    warning ('Warning text');

    error ('Error text');

  • 8/11/2019 Ax2012 Enus Devii 02

    42/42

    Development II in Microsoft DynamicsAX 2012