Extending Microsoft Dynamics NAV 2016 Cookbook - Alexander Drogin - E-Book

Extending Microsoft Dynamics NAV 2016 Cookbook E-Book

Alexander Drogin

0,0
44,39 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Microsoft Dynamics NAV is an enterprise resource planning (ERP) software suite for organizations. The system offers specialized functionality for manufacturing, distribution, government, retail, and other industries. Its integrated development environment enables customizations with minimal disruption to business processes.
The book starts explaining the new features of Dynamics NAV along with how to create and modify a simple module. Moving on, you will learn the importance of thinking beyond the boundaries of C/AL development and the possibilities opened by with it. Next, you will get to know how COM can be used to extend the functionalities of Dynamics NAV.
You’ll find out how to extend the Dynamics NAV 2016 version using .NET interoperability and will see the steps required to subscribe to .NET events in order to extend Dynamics NAV. Finally, you’ll see the cmdlets available to manage extension packages.
By the end of the book, you will have the knowledge needed to become more efficient in selecting the extending methods, developing and deploying them to the Dynamics NAV, and practicing the best practices.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 443

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Extending Microsoft Dynamics NAV 2016 Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
Why subscribe?
Customer Feedback
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Writing Basic C/AL Code
Introduction
Installing NAV Development Environment
Getting ready
How to do it...
How it works...
Application object triggers
How to do it...
How it works...
NAV Development Environment - C/SIDE
How to do it...
How it works...
Compiling objects and error handling
How to do it...
How it works...
Importing and exporting application objects
How to do it...
How it works...
Basic C/AL programming
How to do it...
How it works...
Accessing the database in C/AL
How to do it...
How it works...
Configuring NAV Server
Getting ready
How to do it...
How it works...
Creating a NAV user account
Generating a self-signed certificate
Obtaining the certificate thumbprint
Changing the server configuration
Configuring web server
Getting ready
How to do it...
How it works...
There's more...
See also
2. Advanced C/AL Development
Introduction
Creating custom tables
How to do it...
How it works...
Understanding database triggers
How to do it...
How it works...
Implementing a user interface with pages
How to do it...
How it works...
Linking datasources in subpages
How to do it...
How it works...
Working with page triggers
How to do it...
How it works...
Presenting related data in FactBoxes
How to do it...
How it works...
Designing reusable code
How to do it...
How it works...
See also
Accessing temporary tables
How to do it...
How it works...
See also
Role-Tailored client and role centers
How to do it...
How it works...
Assigning role centers to user profiles
Getting ready
How to do it...
How it works...
Simplifying data access with queries
How to do it...
How it works...
Improving performance with indexes
How to do it...
How it works...
Linking datasources with advanced queries
How to do it...
How it works...
Exchanging data with XMLPort objects
How to do it...
How it works...
Designing the user menu
How to do it...
How it works...
Referencing records and fields via RecordRef and FieldRef
How to do it...
How it works...
Working with single instance codeunits
How to do it...
How it works...
Running tasks in background sessions
How to do it...
How it works...
See also
3. Reporting and Data Analysis
Introduction
Designing reports in Visual Studio
How to do it...
How it works...
Developing Word layout for RDLC reports
Getting ready
How to do it...
How it works...
There's more...
Writing C/AL code in a report
Getting ready
How to do it...
How it works...
Designing the report request page
Getting ready
How to do it...
How it works...
Writing RDLC code in a report
Getting ready
How to do it...
How it works...
Using built-in expressions in the report layout designer
Getting ready
How to do it...
How it works...
Including user interaction in reports
Getting ready
How to do it...
How it works...
Updating NAV data with the Excel add-in
Getting ready
How to do it...
How it works...
Retrieving data from NAV with Power Query
Getting ready
How to do it...
How it works...
Creating pivot tables with Power Query
Getting ready
How to do it...
Analyzing data with Power BI
Getting ready
How to do it...
How it works...
Data hierarchies in Power BI reports
How to do it...
Statistical data analysis in Power BI with R
Getting ready
How to do it...
How it works...
Sales forecast in Power BI with R
Getting ready
How to do it...
How it works...
Designing server-side reports in SQL Server Reporting Studio
Getting ready
How to do it...
How it works...
There's more...
4. .NET Interoperability in C/AL
Introduction
Using .NET assemblies in C/AL
How to do it...
How it works...
Understanding static classes and methods
How to do it...
How it works...
Developing server-side extensions
How to do it...
How it works...
Developing client-side extensions
How to do it...
How it works...
Working with generics in C/AL
How to do it...
How it works...
Working with interfaces
How to do it...
How it works...
Accessing collections with the FOREACH statement
How to do it...
How it works...
Working with .NET strings and arrays in C/AL
How to do it...
How it works...
Invoking .NET methods via reflection
How to do it...
How it works...
Handling exceptions with try functions
How to do it...
How it works...
Handling .Net events in C/AL
How to do it...
How it works...
Developing your own .NET class
How to do it...
How it works...
Starting processes in separate threads
Getting ready
How to do it...
How it works...
5. Extending C/AL with COM Components
Introduction
Using COM type libraries in C/AL
How to do it...
How it works...
Mapping COM datatypes to C/AL
How to do it...
How it works...
Disposing of COM objects
How to do it...
How it works...
Working with the Variant datatype
How to do it...
How it works...
Sending data to the Excel automation server
How to do it....
How it works...
Creating a Word document using automation objects
How to do it...
How it works...
Creating and registering a COM component that can be used in NAV
How to do it...
How it works...
6. SharePoint Integration
Introduction
Creating a developer SharePoint site
How to do it...
Developing NAV apps for SharePoint
Getting ready
How to do it...
How it works...
Embedding NAV page objects in site pages
Getting ready
How to do it...
How it works...
Publishing NAV reports in SharePoint
How to do it...
Deploying applications on SharePoint
How to do it...
How it works...
Configuring user permissions
How to do it...
How it works...
7. Control Add-ins
Introduction
Developing a control add-in
How to do it...
How it works...
Signing the control add-in assembly
How to do it...
How it works...
Registering and embedding a control add-in
How to do it...
How it works...
JavaScript in web, phone, and tablet clients
Getting ready
How to do it...
How it works...
Installing and using JavaScript control add-ins
How to do it...
How it works...
Sending events from add-ins to NAV server
Getting ready
How to do it...
How it works...
Linking add-ins with the database
How to do it...
How it works...
Exchanging data with add-ins
How to do it...
How it works...
8. Web Services
Introduction
Publishing a SOAP web service
How to do it...
Calling object methods in SOAP web services
How to do it...
How it works...
Exposing and consuming OData web services
How to do it...
How it works...
Querying NAV OData web services with LINQ
How to do it...
How it works...
Updating NAV data through web services
Getting ready
How to do it...
How it works...
Securing access to web services
Getting ready
How to do it...
How it works...
Consuming the NAV web service from Java
Getting ready
How to do it...
How it works...
9. Events and Extension Packages
Introduction
Subscribing to business and integration events
How to do it...
How it works...
Subscribing to global events
How to do it...
How it works...
Using database trigger events
How to do it...
How it works...
Extending UI with page trigger events
How to do it...
How it works...
Creating custom events
How to do it...
How it works...
Subscribing to events in runtime
How to do it...
Developing an extension
Getting ready
How to do it...
How it works...
Installing an extension
Getting ready
How to do it...
10. PowerShell
Introduction
Managing the database
How to do it...
How it works...
Managing users and user permissions
How to do it...
How it works...
Managing companies
How to do it...
Administering NAV services with PowerShell
How to do it...
How it works...
Handling application objects
How to do it...
How it works...
Merging application objects
How to do it...
How it works...

Extending Microsoft Dynamics NAV 2016 Cookbook

Extending Microsoft Dynamics NAV 2016 Cookbook

Copyright © 2017 Packt Publishing

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.

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 Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: January 2017

Production reference: 1130117

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham 

B3 2PB, UK.

ISBN 978-1-78646-060-8

www.packtpub.com

Credits

Author

Alexander Drogin 

Copy Editor

Safis Editing

Reviewer

Oleg Romashkov

Project Coordinator

Vaidehi Sawant 

Commissioning Editor

Aaron Lazar

Proofreader

Safis Editing

Acquisition Editor

Sonali Vernekar

Indexer

Mariammal Chettiyar

Content Development Editor

Siddhi Chavan

Production Coordinator

Arvindkumar Gupta

Technical Editors

Dhiraj Chandanshive

Bhavin Savalia

About the Author

Alexander Drogin started working with Navision Attain version 3.01 in 2002 as a software developer at a consulting company. After 7 years of development, he shifted his focus to end-user support. In 2012, he joined the Microsoft Russia development team as a software engineer in testing, and worked on NAV test automation. Currently, he leads the sustained engineering team in the Supply Chain Management area at Microsoft.

I would like to thank my colleagues who helped me in my work on this book--Oleg Romashkov, for reviewing the book and testing the code samples, whose valuable feedback on the content helped improve the quality of the book; and Sergey Iazovskiy, who helped me in designing numerous .NET examples and solving issues with .NET Interoperability.

About the Reviewer

Oleg Romashkov has been a NAV developer since 2001. He worked for eight years with Microsoft by developing new features and country localizations for NAV 4.00 – NAV 2015. Also he spent 7 years working for a few MS partners where he implemented NAV for more than 20 customer projects.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development 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 Feedback

Thank you for purchasing this Packt book. We take our commitment to improving our content and products to meet your needs seriously—that's why your feedback is so valuable. Whatever your feelings about your purchase, please consider leaving a review on this book's Amazon page. Not only will this help us, more importantly it will also help others in the community to make an informed decision about the resources that they invest in to learn.

You can also review for us on a regular basis by joining our reviewers' club. If you're interested in joining, or would like to learn more about the benefits we offer, please contact us: [email protected].

Preface

Microsoft Dynamics NAV 2016 is a modern enterprise resource planning application that covers a wide range of user demands. The NAV technical platform gives end-users and applications developers access to cutting-edge technologies, while the front-end business application meets most of the daily needs of small and medium-sized companies. Still every business is individual and must face unique challenges, and it is impossible to foresee all demands from business users to the ERP software.

To satisfy the requirements of each unique company, NAV offers a wide variety of tools to extend standard functionality. This toolset includes the internal development environment that enables developers to tailor the business application to individual needs. Besides, in this book you will find multiple recipes guiding you through the integration of external libraries developed in .NET languages, into NAV applications.

With the recipes in this book, you will customize NAV applications, develop business logic, extend user interfaces, and organize solutions with custom role centers arranged specifically for each functional role in the organization.

The book then proceeds to reporting tools, which are the essential part of any enterprise software. You will build informative and interactive reports with built-in NAV tools, and use Visual Studio reporting tools and SQL Server Reporting Services to design and publish reports. Readers not so skillful in application development, but proficient in Excel or Power BI, will learn how to load data from NAV into their favorite reporting system and model comprehensive reports.

System administrators will find useful recipes on different aspects of NAV server configuration and security features.

What this book covers

Chapter 1, Writing Basic C/AL Code, describes NAV 2016 server and client installation and configuration and introduces the NAV 2016 development environment along with the basics of the NAV application language, C/AL.

Chapter 2, Advanced C/AL Development, delves deeper into C/AL development and NAV application objects. You will learn how to store your data in tables, present the data in UI with pages, export, import, and structure the data in XMLPorts and queries, and write efficient and reusable code.

Chapter 3, Reporting and Data Analysis, introduces the reader to NAV reporting capabilities. The chapter begins with an in-depth description of C/SIDE Report objects, shifting to integration with external tools in the second part. You will learn how to present NAV data in different reporting systems, including Power BI, SQL Server Reporting Services, and MS Excel.

Chapter 4, .NET Interoperability in C/AL, covers the integration of .NET assemblies into the NAV client application language. Recipes in this chapter give an overview of the DotNet data type in NAV, various extensions of C/AL aimed at supporting the .NET interoperability and development of custom .Net assemblies and their integration into NAV.

Chapter 5, Extending C/AL with COM Components, walks the reader through developing COM components and the integration of COM into the NAV application.

Chapter 6, SharePoint Integration, provides an overview of corporate web portals on the SharePoint platform and various ways to integrate NAV elements into the corporate sites.

Chapter 7, Control Add-ins, covers extending the NAV user interface with custom controls written in .NET languages, such as C#, or in JavaScript.

Chapter 8, Web Services, covers publishing SOAP and OData web services from NAV to expose data and functionality through standard communication interfaces over the Web. You will learn how to publish and consume NAV web services and protect web service endpoints from unauthorized access.

Chapter 9, Events and Extension Packages, covers the events which have been introduced in NAV 2016 to allow application developers to extend NAV functionality without modification to the base application code. We will go through subscribing to different types of events to receive notifications of changes in database, user actions, and events in the app business logic. The chapter then covers developing extension packages that utilize the idea of events to bind third party extensions to NAV application code.

Chapter 10, PowerShell, gives an overview of the reach set of PowerShell cmdlets available in NAV shell.

What you need for this book

Microsoft Dynamics NAV 2016

Microsoft SQL Server 2012 Service Pack 2 Express, Standard, or Enterprise

Microsoft Visual Studio 2012 Professional, Premium or Ultimate edition

Instead of Visual Studio 2012, you can use its free version, Visual Studio Code, to develop .NET code in C#

To design report layouts, Visual Studio is also required. VS report designer can be replaced with the free Microsoft SQL Server 2012 Report Builder

Microsoft Office 2016. The book covers different aspects of integration between NAV and Office applications.

Power BI is required for data analysis in Chapter 3, Reporting and Data Analysis. 

The R language environment. Two recipes in Chapter 3, Reporting and Data Analysis, use R scripts for statistical analysis of NAV data. These will require R.

SharePoint Server 2016 or SharePoint Online subscription

Java SE Development Kit 8 and an IDE for Java development, for example, Eclipse.

Windows Management Framework 3.0 must be installed to use features of PowerShell 3.0. Installation is required on Windows 7 or Windows Server 2008. In Windows 8, Windows Server 2012 and higher versions, PowerShell 3.0 is integrated into the operating system.

Who this book is for

This book is intended for NAV developers, administrators, and advanced users who want to take the most from NAV implementation. The reader is expected to be familiar with basic programming and have a good knowledge of NAV business application. Understanding of object-oriented principles, as well as some experience of programming in C# and/or Java would be helpful.

Sections

In 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).

To give clear instructions on how to complete a recipe, we use these sections as follows:

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or 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 previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of 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: "Open the ClientUserSettings.config file located in the AppData directory."

A block of code is set as follows:

SalesLine.SETFILTER(   "Document Type",'%1|%2',   SalesLine."Document Type"::Order,   SalesLine."Document Type"::Invoice);

Any command-line input or output is written as follows:

Install-NAVApp -ServerInstance DynamicsNAV90 ` -Name "ILE Posting DateTime"

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 Next, then select the option Do not export the private key."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the 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 or contributing to a book, see our author guide at www.packtpub.com/authors .

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://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:

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.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Extending-Microsoft-Dynamics-NAV-2016-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although 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 be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy 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 come across any illegal copies of our works in any form on the Internet, please provide us with the 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.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Chapter 1.  Writing Basic C/AL Code

In this chapter we will cover the following recipes:

Installing NAV Development EnvironmentApplication object triggersNAV Development environment - C/SIDECompiling objects and error handlingImporting and exporting application objectsBasic C/AL programmingAccessing the databaseConfiguring NAV ServerConfiguring Web Server

Introduction

Microsoft Dynamics NAV 2016 has a rich toolset for extending functionality. Additionally, a wide number of external tools can be connected to the NAV database to enrich data processing and analysis experience. But C/AL, the internal NAV application language, is still the primary means of enhancing user experience when it comes to developing new functionality.

This chapter will introduce you to the basics of NAV Client Application Language development, from installing the development environment and configuring the server to the fundamentals of data manipulation with C/AL.

C/AL Development is framed around objects representing different kinds of functionality and designers associated with each object type. While the details of design for each type of objects will be covered in the next chapter, this chapter will introduce readers to the concept of objects and triggers and present the integrated development environment.

In the last recipe we will concentrate on secure access to the NAV server from the web and mobile client.

Installing NAV Development Environment

This introductory recipe describes the basic steps of installing the C/SIDE - NAV development environment. This is the initial requirement for all recipes involving the development of NAV objects.

Getting ready

Microsoft Dynamics NAV 2016 server and development environment can be installed on a computer running Windows 7 Home edition or higher versions. But the recommended minimum requirement is Windows 7 Service Pack 1 Professional edition. Some of the features described in this book are supported only on Windows 7.1 Professional or higher versions.

If you need detailed instructions on system requirements, refer to the MSDN article System Requirements for Microsoft Dynamics NAV 2016. Further in this book, we will assume that the minimum requirements described in this article are satisfied.

How to do it...

Run setup.exe from the installation media.After accepting the licensing terms, you will have two setup modes to choose from:
Install Demo: This installs a preconfigured set of components for the demonstration environment without manual configuration.Choose an installation option: You can choose which components to install and manually configure setup options.
Click the Choose an installation option. Install Demo mode is convenient for a quick unattended setup, but it won't install all components required for the recipes in this book.In the list of installation options, choose Developer and click Customize. Options that should be installed include:
ClientDevelopment Environment (C/SIDE)Microsoft Office Excel Add-inAdministration ToolServerMicrosoft Office Outlook IntegrationSQL Server Database ComponentsDemo DatabaseMicrosoft Office Outlook Add-inWeb Server Components
Click Next and review the installation parameters.If you have the Microsoft SQL Server installed on your development computer, all parameters can be left with their default values. Otherwise specify the SQL Server name and SQL Server instance name.Click Apply to run the installation.After installation completes, run the Dynamics NAV 2016 Development Environment from the Start menu. C/SIDE client will connect to the SQL Server database created during the installation process.The following is the Object Designer window that opens when you connect to the database in the NAV Development Environment:

Note

If you don't see this window after connecting to the database, click Object Designer in the Tools menu or press Shift + F12.

How it works...

We chose to install Dynamics NAV 2016 components required for the recipes in this book. Extended testability options, automated data capture system, and click Once installation are not covered in the book and remain optional.

The help server must be installed if you intend to use local help files. If you prefer looking for information on MSDN or online communities, it can be skipped. All reference documents installed along with the help server are available online.

Installation will create and start a service named DynamicsNAV90. You can find it in your computer's services list as Microsoft Dynamics NAV Server [DynamicsNAV90].

To verify the service installation, run the Dynamics NAV 2016 Client from the Start menu, click Select Server in the application menu, and enter the server address:

localhost:7046/DynamicsNAV90

The web server components installation creates a web site called DynamicsNAV90 in the Internet Information Services.

Dynamics NAV can now be accessed in a web browser on the following address:

http://localhost:8080/DynamicsNAV90

Application object triggers

Trigger is a piece of code that is executed in response to some external action. All objects in NAV, except Menu Suite, have a set of triggers that can be programmed to respond to certain user's or system actions. For example, when a page with data is displayed on the screen, a sequence of triggers are fired in the application.

OnInit: Page object is initializedOnOpenPage: Page is displayedOnAfterGetRecord: Table record displayed on the page is read from the databaseOnAfterGetCurrRecord: Table record currently selected is read from the database

There are other triggers reacting to UI elements, data modifications or to external events from .NET components. We will delve deeper into different types of objects and corresponding triggers later in the book. Now let's create a code module (called a codeunit in NAV) with a single trigger that fires when the object is executed.

How to do it...

In the left column of the object designer, click on the codeunit object.Click the New button in the bottom part of the Object Designer form. A new codeunit object is created.Each object in NAV must have a unique name and number that are assigned to the object when it is saved in the database. Click File | Save and fill in the ID and Name fields in the Save As dialog. Leave the Compiled option checked:The new codeunit has two system-created triggers. Position the cursor in the empty line below Documentation and write a short description of your new codeunit. For example, This is my first NAV codeunit:Move the cursor to the OnRun trigger and enter a line of code that will be executed when the trigger fires: MESSAGE('Codeunit OnRun trigger'); Save the codeunit and close the editor window.In the object designer, select the codeunit 50000 and click the Run button located under the list objects. This action will start the role-tailored client and execute the codeunit. Execution of the codeunit fires its OnRun trigger. When run, it will show a message box with the codeunit OnRun trigger in it.In the Object Designer window, create another codeunit, save it with ID 50001 and name it NAV Codeunit Runner.Write a line of code in the OnRun trigger that will invoke the first codeunit: CODEUNIT.RUN(CODEUNIT::"First NAV Codeunit"); Close the code editor and run codeunit 50001 from the object designer. The same message box with the codeunit OnRun trigger will be shown.

How it works...

In most cases all triggers supported by an object are available in the C/AL code editor as soon as the new object is created. There are several exceptions when a trigger must be explicitly declared as a function having specific signature, but these triggers are outside the material covered in this chapter. All application triggers we are going to work with will be created by the C/SIDE without developer's intervention.

All NAV objects that can execute C/AL code (that is, all objects except Menu Suite), have the Documentation section. This object section is often referred to as a trigger, and looks like a function in the code editor, although it is never executed. Documentation is used to comment the object - usually comments applicable to the object in general are placed here.

Codeunit objects support only one trigger OnRun that is called when the object is executed. In Step 7 we run the codeunit manually from the object designer. In the steps, Step 8 to Step 10, the same trigger fires when execution of the codeunit is initiated from another codeunit's OnRun trigger. This way, triggers can be chained, when the execution of an object can cause another trigger to fire.

To run the codeunit we use the system function CODEUNIT.RUN which takes the codeunit ID as the parameter. It can simply be a number (50000). Or we can refer to the codeunit by its name, making the code more human-readable.

NAV Development Environment - C/SIDE

C/SIDE is the NAV integrated development environment where we create application objects, design the user interface, and write code. The next recipe gives an overview of the environment and presents some new features introduced to the IDE in NAV 2016.

How to do it...

Open NAV Object Designer and create a new codeunit.In the C/AL Code Editor window, click C/AL Globals in the View menu to access the list of global variables, text constants, and functions.Select the Functions tab in the C/AL Globals window and type the function name. Name the new function Multiply. By default, a new function is created with the Local attribute. Local functions are visible only inside the object where they are declared and cannot be called from other objects.Close the declarations window. Now you can see the new function Multiply in the C/AL editor.Position the cursor on an empty line inside the function and open the C/AL Locals window. Here you can declare local variables available inside the function, as well as the function's parameters and return type.In the Parameters tab, enter the name and the type of a new function parameter you want to declare. Create a parameter X of type Integer. To do this, enter X in the Name field and choose Integer from the drop-down list in the DataType field.Add one more integer variable, Y:Switch to the Return Value tab and fill the Return Type field. Select Integer in the list of types. Close the window and review the changes to the function in the code editor. Now you have declared a function that takes two Integer parameters and returns an Integer result.We want this function to return the result of the multiplication of two parameters X and Y. EXIT statement serves this purpose, so the function's code should consist of one line: EXIT(X * Y). Start typing the first statement EXIT. As you type, IntelliSense will suggest possible language structures:

When you see the function EXIT in the suggested autocompletion list, select it by pressing the up and down keys on the keyboard and press Enter to confirm the selection.

Complete the function. Enter the line EXIT(X * Y);.Move to the OnRun trigger, declare a local Integer variable Z and start typing the invocation of the function Multiply: Z := Multiply(5,8). As you type the first symbols of the function name, IntelliSense will show a list of suggestions. After you type the opening bracket before entering the function arguments, IntelliSense will show the parameter names and types along with the function return type:

How it works...

Unlike many other programming languages, like C++, C# or Java, variables and functions declaration in C/SIDE are separated from the program text. All global and local declarations are accessed in the code editor via the main menu.

Variables and text constants declared in the C/AL Locals can be used only in the function where they are created. C/AL Globals declarations are accessible from any function in the same object.

Functions can only be created in the C/AL Globals and can be accessed from anywhere in the same object. Function do not have to return a value and can be declared without any return type. If you want the function to return a result, you must assign a return type to it and use the EXIT statement to return a value to the caller function.

In the steps from Step 7 to Step 11 we demonstrate how IntelliSence integrates with the NAV development environment. IntelliSense is a Microsoft code completion feature widely used in Visual Studio. It aides a developer in coding by suggesting possible variable and function names, function parameters, and many other things. Such code hints speed up coding and reduce the risk of typos, and many plain coding mistakes.

Compiling objects and error handling

The C/AL code in NAV objects is not executable itself. Before a C/AL object can be used in the application, it must be compiled into binary code that can be run.

The C/AL compiler is a part of the C/SIDE development environment, and can be run either from the object designer or in the code editor while writing the application code.

How to do it...

Open NAV object designer and create a new codeunit.In the OnRun trigger, declare a local variable CurrDate of type Integer:

Name

DataType

CurrDate

Integer

Add two code lines in the OnRun trigger: CurrDate := TODAY; MESSAGE('Today is %1,CurrDate); The preceding code contains two errors. Let's try to compile it. Press F11 or click Compile in the Tools menu to compile the code. A message will inform you about an incorrect type conversion and position the cursor in the line containing the first error.Click Save in the File menu, assign an ID and name to the new codeunit, uncheck the Compiled checkmark in the dialog box, and click OK:The object is saved without compiling. The Compiled column in object designer does not have a checkmark, which indicates that the object is uncompiled:

Note

Uncompiled objects cannot be executed.

Select the codeunit 50002 and click Run in the object designer. An error message will inform you that the object must be saved in the compiled form before it can be run.Close the message dialog and click Design.To fix the first error in the code, open C/AL Locals in the OnRun trigger and change the data type of the CurrDate variable. Replace Integer with Date.After fixing the error, Click Compile. This time, compilation will stop on the second line informing you about a syntax error.Insert the missing apostrophe to close the text constant and fix the erroneous line. The following is the correct function code: CurrDate := TODAY; MESSAGE('Today is %1',CurrDate); Save the object, this time with the Compiled option, and run it from the object designer.

How it works...

Each of the two lines at the beginning of this exercise contains an error. In the first line we are assigning a date to an integer variable, and the second line is missing an apostrophe closing the text constant. When an object is compiled, only the first error is shown if the compilation breaks. Errors must be fixed one by one.

In Step 5 we are saving the object without compiling. This option is often used in the middle of the development process, when the object is incomplete and not syntactically correct yet.

It is not necessary to open objects in the code editor to compile them one at a time. It is possible to compile multiple objects in one batch. Select all objects you want to compile in the object designer and press F11 - it will run compilation for all selected objects. If several objects are selected and there are compilation errors in any of them, the list of errors will be displayed in a summary table.

Importing and exporting application objects

Dynamics NAV application objects can be exported in plain text format and edited with external tools. Although editing code outside C/SIDE is not as convenient as doing it in the C/SIDE code editor, this may be useful when, for example, you need to compare different versions of the same object with a file comparison program or export the source file into a code repository.

Objects can also be exported and imported in binary format as .fob files. Binary files cannot be edited directly, so the format is convenient when you do not want to disclose the internal application code. Besides, .fob files do not require a developer's license to be imported, and therefore are used to deploy objects on the customer's site.

How to do it...

First let us export an object into a text file and edit it outside C/SIDE editor.

Open NAV object designer and create a new codeunit.In the OnRun trigger, add a single line of code:        MESSAGE('Hello World'); Click Save, fill in the ID and Name fields: 50003 HelloWorld, close the code editor.Select the codeunit 50003 in the object designer and click Export in the File menu.Choose the folder where you want to export the codeunit to and name the file COD50003.txt.Select Text Format (*.txt) in the File Type drop-down list and click Save.In a file manager, locate the file COD50003.txt and open it in a text editor. This is how the exported object looks in a text editor:        OBJECT Codeunit 50003 Hello World        {        OBJECT-PROPERTIES        {        Date=22.07.16;        Time=23:44:09;        Modified=Yes;        Version List=;        }        PROPERTIES        {        OnRun=BEGIN MESSAGE('Hello World');        END;        }        CODE        {        BEGIN        END.        }        } In the object text locate the line MESSAGE('Hello World'); and replace the message text, MESSAGE('Exported NAV object');.Save the object and close the editor.Return to NAV object designer, click Import from the File menu, select Text Files in the file type filter, and choose the file COD50003.txt.Click Design in the object editor window and review the object code. It contains code modified outside of the C/AL editor.

Note

If the object you are importing already exists in the application, it will be replaced with the new version without warning. Any changes made to the object will be lost.

In the object designer, select the codeunit 50003 we created in the previous step and click Export in the File menu.Select Dynamics NAV Object Format (*.fob) in the File Type drop-down list.Choose the folder where you want to export the codeunit to and name the file COD50003. It will be automatically assigned an extension .fob. Save the file.Back in the object designer click Design to edit the codeunit and replace the message text with the empty string: MESSAGE(''). Then save the codeunit and close the code editor.In the object designer, click Import from the File menu. In the Import Objects dialog, select Dynamics NAV Object Files in the file type filter, locate the file COD50003.fob, and click Open.C/SIDE will warn you that there is an object with conflicting versions in the database. Click OK to switch to Import Worksheet:Click OK to import the object replacing the codeunit existing in the database.

How it works...

When importing application objects in plain text format, C/SIDE does not check objects for possible conflicts. Merging code must be done manually by the developer.

Binary files are automatically checked for conflicts during the import if there are objects with the same ID in the database and in the file being imported. If both files have the Modified flag checked, this is considered as a conflict that must be resolved in the Import Worksheet dialog. In the Action field, you can choose how to handle conflicting objects. Possible options are:

Replace to replace the object in the database with the new one.Skip to leave the existing object unchanged and ignore the new object.Merge to automatically merge changes from both objects (only applicable for tables)

Accessing the database in C/AL

Microsoft Dynamics NAV is an information system, and its primary purpose is to collect, store, organize, and present data. Therefore C/AL has a rich set of functions for data access and manipulation.

The next example will present a set of basic functions to read data from the NAV database, filter and search records in a table, and calculate aggregated values based on database records.

In this example, suppose we want to calculate the total amount in all open sales orders and invoices for a certain customer in a specified period.

How to do it...

In the NAV Object Designer, create a new codeunit object.Open the codeunit you just created in code designer, position it in the OnRun trigger, and open the local declarations window (C/AL Locals). Declare the following local variables:

Name

DataType

Subtype

SalesLine

Record

Sales Line

StartingDate

Date

EndingDate

Date

Close the local variables window and declare a global text constant in the C/AL Globals window:

Name

ConstValue

SalesAmountMsg

Total amount in sales documents: %1

Return to the code editor and type the function code: StartingDate := CALCDATE('<-1M>',WORKDATE); EndingDate := WORKDATE; SalesLine.SETRANGE("Sell-to Customer No.",'10000'); SalesLine.SETFILTER( "Document Type",'%1|%2', SalesLine."Document Type"::Order, SalesLine."Document Type"::Invoice); SalesLine.SETRANGE( "Posting Date",StartingDate,EndingDate); SalesLine.CALCSUMS("Line Amount"); MESSAGE(SalesAmountMsg,SalesLine."Line Amount"); Save the changes, then close the code editor and run the codeunit.

How it works...

A record is a complex data type. Variable declared as record refers to a table in the database. A variable contains a single table record and can move forward and backward through the recordset. A C/AL record resembles an object in object-oriented languages, although they are not exactly the same. You can call record methods and read fields using dot notation.

For example below are valid statements with the Customer record variable:

Customer.Name := 'New Customer'; IF Customer.Balance <= 0 THEN MESSAGE

The variable we just declared refers to the table Sales Line, which stores all open sales documents lines.

Since we want to calculate the sales amount in a certain period, first of all we need to define the date range for the calculation.

The first line in the code example finds the starting date of the period. In this calculation we refer to the system-defined global variable WORKDATE. If you are an experienced NAV user, you know what a workdate is; this is the default date for all documents created in the system. It does not always match the calendar date, so in the application code we use WORKDATE as the pivot date. Another system variable TODAY stores the actual calendar date, but it is used much less frequently than workdate.

Workdate is the last date of the period we want to analyze. To find the first date, use the CALCDATE function. It calculates a date based on the formula and the reference date. CALCDATE('<-1M>',WORKDATE) means that the resulting date will be one month earlier than the workdate. In the NAV 9.0 demo database workdate is 25.01.2017, so the result of this CALCDATE will be 25.12.2016.

The next line sets a filter on the SalesLine table. Filtering is used in C/AL to search for records corresponding to given criteria. There are two functions to apply filters to a table: SETFILTER and SETRANGE. Both take the field name to which the filter is applied, as the first parameter.

SETRANGE can filter all values within a given range or a single value. In the code example we use it to filter sales lines where the customer code is '10000