Microsoft DynamicsAX 2012 R3 DevelopmentCookbookOver 80 effective recipes to help you solve real-worldMicrosoft Dynamics AX development problemsMindaugas PociusBIRMINGHAM - MUMBAI

Microsoft Dynamics AX 2012 R3Development CookbookCopyright 2015 Packt PublishingAll 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 thepublisher, except in the case of brief quotations embedded in critical articles or reviews.Every effort has been made in the preparation of this book to ensure the accuracy of theinformation presented. However, the information contained in this book is sold withoutwarranty, either express or implied. Neither the author, nor Packt Publishing, and itsdealers and distributors will be held liable for any damages caused or alleged to becaused directly or indirectly by this book.Packt Publishing has endeavored to provide trademark information about all of thecompanies and products mentioned in this book by the appropriate use of capitals.However, Packt Publishing cannot guarantee the accuracy of this information.First published: December 2009Second edition: May 2012Third edition: April 2015Production reference: 1230415Published by Packt Publishing Ltd.Livery Place35 Livery StreetBirmingham B3 2PB, UK.ISBN 978-1-78528-169-3www.packtpub.comFM-2

CreditsAuthorMindaugas PociusCopy EditorsCharlotte CarneiroDipti KapadiaReviewersPalle AgermarkPankaj ChaturvediProject CoordinatorSuzanne CoutinhoFatih DemirciStefan EbertRodrigo FragaKishor JadhavUmesh PanditCommissioning EditorAmarabha BanerjeeAcquisition EditorVinay ArgekarContent Development EditorAmey VarangaonkarProofreadersSimran BhogalBridget BraundMaria GouldPaul HindleIndexerTejal SoniProduction CoordinatorManu JosephCover WorkManu JosephTechnical EditorAnkita ThakurFM-3

About the AuthorMindaugas Pocius is currently a freelance Dynamics AX technical and functional consultantand trainer at DynamicsLab Limited ( The company specializes inproviding development, consulting, and training services for Microsoft Dynamics AX resellersand customers.Mindaugas started his IT consulting career back in 2001 while he was still pursuing hismaster's degree in information technology at Kaunas University of Technology in Lithuania.Since then, he has become a recognized Microsoft Certified Professional for Dynamics AXin all major areas, such as development, configuration and installation, financials, projects,and trade and logistics. He is also a Certified Microsoft Trainer for Dynamics AX and hasdelivered numerous Dynamics AX trainings.Mindaugas has participated in over 20 Dynamics AX implementations. He has held a widerange of development, consulting, and lead roles while always maintaining the significantrole of a business application developer.In December 2009, he released his first book, Microsoft Dynamics AX 2009 DevelopmentCookbook, and then in May 2012, its second edition, Microsoft Dynamics AX 2012Development Cookbook, both of which are published by Packt Publishing.First of all, I would like to thank my wife, Rasa, and my two boys, Dominykasand Augustas, for their support and understanding during the long hoursthat I spent on this book. I also want to apologize for the time I've stolenfrom them to make this book a reality.Secondly, I wish to thank all the reviewers, who provided very valuablecomments to improve the code in this book and who helped to makethe code's explanations clearer.Lastly, a special thanks goes to the Packt Publishing team who made thisbook possible.FM-4

About the ReviewersPalle Agermark has worked as a developer and technical consultant with Concorde XALand Microsoft Dynamics AX for more than 20 years. He has worked for a number of years atthe Microsoft Development Center, Copenhagen, primarily developing the financial, accountspayable, and accounts receivable modules; he has also worked on other things, such as theUnit Test framework.Currently, Palle works for one of Scandinavia's largest Microsoft Dynamics AX partners, EG,in Copenhagen.In 2006, Palle wrote a chapter titled Extending Microsoft Dynamics AX for Inside MicrosoftDynamics AX 4.0, Microsoft Press. He has been a reviewer of several books from PacktPublishing, including Microsoft Dynamics AX 2012 R2 Services.I'd like to thank the author and publisher for putting their time and moneyinto this excellent book, which will be very helpful to the entire Dynamics AXdeveloper community.Pankaj Chaturvedi is an experienced Dynamics AX technical consultant. He is currentlyworking with Sonata Software Ltd. in Bangalore, India.Pankaj began working with AX in 2006 and has a wide range of expertise, both technical andfunctional. Apart from Dynamics AX, he also works with other Microsoft technologies, includingMicrosoft NAV, SharePoint, Reporting Services, Analysis Services, and Visual Studio.Pankaj has worked on many Dynamics AX implementations, which specialize in businesssolutions design, X programming, reporting, and business intelligence. He is a MicrosoftCertified Professional for AX (development, installation, and configuration) as well as for keymodules (finance and trade and logistics). He is also a Microsoft Certified Trainer for AX.FM-5

Fatih Demirci (MCT) is a technical consultant and trainer. He has been workingprofessionally on Dynamics AX since 2006. He has worked with many Microsoft partnersand customers. He has over 9 years of consulting experience, where he has played a varietyof roles, including senior software engineer, team leader, trainer, and technical consultant inDynamics AX. He is one of the cofounders of DMR Consultancy, which is the most promisingERP consultancy company in Turkey, and he works with some of the most experienced andcreative Dynamics AX professionals.Fatih runs a professional and technical blog at, and shares histhoughts and readings on Twitter and LinkedIn.I would like to thank my family and friends for motivating me and for alwayspushing me to do my best.Stefan Ebert started his Dynamics AX career in 2007 after studying computer science atHochschule Darmstadt. As a consequence of working on IT projects for a large manufacturingcompany for more than 10 years, he has a deep and wide knowledge of the company'sbusiness and economic activities.He is experienced in the overall software development cycle, from designing, implementing,and integrating to testing, building, and deploying applications and tools. He is a thoroughprofessional and loves topics such as quality, performance, testing, reviewing, and versioncontrol systems.Stefan can be contacted via LinkedIn at would like to thank Mindaugas and Packt Publishing for letting me be apart of the making of this book. It was a great experience.Rodrigo Fraga has been working with Dynamics AX since 2006 and has participated indifferent projects, implementing AX, across South and North America.Currently, Rodrigo works for Hewlett-Packard, allocated at Suncor, one of the largest AXimplementations in the world.FM-6

Kishor Jadhav is currently working as a Microsoft Dynamics AX senior technical consultantwith 42 Hertz INC. He has completed his master's degree in computer application from theUniversity of Mumbai, and his bachelor's degree in information technology from VidyalankarSchool of Information Technology, Mumbai.Kishor has around 6 years of IT experience. He has worked with Godrej Infotech Ltd., Mumbai,as a Dynamics AX technical consultant. He has a deep understanding of Microsoft DynamicsAX ERP systems. He has worked with different versions of AX, such as AX 5.0 (AX 2009) andAX 6.0 (AX 2012, AX 2012 R2, and AX 2012 R3). He has a good knowledge of Microsofttechnologies such as SQL, VB 6.0, C#, SSRS, and SSAS.He can be contacted via Skype (kishorworld) or e-mail ([email protected]),and he blogs at would like to thank Mindaugas Pocius, Suzanne Coutinho, and PacktPublishing team for giving me the opportunity to review this book.Umesh Pandit is a Microsoft Dynamics AX deployment senior specialist who currently workswith Hitachi Solutions, India. He has completed his master's degree in computer applications,with first division, having specialized in ERP from Ideal Institute of Technology, Ghaziabad.Umesh is also a Microsoft Certified Professional for Microsoft Dynamics AX 2009 Installationand Configuration, Microsoft Dynamics AX 2012 Installation and Configuration, ServerVirtualization with Windows Server Hyper-V and System Center, Microsoft Dynamics AX 2012Development Introduction I, Microsoft Dynamics POS 2009, Administering Microsoft SQLServer 2012 Databases, and Implementing Microsoft Azure Infrastructure Solutions.In the past, he has successfully reviewed Microsoft Dynamics AX 2012 Reporting Cookbookby Kamalakannan Elangovan, Developing SSRS Reports for Dynamics AX by Mukesh Hirwani,Microsoft Dynamics AX 2012 Programming: Getting Started by Mohammed Rasheed andErlend Dalen, and Reporting in TFS by Dipti Chhatrapati, all by Packt Publishing.He has worked with top IT giants, such as KPIT Technologies, Capgemini India, and GoogleIndia, as well as with a cable manufacturing company called Cords Cable Industries Limited.FM-7

Umesh has a deep understanding of ERP systems, such as Microsoft Dynamics AX and SAP.He has worked with different versions of Microsoft Dynamic AX, starting with Axapta versions,such as AX 3.0, AX 4.0, AX 2009, AX 2012, AX 2012 R2, AX 2012 R3, and AX 2012 R3 CU8.He has vast knowledge of Microsoft Technologies, such as SQL 2014, CRM, TFS, Office 2013,Windows Server 2003, Window Server 2008, Windows Server 2012, Office 365, MicrosoftDynamics NAV, SSRS, Cubes, Management Reporter, SSAS, and Visual Studio.He can be reached at [email protected], and he blogs at would like to give special thanks to my close friend Pramila who supportedme a lot, and best buddies at work—Sunil Wadhwa, Rohan Sodani, FareedaBegum, Aman Bhatia, Gyan Chand Kabra, Debashish Ray, Arjita Choudhury,and Meenakshi Pandey—who have guided me and encouraged my passion.FM-8

www.PacktPub.comSupport files, eBooks, discount offers, and moreFor support files and downloads related to your book, please visit you know that Packt offers eBook versions of every book published, with PDF and ePubfiles available? You can upgrade to the eBook version at and as a printbook customer, you are entitled to a discount on the eBook copy. Get in touch with us [email protected] for more details.At, you can also read a collection of free technical articles, sign up for arange of free newsletters and receive exclusive discounts and offers on Packt books and ion/packtlibDo you need instant solutions to your IT questions? PacktLib is Packt's online digital booklibrary. Here, you can search, access, and read Packt's entire library of books.Why subscribe?fffFully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browserFree access for Packt account holdersIf you have an account with Packt at, you can use this to access PacktLibtoday and view 9 entirely free books. Simply use your login credentials for immediate access.Instant updates on new Packt booksGet notified! Find out when new books are published by following @PacktEnterprise onTwitter or the Packt Enterprise Facebook page.FM-9

Table of ContentsPrefaceChapter 1: Processing Datav1IntroductionCreating a new number sequenceRenaming the primary keyMerging two recordsAdding a document handling noteUsing a normal table as a temporary tableCopying a recordBuilding a query objectUsing a macro in a SQL statementExecuting a direct SQL statementEnhancing the data consistency checkExporting data to an XML fileImporting data from an XML fileCreating a comma-separated value fileReading a comma-separated value fileUsing the date effectiveness feature22811141719232729364043454852Chapter 2: Working with Forms57IntroductionCreating dialogs using the RunBase frameworkHandling a dialog eventBuilding a dynamic formAdding a form splitterCreating a modal formModifying multiple forms dynamicallyStoring user selections5758636873788082i

Table of ContentsUsing a Tree controlBuilding a checklistAdding the View details link8697106Chapter 3: Working with Data in Forms109Chapter 4: Building Lookups163Chapter 5: Processing Business Tasks207IntroductionUsing a number sequence handlerCreating a custom filter controlCreating a custom instant search filterBuilding a selected/available listPreloading imagesCreating a wizardProcessing multiple recordsColoring recordsAdding an image to recordsIntroductionCreating an automatic lookupCreating a lookup dynamicallyUsing a form to build a lookupBuilding a tree lookupDisplaying a list of custom optionsDisplaying custom options in another wayBuilding a lookup based on the record descriptionBuilding the browse for folder lookupBuilding a lookup to select a fileCreating a color picker lookupIntroductionUsing a segmented entry controlCreating a general journalPosting a general journalProcessing a project journalCreating and posting a ledger voucherChanging an automatic transaction textCreating a purchase orderPosting a purchase orderCreating a sales orderPosting a sales orderCreating an electronic payment 4247252

Table of ContentsChapter 6: Integration with Microsoft Office261Chapter 7: Using Services285Chapter 8: Improving Development Efficiency319Chapter 9: Improving Dynamics AX Performance343Index361IntroductionCreating an Excel fileReading an Excel fileCreating a Word document from a templateCreating a Word document with repeating elementsCreating a Microsoft Project fileSending an e-mail using OutlookIntroductionConsuming the system query serviceConsuming the system metadata serviceConsuming an existing document serviceCreating a document serviceConsuming a document serviceUsing an enhanced document serviceCreating a custom serviceConsuming a custom serviceConsuming an external serviceIntroductionCreating a code editor templateModifying the Tools menuModifying the right-click context menuSearching for an object in a development projectModifying the Personalization formModifying the About Microsoft Dynamics AX dialogIntroductionCalculating code execution timeWriting efficient SQL statementsCaching a display methodUsing Dynamics AX Trace ParserUsing SQL Server Database Engine Tuning 10313315319320325327333336340343343346348351357iii

PrefaceAs a Dynamics AX developer, your responsibility is to deliver all kinds of applicationcustomizations, whether it is a small adjustment or a bespoke module. Dynamics AX is ahighly customizable system and requires a significant amount of knowledge and experienceto deliver quality solutions. One goal can be achieved in multiple ways, and there is alwaysthe question of which way is the best.This book takes you through numerous recipes to help you with daily development tasks.Each recipe contains detailed step-by-step instructions along with the application screenshotsand in-depth explanations. The recipes cover multiple Dynamics AX modules, so at the sametime, the book provides an overview of the functional aspects of the system for developers.What this book coversThe book's content is presented in nine chapters that cover various aspects of Dynamics AX.Chapter 1, Processing Data, focuses on data manipulation. It explains how to build dataqueries, how to check and modify existing data, how to read and write external files, andhow to use date effectiveness.Chapter 2, Working with Forms, covers various aspects of building forms in Dynamics AX.In this chapter, dialogs and their events are explained. Also, various useful features suchas splitters, tree controls, and checklists are explained here.Chapter 3, Working with Data in Forms, basically supplements Chapter 2, Working withForms, and explains about data organization in forms. Examples in this chapter includeinstructions about how to build filter controls on forms, process multiple records, and workwith images and colors.Chapter 4, Building Lookups, covers all kinds of lookups in the system. The chapter startswith a simple, automatically generated lookup, continues with more advanced ones, andfinishes with standard Windows lookups, such as the file selection dialog or color picker.v

PrefaceChapter 5, Processing Business Tasks, explains the usage of the Dynamics AX business logicAPI. In this chapter, topics such as how to process journals, as well as purchase and salesorders are discussed. Other features such as posting ledger vouchers, modifying transactiontexts and creating electronic payment formats are included as well.Chapter 6, Integration with Microsoft Office, shows how Word, Excel, Outlook, and Projectapplications can be integrated with Dynamics AX.Chapter 7, Using Services, explains how to use services in Dynamics AX. The chapter coversstandard query, metadata, and document system services. It also demonstrates how to createcustom services and how to consume external services.Chapter 8, Improving Development Efficiency, presents a few ideas on how to make dailydevelopment tasks easier. The chapter demonstrates how to build code templates, modify thetools and the right-click context menus, use search in development projects, and customizethe Personalization form.Chapter 9, Improving Dynamics AX Performance, discusses how system performance canbe improved by following several simple rules. The chapter explains how to calculate codeexecution time, how to write efficient SQL statements, how to properly cache display methods,and how to use Dynamics AX Trace Parser and SQL Server Database Engine Tuning Advisor.Exceptions and considerationsThe code in this book follows the best practice guidelines provided by Microsoft, but there aresome exceptions:fNo text labels were used to make the code clearfNo three-letter code was used in front of each new AOT objectfNo configuration or security keys were usedfObject properties that are not relevant to the topic being discussed are not setAlso, here are some considerations that you need to keep in mind when reading the book:fEach recipe only demonstrates the principle and is not a complete solutionfThe data in your environment might not match the data used in the recipes, so thecode might have to be adjusted appropriatelyfFor each recipe, the assumption is that no other modifications are present in thesystem, unless it is explicitly specifiedfThe code might not have all the possible validations that are not relevant to theprinciple being explainedvi

PrefacefThe code might have more variables than required in order to ensure that it is clearfor all audiencesfSometimes, unnecessary code wrapping is used to make sure the code fits into thepage width of this book and is easy readableWhat you need for this bookAll the coding examples were performed in a virtual Microsoft Dynamics AX 2012 R3 imagedownloaded from the Microsoft CustomerSource or PartnerSource websites. The following listof software from the virtual image was used in this book:fMicrosoft Dynamics AX 2012 R3 (kernel:, application: Dynamics AX Trace Parser (version: Windows Server 2012 R2 DatacenterfMicrosoft SQL Server 2014fMicrosoft Office Excel 2013fMicrosoft Office Word 2013fMicrosoft Office Outlook 2013fMicrosoft Office Project 2013fMicrosoft Internet Explorer 11fWindows NotepadAlthough all the recipes have been tested on the previously-mentioned software, theymight work on older or newer software versions without any implications or with minorcode adjustments.Who this book is forThis book is for Dynamics AX developers primarily focused on delivering time-proven applicationmodifications. Although new X developers can use this book along with their beginner guides,this book is more focused on people who are willing to raise their programming skills abovebeginner level and, at the same time, learn the functional aspects of Dynamics AX. So, someDynamics AX coding experience is expected.SectionsIn this book, you will find several headings that appear frequently (Getting ready, How to do it,How it works, There's more, and See also).vii

PrefaceTo give clear instructions on how to complete a recipe, we use these sections as follows:Getting readyThis section tells you what to expect in the recipe, and describes how to set up any software orany preliminary settings required for the recipe.How to do it This section contains the steps required to follow the recipe.How it works This section usually consists of a detailed explanation of what happened in the previous section.There's more This section consists of additional information about the recipe in order to make the readermore knowledgeable about the recipe.See alsoThis section provides helpful links to other useful information for the recipe.ConventionsIn this book, you will find a number of text styles that distinguish between different kinds ofinformation. Here are some examples of these styles and an explanation of their meaning.Code words in text, all Application Object Tree (AOT) object names like tables, forms, extendeddata types, classes and others, folder names, filenames, file extensions, pathnames, dummyURLs, and user input are shown as follows: "We start the recipe by adding a number sequenceinitialization code into the NumberSeqModuleCustomer class."A block of code is set as stGroupId));datatype.parmReferenceHelp("Customer group ardIsChangeUpAllowed(NoYes::Yes);viii

qParameterType::DataArea, true, false);this.create(datatype);New terms and important words are shown in bold. Words that you see on the screen,for example, in menus or dialog boxes, appear in the text like this: "Click on Details toview more information."Reader feedbackFeedback from our readers is always welcome. Let us know what you think about thisbook—what you liked or disliked. Reader feedback is important for us as it helps usdevelop titles that you will really get the most out of.To send us general feedback, simply e-mail [email protected], and mentionthe book's title in the subject of your message.If there is a topic that you have expertise in and you are interested in either writing orcontributing to a book, see our author guide at supportNow that you are the proud owner of a Packt book, we have a number of things to help you toget the most from your purchase.Downloading the example codeYou can download the example code files from your account at http://www.packtpub.comfor all the Packt Publishing books you have purchased. If you purchased this book elsewhere,you can visit and register to have the files e-maileddirectly to you.Downloading the color images of this bookWe also provide you with a PDF file that has color images of the screenshots/diagrams usedin this book. The color images will help you better understand the changes in the output.You can download this file from: ads/1693EN ColorImages.pdf.ix

PrefaceErrataAlthough we have taken every care to ensure the accuracy of our content, mistakes do happen.If you find a mistake in one of our books—maybe a mistake in the text or the code—we would begrateful if you could report this to us. By doing so, you can save other readers from frustrationand help us improve subsequent versions of this book. If you find any errata, please report themby visiting, selecting your book, clicking onthe Errata Submission Form link, and entering the details of your errata. Once your errata areverified, your submission will be accepted and the errata will be uploaded to our website oradded to any list of existing errata under the Errata section of that title.To view the previously submitted errata, go to and enter the name of the book in the search field. The requiredinformation will appear under the Errata section.PiracyPiracy of copyrighted material on the Internet is an ongoing problem across all media.At Packt, we take the protection of our copyright and licenses very seriously. If you comeacross any illegal copies of our works in any form on the Internet, please provide us withthe location address or website name immediately so that we can pursue a remedy.Please contact us at [email protected] with a link to the suspected pirated material.We appreciate your help in protecting our authors and our ability to bring you valuable content.QuestionsIf you have a problem with any aspect of this book, you can contact us at question[email protected], and we will do our best to address the problem.x

1Processing DataIn this chapter, we will cover the following recipes:fCreating a new number sequencefRenaming the primary keyfMerging two recordsfAdding a document handling notefUsing a normal table as a temporary tablefCopying a recordfBuilding a query objectfUsing a macro in a SQL statementfExecuting a direct SQL statementfEnhancing the data consistency checkfExporting data to an XML filefImporting data from an XML filefCreating a comma-separated value filefReading a comma-separated value filefUsing the date effectiveness feature1

Processing DataIntroductionThis chapter focuses on data manipulation exercises. These exercises are very useful whendoing data migration, system integration, custom reporting, and so on. Here, we will discusshow to work with query objects from the X code. We will also discuss how to reuse macros inX SQL statements and how to execute SQL statements directly in the database. This chapterwill explain how to rename primary keys, how to merge and copy records, how to add documenthandling notes to selected records, and how to create and read XML and comma-separatedvalue (CSV) files. The chapter ends with a recipe about the date effectiveness feature.Creating a new number sequenceNumber sequences in Dynamics AX are used to generate specifically formatted numbers usedfor various identification. These number sequences can be anything from voucher numbers ortransaction identification numbers to customer or vendor account codes.When developing custom functionality, often one of the tasks is to add a new number sequenceto the system in order to support newly created tables and forms. Adding a number sequenceto the system is a two-step process. First, we create the number sequence itself; second, westart using it in some particular form or from the code. Number sequences can be created eithermanually or automatically by the wizard.Dynamics AX contains a list of NumberSeqApplicationModule derivative classes, whichhold the number sequence's setup data for the specific module. These classes are read by thenumber sequence wizard, which detects already created number sequences and proposesto create the missing ones. The wizard is normally run as part of the application initialization.It can also be rerun any time later when expanding the Dynamics AX functionality used. Thewizard also has to be rerun if new custom number sequences are added to the system.In this recipe, we will do the first step, that is, add a new number sequence to the system. In astandard application, the customer group number is not driven by a number sequence, so wewill enhance this by creating a new number sequence for customer groups. The second stepis explained later in the Using a number sequence handler recipe in Chapter 3, Working withData in Forms.How to do it.Carry out the following steps in order to complete this recipe:1. Open the NumberSeqModuleCustomer class in the Application Object Tree (AOT)and add the following code snippet at the bottom of the loadModule() tGroupId));datatype.parmReferenceHelp("Customer group ID");datatype.parmWizardIsContinuous(false);2

Chapter ataArea, true, false);this.create(datatype);Downloading the example codeYou can download the example code files for all Packt books you havepurchased from your account at If youpurchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.2. Create a new job with the following lines of code and run it:static void NumberSeqLoadAll(Args args){NumberSeqApplicationModule::loadAll();}3. Navigate to Organization administration Common Number sequences and openthe Number sequences list page. Run the number sequence wizard by clicking on theGenerate button. On the first wizard's page, click on the Next button, as shown in thefollowing screenshot:3

Processing Data4. On the next page, click on Details to view more information. Delete everything apartfrom the rows where Area is Accounts receivable and Reference is Customer group.Note the number sequence codes and click on the Next button, as shown here:5. On the last page, click on the Finish bu

Virtualization with Windows Server Hyper-V and System Center, Microsoft Dynamics AX 2012 Development Introduction I, Microsoft Dynamics POS 2009, Administering Microsoft SQL Server 2012 Databases, and Implementing Microsoft Azure Infrastructure Solutions. In the past, he has successfully reviewed