• No results found

AX2012_ENUS_DEV_2

N/A
N/A
Protected

Academic year: 2021

Share "AX2012_ENUS_DEV_2"

Copied!
162
0
0

Loading.... (view fulltext now)

Full text

(1)

COURSE: 80304

DEVELOPMENT II IN

MICROSOFT DYNAMICS

®

AX 2012

(2)

Last Revision: August 2011

This courseware is provided “as-is”. Information and views expressed in this courseware, including URL and other Internet Web site references, may change without notice.

Unless otherwise noted, the examples depicted herein are provided for illustration only and are fictitious. No real association or connection is intended or should be inferred.

This courseware does not provide you with any legal rights to any intellectual property in any Microsoft product. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this courseware may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means or for any purpose, without the express written permission of Microsoft Corporation.

Copyright © 2011 Microsoft Corporation. All rights reserved.

Microsoft®,MicrosoftDynamics®, Microsoft® PowerPoint®,Microsoft® SQL Server® data management software

and Microsoft Dynamics® AX are trademarks of the Microsoft group of companies. All other trademarks are

property of their respective owners.

(3)

Introduction 0-1

  Welcome ... 0-1  Microsoft Dynamics Courseware Contents ... 0-2  Documentation Conventions ... 0-3  Student Objectives ... 0-4 

Chapter 1: Introduction to X++

1-1

  Objectives ... 1-1  Introduction ... 1-1  Characteristics of X++ ... 1-2  Scenario ... 1-2  Development Tools ... 1-2  Reverse Engineering ... 1-17  Best Practices ... 1-19  Lab 1.1 - Print to the Screen ... 1-22  Lab 1.2 - Debug the Job ... 1-23  Lab 1.3 - Create a Data Model ... 1-24  Lab 1.4 - Create an XML Developer Document ... 1-25  Summary ... 1-26  Test Your Knowledge ... 1-27  Quick Interaction: Lessons Learned ... 1-28  Solutions ... 1-29 

Chapter 2: X++ Control Statements

2-1

  Objectives ... 2-1  Introduction ... 2-1  Introduction to Variables ... 2-2  Operators ... 2-6  Conditional Statements ... 2-10  Loops ... 2-16  Lab 2.1 - Create a Times Table Using a While Loop ... 2-20  Lab 2.2 - Create a Times Table Using a Do...while Loop ... 2-21  Lab 2.3 - Create a Times Table Using a for Statement ... 2-22  Built-in Functions ... 2-23  Communication Tools ... 2-24  Lab 2.4 - Create a YesNo Box ... 2-31  Lab 2.5 - Create an Infolog Tree ... 2-32  Lab 2.6 - Create a Dialog Box ... 2-33  Lab 2.7 - Use X++ Control Statements ... 2-34  Summary ... 2-36  Test Your Knowledge ... 2-37  Quick Interaction: Lessons Learned ... 2-39  Solutions ... 2-40 

Chapter 3: Objects and Classes

3-1

  Objectives ... 3-1  Introduction ... 3-1  Classes ... 3-2  Lab 3.1 - Create a New Class ... 3-4 

(4)

Method Access Control ... 3-5  Lab 3.2 - Allow Access to Methods ... 3-6  Inheritance ... 3-7  Objects ... 3-8  Lab 3.3 - Instantiating a Class ... 3-10  Scoping and Parameters in X++... 3-11  Lab 3.4 - Use Method Parameters ... 3-13  Referencing Object Methods ... 3-14  Lab 3.5 - Create a Run Method ... 3-15  Method Types ... 3-16  Tables as Classes ... 3-18  Eventing ... 3-18  Lab 3.6 - Create a Calculator Class ... 3-22  Summary ... 3-24  Test Your Knowledge ... 3-25  Quick Interaction: Lessons Learned ... 3-26  Solutions ... 3-27 

Chapter 4: Accessing the Database

4-1

  Objectives ... 4-1  Introduction ... 4-1  Retrieving Data ... 4-2  Lab 4.1 - Retrieving Data ... 4-10  Data Manipulation ... 4-11  Lab 4.2 - Update ... 4-15  Queries ... 4-17  Lab 4.3 - Create a Query Using X++ ... 4-21  Summary ... 4-22  Test Your Knowledge ... 4-23  Quick Interaction: Lessons Learned ... 4-24  Solutions ... 4-25 

Chapter 5: Exception Handling

5-1

  Objectives ... 5-1  Introduction ... 5-1  Exceptions ... 5-2  Try and Catch Statements ... 5-3  Throwing Exceptions ... 5-4  Optimistic Concurrency Exceptions ... 5-6  Lab 5.1 - Handle an Exception ... 5-8  Summary ... 5-10  Quick Interaction: Lessons Learned ... 5-13  Solutions ... 5-14 

Chapter 6: Security for Developers

6-1

  Objectives ... 6-1  Introduction ... 6-1  Permissions ... 6-2  Security Policies ... 6-3  Code Access Security ... 6-6 

(5)

Display Method Authorization ... 6-8  Summary ... 6-9  Quick Interaction: Lessons Learned ... 6-11  Solutions ... 6-12 

(6)
(7)

INTRODUCTION

Welcome

We know training is a vital component of retaining the value of your Microsoft Dynamics® AX 2012. investment. Our quality training from industry experts

keeps you up-to-date on your solution and helps you develop the skills necessary for fully maximizing the value of your solution. Whether you choose Online Training, Classroom Training, or Training Materials; there is a type of training to meet everyone's needs. Choose the training type that best suits you so you can stay ahead of the competition.

Online Training

Online Training delivers convenient, in-depth training to you in the comfort of your own home or office. Online training provides immediate access to training 24 hours-a-day. It is perfect for the customer who does not have the time or budget to travel. Our newest online training option, eCourses, combine the efficiency of online training with the in-depth product coverage of classroom training, with at least two weeks to complete each course.

Classroom Training

Classroom Training provides serious, in-depth learning through hands-on interaction. From demonstrations to presentations to classroom activities, you receive hands-on experience with instruction from our certified staff of experts. Regularly scheduled throughout North America, you can be sure you will find a class convenient for you.

Training Materials

Training Materials enable you to learn at your own pace, on your own time with information-packed training manuals. Our wide variety of training manuals feature an abundance of tips, tricks, and insights you can refer to again and again:

Microsoft Dynamics Courseware

The Microsoft Dynamics Courseware consists of detailed training manuals, designed from a training perspective. These manuals include advanced topics as well as training objectives, exercises, interactions and quizzes.

Look for a complete list of manuals available for purchase on the Microsoft Dynamics website: www.microsoft.com/Dynamics.

(8)

Microsoft Dynamics Courseware Contents

Test Your Skills

Within the Microsoft Dynamics Training Materials you find a variety of different exercises. These exercises are offered in three levels to accommodate the variety of knowledge and expertise of each student. We suggest you try the level three exercises first, if you need help completing the task look to the information in the level two exercises. If you need further assistance each step of the task is outlined in the level one exercise.

Challenge Yourself!

Level 3 exercises are the most challenging. These exercises are designed for the experienced student who requires little instruction to complete the required task.

Need a Little Help?

Level 2 exercises are designed to challenge students, while providing some assistance. These exercises do not provide step by step instructions, however, do provide you with helpful hints and more information to complete the exercise.

Step by Step

Level 1 exercises are geared towards new users who require detailed instructions and explanations to complete the exercise. Level 1 exercises guide you through the task, step by step, including navigation.

Quick Interaction: Lessons Learned

At the end of each chapter within the Microsoft Dynamics Training Material, you find a Quick Interaction: Lessons Learned page. This interaction is designed to provide the student with a moment to reflect on the material they have learned. By outlining three key points from the chapter, the student is maximizing knowledge retention, and providing themselves with an excellent resource for reviewing key points after class.

(9)

Documentation Conventions

The following conventions and icons are used throughout this documentation to help you quickly and effectively navigate through the information.

CAUTION: Cautions are found throughout the training manual and are preceded by the word CAUTION in bold. Cautions are used to remind you of a specific result of a specific action which may be undesirable.

HINT: Hints are found throughout the training manual and are preceded by the word HINT in bold. Hints are used to suggest time-saving features or alternative methods for accomplishing a specific task.

NOTE: Notes are found throughout the training manual and are preceded by the word NOTE in bold. Notes are used to provide information which, while not critical, may be valuable to an end user.

BEYOND THE BASICS: Advanced information found throughout the training manual is preceded by the words BEYOND THE BASICS in bold. Beyond the Basics provides additional detail, outside of standard functionality, that may help you to more optimally use the application.

EXAMPLE: Examples are found throughout the training manual and are preceded by the word EXAMPLE in bold. Examples bring to light business scenarios that may better explain how an application can be used to address a business problem.

(10)

Student Objectives

What do you hope to learn by participating in this course? List three main objectives below.

1.

2.

(11)

CHAPTER 1: INTRODUCTION TO X++

Objectives

The objectives are:

• Identify key features of developing with X++.

• Describe the basic foundation of object-oriented programming. • Use the development tools available within Microsoft Dynamics®

AX.

• Create object and data models from existing application elements by using the Reverse Engineering tool.

• Use best practices to instill good programming habits.

Introduction

X++ is the primary programming language used in the MorphX Development environment. When you develop with X++, refer to Microsoft Dynamics AX Developer Help, available from the Help menu for detailed information. The following are important features of X++:

• X++ resembles other popular languages such as C# and Java. Due to this resemblance, programmers already familiar with these languages will be able to transition into the MorphX development environment quickly.

• Because X++ includes many integrated SQL commands, Microsoft Dynamics AX can build complex accounting and business

management systems.

• X++ is an object-oriented language and provides a clean and efficient object-based development platform.

• Programmers who use X++ can access existing Microsoft Dynamics AX system classes that provide functionality ranging from basic I/O, XML, to changing controls in the graphical user interface at run time. These system classes can be extended to provide new behavior.

(12)

Characteristics of X++

The following are characteristics of X++:

• Reliable: X++ provides extensive compile-time checking, followed by a second level of run-time checking. Language features guide programmers toward reliable programming habits. The memory management model is simple; objects are created by using a "new" operator and there is automatic garbage collection. There are no explicit programmer-defined pointer data types or arithmetic. This model eliminates entire classes of programming errors.

• Interpreted and Dynamic: Benefit from faster development cycles - prototyping, experimentation, and rapid development, versus the traditional compile, link, and test cycles.

• Interoperable: Components in Microsoft Dynamics AX are seamlessly available to any application supporting .NET, and

conversely X++ is able to consume external managed code and COM objects.

Scenario

Systems developers in a large development environment have joined a team that is customizing a Microsoft Dynamics AX application. This is the team's first project in X++ so they need to learn what development tools are available to them within Microsoft Dynamics AX.

Development Tools

All elements that comprise the Microsoft Dynamics AX application (classes, forms, tables, and more) are organized in the Application Object Tree (AOT). This is a central, organized index to all application elements, displayed in a graphical tree view.

Microsoft Dynamics AX customizations are developed by modifying one or more elements from the AOT. These elements are usually assembled in a project, or, in other words, a container for elements that implement an application in Microsoft Dynamics AX. Projects help manage development efforts by organizing units of functionality.

As developers create new projects or modify existing projects, they use a series of development tools. These tools include the following:

• X++ Editor • X++ Compiler • X++ Debugger • Visual Studio

(13)

Other tools exist to aid developers while writing code and for managing modifications they make to elements in the AOT.

All these tools, apart from Visual Studio, are accessible from the Development Workspace. This is a unique version of the regular workspace, designed

specifically for developers to work in. To launch a development workspace press

Ctrl+Shift+W from the regular workspace. Alternatively, a command line

parameter (-development) can be added to the Microsoft Dynamics AX client shortcut, to automatically launch in the development workspace. Development cannot be done in the regular workspace, so a development workspace must be opened before doing any development.

The development workspace tools are described in the following sections.

The X++ Editor

Double-clicking many of the nodes in the AOT opens them in the X++ editor. The X++ editor can also be started by selecting View Code in the right-click context menu.

The X++ editor window consists of two panes:

• The left pane contains a list of current methods or jobs • The right pane displays the X++ code

FIGURE 1.1 CODE EDITOR WINDOW

There are several toolbar buttons in the heading of the X++ editor window. Many of these functions can be started using keyboard shortcuts. Moving the pointer over these buttons reveals the button's function. These buttons are described in the following table:

(14)

Button Keystroke Description

New Ctrl + N Creates a new method or job. Save Ctrl + S Saves the changes to the active

method.

Undo Ctrl + Z Undo the last edit.

Redo Ctrl + Y Redo the last undone edit.

Go F5 Executes the class, form, or project. Toggle Breakpoint F9 Turns breakpoints on and off. Enable/Disable

Breakpoints

Ctrl + F9 Enables or disables a breakpoint. Remove all

breakpoints

Ctrl + Shift + F9

Deletes all breakpoints from the method.

Compile F7 Checks the code for errors, compiles the code, and saves it.

Lookup label/text Ctrl + Alt + Space

Helps you find a label.

Script Alt + R Helps you choose between a selection of scripts.

Add to Version Control

Adds the current element to Version Control and checks the element out. Check In Alt + I Checks in the current element. Check Out Alt + O Checks out the current element. Undo Check Out Alt + U Reverts all edits since the last check

out.

History Opens the Version Control History form.

Get Latest Get latest version of the element from Version Control history.

Help F1 Accesses the X++ editor window help. Toggle line

numbers

Turns the line numbers on and off. Toggle change

tracking margin

Turns the change tracking margin on and off.

(15)

To make reading easier, the X++ editor color-codes different kinds of code as follows:

Color Code type

Blue Reserved words Green Comments Dark Red Strings

Bright Red Numbers Purple Labels

Black Everything else

Jobs

A job is a stand-alone block of code in Microsoft Dynamics AX that can be run from the X++ editor. Jobs are used primarily for testing code during development and running batch processes within Microsoft Dynamics AX that affect large amounts of data.

This course uses jobs as a mechanism to write code and run it directly from the X++ editor. Most code for applications is written in classes, methods, tables, and forms. However, jobs are useful for testing blocks of code before inserting them into methods or classes.

The following is default code when you create a new job in the AOT:

static void Job1(Args _args) {

}

NOTE: Unlike classes and other elements in the AOT, jobs can only be renamed

in the Code Editor. Most other AOT elements can have their name changed in the

Property window, or directly on the AOT node.

Create a new job by right-clicking the Job node on the AOT, and selecting New Job. The X++ editor opens, displaying the new job. The job can be renamed in the text editor or in the AOT. In the example above, the job is called Job1 and can be renamed by change Job1 to the required namein the text editor.

(16)

Compiler

When code that is written in X++ is ready to be executed, use the compiler. The compiler is a translation program that converts X++ into a language that can be interpreted.

Code can be compiled by clicking the Compile button in the X++ editor toolbar or by pressing F7. It can also be compiled by right-clicking the node in the AOT and selecting Compile.

In this course you will also learn about inheritance. Classes that inherit from, or extend, other classes can be compiled by right-clicking the main class, then selecting Add-Ins > Compile forward. This means any changes that are made to the main class are propagated down to the sub-classes correctly.

Use the Compiler Output window to view information to help improve and correct errors in the code. The Output window will update its contents every time a compilation is performed.

FIGURE 1.2 COMPILER OUTPUT WINDOW

There are four different compile result types:

Result type Description

Error These are compile errors, and must be resolved before

code can be run.

Warning These are compile warnings, and should be resolved,

but will not prevent the code from being run.

Best Practice These are found when an element contains code or properties that deviate from the list of Microsoft Dynamics AX Developers Best Practices. Best Practice deviations are only found by the compiler when the

Diagnostic level is set to Level 4. The Diagnostic level

is a parameter accessible from the Setup button, explained later in this material.

Task Tasks are placeholders that can be added to X++ code

to remind developers that something is unfinished. To create a task, use a single line comment, followed by the word ToDo and a description of the task. For example:

(17)

The Compiler window contains the following features:

• Filter buttons: At the top of the window, there are buttons to toggle the four different compile result types on and off. Toggling the result type off will remove results of that type from the Compiler Output window's list.

• Reset button: This button will reset the contents of the Compiler

Output window.

• Edit button: This button will open the X++ editor or Property sheet corresponding to the selected compile result.

• Import/Export button: This button allows compile results to be exported to an HTML file, or imported into the Compiler Output window from an HTML file.

• Setup button: This button accesses forms where the Compiler

Output window parameters can be set for the user. These include

settings such as the Diagnostic level of the compiler, and which Best Practices will be enforced.

Debugger

Microsoft Dynamics AX includes a powerful stand-alone debugging tool for X++ code. Use the Debugger to debug X++ code running on the:

• Microsoft Dynamics AX Client

• Microsoft Dynamics AX Object Server (AOS)

NOTE: Managed code and X++ compiled into Intermediate Language (IL) are

debugged using the Visual Studio debugger. This topic will be covered in the Visual Studio Integration chapter of the Development III course. This topic only covers debugging standard X++ code.

Use the Debugger to:

• Run a program to a certain point and then stop at a defined breakpoint.

• Step through the program one statement at a time. • Display the call stack with code line numbers.

• Watch specific variables and modify their values during execution. • Track messages being sent to the infolog.

(18)

Breakpoints

Breakpoints are set on individual lines of code. This is a command to stop program execution at that point and enter the debug mode.

When the logic flow of the code in a user's session reaches a breakpoint set by the same user, the debug session begins and the debugger is automatically started.

To set a breakpoint:

1. Rest the cursor within the X++ code in the editor where you want to insert the breakpoint.

2. Click the Breakpoint button in the toolbar or press F9. 3. Click in the gray area to the left of the line of code.

The line of code is highlighted in dark red to indicate that a breakpoint is enabled. A disabled breakpoint is indicated with a red border only. Disabled breakpoints will not cause program execution to stop, but are useful when a specific location needs to be remembered, perhaps to enable the breakpoint at a later point.

Breakpoints can also be set by inserting the keyword Breakpoint into the code. This should be used with caution, because it will mean that all users will enter the debugger when the code reaches this point.

All these methods of settings breakpoints are shown in the following figure:

(19)

To turn debugging off, you can visit Tools > Options, and select the Developer tab. In the Debug field, select None. When you set a breakpoint in code, this field will automatically be set back to When Breakpoint.

Breakpoints are only recognized on the tiers (client or server) that have been configured to recognize them. Code running on the client tier will always stop at a breakpoint in a user's session, when the user has debugging turned on. Code running on the server tier will only stop at a breakpoint when the AOS has specifically been configured to enable breakpoints. This is a setting on the Microsoft Dynamics AX Server Configuration Utility.

The Debugger can display up to six information windows. The windows display detailed information about the current state of the executing code while you are debugging. The information windows available are as follows:

Window Description

Code Displays the X++ code currently being debugged. The red

dot indicates where the breakpoint is inserted. The yellow arrow indicates the line that is being executed. The arrow can be dragged to a different line of code so that code is either re-executed or skipped.

Variables Displays the value of the variables. Modified variables appear in different colors to indicate change. Users can alter the value of variables in the debugger to see how the program would run under different conditions.

Call Stack Indicates which method is currently being debugged. Double-clicking a method further down the stack will take the Code window to that method.

Watch Contains a user-defined range of variables. The variables

can be dragged and dropped from the Variables window or the Code window.

Breakpoints Displays the list of currently defined breakpoints with their enabled status and line number.

Output Displays separate views of text written to the window from

X++ code and kernel code. These views organize information sent to the Output window.

HINT: The Microsoft Dynamics AX Debugger Help Guide can be accessed

directly by pressing F1 in the debugger. This guide lists keyboard shortcuts that make it easier and faster to use the debugger.

(20)

Use the toolbar located above the Output window to navigate through the code and perform other actions.

FIGURE 1.4 DEBUGGER TOOLBAR

Moving the pointer over these buttons reveals the button's function and a keyboard shortcut.

The more generally used buttons are described in the following table, together with the keyboard shortcut:

Button Keystroke Description

Go F5 Continues the execution. Stop

Debugging

Shift + F5 Terminates the execution at the current line.

Insert/Remove Breakpoint

F9 Inserts or clears a breakpoint. Enable/Disable

Breakpoint

Ctrl + F9 Enables or disables a breakpoint. Remove all

breakpoints

Ctrl + Shift + F9

Clears all breakpoints.

Step Over F10 Steps to the next line of code in the current method.

Step Into F11 Steps into the current line if it contains a method call.

Step Out Shift + F11 Steps out of the current method.

Run to Cursor Ctrl + F8 Continues the execution until reaching the location of the cursor in the Source window.

By default, for performance reasons, debugging in code that is executed on the AOS is disabled. During development it is often required to debug this code. The following procedure will enable code run on the AOS to be debugged.

1. Close the Microsoft Dynamics AX client

2. Click Start > Administrative Tools > Microsoft Dynamics AX

2012 Server Configuration

3. Click Manage > Create Configuration

4. In the Configuration Name, enter a name, for example AOS_Debug. 5. Click OK

6. Check the box Enable breakpoints to debug X++ code running on

(21)

7. Click Apply

8. Click Yes to restart the AOS service. This may take one or two minutes.

9. Click OK to close the Server Configuration Utility. 10. Restart the Microsoft Dynamics AX client.

Demonstration: Using the Debugger

Perform the following steps to use the debugger. 1. Open the AOT.

2. Expand Tables > SalesLine > Methods 3. Double-click the method ItemIdChanged. 4. Position the cursor on the folloing line of code

this.initfromInventTable(this.inventTable(), _resetPrice);

5. Press F9 to set a breakpoint. The line of code should be highlighted in red to indicate a breakpoint has been set. F9 will toggle this breakpoint on and off.

6. An infolog message may appear warning you that debugging is not enabled on the server. If it does, click Close.

7. Close the X++ editor.

8. In the Application workspace, click on Sales and marketting. 9. In the Common section click on Sales orders > All sales orders. 10. Click New > Sales Order.

11. Select a customer account. 12. Click OK.

13. Click the drop down button on the Item number field and select an item.

14. The debugger should start.

15. Look at the windows that are available.

16. In the Variables window, find the variable this. 17. Press F10 to step through the code.

18. Note how the field values change and are highlighted in red. 19. Press F5 to run the code and stop debugging.

Compare

Use the compare tool to highlight differences between versions of a single element:

• In two different layers

• In an old version of an element • In two different elements • An element that will be imported

(22)

The most common use is to review differences between two layers. This is useful when determining what was changed in a standard element. To compare two layers, right-click the element and select Compare. Select which two layers to compare and then click Compare.

Any element nodes that contain differences will be listed in the lower-left pane, and the differences can be seen in the lower-right pane. The differences are color coded to make it clear which version the differences come from.

FIGURE 1.5 COMPARE SYS TO USR

You can also use the compare tool to move code and element properties between layers. When a difference is found, a black arrow is displayed in the left margin of the lower-right pane. The icon will delete code from the current layer, or paste code in to the current layer. This feature is useful when upgrading code.

NOTE: You can view code in a different layer by right-clicking the element and

selecting Layers.

Demonstration: Using the Compare Tool

Perform the following steps to use the compare tool. 1. Open the AOT.

2. Expand the Classes node. 3. Expand the Activities class.

4. Double-click the Construct method. 5. Add the following line of code:

// Compare tool demonstration

6. Press F8 to compile and save. 7. Right-click the Activities class.

(23)

9. Click the Compare button.

10. Note how the tool displays differences in the color of the version the code is in.

11. Note the icon to remove the code from the USR layer.

X++ Attributes

Microsoft Dynamics AX supports attributes being assigned to X++ code. This allows for a rich set of metadata to be built. It describes methods and types that are defined within X++ code.

Attributes are defined as classes that are derived from the SysAttribute class. The following code for the SampleAttribute class is an example of an attribute class:

public class SampleAttribute extends SysAttribute {

str sMetadata; // A field in classDeclaration. public str GetMetadata()

{

return sMetadata; }

public void new(str _sMetadata) {

super();

sMetadata = _sMetadata; }

}

Attributes can then be used on other classes and methods. The following example shows the structure of a new Attribute class, AuthorAttribute:

class AuthorAttribute extends SysAttribute { str author; public str Author() { return author; }

public void new(str _author) {

super();

author = _author; }

(24)

In the following example, AuthorAttribute is used to decorate other classes and methods:

[AuthorAttribute("Isaac")] public class MyClass() { ... } [AuthorAttribute("Isaac")] void MyMethod() { ... }

Type Hierarchy Browser

The Type Hierarchy Browser is a tool for viewing at a glance, which other elements one element inherits from. For example, open the Type Hierarchy Browser for the CustAccount extended data type. This can be done from the elements context menu > Add-ins > Type hierarchy browser:

FIGURE 1.6 TYPE HIERARCHY BROWSER FOR CUSTACCOUNT

Notice that CustAccount inherits from CustVendAC, which inherits from

ExternalAccount, which inherits from the primitive string type. This is

displayed in a tabular format so that the value of properties at each level of the hierarchy can be compared side-by-side.

(25)

The browser can also be used to explore the hierarchy farther down the tree. In the tree view on the left-hand pane, expand the selected node to display all elements that inherit it. In this example, you can expand the CustAccount node, to display all extended data types that inherit it. The following figure shows the same browser shown earlier in this topic. The difference now is that the

CustInvoiceAccount type is selected:

(26)

This tool can also be used on other elements, such as classes. When browsing the hierarchy on classes, the blue boxes in the grid represent a method that is

overridden, or that exists only, on that class. The following figure shows a view of the hierarchy for the SalesLineType_Sales class:

FIGURE 1.8 CLASSES IN TYPE HIERARCHY BROWSER

Type Hierarchy Context

In addition to the Type Hierarchy Browser, the Type Hierarchy Context window can be used to view the hierarchy of an element in the AOT. The Type

Hierarchy Context window can be docked to the workspace, and will change

dynamically as AOT nodes are selected.

Open the Type Hierarchy Context window by navigating to: Tools > Type

Hierarchy Context.

With the Type Hierarchy Context window open, select a few different nodes in the AOT, and notice how the window changes its contents based on the selected node.

(27)

The following figure shows a view of the Type Hierarchy Context window, with the SalesLineType_Sales class node selected in the AOT:

FIGURE 1.9 TYPE HIERARCHY CONTEXT

Each of the nodes in the Type Hierarchy Context window is also a hyperlink that will open the Type Hierarchy Browser for an element.

Reverse Engineering

Reverse engineering is used by partners to easily retrieve detailed information about the structures and relationships of the Microsoft Dynamics AX business logic and data model. The goals of reverse engineering are to extract

relationships, and integrate and view collections in Microsoft Office Visio as UML diagrams.

The feature handles both reverse engineering of the data model and the object model.

You can use the Reverse Engineering tool to visualize data and object models generated from projects in Microsoft Dynamics AX. These models are created as Microsoft Visio documents.

To open the Reverse Engineering tool, right-click a project and select Add- ins >

Reverse engineer.

The information Microsoft Dynamics AX provides Visio depends on whether you are creating a data or an object model from a project. The following table shows what is provided for each model type:

Data Model Object Model

Tables ● ●

Table Group property ●

Table Fields ● ● Table Index information ●

(28)

Data Model Object Model

Classes (extended and referenced) ● All Extended Data Types ● ● All Base Enums ● ● All X++ Data Types ● ●

Procedure: Reverse Engineering an Object Model

Perform the following steps to generate an object model that is based on elements included in a project.

1. Create a project.

2. Drag AOT elements into the project you want to reverse engineer into an object model.

3. Right-click the project and select Add- ins > Reverse engineer. 4. Click Visio UML Object model to create a UML object model. 5. Select a name and path for the file and then click OK.

6. From Microsoft Visio, drag object nodes into the center grid to lay out the desired model.

Procedure: Reverse Engineering a Data Model

Perform the following steps to generate a data model that is based on elements included in a project.

1. Create a project.

2. Drag the AOT elements into the project you want to reverse engineer into a data model.

3. Right-click the project and select Add-ins > Reverse engineer. 4. Click Visio UML Data model to create a UML data model. 5. Select a name and path for the file and then click OK.

6. From Microsoft Visio drag table nodes into the center grid to lay out the desired model.

(29)

Best Practices

Best practices involve understanding all the things that you should do and distinguishing them from the things that you can do.

Best Practices in Microsoft Dynamics AX apply to programming in a standard application, certified solutions, and they are recommended for any Microsoft Dynamics AX partner or an end-user enhancing or customizing Microsoft Dynamics AX.

Some benefits of using best practices include:

• They guarantee consistency throughout the code. This lets other developers more easily read and understand your code.

• Code is more secure. • There is no redundant code.

• Upgrading is easier and quicker, and has less risk of errors.

Refer to the "Microsoft Dynamics AX Developer's Help" for detailed information on best practices.

Naming Conventions

Naming conventions contribute to consistency and to making the application easier to understand.

Where you can, application element names should be constructed hierarchically from three basic components:

{business area name} + {business area description} + {action performed (for classes) or type of contents (for tables)}

Examples: • CustJournalPrintOutInvoice • PriceDiscAdmDelete • PriceDiscAdmSearch • PriceDiscAdmName • PriceDiscAdmTrans

(30)

Additionally:

• All names must be in U.S. English.

• The default rule is to use logical and descriptive names if no other specialized rules apply.

• Identifier names have a limit of 40 characters. • Names must be spelled correctly.

• Names must be used consistently.

• All texts that appear in the user interface must be defined by using a label.

• Do not begin a name with nonsensical or confusing prefixes, such as "aaa" or "CopyOf".

• Do not begin a name with "DEL_" unless it is a table, extended data type or enum, and it is needed for data upgrade purposes - doing this may cause unexpected results.

Code Placement

The placement of code depends on the code you are writing. The preferred procedure in an object-oriented programming language is to place code in a class that can be reused and called when it is needed.

You can place code in classes to have better control over where the code is executed. Performance considerations frequently dictate where code should run, and so controlling this is desirable. Code included in forms always runs on the client, and this could cause excessive client/server communication where it might not be necessary.

When deciding where to place code, ask the following questions:

• Is the code related to the form's appearance or to the data that is entered through the form?

• Can I use the code's functionality elsewhere in the application or in a different application?

• Does the code execute on the client or on the server?

BEST PRACTICE: Always place the code nearest to the source so that it can be

more easily manipulated. For example, code that manipulates a table should be placed in that table's methods.

(31)

Comments

A best practice for all programming is to consistently use comments. It is important when developing X++ programs in Microsoft Dynamics AX to use comments and document what the code does and how parameters are used. It is also good to know who made the change and why. When upgrading code, you have to decide whether to merge code and if this is the case, how to merge it; comments are useful to help determine why a code change is made. Note the following about how to use comments:

• Comments can be inserted directly into the lines of code. • Comments are ignored by the compiler.

• Comments turn the code green in the editor. Some of the comments include the following:

• Single line "//"

• Block comments "/* */"

• To do comments "TODO." To do comments appear in the compiler's

Tasks tab page.

• XML documentation comments

// This is a single line comment /* This is a block comment because It contains more than one line */ /// <summary>

/// Comment where XML tags distinguish sections. /// </summary>

The preceding XML documentation comments can be used to build XML documents that contain developer documentation. The XML documentation comments are also used to display "hover-over" help in the X++ editor. To extract an XML documentation file from code, right-click a development project node, and select Add-ins > Extract XML documentation.

(32)

Lab 1.1 - Print to the Screen

Scenario

The client wants you to demonstrate how to print a message to the screen. Create a job that prints a message to the screen.

Challenge Yourself!

Create a job that prints the message "Microsoft Dynamics AX is fantastic."

Step by Step

1. Open the AOT.

2. Right-click the Jobs node and select New Job. 3. Rename the job.

4. Add the following code.

info("Microsoft Dynamics AX is fantastic.");

5. Compile (press F7 or click the Compile button on the toolbar). 6. Run the job (press F5 or click the Go button on the toolbar).

(33)

Lab 1.2 - Debug the Job

Scenario

The client wants you to verify the code executes without errors. Debug the job that you created in the previous lab.

Challenge Yourself!

Set a breakpoint in the code in the job from the previous lab. Run the code and step through it.

Step by Step

1. Set a breakpoint in your job on this line of code:

static void <your jobname>(Args _args)

2. Save the code by using a keyboard shortcut. 3. Run the code.

NOTE: You should enter the Microsoft Dynamics AX Debugger at this point. If

not, ask your instructor.

(34)

Lab 1.3 - Create a Data Model

Scenario

You have been asked to evaluate the Project Accounting data model to prepare for required customizations according to customer requirements.

Challenge Yourself!

Make the data model for the Project Accounting module in Microsoft Visio by using the Reverse Engineering tool in Microsoft Dynamics AX.

Step by Step

1. Create a new Project.

2. Rename it to Reverse_Engineering. 3. Open the Reverse_Engineering project.

4. Open the AOT in another window and expand the Tables node 5. Drag-and-drop some project tables (tables starting with Proj) from

the AOT, to the Reverse_Engineering project.

6. Right-click the Reverse_Engineering project root node.

7. Select Add-ins > Reverse Engineer. Ensure that the Data model option is marked.

8. Enter the path for the Microsoft Visio file.

9. Once the file is generated in Microsoft Visio, drag the tables to the workspace and show the relationships.

(35)

Lab 1.4 - Create an XML Developer Document

Scenario

You have been asked to create developer documentation for the Credit Limit modifications made in the standard Microsoft Dynamics AX application.

Challenge Yourself!

Create an XML file by using the XML documentation generation, for the Credit Limit development project.

Step by Step

1. Open the development project tree. 2. Find the Credit Limit project.

3. Right-click the project, and select Add-ins > Extract XML

documentation.

4. Enter a file name. 5. Click OK.

6. Click Close to close the infolog window. 7. Review the file created.

(36)

Summary

This lesson introduced some development tools that you will use to make modifications to Microsoft Dynamics AX. You learned how to use the X++ editor to write code; how to compile code and review errors with the Compiler; and how to create breakpoints and step through executing code with the Debugger. Other tools like the Compare, Type Hierarchy Browser, Type Hierarchy Context, and Reverse Engineering tools were also introduced. The next lesson will show how to use these tools by creating a Calculator Class that uses four basic methods.

(37)

Test Your Knowledge

Test your knowledge with the following questions.

1. What are the three main Object-Oriented Programming components?

2. What are the functions of the six Debugger window panes?

(38)

Quick Interaction: Lessons Learned

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

1.

2.

(39)

Solutions

Test Your Knowledge

1. What are the three main Object-Oriented Programming components? MODEL ANSWER:

Classes are blueprints that describe the objects derived from them. A class is a model classification of the methods and variables in a specific type of object. Objects are instances of classes. Each instance has data members and logic (methods) defined in the class. Methods are functions (subroutines) associated with a class or an object. An object implements its behavior with methods.

2. What are the functions of the six Debugger window panes? MODEL ANSWER:

The Code window pane displays the X++ code that is currently being debugged. The Variables window displays the value of the variables in the current block of code. Modified variables appear in different colors to indicate change. The Call Stack window tells you which method is currently being worked on. The Watch Status window displays a user-defined range of variables. The Breakpoint window consists of a header with two columns and the list of currently defined breakpoints. The Output window in the Microsoft Dynamics AX Debugger has separate views that display text written to the window from X++ code and kernel code. These views organize the information that is sent to the Output window.

3. What do you use the X++ editor for? MODEL ANSWER:

The X++ editor is used for editing and creating X++ code. This editor contains many functions in the toolbar, through keyboard shortcuts, and also by using the context (right-click) menu. The X++ editor has two panes: the left side shows a list of the current methods and the right side shows the current X++ code.

(40)
(41)

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.

(42)

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 Help under 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 must be 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 the variable 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 the Development I in Microsoft Dynamics 2012 course.

(43)

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 of

characters. 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.

(44)

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;

(45)

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 variables

and 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 the container.

conDel Removes a value from a specific position in the container. conNull Returns an empty container.

(46)

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 the

container, 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 values

in a variable or field.

• Relational operators evaluate how two values relate to one another and 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.

(47)

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.

<< Left shift Performs expression2 left shift (a multiplication with two) on expression1.

>> 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 << 3 i = 24 (i = 3*2*2*2)

(48)

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.

<= less than or equal

Returns true if expression1 is less 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.

(49)

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 <= 11) TRUE: both expressions are true. !('abc' = = 'def') || (8 > 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. The highest 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 ? :

(50)

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 true or false. There are three primary conditional statements:

• If statement • Switch statement • Ternary operators

All these statements are evaluated using operators.

If

The if statement 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 if statement is as follows:

if (condition) {

//if true these statements are executed }

The following is an example of an if statement. 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 if statement using multiple expressions to evaluate the condition.

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

print a; }

(51)

If...else

An if statement checks for only one possibility and ignores all other conditions. An if…else statement checks one condition and if true, the block of code is executed. Otherwise, an alternative statement is executed. The syntax for an if…else 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 multiple alternatives, you can use an if…else...if statement. The syntax for this statement is as follows: if (condition1) { //statement1 } else { if (condition2) { //statement2 } else { //statement3 } }

(52)

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's

homework sections.

3. If the student has passed the exam and the homework sections, the student 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 if…else statement. The main reason to use the ternary operator is convenience in coding. Its syntax is as follows:

(53)

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 switch statement 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 is listed 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

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

following shows the syntax for a switch statement:

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 switch statement and continue immediately after the switch. This can also be used elsewhere in X++ coding. The default case executes if the result of the expression does not match any of the cases. Using the default case is optional.

(54)

The following example compares a switch statement with an if…else statement. 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 {

(55)

if (score == 60) { grade = "D"; } else { grade = "Failed!"; } } } }

As illustrated on the previous page, the switch statement 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"; }

References

Related documents

The 8-month Video Game Sound Professional Program provides professional-grade training in Pro Tools, Reason, Logic, Ableton Live Music Production, Music Business, Music

May 15 Poultry Ownership Date May 15 Rabbit Ownership Date June 8 Market Goat Ownership Date June 10 Market Sheep Ownership Date. Annual Animal Ownership Dates for Adams

 Understand the various possible contra-actions, resulting from the Reiki treatment and/or attunement. METAPHYSICAL IMBALANCES The student will be

During the 2014-2015 academic year, students, in collaboration with employees, organized a Black Lives Matter event, an Acting for Justice Troupe, and a state-wide summit focused

Since immigration policy might influence the composition of immigration flows and since formal and informal human capital endowments mainly determine the economic performance of

Pred spustením každého umývacieho cyklu musí byť dávkovač znovu naplnený podľa pokynov uvedených v tabuľke umývacích cyklov. Vaša umývačka riadu používa menej umývacieho

Since cerebral amyloid angiopathy is an almost invariable pathological finding in Alzheimer’s disease, we hypothesized that MRI-visible perivascular spaces in the

Specifically, this study examines how different patterns of organized activity involvement (including intensity, breadth, and duration of participation) impact