Dynamics 365 For Finance And Operations Development

Transcription

Dynamics 365 for Finance andOperations DevelopmentCookbookFourth EditionBuild extensive, powerful, and agile business solutionsDeepak AgarwalAbhimanyu SinghBIRMINGHAM - MUMBAI

Dynamics 365 for Finance and OperationsDevelopment CookbookFourth EditionCopyright 2017 Packt PublishingAll rights reserved. No part of this book may be reproduced, stored in a retrieval system, ortransmitted 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 authors, nor Packt Publishing, and itsdealers and distributors will be held liable for any damages caused or alleged to be causeddirectly 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 2015Fourth edition: August 2017Production reference: 1100817Published by Packt Publishing Ltd.Livery Place35 Livery StreetBirminghamB3 2PB, UK.ISBN 978-1-78646-886-4www.packtpub.com

CreditsAuthorsDeepak AgarwalAbhimanyu SinghCopy EditorSafis EditingReviewerSantosh ParuvellaProject CoordinatorPrajakta NaikCommissioning EditorAaron LazerProofreaderSafis EditingAcquisition EditorDenim PintoIndexerFrancy PuthiryContent Development EditorLawrence VeigasGraphicsAbhinash SahuTechnical EditorMehul SinghProduction CoordinatorNilesh Mohite

About the AuthorsDeepak Agarwal is a Microsoft Certified Professional who has more than 6 years ofrelevant experience. He has worked with different versions of Axapta, such as AX 2009, AX2012, and Dynamics 365. He has had a wide range of development, consulting, and leadingroles, while always maintaining a significant role as a business application developer.Although his strengths are rooted in X development, he is a highly regarded developerand expert in the technical aspects of Dynamics AX development and customization. Hehas also worked on base product development with the Microsoft team.He was awarded the Most Valuable Professional (MVP) award from Microsoft forDynamics AX four times in a row, and he has held this title since 2013.He shares his experience with Dynamics AX on his blog Axapta V/s Me.Deepak has also worked on the following Packt books:1. Microsoft Dynamics AX 2012 R3 Reporting Cookbook2. Dynamics AX 2012 Reporting Cookbook3. Microsoft Dynamics AX 2012 Programming: Getting StartedI would like to thank my wife for her support during this duration. Big thanks for herunderstanding while I spent late hours working on this book. Thanks to my co-author,Abhimanyu, and the Packt team for their support and efforts.

Abhimanyu Singh works as a Microsoft Dynamics 365 for Finance and Operationsconsultant. Since the start of his career in 2012, he has worked in the development anddesigning of business solutions for customers in supply chain management, banking, andfinance domain using Microsoft technologies. He has several certifications, including theMicrosoft Certified Dynamics Specialist certification.I would like to thank my parents, sister, and brother-in-law for their support andinspiration during the time spent on this book. Secondly, I wish to thank the co-author ofthis book, and my friend, Deepak Agarwal--a very experienced Dynamics AX consultant.

About the ReviewerSantosh Paruvella has 12 years of experience in Dynamics AX, and he has worked onvarious versions of it, from 3.0 to 2012, and Dynamics 365 for Finance and Operations. He ispresently working as a Technical Architect and Lead for various implementation projects,designing the solutions and leading the team towards successful implementations.I have got the chance to review this Dynamics 365 for finance and OperationsDevelopment Cookbook, and I am very thankful to the Packt team and the author for thisopportunity. This is a very good book for beginners to start with AX development.

www.PacktPub.comFor support files and downloads related to your book, please visit www.PacktPub.com. Didyou know that Packt offers eBook versions of every book published, with PDF and ePubfiles available? You can upgrade to the eBook version at www.PacktPub.comand as a printbook customer, you are entitled to a discount on the eBook copy. Get in touch with us atservice@packtpub.com for more details.At www.PacktPub.com, 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 andeBooks.https:/ / www. packtpub. com/ maptGet the most in-demand software skills with Mapt. Mapt gives you full access to all Packtbooks and video courses, as well as industry-leading tools to help you plan your personaldevelopment and advance your career.Why subscribe?Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Customer FeedbackThanks for purchasing this Packt book. At Packt, quality is at the heart of our editorialprocess. To help us improve, please leave us an honest review on this book's Amazon pageat https:/ / www. amazon. com/ dp/ 1786468867.If you'd like to join our team of regular reviewers, you can e-mail us atcustomerreviews@packtpub.com. We award our regular reviewers with free eBooks andvideos in exchange for their valuable feedback. Help us be relentless in improving ourproducts!

This book is dedicated to my grandpa, the late Mr. M.R. Agarwal. You are always a blessingindeed.- Deepak Agarwal

Table of ContentsPrefaceChapter 1: Processing DataIntroductionCreating a new project, package, and modelHow to do it.There's more.Creating a new number sequenceHow to do it.How it works.See alsoRenaming the primary keyHow to do it.How it works.Adding a document handling noteGetting readyHow to do it.How it works.Using a normal table as a temporary tableHow to do it.How it works.Copying a recordHow to do it.How it works.There's more.Building a query objectHow to do it.How it works.There's more.Using the OR operatorSee alsoUsing a macro in a SQL statementHow to do it.How it works.Executing a direct SQL 3839404142434444454647

How to do it.How it works.There's more.Enhancing the data consistency checksGetting readyHow to do it.How it works.There's more.Using the date effectiveness featureHow to do it.How it works.Chapter 2: Working with Forms475051535355575858596263IntroductionCreating dialogs using the RunBase frameworkHow to do it.How it works.Handling the dialog eventHow to do it.How it works.See alsoCreating dialogs using the SysOperation frameworkGetting readyHow to do it.Building a dynamic formHow to do it.How it works.Adding a form splitterHow to do it.How it works.Creating a modal formHow to do it.How it works.There's more.See alsoModifying multiple forms dynamicallyHow to do it.How it works.Storing the last form valuesHow to do 899101101102

How it works.Using a tree controlHow to do it.How it works.See alsoAdding the View details linkHow to do it.How it works.Selecting a form patternHow to do itFull list of form patternsHow to do it.Creating a new formGetting readyHow to do it.How it 1126Chapter 3: Working with Data in Forms127IntroductionUsing a number sequence handlerHow to do it.How it works.See alsoCreating a custom filter controlHow to do it.How it works.See alsoCreating a custom instant search filterHow to do it.How it works.See alsoBuilding a selected/available listHow to do it.How it works.There's more.Creating a wizardHow to do it.How it works.Processing multiple recordsHow to do 146147151152162164164

How it works.Coloring recordsGetting readyHow to do it.How it works.See alsoAdding an image to recordsHow to do it.How it works.There's more.Displaying an image as part of a formSaving a stored image as a fileChapter 4: Building oductionCreating an automatic lookupHow to do it.How it works.There's more.Creating a lookup dynamicallyHow to do it.How it works.There's more.Using a form to build a lookupHow to do it.How it works.See alsoBuilding a tree lookupHow to do it.How it works.See alsoDisplaying a list of custom optionsHow to do it.How it works.There's more.Displaying custom options in another wayHow to do it.How it works.There's more.Building a lookup based on the record 93193193196197197198200200200201204204207

How to do it.How it works.There's more.Building the browse for folder lookupHow to do it.How it works.There's more.Creating a color picker lookupHow to do it.How it works.Chapter 5: Processing Business TasksIntroductionUsing a segmented entry controlHow to do it.How it works.There's more.See alsoCreating a general journalHow to do it.How it works.There's moreSee alsoPosting a general journalHow to do it.How it works.See alsoProcessing a project journalHow to do it.How it works.There's more.Creating and posting a ledger voucherHow to do it.How it works.See alsoChanging an automatic transaction textGetting readyHow to do it.How it works.There's 245248250250251251253253

Creating a purchase orderHow to do it.How it works.There's more.Posting a purchase orderHow to do it.How it works.There's more.Creating a sales orderHow to do it.How it works.There's more.Posting a sales orderHow to do it.How it works.There's more.Creating an electronic payment formatHow to do it.How it works.Chapter 6: Data 64265265266266271273IntroductionData entitiesGetting readyHow to do it.How it works.There's more.Building a data entity with multiple data sourcesHow to do it.How it works.There's more.Data packagesGetting ready.How to do it.There's more.See alsoData migrationGetting readyHow to do it.How it 302302303305308

Importing dataHow to do it.How it works.TroubleshootingGetting readyHow to do it.How it works.There's more.308308314314314315322326Chapter 7: Integration with Microsoft OfficeIntroductionConfiguring and using the Excel Data Connector add-inHow to do it.How it works.Using Workbook DesignerHow to do it.How it works.Export APIHow to do it.How it works.Lookup in Excel - creating a custom lookupHow to do it.How it works.Document managementHow to do it.How it works.There's more.Chapter 8: Integration with Power 344344346IntroductionConfiguring Power BIHow to do it.How it works.There's more.See alsoConsuming data in ExcelHow to do it.How it works.See alsoIntegrating Excel with Power BI346347347354355355356356361362363[]

How to do it.How it works.See alsoDeveloping interactive dashboardsHow to do it.How it works.Embedding Power BI visualsHow to do it.How it works.Chapter 9: Integration with Authenticating a native client appGetting readyHow to do it.How it works.There's more.See alsoCreating a custom serviceGetting readyHow to do it.How it works.Consuming custom services in JSONGetting readyHow to do it.How it works.There's more.Consuming custom services in SOAPGetting readyHow to do it.How it works.Consuming OData servicesGetting readyHow to do it.How it works.There's more.See alsoConsuming external web servicesGetting readyHow to do 396397397398400401401402405406406406406406

How it works.There's more.See also412413414Chapter 10: Improving Development Efficiency and PerformanceIntroductionUsing extensionsHow to do it.How it works.Caching a display methodHow to do it.How it works.There's more.Calculating code execution timeHow to do it.How it works.There's more.Enhancing insert, update, and delete operationsHow to do it.How it works.There's more.Using delete fromUsing update recordSet for faster updatesWriting efficient SQL statementsHow to do it.How it works.There's more.See alsoUsing event handlerHow to do it.How it works.There's more.Creating a Delegate methodGetting ready.How to do it.How it works.There's more.See 45447447447448[]

PrefaceAs a Dynamics 365 for Finance and Operations developer, your responsibility is to deliverall kinds of application customization, whether small adjustments or a bespoke modules.Dynamics 365 for Finance and Operations is a highly customizable system and requires asignificant amount of knowledge and experience to deliver quality solutions. One goal canbe achieved in multiple ways, and there is always the 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 applicationscreenshots and in-depth explanations. The recipes cover multiple Dynamics 365 forFinancial and Operations modules, so, at the same time, the book provides an overview ofthe functional aspects of the system for developers.What this book coversChapter 1, Processing Data, focuses on data manipulation. It explains how to build dataqueries, check and modify existing data, read and write external files, and use dataeffectively.Chapter 2, Working with Forms, covers various aspects of building forms in Dynamics 365for Finance and Operations. In this chapter, dialogs and their events are explained. Also,various useful features, such as splitters, tree controls, and checklists, are explained.Chapter 3, Working with Data in Forms, basically supplements Chapter 2, Working withForms, and explains the data organization in forms. The examples in this chapter includeinstructions for building filter controls on forms, processing multiple records, and workingwith images and colors.Chapter 4, Building Lookups, covers all kinds of lookups in the system. This chapter startswith a simple, automatically generated lookup, continues with more advanced ones, andfinishes with standard Windows lookups, such as the file selection dialog and the colorpicker.Chapter 5, Processing Business Tasks, explains how to use the Dynamics 365 for Finance andOperations business logic API. In this chapter, topics such as how to process journals,purchase orders, and sales orders are discussed. Other features, such as posting ledgervouchers, modifying transaction texts, and creating electronic payment formats, areincluded as well.

PrefaceChapter 6, Data Management, explains the data management and data entity concepts, howto build a data entity, data packages, and import and export in Dynamics 365 for Financialand Operations.Chapter 7, Integration with Microsoft Office, explains how to configure and use the ExcelData Connector add-in, and design Excel workbooks with the data feed from Dynamics 365from Operations using OData. It also covers how to use the export API and documentmanagement.Chapter 8, Integration with Power BI, explains the configuration of Power BI and itsintegration with Dynamics 365 for Financial and Operations to develop interactivedashboards and embed them in Dynamics 365 for Financial and Operations workspaces.Chapter 9, Integration with Services, explains how to use services in Dynamics 365 forFinancial and Operations. This chapter covers how to create services, authentication, SOAPapplications, JSON applications, and OData services. It also demonstrates how to consumeexternal services.Chapter 10, Improving Development Efficiency and Performance, presents a few ideas on howto make daily development tasks easier. It discusses how system performance can beimproved by following several simple rules. This chapter explains how to calculate codeexecution time, how to write efficient SQL statements, and how to properly cache displaymethods.Exceptions and considerationsThe code in this book follows the best practice guidelines provided by Microsoft, but thereare some exceptions:No text labels were used to make the code clearNo three-letter code was used in front of each new AOT objectNo configuration or security keys were usedObject 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 this book:Each recipe only demonstrates the principle and is not a complete solutionThe data in your environment might not match the data used in the recipes, sothe code might have to be adjusted appropriatelyFor each recipe, the assumption is that no other modifications are present in thesystem, unless it is explicitly specified[2]

PrefaceThe code might not have all the possible validations that are not relevant to theprinciple being explainedThe code might have more variables than required in order to ensure that it isclear for all audiencesSometimes, unnecessary code wrapping is used to make sure the code fits intothe page width of this book and is easily readableWhat you need for this bookAll the coding examples were performed in a Microsoft Azure-hosted Microsoft Dynamics365 for Financial and Operations environment. The following list of software from thevirtual image was used in this book:Microsoft Dynamics 365 for Financial and Operations (Update 6)Microsoft Visual studio 2015Microsoft Windows Server 2015 EnterpriseMicrosoft SQL Server 2016Microsoft Power BIMicrosoft Office Excel 2015Microsoft Office Word 2015Microsoft Internet ExplorerWindows NotepadAlthough all the recipes have been tested on the previously-mentioned software, they maywork on older or newer software versions with minor code adjustments. As Microsoft iscontinuously evolving on Dynamics 365 for Financial and Operations, we might see somedifferences while using the same code in older or newer updates of application. Stick to theconcept and customize or extend the application.Who this book is forIf you are a Dynamics AX developer primarily focused on delivering time-provenapplications, then this book is for you. This book is also ideal for people who want to raisetheir programming skills above the beginner level, and, at the same time, learn thefunctional aspects of Dynamics 365 for Financial and Operations. Some X codingexperience is expected.[3]

PrefaceSectionsIn this book, you will find several headings that appear frequently (Getting ready, How todo it, How it works, There's more, and See also).To 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 softwareor any 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 previoussection.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 kindsof information. Here are some examples of these styles and an explanation of their meaning.Code words in text, database table names, folder names, filenames, file extensions,pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Then, tooverride the data source's write() method."[4]

PrefaceA block of code is set as Str(CustGroup,CustGroup), FormDataSourceEventType::Written)]public void CustGroup OnWritten(FormDataSource sender,FormDataSourceEventArgs eWrite();}New terms and important words are shown in bold. Words that you see on the screen, forexample, in menus or dialog boxes, appear in the text like this: "Clicking the Next buttonmoves you to the next screen."Warnings or important notes appear like this.Tips and tricks appear like this.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 us developtitles that you will really get the most out of.To send us general feedback, simply e-mail feedback@packtpub.com, and mention thebook'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 www.packtpub.com/authors.Customer supportNow that you are the proud owner of a Packt book, we have a number of things to help youto get the most from your purchase.[5]

PrefaceDownloading the example codeYou can download the example code files for this book from your account athttp://www.packtpub.com. If you purchased this book elsewhere, you can visithttp://www.packtpub.com/support and register to have the files e-mailed directly to you.You can download the code files by following these steps:1.2.3.4.5.6.7.Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.Once the file is downloaded, please make sure that you unzip or extract the folder using thelatest version of:WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for LinuxThe code bundle for the book is also hosted on GitHub at https:/ / github. com/PacktPublishing/ Dynamics- 365- for- Finance- and- Operations- DevelopmentCookbook- Fourth- Edition. We also have other code bundles from our rich catalog ofbooks and videos available at https:/ / github. com/ PacktPublishing/ . Check themout!ErrataAlthough we have taken every care to ensure the accuracy of our content, mistakes dohappen. If you find a mistake in one of our books-maybe a mistake in the text or the codewe would be grateful if you could report this to us. By doing so, you can save other readersfrom frustration and help us improve subsequent versions of this book. If you find anyerrata, please report them by visiting http://www.packtpub.com/submit-errata, selectingyour book, clicking on the Errata Submission Form link, and entering the details of yourerrata. Once your errata are verified, your submission will be accepted and the errata willbe uploaded to our website or added to any list of existing errata under the Errata section ofthat title.[6]

PrefaceTo view the previously submitted errata, go tohttps://www.packtpub.com/books/content/support and enter the name of the book in thesearch field. The required information will appear under the Errata section.PiracyPiracy of copyrighted material on the Internet is an ongoing problem across all media. AtPackt, 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 copyright@packtpub.com with a link to the suspected piratedmaterial.We appreciate your help in protecting our authors and our ability to bring you valuablecontent.QuestionsIf you have a problem with any aspect of this book, you can contact us atquestions@packtpub.com, and we will do our best to address the problem.[7]

1Processing DataIn this chapter, we will cover the following recipes:Creating a new project, package, and modelCreating a new number sequenceRenaming the primary keyAdding 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 checksUsing the date effectiveness featureIntroductionThis chapter focuses on data manipulation exercises in all new Dynamics 365 for Financeand Operations. These exercises are very useful when doing data migration, systemintegration, custom reporting, and so on. Here, we will discuss how to work with queryobjects from the X /C# code. We will also discuss how to reuse macros in X SQLstatements and how to execute SQL statements directly to the database. This chapter willexplain how to rename primary keys, how to merge and copy records, how to adddocument handling notes to selected records, and how to create and read XML and commaseparated files. The chapter ends with a recipe about the date effectiveness feature.

Processing DataCreating a new project, package, and modelElements in Dynamics 365 for Finance and Operations represent every individual elementof AOT such as class, table, form, and so on. Elements in Dynamics 365 for Finance andOperations are stored on disk as XML files; these files contain the metadata and source codefor the element. The XML files are the unit of Source Control.Projects works the same as AX2012, but in D365 an element can be customized only oncethey are added to a specific Visual Studio project. The project may only belong to onemodel.A Dynamics 365 for Finance and Operations model is a group of elements. Standardelements are part of a standard model; you can add them into your model and docustomization. A model is a design-time concept. An example of models: warehousemanagement model, a project accounting model, and more. Models can have one or moreprojects. Models may only belong to one package.A Dynamics 365 for Finance and Operations package is a deployment and compilationunit of one or more models. It includes model metadata, binaries, cubes, and otherassociated resources. One or more D365 packages can be packaged into a deploymentpackage, which is the vehicle used for deployment on UAT and production environments.Packages are packaged into a deployable package file for deployment to Sandbox orproduction environments. A package can have one or more models. Packages can havereferences to other packages, just like .NET assemblies can reference each other.How to do it.To create a new project, follow these steps:1.2.3.4.5.6.7.Open Visual Studio as admin.On the File menu, point to New, and then click Project.In the list of template types, expand the Installed node.Expand the Templates node.Select the Microsoft Dynamics 365 for Operations category.Select the D365 Project template.Enter the name and location for the new project.[9]

Processing Data8. Select Create directory for solution if you want to create a new solution for thisproject, uncheck if you want to add in your current solution.To create a new model, follow these steps:1. Open Visual Studio as admin.2. On the Dynamics 365 menu, point to Model management and select Createmodel.[ 10 ]

Processing Data3. Give a model, publisher name, and other values:[ 11 ]

Processing Data4. Now here you can create a new package or select any existing package. We couldcreate a new package and select the required package as referenced packages:[ 12 ]

Processing Data5. Double-check the summary with details. Select Create new project if you want tocreate a new project in this model once created. You can mark this model to allyour new projects by selecting options:There's more.As you saw, there was one more step while creating a model, Select referenced packages.When you create your own package you can select from an existing package to add them asreferences in your new package. You may need to add some standard package reference ifyou want to add them into your customization.[ 13 ]

Processing DataHere are the steps to create a new package:1. Open Visual Studio as admin.2. On the Dynamics 365 menu, point to Model management and select Createmodel.3. Give a model, publisher name, and other values.4. On the next step select Create new package5. Give a name to your package.6. Next select the existing package as a reference to this new package.7. Click on Finish.So now you have your own model with a new package.Creating a new number sequenceNumber sequences in Dynamics 365 for Finance and Operations are used to generatespecifically formatted numbers for record identification. These number sequences can beanything from voucher numbers or transaction identification numbers to customer orvendor accounts.When developing custom functionality, often one of the tasks is to add a new numbersequence to the system in order to support newly created tables. Adding a numbersequence to the system is a two-step process. First, we create the number sequence itself;second, we start using it in some particular form or from the code.D365 contains a list of NumberSeqApplicationModule derivative classes, which hold thenumber sequence's setup data for the specific module. These classes are read by the numbersequence wizard, which detects existing number sequences and

Dynamics AX four times in a row, and he has held this title since 2013. He shares his experience with Dynamics AX on his blog Axapta V/s Me. Deepak has also worked on the following Packt books: 1. Microsoft Dynamics AX 2012 R3 Reporting Cookbook 2. Dynamics AX 2012 Reporting Cookbook 3