Book Image

Programming Microsoft Dynamics NAV - Fifth Edition

By : Marije Brummel, David Studebaker, Christopher D. Studebaker
Book Image

Programming Microsoft Dynamics NAV - Fifth Edition

By: Marije Brummel, David Studebaker, Christopher D. Studebaker

Overview of this book

Microsoft Dynamics NAV is a full business solution suite, and a complete ERP solution that contains a robust set of development tools to support customization and enhancement. These tools provide greater control over financials and can simplify supply chain, manufacturing, and operations. This book will take you from an introduction to Dynamics NAV and its integrated development tools to being a productive developer in the Dynamics NAV Development Environment. You will find this book very useful if you want to evaluate the product's development capabilities or need to manage Dynamics NAV based projects. It will teach you about the NAV application structure, the C/SIDE development environment, the C/AL language paired with the improved editor, the construction and uses of each object type, and how it all fits together to build universal applications. With this new edition, you will be able to understand how to design and develop using Patterns and new features such as Extensions and Events.
Table of Contents (10 chapters)

Hands-on development in NAV 2017

One of the best ways to learn a new set of tools, like those that make up a programming language and environment, is to experiment with them. We're going to have some fun doing that throughout this book. We're going to experiment where the cost of errors (otherwise known as learning) is small. Our development work will be a custom application of NAV 2017 for a relatively simple, but realistic, application.

We're going to do our work using the Cronus demo database that is available with all NAV 2017 distributions and is installed by default when we install the NAV 2017 demo system. The simplest way to install the NAV 2017 demo is to locate all the components on a single workstation. A 64-bit system running Windows 10 will suffice. Additional requirements information is available in the MSDN library (https://msdn.microsoft.com/en-us/dynamics-nav/system-requirements-for-microsoft-dynamics-nav) under the heading System Requirements for Microsoft Dynamics NAV 2017. Other helpful information on installing NAV 2017 (the demo option is a good choice for our purposes) and addressing a variety of setup questions is available in the NAV 2017 area of the MSDN library. In fact, all the help information for NAV 2017 is accessible in the MSDN library.

The Cronus database contains all of the NAV objects and a small, but reasonably complete, set of data populated in most of the system's functional applications areas. Our exercises will interface very slightly with the Cronus data, but will not depend on any specific data values.

To follow along with all our exercises as a developer, you will need a developer license for the system with rights allowing the creation of objects in the 50,000 to 50,099 number range. This license should also allow at least read access to all the objects numbered below 50,000. If you don't have such a license, check with your Partner or your Microsoft sales representatives to see if they will provide a training license for your use.

NAV 2017 development exercise scenario

Our business is a small radio station that features a variety of programming, news, music, listener call-ins, and other program types. Our station call letters are WDTU. Our broadcast materials come from several sources and in several formats: vinyl records, CDs, MP3s, and downloaded digital (usually MP3s). While our station has a large library, especially of recorded music, sometimes our program hosts (also called disc jockeys or DJs) want to share material from other sources. For that reason, we need to be able to easily add items to our playlists (the list of what is to be broadcast) and also have an easy-to-access method for our DJs to preview MP3 material.

Like any business, we have accounting and activity tracking requirements. Our income is from selling advertisements. We must pay royalties for music played, fees for purchased materials such as prepared text for news, sports, and weather information, and service charges for our streaming Internet broadcast service. As part of our licensed access to the public airwaves, a radio station is required to broadcast public service programming at no charge. Often, that is in the form of Public Service Announcements (PSAs) such as encouraging traffic safety or reduction in tobacco use. Like all radio stations, we must plan what is to be broadcast (create schedules) and track what has been broadcast (such as ads, music, purchased programming, and PSAs) by date and time. We bill our customers for the advertising, pay our vendors their fees and royalties, and report our public service data to the appropriate government agency.

Getting started with application design

The design for our radio station will start with a Radio Show table, a Radio Show Card page, a Radio Show List page, and a simple Radio Show List report. Along the way, we will review the basics of each NAV object type.

When we open the NAV Development Environment for the first time or to work on a different database, we must define what database should be opened. Click on File | Database | Open... and then choose a database:

Application tables

Table objects are the foundation of every NAV application. Tables contain data structure definitions, as well as properties that describe the behavior of the data, including data validations and constraints.

More business logic is required in complex applications than in simple data type validation, and NAV allows C/AL code to be put in the table to control the insertion, modification, and deletion of records as well as logic on the field level. When the bulk of the business logic is coded on the table level, it is easier to develop, debug, support, modify, and even upgrade. Good design in NAV requires that as much of the business logic as possible resides in the tables. Having the business logic coded on the table level doesn't necessarily mean the code is resident in the table. NAV 2017 Help recommends the following guidelines for placing C/AL code:

In general, put the code in codeunits, instead of on the object on which it operates. This promotes a clean design and provides the ability to reuse code. It also helps enforce security. For example, typically users do not have direct access to tables that contain sensitive data, such as the General Ledger Entry table, nor do they have permission to modify objects. If you put the code that operates on the general ledger in a codeunit, give the codeunit access to the table, and give the user permission to execute the codeunit, then you will not compromise the security of the table and the user will be able to access the table. If you must put code on an object instead of in a codeunit, then put the code as close as possible to the object on which it operates. For example, put code that modifies records in the triggers of the table fields.

Designing a simple table

Our primary master data table will be the Radio Show table. This table lists our inventory of shows available to be scheduled.

First, open the NAV Development Environment, click on Tools | Object Designer and select Table. We can view or modify the design of existing master tables in NAV by highlighting the table (for example, Table 18 - Customer, or Table 27 - Item) and clicking on Design.

Each master table has a standard field for the primary key (a Code data type field of 20 characters called No.) and has standard information regarding the entity the master record represents (for example, Name, Address, City, and so on, for the Customer table and Description, Base Unit of Measure, Unit Cost, and so on for the Item table).

The Radio Show table will have the following field definitions (we may add more later):

In the preceding list, three of the fields are defined as Code fields, which are text fields that limit the alphanumeric characters to upper case values. Code fields are used throughout NAV for primary key values. Code fields are used to reference or be referenced by other tables (foreign keys). No. will be the unique identifier in our table. We will utilize a set of standard internal NAV functions to assign a user-defined No. series range that will auto-increment the value on table insertion and possibly allow for user entry (as long as it is unique in the table) based on a setup value. The Host No. references the standard Resource table and the Radio Show Type field will reference a custom table we will create to allow for flexible Type values.

We will have to design and define the reference properties at the field level in the Table Designer, as well as compile them, before the validation will work. At this point, let's just get started with these field definitions and create the foundation for the Radio Show table.

Creating a simple table

To invoke the table designer, open the NAV 2017 Development Environment and the database in which we will be doing our development. In the Object Designer, click on Table (in the left column of buttons) and click New (in the bottom row of buttons). Enter the first field number as 1 (the default is 1), and increment each remaining field number by 10 (the default is 1). Sometimes, it is useful to leave large gaps (such as jumping from 80 to 200 or 500) when the next set of fields have a particular purpose not associated with the prior set of fields.

The fields combining the primary key can use the numbers up to 9 since they are very unlikely to change. If this is changed, there is a substantial amount of refactoring to be done.

NAV 2017 Help says to not leave gaps in field numbers. Based on many years of experience, the authors disagree. Leaving numbering gaps will allow us to later add additional fields between existing fields, if necessary. The result will be data structures that are (at least initially) easier to read and understand. Once a table is referenced by other objects or contains any data, the field numbers of previously defined fields should not be changed.

The following screenshot shows our new table definition in the Table Designer:

Now we can close the table definition (click on File | Save or Ctrl + S or press Esc or close the window - the first two options are the explicit methods of saving our work). We will see a message reminding us to save our changes:

Click on Yes. We must now assign the object number (use 50000) and a unique name (it cannot duplicate the same first 30 characters of another table object in the database). We will name our table Radio Show based on the master record to be stored in the table:

Note that the Compiled option is automatically checked and the Synchronize Schema option is set to Now - with validation, which are the defaults for NAV. Once we press OK and the object is successfully compiled, it is immediately ready to be executed within the application. If the object we were working on was not ready to be compiled without error, we could uncheck the Compiled option in the Save As window.

Uncompiled objects will not be considered by C/SIDE when changes are made to other objects. Be careful. Until we have compiled an object, it is a "work in progress", not an operable routine. There is a Compiled flag on every object that gives its compilation status. Even when we have compiled an object, we have not confirmed that all is well. We may have made changes that affect other objects which reference the modified object. As a matter of good work habit, we should recompile all objects before we end work for the day.

The Synchronize Schema option choice determines how table changes will be applied to the table data in SQL Server. When the changes are validated, any changes that would be destructive to existing data will be detected and handled either according to a previously defined upgrade codeunit or by generating an error message. The Synchronize Schema option choices are shown in the following screenshot:

Refer to the documentation (https://msdn.microsoft.com/en-us/dynamics-nav/synchronizing-table-schemas) in the section called Synchronizing Table Schemas for more detail.

Pages

Pages provide views of data or processes designed for on-screen display (or exposure as web services) and also allow for user data entry into the system. Pages act as containers for action items (menu options).

There are several basic types of display/entry pages in NAV 2017:

  • List
  • Card
  • Document
  • Journal/Worksheet
  • List Plus
  • Confirmation Dialog
  • Standard Dialog

There are also page parts (they look and program like a page, but aren't intended to stand alone) as well as UIs that display like pages, but are not page objects. The latter user interfaces are generated by various dialog functions. In addition, there are special page types such as Role Center pages and Navigate pages (for Wizards).

Standard elements of pages

A page consists of Page properties and Triggers, Controls, Control Properties and Triggers. Data Controls generally are either labels displaying constant text or graphics, or containers that display data or other controls. Controls can also be buttons, Action items, and Page Parts. While there are a few instances where we must include C/AL code within page or page control triggers, it is good practice to minimize the amount of code embedded within pages. Any data-related C/AL code should be located in the table object rather than in the page object.

List pages

List pages display a simple list of any number of records in a single table. The Customers List page (with its associated FactBoxes) in the following screenshot shows a subset of the data for each customer displayed. List pages/forms often do not allow entry or editing of the data. Journal/Worksheet pages look like list pages, but are intended for data entry. Standard list pages are always displayed with the Navigation Pane on the left:

Card pages

Card pages display one record at a time. These are generally used for the entry or display of individual table records. Examples of frequently accessed card pages include Customer Card for customer data, Item Card for inventory items, and G/L Account Card for general ledger accounts.

Card pages have FastTabs (a FastTab consists of a group of controls with each tab focusing on a different set of related customer data). FastTabs can be expanded or collapsed dynamically, allowing the data visible at any time to be controlled by the user. Important data elements can be promoted to be visible even when a FastTab is collapsed.

Card pages for master records display all the required data entry fields. If a field is set to ShowMandatory (a control property we will discuss in Chapter 4, Pages - the Interactive Interface), a red asterisk will display until the field is filled. Typically, card pages also display FactBoxes containing summary data about related activity. Thus cards can be used as the primary inquiry point for master records. The following screenshot is a sample of a standard Customer Card:

Document pages

A document page looks like a card page with one tab containing a List Part page. An example is the Sales Order page shown in the following screenshot. In this example, the first tab and last four tabs are in card page format showing Sales Order data fields that have a single occurrence on the page (in other words, do not occur in a repeating column).

The second tab from the top is in List Part page format (all fields are in repeating columns) showing the Sales Order line items. Sales Order Line items may include product to be shipped, special charges, comments, and other pertinent order details. The information to the right of the data entry area is related data and computations (FactBoxes) that have been retrieved and formatted. The top FactBox contains information about the ordering customer. The bottom FactBox contains information about the item on the currently highlighted sales line:

Journal/Worksheet pages

Journal and Worksheet pages look very much like List pages. They display a list of records in the body of the page. Many also have a section at the bottom that shows details about the selected line and/or totals for the displayed data. These pages may include a Filter pane and perhaps a FactBox. The biggest difference between Journal/Worksheet pages and basic List pages is that Journal and Worksheet pages are designed to be used for data entry (though this may be a matter of personal or site preference). An example of the General Journal page in Finance is shown in the following screenshot:

Creating a List page

Now we will create a List page for the table we created earlier. A List page is the initial page that is displayed when a user accesses any data table. The NAV Development Environment has Wizards (object generation tools) to help create basic pages. Generally, after our Wizard work is done, we will spend additional time in the Page Design tool to make the layout ready for presentation to users.

Our first List page will be the basis for viewing our Radio Show master records. From the Object Designer, click on Page, then click on New. The New Page screen will appear. Enter the name (Radio Show) or table object ID (50000) in the Table field. This is the table to which the page will be bound. We can add additional tables to the page object C/AL Global Variables after we close the Wizard, as then we will be working in the Page Designer. Choose the Create a page using a wizard: option and select List, as shown in the following screenshot. Click on OK:

The next step in the wizard shows the fields available for the List page. We can add or remove any of the field columns using the >, <, >>, and << buttons:

Add all the fields using >> and click on Next >:

The next Wizard step shows the Subforms, System FactBoxes, and Charts that are available to add to our page:

Subforms should properly be named Subpages. Such a change is being considered by Microsoft.

We can add these later in the Page Designer as needed. Click Finish to exit the wizard and enter the Page Designer:

Click on Preview to view the page with the default ribbon. Note that in Preview mode, we cannot insert, modify, or delete any of the layout or enter data. The Preview page is not connected to the database data. We need to compile the page and Run it to manipulate data. In the following screenshot, some fields are out of sight on the right-hand side:

The availability of some capabilities and icons (such as OneNote) will depend on what software is installed on our development workstation. Close the preview of the List page and close the window or press Esc to save. Number the page 50000 and name the object Radio Show List:

Creating a Card page

Next, let's create a Card page. The Wizard process for a Card page is almost the same as for a List page, with an additional step. In Object Designer, with Page selected, click New again. Enter the same table (Radio Show) and make sure the Create a page using a wizard: option is selected and Card is highlighted:

The next step in the wizard is specific to Card pages. It allows us to create FastTabs. These are the display tools that allow the user to expand or collapse window sections for ease of viewing. For our Radio Show card we will divide our table fields into two sections, General (primary key, description, resource information, and duration) and Statistics (data about the show):

After defining the FastTab names, we must assign the data fields to the tabs on which they are to appear. We will populate the tabs based on the FastTab names we assigned. We can select the fields from the Available Fields list and assign the order of appearance as we did in the List Page Wizard. Click on the Next > button to proceed.

For the General FastTab, select the following fields: No., Show Code, Name, Run Time, Host Code, and Host Name, as shown in the following screenshot:

Click on the Statistics tab to populate the Statistics FastTab, select Average Listeners, Audience Share, Advertising Revenue, and Royalty Cost:

The last Card Page Wizard step is to choose from the available Subforms (Subpages), System FactBoxes, and Charts. If we decide later we want any of those, we will add them using the Page Designer:

Click Finish to view the generated code in the Page Designer:

Click the Preview button to show a view-only display of the Card page:

Exit the preview and Page Designer and save the page as ID as 50001, and Name as Radio Show Card:

Later on, we can add an action to the List page which will link to the Card page for inserting and editing radio show records and also add the List page to the Role Center page for our radio station user.

Creating some sample data

Even though we haven't added all the bells and whistles to our Radio Show table and pages, we can still use them to enter sample data. The Radio Show List page will be the easiest to use for this.

In Object Designer, with pages selected, highlight page 50000 - Radio Show List, and click Run. Then click the New icon on the ribbon. An empty line will open, where we can enter our sample data. Of course, since our table is very basic at this point, without any validation functionality, table references, function calls, and so on, we will have to be creative (and careful) to enter all the individual data fields accurately and completely without guidance:

Enter the data shown in the following table so we can see what the page looks like when it contains data. Later on, after we add more capabilities to our table and pages, some fields will validated, and some will be either automatically entered or available on a lookup basis. But for now, simply key in each field value. If the data we key in now conflicts with the validations we create later (such as data in referenced tables), we may have to delete this test data and enter new test data later:

We will use the testability framework for automated testing later in this book. A test codeunit is provided in the downloads, but for now, it is recommended to key in the data manually.
No. Radio Show Type Description Host Code Host Name Run Time
RS001 TALK CeCe and Friends CECE CeCe Grace 2 hours
RS002 MUSIC Alec Rocks and Bops ALEC Alec Benito 2 hours
RS003 CALL-IN Ask Cole! COLE Cole Henry 2 hours
RS004 CALL-IN What do you think? WESLEY Wesley Ernest 1 hour
RS005 MUSIC Quiet Times SASKIA Saskia Mae 3 hours
RS006 NEWS World News DAAN Daan White 1 hour
RS007 ROCK Rock Classics JOSEPH Josephine Perisic 2 hours

Creating a list report

Open Object Designer, select Report, and click New. The Report Dataset Designer is empty when it displays, so we need to add a Data Source (table) to the first blank row. Type 50000 or Radio Show into the Data Source column:

To add multiple data fields from the table, we can use the Field Menu, which is accessed via the icon on the toolbar or the View | Field Menu option. The Field Menu will show a list of all the fields in the Radio Show table:

Highlight the first six fields in the Field Menu. Then click on next blank line in the Report Dataset Designer:

A confirmation box will appear, asking if we want to add the fields selected. Click Yes:

The fields will appear in the Report Dataset Designer without having to type them in manually:

There are two options for RDLC report layout development tools. They are the current version of Visual Studio 2015 Community Edition or the SQL Server Report Builder (which can be downloaded here: https://www.visualstudio.com/vs/community/). NAV defaults to using Visual Studio, which we will use in this book. If the free SQL Server Report Builder is installed, it can be activated for NAV 2017 by accessing the Options... screen from the Tools menu option:

On the Options screen, set Use Report Builder to Yes:

Click on View | Layout to proceed to the chosen report layout tool:

The RDLC report layout tool opens with a blank design surface and no dataset controls visible. Unlike the Page Designer, there is no report wizard to help with the layout of a new report. All the report layout design work must start from scratch with a blank design surface:

To show the dataset available from NAV, click on View and select Report Data (the last item on the list):

A new Report Data pane will show on the left of the Visual Studio layout window:

To create our simple list, we will insert a simple table object (a data region with a fixed number of columns but a variable number of rows) in the design surface. Right-click anywhere on the design surface and expand the Insert sub-menu to view the tools available on the report. Click the Table tool object, then use drag-and-drop to bring a control from the toolbox to the design surface:

The table layout object defaults to three columns with a header row (repeated once) and a data row (repeated for each row of data retrieved from NAV):

Drag and drop each of the six elements in the DataSet_Result into columns in the table object. To add additional columns, right-click on the table object header and select Insert Column (we could also drag-and-drop a field from the dataset to the table). The caption with the basic format of Field Name Table Name will default into the header row:

Let's do a little clean-up in the header row by making the captions look like they do in standard NAV reports by manually typing in the field names:

We will save our work by clicking on File | Save All (or Ctrl + Shift + S) then exit Visual Studio (File | Exit or Alt + F4). Back in NAV's Object Designer, we will exit the report or click File | Save; then, we'll need to respond to two confirmation boxes. The first asks if we want to save the report layout from Visual Studio. This allows us to load the RDLC report layout XML into the NAV database report object. Click Yes:

This is followed by the second confirmation screen. Enter 50000 for the ID, and Name the report Radio Show List. Click OK to save:

To view the report, make sure the new report object is selected, then click Run at the bottom of the Object Designer screen:

An RTC instance will open with the Report Request Page showing. This is where the user can set filters, choose a sort sequence, and choose print options:

Click on Preview to display the report onscreen. The report will show our simple table layout with the fixed definition column captions showing exactly as we typed them:

Much more to come. All we've done so far is scratch the surface. But you should have a pretty good overview of the development process for NAV 2017.

You will be in especially good shape if you've been able to following along in your own system, doing a little experimenting along the way.