Covers DAX 5 and DAX 6
DAX SOFTRONICS (INDIA) PVT. LTD.
DAX HAND BOOK
T A S K Kumar | www.axaptaschool.com
DAX Hand Book
T A S K Kumar
www.AxaptaSchool.com
Page 2
DAX Hand Book
DAX Softronics (India) Pvt. Ltd.
DAX Hand Book
Covers AX 2009 and AX 2012
T A S K Kumar www.axaptaschool.com
T A S K Kumar
www.AxaptaSchool.com
Page 3
DAX Hand Book
DAX Hand Book
Copyright © 2013 DAX Softronics (India) Pvt. Ltd. All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews which are done in consent of author or publishers. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor DAX Softronics, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. DAX Softronics has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, DAX Softronics cannot guarantee the accuracy of this information. First edition: March 2013 Product Id: AX6DHB ISBN: 978-162840425-8 Product Reference: 1270426 Published by DAX Softronics (India) Pvt. Ltd. Andhra Pradesh, India. www.daxsoftronics.com www.axaptaschool.com
Cover Image is created using official logo of Axapta School © DAX Softronics (India) Pvt. Ltd. and is used by DAX Softronics and Axapta School as part of promoting the Microsoft Dynamics AX technology and the copies of this book are distributed for free to promote the technology. All the images, logos and some other tabular content which are not relevant to Axapta School and DAX Softronics are taken from respective owners and are not used for commercial use. Axapta School and DAX Softronics will not encourage piracy in any form and request the readers to let us know if the material of this book is copied into any format without proper consent of Author and/or DAX Softronics Pvt Ltd. Any judicial or legal issues will be followed in Courts of Hyderabad only as per the Indian Penal Code and is subject to Indian Laws.
T A S K Kumar
www.AxaptaSchool.com
Page 4
DAX Hand Book
Thanks to my Mom, Dad and Bro who supported me a lot while I was working on this book. Specially my dad whom I love the most in universe.
T A S K Kumar
www.AxaptaSchool.com
Page 5
DAX Hand Book
T A S K Kumar
www.AxaptaSchool.com
Page 6
DAX Hand Book
Acknowledgements Thanks Mohan G Rao my guru, who pushed, helped and supported while working on this book. Surya, my favorite lead and who taught me. Special thanks to my guru Sree who taught me Axapta in my early stages. Eshwar, my favorite student guru who made me learn many things and all learners of this book.
T A S K Kumar
www.AxaptaSchool.com
Page 7
DAX Hand Book
T A S K Kumar
www.AxaptaSchool.com
Page 8
DAX Hand Book
Contents at a Glance Introduction Unit I 1. Architectural Overview 2. ERP and AX 3. MorphX Environment Unit II 4. 5. 6. 7. 8. 9.
X++ Introduction Object Oriented Programming in X++ Data Dictionary Macros Queries Resources
10. 11. 12. 13. 14. 15.
Forms Reports Menus and Menu Items Files Frameworks Miscellaneous
Unit III
Appendixes 16. 17. 18. 19. 20. 21. 22. 23.
New improvements and CIL in AX 2012 Installation and configuration Using Debugger in AX Label Wizard and Label Editor Basic Administration Interesting tools in AX Development environment Best practices and their requirement Tips while working in AX development environment.
Links
T A S K Kumar
www.AxaptaSchool.com
Page 9
DAX Hand Book
T A S K Kumar
www.AxaptaSchool.com
Page 10
DAX Hand Book
Table of Contents Introduction Unit I 1. Architectural Overview a. 3-Tier Architecture b. Layered Architecture and Model Store c. Application Development and Run Time Environments d. Application Framework 2. ERP and AX a. What is ERP b. AX and ERP c. Modules 3. MorphX Environment a. Application Object Tree
21 21 22 25 26 27 27 29 30 33 33
4. X++ Introduction a. Programming in Microsoft Dynamics AX b. Jobs c. Variables and Types d. Operators e. Control Flow Statements f. Built-in functions g. Basic Input and Output 5. Object Oriented Programming in X++ a. Classes i. Creating Classes ii. Variables/Methods/Constructors/Destructors/Access Modifiers iii. Encapsulation iv. Inheritance v. Interfaces and Miscellaneous Concepts vi. Polymorphism vii. Eventing viii. Creating and using Attributes ix. Importance of Classes in DAX b. Types of Classes i. System Classes ii. Application Classes c. Exception Handling d. Other Fundamental Classes [Collections]
41 41 44 46 49 50 64 65 73 75 76 78 85 85 102 104 108 110 111 111 111 111 112 114
Unit II
T A S K Kumar
www.AxaptaSchool.com
Page 11
DAX Hand Book 6. Data Dictionary a. Extended Data Types i. What are EDTs ii. Power of EDTs in DAX iii. EDT Relations iv. Array Elements in EDT b. Base Enums i. What are Base Enums ii. How to create Base Enums c. Tables i. Basic Persistent Store ii. System Tables and Application Tables iii. Creating Tables/Fields/Various Data Types and Usage iv. Using EDTs and Base Enums v. How the tables in DAX store data vi. Basic Table Properties and Field Properties vii. Field Groups and Requirement viii. Table Indexing/Primary Index/Pros and Cons of Indexing ix. Surrogate Keys x. Table Relations and Types of Table Relations xi. Difference Between EDT Relations and Table Relations xii. Delete Actions/How to play with Cascade + Restricted xiii. Methods as Events in Table/Alternative to PL/SQL Triggers xiv. Transaction Tracking System xv. New Features and Differences in DAX 6 compared to DAX 5 a) Table Inheritance d. Maps i. What are Maps ii. Creating and Using Maps iii. Where and Where not to use Maps e. Views i. What are Views ii. Requirement of Views iii. Creating Simple and Complex Views iv. Methods in Views f. License Codes g. Configuration Keys i. What are Configuration Keys ii. Usage and Applying Configuration Keys in Practical h. Security Keys i. Requirement of Security Keys
T A S K Kumar
www.AxaptaSchool.com
123 123 123 124 126 126 127 127 127 128 128 128 129 129 132 134 134 135 137 138 138 143 150 161 163 163 168 169 170 173 173 174 174 174 175 176 176 177 178 180 180
Page 12
DAX Hand Book
7. Macros a. Macro Commands b. Constants c. Create Macros d. Passing Values 8. Queries a. What are Queries and Requirement of Queries b. Inline Queries i. What are Inline Queries ii. Using loops 1. Why Inline Queries in spite of Other Queries available c. AOT Queries i. Creating AOT Queries ii. Using AOT Queries in X++ iii. Child Data Sources/Ranges/Sorting and Ranges iv. Data Source Relations v. Data Sources and the properties of Data Sources vi. Composite Queries vii. Why AOT Queries and What is the use of AOT Queries viii. Methods in Queries d. X++ Queries i. Creating and Using X++ Queries ii. Data Sources/Ranges/Child Data Sources/Relations e. When and Where to use each type of Query f. Optimize CRUD Operations 9. Resources a. What are Resources b. Adding and Using Resources
181 181 181 182 182 187 187 188 188 190 195 195 195 195 196 202 209 211 212 214 216 217 221 222 222 223 223 225 231 232 241 241 242
10. Forms a. b. c. d. e.
243 243 244 249 254 255
i.
ii. Applying Security Keys in DAX Table Collections i. What are Table Collections ii. Why Table Collections iii. Using Virtual Companies and Table Collections
Unit IV
T A S K Kumar
Basics of Forms Existing Forms Templates available in AX 2012 Creating New Forms Using Data Sources
www.AxaptaSchool.com
Page 13
DAX Hand Book
11.
12.
13.
14.
15.
f. Using resources in a form g. Joining Data Sources h. Methods in Forms/Methods in Data Sources/Form Data Source Field Methods i. Method Calling Sequence j. Placement of code k. Adding filters to forms l. Bound and Un bound Controls/Methods on Controls m. The power of Display and Edit Modifiers n. Using ManagedHost, Splitters etc. o. Calling a form from code p. Identify existing forms and personalization Reports a. Basic Report Wizard [MorphX Reports] b. Important Methods in Reports c. The Power of Programmable Sections d. Auto Design and Generated Design e. SQL Server Reporting Services i. Using Visual Studio to Develop SQL Server Reports ii. Auto design and precision design iii. Adding the report to AX iv. Deploying the reports from AX v. Opening and editing existing reports Menus and Menu Items a. Different Types of Menu Items b. Menus Files a. Reading and Writing Text Files b. Creating CSV Files c. Reading and Writing XML Files d. Exporting the Data to Excel Documents Frameworks a. Runbase Framework b. SysOperationFramework c. Number Sequence Framework Miscellaneous a. Using .NET Classes in AX
259 267 274 280 281 282 285 296 298 303 305 309 312 317 318 319 321 326 328 330 331 333 349 349 352 359 359 362 364 367 369 369 379 389 397
Appendixes 16. New improvements and CIL in AX 2012 17. Installation and configuration of AX 2012 18. Using Debugger in AX
T A S K Kumar
www.AxaptaSchool.com
405 407 409
Page 14
DAX Hand Book
19. 20. 21. 22. 23.
a. Debug Standard AX X++ Code b. Configuring Debugger in AX c. Using configuration utility Label Wizard and Label Editor Basic Administration Interesting tools in AX development environment Best Practices and their Requirement Tips while working in AX Environment
409 410 411 417 427 437 443 447
Links - 449
T A S K Kumar
www.AxaptaSchool.com
Page 15
DAX Hand Book
T A S K Kumar
www.AxaptaSchool.com
Page 16
DAX Hand Book
Introduction “Designed for midsize and larger companies, Microsoft Dynamics AX (formerly Microsoft Axapta) is a multi-language, multi-currency enterprise resource planning (ERP) solution. Microsoft Dynamics AX is fully customizable and extensible through its rich development platform and tools.” As said, Microsoft Dynamics AX supports support for ‘n’ languages and ‘n’ number of currencies with localization settings for various countries. Microsoft Dynamics AX is the complete ERP solution for enterprises that provides core ERP functionality for financial, human resources and operations management. Microsoft Dynamics AX delivers a rich industry platform on which partners can build their own vertical applications for mid-sized organizations and divisions of large enterprises. The solution supports the primary and secondary processes of organizations in multiple industries. As said, AX is a powerful tool to manage the entire enterprise day to day operations with support to various industries included in one application. It’s a global solution that is scalable and agile. The solution is made industry focused by embedding core functionality for the industries includes manufacturing, distribution, public sector, retail and service industries. Reading this Book Firstly, I’d like to thank you for choosing the book as your choice of learning Microsoft Dynamics AX. I’m sure, you don’t get bored of even a single line while you go through the topics. There is a vast coverage of various topics in the book which can be used by a fresher through an experienced enterprise developer of AX.Really, it was a great experience to write a book when I learned AX from its core and a lot which I never did. The book was written with a lot of research done to apply the thoughts which might be useful to reader to make the subject easiest possible. As said, I don’t make the readers bored, but request to read the book from first to last line to get complete knowledge on the technology. The book has lot of material and is covered in practical point of view with scenarios. There is a lot of stuff inside in addition to the indexed content which is not given in index. I felt that they are internal part of few topics and the lines are not included in index to avoid the size of the index looking at which you may get bored. I suggest you to read each topic completely which will give you some or the other point which may be useful to you. This book focuses more on the examples and explanation in plain and simple English which can be understood by a simple novice also. Structure and Approach
T A S K Kumar
www.AxaptaSchool.com
Page 17
DAX Hand Book The following section will introduce on how and the way the book is organized. There are 3 units and an appendix which are organized to cover a major part of AX. All the topics includes the basic requirement, technical requirement and samples to practice the topics. This book covers Microsoft Dynamics AX 2012 and discusses some topics of 2009 also to compare various features which can be helpful for developers as many Organizations are still using Dynamics AX 2009 and are trying to upgrade themselves. Each of the unit is divided into topics and sub topics to give an extensive coverage of the topics. The book was planned to cover basic and advanced topics of Microsoft Dynamics AX but the topics were restricted due to a fact that reader get bored of very large books. The subsequent topics will be covered in the subsequent books released from DAX Softronics (India) Pvt. Ltd. You can find the updates from www.daxsoftronics.com or www.axaptaschool.com . Unit I covers the architectural view of AX and the comparison of DAX with ERP and others. This unit also covers the basic environment that is used to work at the client end in Microsoft Dynamics AX. Unit II covers the basic technical stuff required to solve AX technical requirements. The topics in this unit cover basic programming, tables to queries etc., which are used throughout the book. This unit also covers complete Object Oriented Programming of X++ extensively from fresher perspective. In addition, this will cover the types of classes available and some foundation classes. I request the readers to read the topics until they feel that they have understood the concept up to the mark which is useful to understand the continued units/topics in the book. Unit III covers the advanced technical stuff that is required to extend/expand the AX technical/functional requirements. These mainly include the UI components i.e. Forms, and Reports etc. and the entry point of the application, Menus and Menu items. A handful of appendixes are given to cover various topics and some key points which are required while developing with AX. I felt that these will be useful throughout development process and hence, added in this section. The book is covered in practical point of view where developers can learn by doing which is the best approach followed. I request you to send all the queries, feedback which will always contribute for the betterment of the next version of the book and we always appreciate that. Readers who feel some chapters bore, I suggest them to read the topic at least once even if bored and I’m sure, you’ll find some interesting points to note which may be useful further. Last but not least, “Practice makes man perfect”, a fact which should be applied while learning any technology. Please have a good machine installed and configured with Microsoft Dynamics AX to have good practice on the technology from which you will always get great returns. I’d really love to hear your feed back at mailto:
[email protected]. Thanks, T A S K Kumar. Axapta School.
T A S K Kumar
www.AxaptaSchool.com
Page 18
DAX Hand Book
Unit I 1. Architectural Overview 2. ERP and DAX 3. MorphX Environment
T A S K Kumar
www.AxaptaSchool.com
Page 19
DAX Hand Book
T A S K Kumar
www.AxaptaSchool.com
Page 20
DAX Hand Book
Architectural Overview 3-Tier Architecture Architecture is nothing but the flow of data from one part of the application to another part or one application to another application to complete the operation and get expected result. Any application/program has its own way of working and its own architecture. AX architecture is defined for extracting the best performance out of the application and makes the user get best experience working with AX. In Microsoft Dynamics AX, there is a 3-tier infrastructure with a database server, an application object server (AOS), and a client.
As from the above figure, Tier One is the client where users work. This holds the UI.SRC: MSDN In the above figure, UI or client is called as MorphX. This is IDE which is used to communicate with AX server. Custom AX development and modification is done with its own IDE, MorphX, which resides in the same client application that a normal day-to-day user would access, thus allowing development to take place on any instance of the client. Since the Dynamics AX 2012 version, development can also be performed in Microsoft Visual Studio 2010 through a Visual Studio plug-in.
T A S K Kumar
www.AxaptaSchool.com
Page 21
DAX Hand Book MorphX is an integrated development environment in Microsoft Dynamics AX that allows developers to graphically design data types, base enumerations, tables, queries, forms, menus and reports. In addition to design of application objects, it also allows access to any application code by launching the X++ code editor. An Application Object Server (AOS) is a core component of the Microsoft Dynamics AX 2012 installation and is installed by using Setup. An AOS enforces security, manages connections between clients and the database, and provides the foundation where Microsoft Dynamics AX business logic is executed. An AOS is implemented as a Microsoft Windows Service and is listed in the services as Microsoft Dynamics AX Object Server 6.0$InstanceName. When a client requests some operation like posting Sales Order, server handles the request and sends the response to the client. Finally, backend tier is used to store the data. AOS will not store any data except executing business logic and communicate with backend to get and store data. Usually, Microsoft SQL Server 2005 is used for AX 2009 and Microsoft SQL Server 2008 is used for AX 2012 for storing data.
Layered Model In Microsoft Dynamics AX, a layer system is used to manage elements. The USR layer is the top layer and the SYS layer is the bottom layer, and each layer has a corresponding patch layer above it. These layers are used to organize the objects of AX standard package and the customizations done by various users or developers at various levels. The following table describes the application object layers in Microsoft Dynamics AX: Layer Description USR
The user layer is for user modifications, such as reports.
CUS
The customer layer is for modifications that are specific to a company.
VAR
Value Added Resellers (VAR) can make modifications or new developments to the VAR layer as specified by the customers or as a strategy of creating an industry specific solution.
ISV
When an Independent Software Vendor (ISV) creates their own solution, their modifications are saved in the ISV layer.
SLN
The solution layer is used by distributors to implement vertical partner solutions.
FPK
The FPK layer is an application object patch layer reserved by Microsoft for future patching or
T A S K Kumar
www.AxaptaSchool.com
Page 22
DAX Hand Book other updates. GLS
When the application is modified to match country or region specific legal demands, these modifications are saved in the GLS layer.
SYS
The standard application is implemented at the lowest level, the SYS layer. The application objects in the standard application can never be deleted.
Each layer has a corresponding patch layer that can be used to incorporate updates to your application or to store conflicts when you import models into a layer. The following table shows the layers along with the corresponding patch layers: Layer
Patch Layer
USR
USP
CUS
CUP
VAR
VAP
ISV
ISP
SLN
SLP
FPK
FPP
GLS
GLP
SYS
SYP
The patch layers are designed to make it easy to incorporate updates in your application. The basic idea is that when a minor update or correction is made, it is distributed in a patch file. Modified objects in the patch file are automatically used because they take precedence over the regular application objects.
T A S K Kumar
www.AxaptaSchool.com
Page 23
DAX Hand Book
Advantages of Layer Files: The fact that each layer is saved in a dedicated file means that it is easy to locate the file to backup. It also means that you can easily remove undesired modifications by deleting the layer file. The layers ensure that Any users of the Microsoft Dynamics AX application, whether a distributor, a business partner or an end user, can customize the Microsoft Dynamics AX application to suit their needs. The standard application is never overwritten. When you delete an object, you delete it in the current layer only.
Model Store: Models were introduced in Microsoft Dynamics AX 2012 to help partners and customers more easily install and maintain multiple solutions side by side in the same layer. This topic introduces the concept of models, and describes how models relate to layers and label files. This topic also describes the model store, which is a database in which all application elements for Microsoft Dynamics AX are stored. A model is a set of elements in a given layer. Each layer consists of one or more models. Each layer contains one system-generated model that is specific to that layer. Every element in a layer belongs to only one model. In other words, no element can belong to two models in the same layer, and every element must belong to a model. Models are stored in the model store. The model store is a database in which all application elements for Microsoft Dynamics AX are stored. Customizations are also stored in the model store. The model store replaces the Application Object Data (AOD) files that were used in earlier versions of Microsoft Dynamics AX. Models that have been installed in the model store are used at run time. In Microsoft Dynamics AX 2012 R2, the model store was moved into a database that is separate from the business database. Models can be exported to files that have the .axmodel extension. These files are called model files. Model files are deployment artifacts. Model files can be signed with strong name signing and Microsoft Authenticode signing.
The following is the way how models can be used when doing side-by-side customizations: In earlier versions of Microsoft Dynamics AX, multiple partner solutions could not exist side by side in the same layer. However, models now enable side-by-side customizations. Additionally, the following improvements help you work with side-by-side customizations:
T A S K Kumar
www.AxaptaSchool.com
Page 24
DAX Hand Book The development environment for Microsoft Dynamics AX lets you create a project for each model that is installed. Therefore, you can quickly see all the installed customizations in a layer for a given model. When you import a model, elements in the model that you are importing may conflict with another model in the same layer. You can now create a conflict model in the patch layer that is associated with the layer that you are working in. You can then resolve the conflicts in the conflict model. In earlier versions, no warnings about conflicts were displayed. Instead, elements were just replaced. You can now leave the rest of the layer intact when you uninstall a model. In earlier versions, if you wanted to uninstall customizations, you had to either remove the customizations manually from the AOT or remove the layer. By default, each layer contains a model that corresponds to the name of the layer. You can add additional models to layers that you have access to, depending on your license configuration. You can have different versions of the same element in models that are in different layers, but each element within any one layer must be unique. If the same element exists in two models, and you try to import both models into the same layer, the element that exists in both models will cause a conflict. To mitigate the conflict, you can choose one of three options: Abort the operation and leave the model store unchanged. Overwrite existing definitions with the definitions in the new model. Create a new model in the patch layer that contains the conflicts.
If you choose the third option, a conflict model is created in the patch layer that corresponds to the layer you are importing the model into. The conflicting elements are moved to this model. You can then decide how to resolve the conflicts.
Application Development and Run Time Environments: The Dynamics AX 2012 development and run-time environment supports the following three ERP applications: Rich Client Applications: These are developed using MorphX development environment and is run by Dynamics AX runtime. It is better to write code server-centric so that duplication of code will be avoided and the communication is done using ports [i.e. Microsoft RPC communication technology] is a key asset in Dynamics AX. This makes customers, vendors, partners and employees to access the information which is accessible to them directly through web portals, which can be personalized and role based. Web Client Application: We develop these applications using MorphX development environment and Windows SharePoint Services. From AX 2009, we are using Visual Studio for
T A S K Kumar
www.AxaptaSchool.com
Page 25
DAX Hand Book developing web parts for enterprise portals. Business Connectors which will be discussed later in this book are used. As the web is playing an important role and has its own importance being most used platform for electronic work, portals are used extensively with Enterprise Portal and its advancements incorporated into Microsoft Dynamics AX with SharePoint integration. Client Applications used for Integration: We develop these applications using MorphX and/or Visual Studio environments. We use business connectors for developing these kinds of applications. Most of the cases, we do XML Document integration while developing these applications.
Application Frameworks The Dynamics AX application framework is set of API classes and elements that are used for development of most of the features in ERP to get the best user experience. The book covers most of the elements and the new features that are released in different versions of Microsoft Dynamics AX. Some of the important APIs covered are as follows:
Runbase Framework SysOperationFramework Number Sequence Framework Application Integration Framework
We will discuss the above frameworks in subsequent topics throughout the book where ever applicable.
T A S K Kumar
www.AxaptaSchool.com
Page 26
DAX Hand Book
ERP and AX What is ERP Enterprise Resource Planning (also known as ERP) is an effective approach that most businesses implement to enhance their productivity and performance. Known as a systematic approach that most industries use to organize resources as well as improve efficiency and performance, ERP is usually implemented by corporations to centralize the databases and functions of every department in a single system. The system features various components including software modules, which integrate and manage all the business and private records of firms. Enterprise resource planning (ERP) systems integrate internal and external management information across an entire organization, embracing finance/accounting, manufacturing, sales and service, customer relationship management, etc. ERP systems automate this activity with an integrated software application. The purpose of ERP is to facilitate the flow of information between all business functions inside the boundaries of the organization and manage the connections to outside stakeholders. The following are common functional areas covered in an ERP System. In many ERP Systems these are called and grouped together as ERP Modules: Financial Accounting General Ledger, Fixed Asset, Payables, Receivables, Cash Management, Financial Consolidation Management Accounting Budgeting, Costing, Cost Management, Activity Based Costing Human Resources Recruiting, Training, Payroll, Benefits, Retirement, Separation Manufacturing Engineering, Bill of Materials, Work Orders, Scheduling, Capacity, Workflow Management, Quality Control, Manufacturing Process, Manufacturing Projects, Manufacturing Flow, Product Life Cycle Management Supply Chain Management Supply Chain Planning, Supplier Scheduling, Order to Cash, Purchasing, Inventory, Product Configuration, Claim Processing Project Management Project Planning, Resource Planning, Project Costing, Work Break Down Structure, Billing, Time and Expense, Performance Units, Activity Management
T A S K Kumar
www.AxaptaSchool.com
Page 27
DAX Hand Book Data Services Various "self–service" interfaces for customers, suppliers and/or employees Access Control Management of user privileges for various processes
Advantages The fundamental advantage of ERP is that integrating the processes by which businesses operate saves time and expense. Decisions can be made more quickly and with fewer errors. Data becomes visible across the organization. Tasks that benefit from this integration include:
Sales forecasting. History of every transaction through relevant data compilation in every area of operation. Order tracking, from acceptance through fulfillment Revenue tracking, from invoice through cash receipt
ERP systems centralize business data, bringing the following benefits: They eliminate the need to synchronize changes between multiple systems— consolidation of finance, marketing and sales, human resource, and manufacturing applications They enable standard product naming/coding. They provide a comprehensive enterprise view. They make real–time information available to management anywhere, any time to make decisions. They protect sensitive data by consolidating multiple security systems into a single structure.
Benefits ERP can greatly improve the quality and efficiency of a business. ERP provides support to upper level management to provide them with critical decision making information. ERP also creates a more agile company that can better adapt to situations and changes.
Disadvantages Customization is problematic. ERP can cost more than less integrated and/or less comprehensive solutions. High switching costs associated with ERP can increase the ERP vendor's negotiating power which can result in higher support, maintenance, and upgrade expenses. Integration of truly independent businesses can create unnecessary dependencies.
T A S K Kumar
www.AxaptaSchool.com
Page 28
DAX Hand Book
Training requirements take resources from daily operations. Requires a time, planning and money.
The limitations of ERP have been recognized sparking new trends in ERP application development, the four significant developments being made in ERP are, creating a more flexible ERP, Web-Enable ERP, Inter-enterprise ERP and e-Business Suites, each of which will potentially address the failings of the current ERP. Depending on the organization size, capacity and needs, ERP is divided into 3 markets as follows:
Large Enterprise ERP (ERP Tier I) The ERP market for large enterprises is dominated by three companies: SAP, Oracle and Microsoft.
Midmarket ERP (ERP Tier II) For the midmarket vendors include Infor, Lawson, Epicor and IFS etc.
Small Business ERP (ERP Tier III) Exact Globe, Syspro, NetSuite, CDC Software, Activant Solutions etc. round out the ERP vendors for small businesses.
AX and ERP Microsoft Dynamics AX is the complete ERP solution for enterprises that provides a purposebuilt foundation across five industries, along with comprehensive, core ERP functionality for financial, human resources and operations management. It empowers your people to anticipate and embrace change so your business can thrive. All of this is packaged in a single global solution giving you rapid time to value. Microsoft Dynamics AX supports multiple companies, multiple currencies, and multiple languages. Microsoft Dynamics AX can provide your organization with business value in a single ERP solution that extends into every area of your operations to help you:
Improve productivity Manage change and growth Compete globally Simplify compliance
T A S K Kumar
www.AxaptaSchool.com
Page 29
DAX Hand Book
Solutions for the industries: Microsoft Dynamics AX delivers a rich industry foundation on which partners build packaged applications for niche verticals, such as high-tech manufacturing, architecture and engineering, and specialty retail. These industry capabilities can help you improve your ability to cope with individual market dynamics by delivering breakthrough innovation in a single ERP solution for key industries including: Manufacturing: o This covers the requirements of Lean manufacturing, process manufacturing and discrete manufacturing which is a built solution in AX and reduces the complexity in implementing the solution for manufacturing industry. Distribution: o This covers wholesale, warehouse management and distribution of the materials which is built in and reduces the implementation cost and risk for the industry. Retail: o Solution provides implementation for merchandizing, point of sales and store management Services: o Service industries support is provided with this including project and resources operations; talent and skills management Public Sector: o Support for public sector industries which includes grants management, commitment and fund accounting etc. Going back to history, development of Axapta began in 1983 at Danish company Damgaard Data A/S. The software was mainly targeted at the European market, though the North American market grew rapidly following the release of Axapta 2.1 in 2000. Following the merger of the two Danish companies Navision and Damgaard, Axapta was to be known as Navision Damgaard Axapta for versions 2.5 and 3.0 (up until 3.0 SP5). Microsoft acquired Navision Damgaard during the summer of 2002. Navision Damgaard Axapta was first renamed to Microsoft Business Solutions Axapta, then to Microsoft Dynamics AX for versions 3.0 SP6, 4.0, 2009 and now, 2012. Above table is taken from different sources which explain the core capabilities of Microsoft Dynamics AX very clearly. You can check the references section of this book for the sources of the information gathered.
T A S K Kumar
www.AxaptaSchool.com
Page 30
DAX Hand Book
Modules [core ERP capabilities]: SRC: MSDN FINANCE MANAGEMENT General ledger Accounts receivable and payable Bank management Budgetary control Share service support Compliance management
HUMAN CAPITAL MANAGEMENT Organizational and workforce management Recruitment and selection Development, training, and performance management Employee self-service portal Expense management
PRODUCTION • Material and capacity planning • Resource management • Job scheduling and sequencing • Product configuration • Shop floor management
SUPPLY CHAIN MANAGEMENT • Inventory management • Multisite warehouse management • Trade agreements • Order promising • Distribution planning • Quality management SALES AND MARKETING • Sales force and marketing automation • Lead and opportunity management • Sales management • Microsoft Dynamics CRM connector
PROJECT MANAGEMENT AND ACCOUNTING • Project accounting and invoicing • Project cost control • Work breakdown structures • Integration with Microsoft Project
BUSINESS INTELLIGENCE AND REPORTING Standard, ad hoc, and analytical reports with Microsoft SQL Server® Reporting Services Role Tailored, predefined, multidimensional data cubes Dashboard views of key performance indicators Expense management PROCUREMENT AND SOURCING • Direct and indirect procurement • Purchase requisitions • Supplier relationship management • Vendor self-service portal SERVICE MANAGEMENT • Service orders and contracts • Service calls and dispatching • Repair management • Service subscription
We can also combine/integrate Microsoft Dynamics AX with other Microsoft Products and Technologies. Some of them are as follows:
Developer Tools: o o
Microsoft Visual Studio and Microsoft .NET Windows Communication Foundation and Windows Workflow Foundation
Business Productivity Solutions: o o
T A S K Kumar
Microsoft Outlook, Excel, Word Microsoft Lync and SharePoint
www.AxaptaSchool.com
Page 31
DAX Hand Book
Application Platform: o o
T A S K Kumar
Microsoft SQL Server Microsoft BizTalk
www.AxaptaSchool.com
Page 32
DAX Hand Book
MorphX Environment The MorphX Development Suite is the integrated development environment (IDE) in Microsoft Dynamics AX 2009 used to develop and customize both the Windows interface and the Web interface. An IDE integrates development functions such as designing, editing, compiling, and debugging within a common environment. With MorphX, common operations such as building or modifying forms, menus, and reports are done using drag-and-drop techniques with little or no coding. Development environment features in Microsoft Dynamics AX:
Microsoft Dynamics AX MorphX is an integrated development environment (IDE) for developing in Microsoft Dynamics AX. Visual Studio is an alternative development environment for web, report and managed code development. The Application Object Tree (AOT) provides a uniform and compact viewing repository. Drag-and-drop functionality is supported for many programming tasks. Projects help organize and track customized applications in Microsoft Dynamics AX.
Microsoft Dynamics AX Rich Client is the primary client to access Microsoft Dynamics AX functionality. Most forms displayed in the rich client are designed by using the MorphX development environment. Developers can access the developer tools through the MorphX IDE in the Microsoft Dynamics AX client or through Visual Studio Tools in Visual Studio. The Microsoft Dynamics AX application is built of elements that are stored in the model store in the SQL Service database. For example, the following element types make up part of the application: Fields and Tables define data structure. Forms and Menus define how a user interacts with the application. Classes and Methods are code objects that define business logic. The Application Object Tree (AOT) provides a visual representation of the elements that comprise the application. Object-oriented design and Inheritance are key concepts that form the basis of the application.
Application Object Tree The Application Object Tree (AOT) provides a visual representation of the elements that comprise the application. A full definition of all the element types in Application Object Tree (AOT) can be found in the development training material and developer Help files. Some of the root element types include: Data Dictionary contains objects that define basic data structure.
T A S K Kumar
www.AxaptaSchool.com
Page 33
DAX Hand Book
Tables contain a group of associated fields. For example the VendTable contains fields relevant to Vendors. Fields on a table contain individual parts of data. An example is, AccountNum, one of the fields of VendTable contains the vendor account number. Fields on a table inherit properties from a base data type or an extended data types. Extended data types define a data type and extended properties of that base or another extended data type. There are various basic data types such as a string, integer, date, time and enum. For example, AccountNum is a string extended with properties including a length of 20 characters and has few other properties set. Base Enums are enumerated text data types. These are predefined text values that are referenced by an integer value in the database. For example, Gender is an enum that gives the user only two options (Male or Female) as to know gender of an employee.
Classes contain code that is used in the application. Forms have the layout of all of the forms used throughout application. Forms are used to view data in the Microsoft Dynamics AX client. Visual Studio Projects display any development projects created in Visual Studio. Once we create a project in Visual Studio, it should be added to Application Object Tree to get into the AOT, or we don’t find that project in AOT. Menus define forms, reports and executable units of code that appear in the menu in the Microsoft Dynamics AX rich client. Application Object Tree will be covered extensively in subsequent chapters in following text. The following image shows how Microsoft Dynamics AX rich client and MorphX looks: [Please note that the image shown here is of Microsoft AX 2012]
T A S K Kumar
www.AxaptaSchool.com
Page 34
Bread Crumb Bar
Content Pane
DAX Hand Book
File Menu and Shortcuts on right
Status Bar Navigation Pane
In the above image you see, following are the component that can be discussed about: Breadcrumb Bar: The bar in which you are able to see the company selected [DAT], the module selected [Accounts payable]. This is used to navigate through the companies configured, modules [also called as verticals] available. This can also be called as Address bar. On the left side, we are able to see a pane, called as Navigation pane through which we can open the elements like forms/reports etc. which can be used by end users. This is used for navigation between different forms and reports and other elements in a module and you can also navigate between modules. You can also see File menu and few shortcuts which can be used to find help, about Microsoft Dynamics AX version and models information, to switch between Development and User workspace etc. The central part, which occupied most of the space, is called as content pane in which you will find the menu items which are used by end user to open the forms/reports. If you click on a particular menu item, you will be able to see that element on your screen. Finally, there is a status bar which will give you information about unread notifications, the company, currency information etc. You can also configure/customize this to display the items you need and hide items you don’t need. The above image is only user workspace and developer workspace looks as shown in coming image:
T A S K Kumar
www.AxaptaSchool.com
Page 35
DAX Hand Book
The main difference between AX 2012 and AX 2009 regarding to the environments is, in AX 2009, there is only one workspace which is used by both developers and users. Whereas in AX 2012, there are 2 workspaces namely, User Workspace and Developer Workspace. The following are the components we identify in the above figure: A menu bar and shortcut bar which are used to do the standard operations, in which we will discuss some of them in the following sections. The Application Object Tree (shortly AOT), in which you are able to see a tree structured nodes which are used for development of various components used throughout ERP. A properties window which displays the properties of the objects in AOT. Code editor, in which developers can write, edit, compile and execute the code. Code is written in an object oriented programming language called X++, which will be covered in coming sections. A compiler output window in which you can find errors/warnings etc. once you compile the code. The usage of these windows is covered in debugging section of this text. Finally, status bar will give you information about the environment like, the model, layer etc. you are working on. You can customize these to hide or make visible as per your requirement always. As we covered enough introduction stuff, it’s time to get into the basic development stuff. In this text, I’m starting from X++ programming rather than the regular approach to make developers feel
T A S K Kumar
www.AxaptaSchool.com
Page 36
DAX Hand Book the environment and get hands on experience and make familiar to the environment which will help at later stage while developing applications. Those who like to see programming later can follow the AOT and get into the programming at later stage when they feel that they are familiar. I’d like to receive the feedback on the approach for better organizing the structure of the book in further editions.
T A S K Kumar
www.AxaptaSchool.com
Page 37
DAX Hand Book
T A S K Kumar
www.AxaptaSchool.com
Page 38
DAX Hand Book
Unit II 1. 2. 3. 4. 5. 6.
T A S K Kumar
X++ Introduction Object Oriented Programming in X++ Data Dictionary Macros Queries Resources
www.AxaptaSchool.com
Page 39
DAX Hand Book
T A S K Kumar
www.AxaptaSchool.com
Page 40
DAX Hand Book
X++ Introduction X++ is the primary programming language used in the MorphX Development environment. The following are important features of X++: X++ is an Object Oriented Programming Language very similar to Java and C#. Due to this, programmers feel easiness and very convenient working with the language. Complex business logic for accounting and business management systems can be built very easily with the help of many integrated SQL commands. Programmers can access the existing system classes that can be used to extend the functionality of the application.
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. 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. Case Insensitive: X++ is case insensitive, but, some naming conventions are followed for better understanding of code. No pointer arithmetic: X++ doesn’t support pointers, which eliminates complexity in the language.
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.
T A S K Kumar
www.AxaptaSchool.com
Page 41
DAX Hand Book 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 Visual Studio Debugger
All the above tools except Visual Studio are accessible from Microsoft Dynamics AX Development Workspace. To open the development workspace, press Ctrl + Shift + W from regular user workspace or simply add –development to the command line parameters to start development environment using AX client shortcut. The above described tools are discussed as follows.
X++ Editor This is the place where code is written, compiled and executed. Most AOT nodes [methods] which have code can be opened with a double click which will open the below editor and show the lines of code. This editor can also be started by selecting View Code in the right click context menu. The following image shows the look and feel of X++ code editor:
T A S K Kumar
www.AxaptaSchool.com
Page 42
DAX Hand Book The above window (image) consists of two panes: One for displaying the current methods or jobs. The right pane displays the X++ code. There are many toolbars buttons available in heading of X++ editor window. These are used for regular operations like New, Save, Compile, Run etc. You can find the shortcuts for these in Shortcuts section of appendixes. To find the use of specific button, point at the button using your mouse pointer, you will find the use of the button. X++ code editor uses following color codes for better understandability of developer: Color Blue Green Dark Red Bright Red Purple Black
Code type Reserved words Comments Strings Numbers Labels Everything else
As we know the basics of X++ code editor, it is time to start the programming in X++.
My First X++ Program static void job1 (Args _args) { info(“Hello World!”); } The above program displays Hello World! in a window similar to a popup. This window is called as infolog and is used most frequently to display the output on the screen. The following points can be noted from the above program: Every block of program should be enclosed in { and }. Every statement in X++ program should end with ; Now, let’s try to understand where to write the above program and how to execute that, which covers what is job, which is used in the above program.
T A S K Kumar
www.AxaptaSchool.com
Page 43
DAX Hand Book
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 basically for testing code during development and running batch processes within Microsoft Dynamics AX that affect large amounts of data. This section will explain you about using the Jobs for writing code snippets, executing them directly from X++ editor about compiler and basics of X++ compiler. Most of the code for any requirement is written in classes, methods, tables and/or forms. As said above, jobs are useful for testing code before using them directly in methods or classes. Following is the code when you create a Job: static void Job1(Args _args) { }
Note: You can always change the name of Job, which is always advisable to give a better name as per naming conventions and to remember the purpose of the Job. To create a new Job, right click on Jobs node in AOT, select New Job, You will see the X++ editor opening with the newly created job. Rename this job to MyFirstJob. We will write info to display some output: static void MyFirstJob(Args _args) { info(“Hello World!”); }
The above program display a window called as infolog with a line “Hello World!”. To execute the above code snippet, first compile the Job, later execute the job. You can find detailed step by step approach for compilation, debugging and executing in Appendixes. Simply, F7 is used to compile and F5 is used to execute the job. If you get any errors, please check the following frequent errors which an inexperienced developer may encounter: Missed semicolon (;) after end of statement info(). If you are working on AX 2009, you have to give a semicolon (;) before info() as the declaration section should be terminated by a semicolon (;) in AX 2009, which is not required in AX 2012. Missed ( or ) or { or } or “ or misspelled keywords.
T A S K Kumar
www.AxaptaSchool.com
Page 44
DAX Hand Book Please check for the above errors, resolve them, re compile and execute. You should see the output as expected with an infolog. Finally, Args is used to pass arguments from caller. We will discuss about Args more clearly with samples in further sections of this book. Comments: Comments are used to describe about a line of code or the program. There are multiple types of commenting in X++, used for different purposes. Though it is not mandatory, it is advisable to comment consistently where ever applicable for the following: What does the code does and how the parameters are used. Who made the change and why the change was made for future use. Note the following points before comments are used: Comments can be directly inserted into the lines of code at any place and any point of time. Comments are ignored by the compiler i.e. comments are not compiled either they have executable statements or plain English statement. So, if a code is not required (while testing or for time being), you can comment those lines of code. When you comment, comments will turn the code into green in the editor. This makes you identify the commented lines differently. Some commenting styles are as follows: Single line commenting, done using "//". This will comment only one line at time. // This is a single line comment. To comment multiple lines, we use block comments "/* */". “/*” will start the comment and will comment line(s) until you end with “*/”. Please note, if you forget the end, you may encounter an error. /*This is a block comment. This can have more than one line. */ To do comments "TODO." To do comments appear in the compiler's Tasks tab page. These are used to indicate that you have to do some task or add some lines of code. XML documentation comments. These are used to write notes about a method, the parameters used etc., precisely the purpose of the element. An example is as follows: /// ///Comment using XML tags to distinguish sections. ///
T A S K Kumar
www.AxaptaSchool.com
Page 45
DAX Hand Book These XML documentation comments are used to build XML documents that will have the developer documentation, which can be used to display help in X++ editor further. As we became familiar using the jobs, how to write a job, compile that, execute that, it’s time to get into further step, declaration of variables, following with advanced stuff as follows. Variable, a memory block used to store the data which is used in program to get the expected result. Variable holds the data when the program executes. To declare a variable, we need to identify the type of data that is stored in the variable. For example, age of a person is an integer value whereas, the amount that should be collected from customer or to be paid to vendor is a real value. Once the type is identified, declare a variable following the naming conventions. We will see how to declare, use the variables in this section. Following is a sample program which demonstrates how to declare variables: static void Declaring Variables(Args _args) { int age; //This declare a variable named age, which can be used to store integer value. } In the above program, we have declared a variable named age. This variable can store numeric digits, positive and negative but, will not accept characters. Now, let’s assign value to this variable, an = is used to do that as follows: age = 28; The above statement will assign the value 28 to age, when you try to retrieve value of age, 28 will be returned. The following chart describes about the available data types in X++ and the values that can be stored. Data Type
Description
String
A string is a set of characters. X++ Str supports following types of strings: aligned [left or right], fixed length or variable length. The length of a string can be maximum of 999 characters. Null value is represented by empty string. An integer, also named a natural Int digit, is a number without decimal point. Null value is represented by 0. Real values, also called decimals, are Real digits with a decimal point. Null value
Integer
Real
T A S K Kumar
Keyword
www.AxaptaSchool.com
Example Declaration CustomerName
1090
3.14
Page 46
DAX Hand Book
Date UTCDateTime
Enum
Boolean
Time
GUID
Int64
is represented by 0.0. The date type contains day, month, and year. This type contains year, month, day, hour, minute and second. Null value is represented by 1900-01-01. Enum values are represented by integers internally in database though we are able to see as strings in frontend. The first literal has the number 0, the next number 1 and so on. You can use enums as integers in expressions. Element value with 0 is assumed as null value. Booleans can only contain the values false and true. The values false and true are predefined in X++ and recognized by the compiler. This type contains hours, minutes, and seconds. To declare a time, use the system type timeOfDay. Null value is represented by 00:00:00. Global Unique Identifier (GUID) is a reference number which is unique in any context. A large integer, represented by 64 bits.
Date
12/22/2012
utcDateTime
12/22/2012 04:00:59 am
Must be declared Gender as a BaseEnum first
Boolean
TRUE
timeOfDay
04:00:59
Guid
{5D2503A0-4S8055D3-0P9C2908H82C3804} 11234567890
int64
The chart above shows the types, the values that can be stored by variables of that type and a sample declaration/value that is stored when we use the type. The above types are called as primitive types or basic types which are used to store basic values. Note that, each variable can store only one value at a time. If you assign one more value, previous value will be replaced with newly assigned value and if you try to store multiple values, you will get error in return. Syntax for declaring a variable is as follows: ; Following are few examples for the above shown types: int
T A S K Kumar
integerVariable;//This declares a variable of type integer
www.AxaptaSchool.com
Page 47
DAX Hand Book real str str 30 date boolean
realVariable; //This declares a variable which can store real values unboundStringVariable;//This variable stores string with maximum length boundStringVariable; //This variable stores string with maximum of 30 characters dateVariable; //This variable stores date booleanVariable; //This variable can store a Boolean value i.e. True or False.
Now, let’s understand assigning values and understand some basic rules for assignments: int age = 28; //This is direct assignment while declaration int age; //Simple declaration. age = 28; //This is assigning values to variable after declaration age = 27; //This will overwrite the value 28 with 27. Here onwards, age will have 27. You can also declare several variables of same type in one statement as follows: int age, amount, distance; Now, let’s assume a scenario where we need to store multiple values in a single variable, for e.g. we need to store prices of an item in a single variable. We cannot use the above declaration for this. Instead of the above declaration, we use composite data types for this scenario. Composite types are the data types which can be used to store multiple values of a single type or different types. Following are some of the composite data types available in X++: Data type Array Container
Description An array is a list of items with the same data type and the same name; only the index differs. A container is a dynamic list of items that can contain primitive data types and some composite data types.
An example of declaring an array is as follows: int unlimtedArray[]; // Unlimited index values real limitedArray[20]; // maximum of 20 values limitedArray[2] = 9.8; We use [] for declaring an array which can be used to store multiple values in a single variable as shown above. In the above example, unlimitedArray is declared without anything in [], which can be stored multiple numbers compared to second one, limitedArray, which can be used to store maximum of 20 values. Finally, assigning values is not like an ordinary variables, instead, an index is used which says the variable part to use for storing the value. In the above example, limitedArray[2] indicates that, the second slot is used to store the value. Note: Index in X++ starts with 1.
T A S K Kumar
www.AxaptaSchool.com
Page 48
DAX Hand Book As in the above example, an array variable can store multiple values of single type. Unlike arrays, we can store multiple values of different types using containers. Operations on containers are done using inbuilt functions. The following is an example for using a container: container containerVariable; // the container is declared int var1, var2; str var3; real var4; containerVariable = [28, 27, "Sample string", 9.8]; // the container has 4 values set info(conPeek(containerVariable, 3)); // the third element is printed [var1, var2, var3, var4] = containerVariable; // other variables are set from the container In addition to the above functions, we have few more which can be used to access containers as follows: Function conPeek conDel conNull conFind conIns conPoke conLen
Description Returns the value being held in a specific position in the container. Removes a value from a specific position in the container. Returns an empty container. Finds the position in the container that a certain value is being held (if found). Inserts a value into a specific position in the container. Replaces the value being held in a specific position in the container, with a new value. Returns the number of elements in the container.
Note: We will see few samples of container in coming chapters. We will discuss and use all the available functions there. Now, we are able to write a program, compile and execute, declare variables, use the variables, and work with multi-valued variables (i.e. Arrays and Containers), it’s time to work with some complex logic, like let us consider a scenario where if customer purchase amount is greater than 5000, a discount of 2% will be given otherwise, no discounts. To solve similar problems, we rely on conditional statements. Conditional statements in programming define conditions under which certain operations are performed. Conditional statements use logical expressions that are evaluated to either true or false. If the evaluated expression is true, statements in condition will execute or, they will execute the default operations. Conditional statements are basically 3 in number as follows: If statement Switch statement Ternary operators
T A S K Kumar
www.AxaptaSchool.com
Page 49
DAX Hand Book All these statements are evaluated using operators. An operator is a program element that is applied to one or more operands in an expression or statement. For e.g. when you give a statement like c = a + b, + is called an operator that operates between a and b and = is an operator that will assign the output of a and b. + is called as arithmetic operator and = is called as assignment operator. Now, it’s time to try conditional statements with few examples. Operators are used to evaluate an expression and return the result to. Operators take one or two operands and assign to some variable. There are various types of operators available like, Arithmetic operators, which will do arithmetic operations, logical operators and assignment operators which does assignment etc.
The If statement: The If statement is used to execute a block of statements based on the validity of condition given in it. Please note that, block refers to the statements in between { and }. The condition is given as expression with a single operand or multiple operands with operators may be used. This expression if it is evaluated to true, block will be executed and appropriate action is taken otherwise. The following is the syntax of if statement: if(condition) { //Statement1; //Statement2; } We will see a small example, where we will check for the bigger among 2 digits: int a=3, b=4; if(a > b) { }
info(“a is bigger than b”);
In the above case, a has value 3 and b has value 4. The condition a > b is evaluated to 3 > 4, which will result into false, which will not execute the block and skip to the next statement(s) if available, which are not there in our case. In the above case, if we replace the values of a with 4 and b with 3, as the condition will get satisfied, you will get the result as “a is bigger than b”. If you observe the above, we used 2 operands with an operator “>”. Sometimes, we may pass a single value without any operators also, like a Boolean value, which can be used to execute the block if true. Let’s check one more program as follows: boolean
boolValue = false;
if(boolValue) {
T A S K Kumar
www.AxaptaSchool.com
Page 50
DAX Hand Book }
info(“Should not enter this block.”);
if(boolValue == false) { info(“Should enter this block.”); } if(!boolValue) { info(“Should enter this block.”); } Note that, the above program is a different when compared to the first as, we are using only one variable in the condition, a Boolean. Output of the above program is as follows: Should enter this block. Should enter this block. Let’s try to understand why we got this output: boolean
boolValue = false;
if(boolValue) { //Here, boolValue is false and if will fail and will not allow to execute the block of //statements if the condition evaluates to false. So we didn’t see the statement of this //block in output. } if(boolValue == false) { //In this case, condition is an expression, boolValue == false. == is an operator that will //compare both the values and if they are equal, return true otherwise, false. Here, //boolValue is false and the comparison will result true. So, this statement is executed. } if(!boolValue) { //Finally, !boolValue is, !(false), which will evaluate to true, note that ! is a logical NOT. //So, the block gets executed successfully as the condition finally evaluates to true. }
T A S K Kumar
www.AxaptaSchool.com
Page 51
DAX Hand Book Now, it’s time to understand how to use multiple expressions to evaluate the condition. Let us consider a scenario where if the purchase amount of customer is greater than 5000 and less than 10000, a discount of 2% is given, otherwise, no discount as per business policy. Let’s write a program to get the condition work: real
purchaseAmount, discount;
purchaseAmount = 7200.25; if((purchaseAmount > 5000) && (purchaseAmount < 10000)) { discount = 2; } else { discount = 0; } In the above example, there are two expressions, “purchaseAmount > 5000” and “purchaseAmount < 10000”. In addition to these, we used “&&”, which is called as logical AND. This means that, if both expressions are evaluated to true, then, the condition will evaluate to true, otherwise false. The logical AND will check for the said condition i.e. true and true for both the expressions. In the same way, you can add any number of expressions as per the requirement. You can also use “||”, which stands for logical OR, which means successful evaluation of either of the expression is sufficient to execute the block by evaluating the condition. The second point to note is, if the condition fails, the else part gets executed. Else is used when the if fails to provide an alternative. The following example uses an if and else statements where, we are trying to evaluate few discount percentages based on requirement. real purchaseAmount, discount; purchaseAmount = 12000; if(purchaseAmount > 5000 && purchaseAmount < 10000) { discount = 2; } else { if(purchaseAmount< 20000) { discount = 3.5; }
T A S K Kumar
www.AxaptaSchool.com
Page 52
DAX Hand Book else { }
}
discount = 5;
The only thing I’d like to say is, if you have multiple conditions to check, go for if - else if – else [This is not read as else and if else but if, else if, else ladder]. This is a multilevel check done if you have a condition in a condition. You can always use multiple expressions in conditions. I leave this program to you. Please try this program and understand the output for various values of purchaseAmount. Note: If we pass a non-boolean value like integer, a non-zero will evaluate to true and zero will be false. Now, let’s try a scenario, where the company likes to give some discount and special offer for customers based on the total amount of stock they purchased. Following criteria defies this: If the purchase amount is 20000, a discount of 10% and 1+1 offer is given. If the purchase amount is 15000, a discount of 6% and 1+1 offer is given. If the purchase amount is 10000, a discount of 5% and offer is not given. If the purchase amount is 5000, a flat discount of 3% is given without any gift. If the above conditions are not met, neither discount nor offer will be given. int purchaseAmount = 15000; //Taking int as we are discussing about rounded digits int discount; str offer; if (score == 20000) { discount = 10; offer = “1+1”; } else { if (score == 15000) { discount = 6; offer = “1+1”; } else { if (score == 10000) {
T A S K Kumar
www.AxaptaSchool.com
Page 53
DAX Hand Book discount = 5; offer = “”; } else { if (score == 5000) { discount = 3; offer = “”; } else { discount = 0; offer = “”; } } } } If we observe the above program, choice is given to user, where he selects one of the available choices, and the block is executed based on the selection of user. To make this kind of decision, we have one more statement, Switch. Switch statement is a multi-branch control statement that will have an expression whose result leads to a particular logic/block execution. The switch executes based on the result of the expression. Depending on the possible outcomes, we define code segments, called as cases. Each case is a code unit that should be executed when a particular condition is met. All the cases are listed in body of switch statement. These cases will have the executable statements that will be executed when the condition is satisfied. Syntax of switch is as follows: switch(expression) { case choice1: //Statement1; //Statement2; break; case choice2: //Statement3; //Statement4; default: //Statement5; //Statement6; }
T A S K Kumar
www.AxaptaSchool.com
Page 54
DAX Hand Book The break; statement tells the program to leave the switch statement and continue with further statements immediately after the switch. This can also be used at other places in program other than switch in X++ coding which will be discussed in looping statements. The default case executes if the result of the expression does not match any of the cases. Using the default case is optional. Following is the modified version of above program using switch: int purchaseAmount = 15000; //Taking int as we are discussing about rounded digits int discount; str offer; switch (purchaseAmount) { case 20000 : discount = 10; offer = “1+1”; break; case 15000: discount = 6; offer = “1+1”; break; case 10000: discount = 5; offer = “”; break; case 5000: discount = 3; offer = “”; break; default: discount = 0; offer = “”; } In the above program, we took an expression into switch, which is a single value expression. In the switch block, we have 5 cases including default case. Both the examples produce same result but, the first one uses if-else and the second one uses switch. Notice the complexity and the number of lines, readability of the code. Switch statement makes life simple few times compared with if statement. But, we should have a set of choices before we proceed to the actual logic.
T A S K Kumar
www.AxaptaSchool.com
Page 55
DAX Hand Book Let’s try to understand a small updated requirement in the above program, where customer may not buy exactly the same amount as mentioned in all the conditions. Customer may purchase the amount greater than 5000 and less than 10000 in which he should receive the discount but that will not be applied programmatically, as the expression will check for exact match available and qualifies for the execution otherwise, default will be executed. In order to achieve the mentioned discounts, we need an enhanced selection, where an expression should be given instead of a constant as follows. Please observe the program carefully and try to evaluate output: int purchaseAmount = 15000; //Taking int as we are discussing about rounded digits int discount; str offer; switch (true) { case purchaseAmount >= 20000 : discount = 10; offer = “1+1”; break; case purchaseAmount >= 15000: discount = 6; offer = “1+1”; break; case purchaseAmount >= 10000: discount = 5; offer = “”; break; case purchaseAmount >= 5000: discount = 3; offer = “”; break; default : discount = 0; offer = “”; } If you observe the modified version, I’m using an expression in case statement instead of a constant, which will be evaluated and the exact match is executed. I leave the understanding of the program to the readers, as, this kind of evaluation is not possible in all the languages which X++ supports with a wide range of options. Finally, a small program, illustrating the power of switch in X++, where 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.:
T A S K Kumar
www.AxaptaSchool.com
Page 56
DAX Hand Book
str input = "Mon"; str message; switch (input) { case "red", "yellow", "blue" : message = "You selected color."; break; case "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" : message = "You selected day."; break; default : message ="Neither colors nor days selected."; } info(message); The same program can be written using if-else, which looks as follows: str input = "Mon"; str message; if ((input =="red")|| (input =="yellow")|| (input =="blue")) { message = "You selected color."; } else { if ((input =="Mon")|| (input =="Tue"')|| (input =="Wed") || (input =="Thu") || (input =="Fri") || (input =="Sat") || (input =="Sun")) { message = "You selected day."; } else { message ="Neither colors nor days selected."; } } info(message);
T A S K Kumar
www.AxaptaSchool.com
Page 57
DAX Hand Book
Compare both the programs and try to evaluate which is better based on the lines of code, complexity and readability and ease of understanding. Also, try the same example removing break and observe the output. It will execute all the statements which is an odd output which anyone doesn’t expect. Now that we are clear with the conditional statements, it’s time to dig more considering a scenario where you need to calculate the discount amount in the above fashion for 5 of your customers. For this, it is not feasible solution to write entire code for 5 times as the count may grow or shrink based on your customers volume. Instead, an operation or the block of statements should be executed for multiple times. In that case, we use statements called looping statements.
Loops: Looping statements are used to execute a block of statements until the given condition evaluates to true. These are also called as repetitive statements or iterative statements as they will execute multiple times till the condition satisfies and stop when the condition fails. There are 3 types of loops available in X++ as follows: While loop Do while loop For loop Following table differentiates each loop with an example:
Syntax
Working
Initialization
T A S K Kumar
While loop while(condition) { //Statements; }
Do while loop do { //Statements; }while(condition);
For loop for(initialization; condition; increment/decrement) { //Statements; } Will not enter into loop if Will enter into the loop Will not enter into loop if the condition fails for the even if the condition fails the condition fails for the first time. for the first time. first time. 1. Initialize 2. Check condition 3. Execute statements 4. Increment/decrement 5. Go to step 2 Initialization of the looping variable,
1. Initialize 2. Execute statements 3. Increment/decrement 4. Check condition 5. Go to step 2 Initialization of the looping variable,
www.AxaptaSchool.com
1. Initialize 2. Check condition 3. Execute statements 4. Increment/decrement 5. Go to step 2 Initialization of the looping variable,
Page 58
DAX Hand Book increment/decrement done separately. Execution
Example 1
is increment/decrement done separately.
is increment/decrement is done in for as shown in syntax. Will not execute even a Will execute once even if Will not execute even a single time if condition the condition fails. single time if condition fails. fails. int counter = 1; int counter = 1; int counter; while(i