Free eBook - Programming Microsoft Dynamics 365 Business Central - Sixth Edition

4.4 (8 reviews total)
By Marije Brummel , David Studebaker , Christopher D. Studebaker
  • A new free eBook every day on the latest in tech
  • 30 permanently free eBooks from our core tech library
  1. Introduction to Business Central
About this book
Microsoft Dynamics 365 Business Central is a full ERP business solution suite with a robust set of development tools to support customization and enhancement. These tools can be used to tailor Business Central's in-built applications to support complete management functions for finance, supply chain, manufacturing, and operations. Using a case study approach, this book will introduce you to Dynamics 365 Business Central and Visual Studio Code development tools to help you become a productive Business Central developer. You'll also learn how to evaluate a product's development capabilities and manage Business Central-based development and implementation. You'll explore application structure, the construction of and uses for each object type, and how it all fits together to build apps that meet special business requirements. By the end of this book, you'll understand how to design and develop high-quality software using the Visual Studio Code development environment, the AL language paired with the improved editor, patterns, and features.
Publication date:
April 2019
Publisher
Packt
Pages
536
ISBN
9781789137798

 
Introduction to Business Central
"Time changes all things; there is no reason why language should escape this universal law."
– Ferdinand de Saussure
"When we use a language, we should commit ourselves to knowing it, being able to read it, and writing it idiomatically."
Ron Jeffries

Microsoft Dynamics 365 Business Central has one of the largest installed user bases of any enterprise resource planning (ERP) system, serving over 150,000 companies and 2.5 million plus individual users, at the time of writing. The community of supporting organizations, consultants, implementers, and developers continues to grow and prosper. The capabilities of the off-the-shelf product increase with every release. The selection of add-on products and services expands both in variety and depth.

The release of Microsoft Dynamics Business Central continues its 20-plus year history of continuous product improvement. It provides more user options for access and output formatting. For new installations, Business Central includes tools for rapid implementation. For all installations, it provides enhanced business functionality and more support for ERP computing in the cloud, including integration with Microsoft Office 365.

Our goal in this chapter is to gain a big-picture understanding of Business Central. You will be able to envision how Business Central can be used by managers (or owners) of an organization to help manage activities and the resources, whether the organization is for-profit or not-for-profit. You will also be introduced to the technical side of Business Central from a developer's point of view.

In this chapter, we will take a look at Business Central, including the following topics:

  • A general overview of Business Central
  • A technical overview of Business Central
  • A hands-on introduction to Visual Studio Code development in Business Central
 

Business Central – an ERP system

Business Central is an integrated set of business applications designed to service a wide variety of business operations. Microsoft Dynamics 365 Business Central is an ERP system. An ERP system integrates internal and external data across a variety of functional areas, including manufacturing, accounting, supply chain management, customer relationships, service operations, and human resource management, as well as the management of other valued resources and activities. By having many related applications well integrated, a fully-featured ERP system provides an enter data once, use many ways information processing toolset.

Business Central ERP addresses the following functional areas (and more):

  • Basic accounting functions (for example, general ledger, accounts payable, and accounts receivable)
  • Order processing and inventory (for example, sales orders, purchase orders, shipping, inventory, and receiving)
  • Relationship management (for example, vendors, customers, prospects, employees, and contractors)
  • Planning (for example, MRP, sales forecasting, and production forecasting)
  • Other critical business areas (for example, manufacturing, warehouse management, marketing, cash management, and fixed assets)

A good ERP system, such as Business Central, is modular in design, which simplifies implementation, upgrading, modification, integration with third-party products, and expansion for different types of clients. All the modules in the system share a common database and, where appropriate, common data.

The following groupings of individual Business Central functions are based on the Search menu structure, which is supplemented by information from Microsoft marketing materials. The important thing is to understand the overall components that make up the Business Central ERP system:

Business Central has a role tailored User Interface (UI). In Business Central, there are four instances of the role tailored client (RTC)—one each for Windows, web interaction, tablet use, and as a phone client. Generally the various clients are referred to for the most part based on where and how they are displayed (Windows, web, tablet, and so on).

The Windows client is only available for on-premises installations.
 

Financial management

At the foundation of any ERP system is financial management. Irrespective of the business, the money must be kept flowing with a track of it. Business Central's financial management module contains the tools that help to manage the capital resources of the business. These include all or part of the following application functions:

  • General ledger, for managing the overall finances of the firm
  • Cash management and banking, for managing the inventory of financial assets
  • Accounts receivable, for tracking the incoming revenue
  • Accounts payable, for tracking the outgoing funds
  • Analytical accounting, for analyzing the various flows of funds
  • Inventory and fixed assets, for managing inventories of goods and equipment
  • Multicurrency and multilingual, for supporting international business activities
 

Manufacturing

Business Central manufacturing is general-purpose enough to be appropriate for Make to Stock (MTS), Make to Order (MTO), and Assemble to Order (ATO), as well as various subsets and combinations of those. Although off-the-shelf Business Central is not particularly suitable for most process manufacturing and some of the very high-volume assembly line operations, there are third-party add-on and add-in enhancements available for those applications. As with most of the Business Central application functions, manufacturing can be implemented either in a basic mode or as a fully-featured system. Business Central manufacturing includes the following functions:

  • Product design (BOMs and routings), for structure management of product components and the flow management of manufacturing processes
  • Capacity and supply requirement planning, for tracking the intangible and tangible manufacturing resources
  • Production scheduling (infinite and finite), execution, and tracking quantities and costs, plus tracking manufacturing resources' planned use, both on a constrained and unconstrained basis
 

Supply chain management

Some of the functions that are categorized as part of Business Central supply chain management (SCM), such as sales and purchasing, are actively used in almost every Business Central implementation. The supply chain applications in Business Central include all or parts of the following applications:

  • Sales order processing and pricing, to support the heart of every
    business
  • Purchasing (including requisitions), for planning, entering, pricing, and processing purchase orders
  • Inventory management, for managing inventories of goods and materials
  • Warehouse management, including receiving and shipping, for managing the receipt, storage, retrieval, and shipment of material and goods in warehouses

As a whole, these functions constitute the base components of a system that's appropriate for distribution operations, including those that operate on an ATO basis.

 

Business intelligence and reporting

Although Microsoft marketing materials identify business intelligence (BI) and reporting as though it were a separate module within Business Central, it's difficult to physically identify it as such. Most of the components that are used for BI and reporting purposes are (appropriately) scattered throughout various application areas. In the words of one Microsoft document, business intelligence is a strategy, not a product. Functions within Business Central that support a BI strategy include the following:

  • Standard reports: Distributed and ready to use by end users
  • Account schedules and analysis reports: A specialized report writer for general ledger data
  • Query, XMLport, and report designers: Developer tools to support the creation of a wide variety of report formats, charts, and XML and CSV files
  • Analysis by dimensions: A capability embedded in many of the other tools
  • Interfaces into Microsoft Office and Microsoft Office 365, including Excel-communications of data either into Business Central or out of Business Central
  • RDLC report viewer: Provides the ability to present Business Central data in a variety of textual and graphic formats, including user interactive capabilities
  • Interface capabilities such as Dotnet interoperability and web services: Technologies to support interfaces between Business Central and external software products
  • Standard packages for Power BI: Integrated in the role center as well as dashboards
 

Relationship management

Business Central's relationship management (RM) functionality is definitely the little sister (or, if you prefer, little brother) of the fully featured standalone Microsoft CRM system and Dynamics 365 for Sales and Dynamics 365 for Marketing. The big advantage of Business Central RM is its tight integration with Business Central customer and sales data.

Also falling under the heading of the customer relationship module is the Business Central service management (SM) functionality. The different functionalities under RM and SM are as follows:

  • Relationship management:
    • Marketing campaigns, to plan and manage promotions
    • Customer activity tracking, to analyze customer orders
    • To-do lists, to manage what is to be done and track what has been done
  • Service management:
    • Service contracts, to support service operations
    • Labor and part consumption tracking, to track resources that are consumed by the service business
    • Planning and dispatching, to manage service calls
 

Human resource management

The Business Central human resources module is a very small module, but it relates to a critical component of the business: employees. Basic employee data can be stored and reported via the master table (in fact, you can use the human resources (HR) module to manage data about individual contractors in addition to employees). A wide variety of individual employee attributes can be tracked by the use of dimension fields:

  • Employee tracking: Maintain basic employee description data
  • Skills inventory: Inventory of the capabilities of employees
  • Absence tracking: Maintain basic attendance information
  • Employee statistics: Tracking government required employee attribute data such as age, gender, length of service
 

Project management

The Business Central project management module consists of the job functionality that's supported by the resources functionality. Projects can be short or long term. They can be external (in other words, billable) or internal. This module is often used by third parties as the base for vertical market add-ons (such as construction or job-oriented manufacturing). This application area includes parts or all of the following functions:

  • Budgeting and cost tracking, for managing project finances
  • Scheduling, for planning project activities
  • Resource requirements and usage tracking, for managing people and equipment
  • Project accounting, for tracking the results
 

A developer's overview of Business Central

From the point of view of a developer, Business Central consists of about almost six thousand potentially customizable, off-the-shelf program objects, plus the integrated development environment (IDE/Visual Studio Code) development tools that allow us to modify existing objects and create new ones.

 

Business Central object types

Let's start with basic definitions of the Business Central object types:

  • Table extension: Table extensions allow for the creation of companion tables that are linked to tables defined by Microsoft in the base product or by other solutions.
  • Page customization: Page customizations allow controls in existing pages to be modified and moved. As they are primarily a tool for use by end users, they are outside the scope of this book.
  • Page extension: Page extensions allow controls in existing pages to be added or hidden.
  • Table: Tables serve both to define the data structure and to contain the data records.
  • Page: Pages are the way data is formatted and displayed appropriately for each of the client types and user roles.
  • Report: Reports are provided for the display of data to the user in hard copy format, either on-screen (preview mode) or via a printing device. Report objects can also update data in processes with or without data display.
  • Codeunit: Codeunits are containers for code that's been utilized by other objects. Codeunits are always structured in code segments called procedures.
  • Query: Queries support extracting data from one or more tables, making calculations, and outputting them in the form of a new data structure. Queries can output data directly into charts, Excel, XML, and OData. They can be used as an indirect source for pages and reports.
  • XMLport: XMLports allow for the importing and exporting of data to/from external files. The external file structure can be in XML or other file formats.
  • Profile: Profiles allow the definition of Role Centers and group page customizations.
  • Control add-in: Control add-in objects allow the display of HTML5 visualizations based on data from Business Central. These objects can send back events that can be used to trigger additional code.
 

The Visual Studio Code integrated development environment

Business Central includes an extensive set of software development tools. The Business Central development tools are accessed through Visual Studio Code. Visual Studio Code includes the Application Language (AL) compiler extension. All Business Central programming uses AL.

When used on premises, the old development environment C/SIDE can also be used for development. To learn C/SIDE, refer to the following book: Programming Microsoft Dynamics NAV, 2017. The use of C/SIDE for Business Central development is discouraged by Microsoft.

The Visual Studio Code IDE is Microsoft's most popular code editor and is available for Windows, Linux, and macOS. The images used in this book will be from Windows. You can download Visual Studio Code from https://code.visualstudio.com/:

 

Visual Studio Code icons

When we open Visual Studio Code, we will see five icons. The icons appear on the left-hand side part of the screen. The icons determine the navigation part that appears on the left-hand side of your screen. If you click on an icon twice, the navigation part will be hidden and allow full screen code editing.

 

Explorer

The EXPLORER view is the default view when you open a project. It allows you to view the files in a project and select one or more files for editing. The EXPLORER view is shown in the following screenshot:

 

Search

The SEARCH view provides an advanced search and replace option within the files of your project. The SEARCH view is shown in the following screenshot:

 

Source control

Visual Studio Code provides access to a built-in connection to SOURCE CONTROL. When source control is activated, all changes that are made to files are automatically tracked and displayed in this window:

The video at https://www.youtube.com/watch?v=NTY5VELbCWI&t=22s explains how to get started with Source Control in Visual Studio Code.
 

Debugger

You can connect Visual Studio Code to an active session of Business Central and use the built-in debugger to do basic troubleshooting for your code. The DEBUG view is shown in the following screenshot:

 

Extensions

Out-of-the-box Visual Studio Code does not understand the Business Central AL Language syntax. To activate the compiler, an extension needs to be installed in the EXTENSIONS window.

This extension, called AL language, can be downloaded from the Visual Studio Marketplace or installed directly from Visual Studio Code:

The Visual Studio Code Marketplace can be found at https://marketplace.visualstudio.com/.
 

AL programming language

The language in which Business Central is coded is AL. A small sample of AL code within the AL Editor is shown here:

AL syntax is similar to Pascal syntax. Code readability is always enhanced by careful programmer attention to structure and logical variable naming, and ensuring that the process flow is consistent with that of the code in the base product and that there is good documentation both inside and outside of the code.

Good software development focuses on design before coding and accomplishing design goals with a minimal amount of code. Dynamics Business Central facilitates that approach. In 2012, a team made up of Microsoft and Business Central community members began the Business Central design patterns project. As defined by Wikipedia, a design pattern is a general reusable solution to a commonly occurring problem. The following links provide information on the Business Central design patterns project: One of the primary goals of this project is to document patterns that exist within Business Central. In addition, new best practice patterns have been suggested as ways to solve common issues we encounter during our customization efforts. Now, when we work on Business Central enhancements, we will be aided by references to the documentation of patterns within Business Central. This allows us to spend more of our time designing a good solution using existing, proven procedures (the documented patterns) and spend less time writing and debugging code. A good reference for Business Central design and development using patterns can be found here: https://www.packtpub.com/application-development/microsoft-dynamics-nav-2013-application-design.

You can refer to the Reusing Code section of Business Central at https://docs.microsoft.com/en-us/previous-versions/dynamicsnav-2009/dd355277(v=nav.60).

Much of our Business Central development work is done by assembling references to previously defined objects and procedures, adding new data structures where necessary. As the tools for Business Central design and development that are provided both by Microsoft and by the Business Central community continue to mature, our development work becomes more oriented toward design and less toward coding. The end result is that we are more productive and cost-effective on behalf of our customers. Everyone wins.

 

Business Central object and system elements

Here are some important terms that are used in Business Central:

  • Language extension: A file that's downloaded from the Visual Studio Code Marketplace or supplied by Microsoft. The version of the language extension in use must match the build version of Business Central with which you are working. Microsoft does a monthly update of Business Central and the language extension. There is also an insider program that allows early access before the language extension is published on the Marketplace.
  • Field: An individual data item, defined either in a table or in the working storage (temporary storage) of an object.
  • Record: A group of fields (data items) that are handled as a unit in many operations. Table data consists of rows (records) with columns (fields).
  • Control: In MSDN, a control is defined as a component that provides (or enables) UI capabilities.
  • Properties: These are the attributes of the element, such as an object, field, record, or control that define some aspect of its behavior or use. Example property attributes include display captions, relationships, size, position, and whether the element is editable or viewable.
  • Trigger: These are mechanisms that initiate (fire) an action when an event occurs and is communicated to the application object. A trigger in an object is either empty, contains code that is executed when the associated event fires the trigger, or only contains comments (in a few cases, this affects the behavior of the trigger). Each object type, data field, control, and so on may have its own set of predefined triggers. The event trigger name begins with On, such as OnInsert, OnOpenPage, or OnNextRecord. Business Central triggers have similarities to those in SQL, but they are not the same (similarly named triggers may not even serve similar purposes). Business Central triggers are locations within objects where a developer can place comments or AL code. When we view the AL code of an object in its designer, we can see non-trigger code groups that resemble Business Central event-based triggers.
  • Procedures: These can be defined by the developer. They are callable routines that can be accessed by other AL code from either inside or outside the object where the called function resides. When we view the AL code of an object in its designer, we can see non-trigger code groups that resemble Business Central event-based triggers. Many procedures are provided as part of the standard product. As developers, we may add our own custom procedures as needed.
  • Object numbers and field numbers: All objects of the same object type are assigned a number that's unique within the object type. All fields within an object are assigned a number that's unique within the object (that is, the same field number may be repeated within many objects, regardless of whether it is referring to similar or different data). In this book, we will generally use comma notation for these numbers (fifty thousand is 50,000). In AL, no punctuation is used. The object numbers from 1 (one) to 50,000 and in the 99,000,000 (99 million) range are reserved for use by Business Central as part of the base product. Objects in these number ranges can be modified or deleted with a developer's license, but cannot be created. Field numbers in standard objects often start with one (1). Historically, object and field numbers from 50,000 to 99,999 are generally available to the rest of us for assignment as part of customizations that are developed in the field using a normal development license. Field numbers from 90,000 to 99,999 should not be used for new fields that have been added to standard tables as those numbers are sometimes used in training materials. Microsoft allocates ranges of object and field numbers to Independent Software Vendor (ISV) developers for their add-on enhancements. Some such objects (the 14 million range in North America, and other ranges for other geographic regions) can be accessed, modified, or deleted, but not created using a normal development license. Others (such as in the 37 million range) can be executed but not viewed or modified with a typical development license. The following table summarizes the object numbering practice:

Object number range

Usage

1 - 9,999

Base-application objects

10,000 - 49,999

Country-specific objects

50,000 - 99,999

Customer-specific objects

100,000 - 98,999,999

Partner-created objects

Above 98,999,999

Microsoft territory

  • Events: Procedures can subscribe to events that are raised in the system. Business Central has both platform and manual events. Procedures can also be used to raise events.
  • Work date: This is a date that's controlled by the user operator. It is used as the default date for many transaction entries. The system date is the date that's recognized by Windows. The work date that can be adjusted at any time by the user is specific to the workstation, and can be set to any point in the future or the past. This is very convenient for procedures such as the ending sales order entry for one calendar day at the end of the first shift, and then entering sales orders by the second shift dated to the next calendar day. There are settings to allow you to limit the range of work dates allowed. The work date can be set by clicking on the cogwheel drop-down list next to the question mark icon and selecting the My Settings option:

Clicking on My Settings in the drop-down options displays the My Settings screen. Here, we can enter a new Work Date:

 

Business Central functional terminology

For various application functions, Business Central uses terminology that is more similar to accounting than to traditional data processing terminology. Here are some examples:

  • Journal: A table of unposted transaction entries, each of which represents an event, an entity, or an action to be processed. There are general journals for general accounting entries, item journals for changes in inventory, and so on.
  • Ledger: A detailed history of posted transaction entries that have been processed, for example, the general ledger, customer ledger, vendor ledger, and item ledger. Some ledgers have subordinate detail ledgers, typically providing a greater level of quantity and/or value detail. With minor exceptions, ledger entries cannot be edited. This maintains auditable data integrity.
  • Posting: The process by which entries in a journal are validated, and then entered into one or more ledgers.
  • Batch: A group of one or more journal entries, posted at the same time.
  • Register: An audit trail showing a history, by entry number ranges, of posted journal batches.
  • Document: A formatted page such as an invoice, a purchase order, or a payment check, typically one page for each primary transaction (a page may require display scrolling to be fully viewed).
 

User interface

The Business Central UI is designed to be role oriented (also called role tailored). The term role oriented means tailoring the available options to fit the user-specific job tasks and responsibilities.

The first page that a user will see is the Role Center page. The Role Center page provides the user with a view of work tasks to be done; it acts as the user home page. The home Role Center page should be tailored to the job duties of each user, so there will be a variety of Role Center page formats for any installation.

Someone whose role is focused on order entry will probably see a different Role Center home page than the user whose role focuses on invoicing, even though both user roles are in what we generally think of as sales and receivables. The Business Central tailorable Role Center allows a great deal of flexibility for implementers, system administrators, managers, and individual users to configure and reconfigure screen layouts and the set of functions that are visible to a particular user.

The following screenshot is the out-of-the-box Role Center:

The key to properly designing and implementing any system, especially a role tailored system, is the quality of the user profile analysis that's done as the first step in requirements analysis. User profiles identify the day-to-day needs of each user's responsibilities, relative to accomplishing the business's goals. Each user's tasks must be mapped to individual Business Central functions or elements, identifying how those tasks will be supported by the system. A successful implementation requires the use of a proven methodology. It is very important that the up-front work is done and done well. The best programming cannot compensate for a bad definition of goals.

In our exercises, we will assume that the up-front work has been well done, and we will concentrate on addressing the requirements that have been defined by our project team.

 

Hands-on development in Business Central

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 Business Central for a relatively simple, but realistic, application.

We're going to do our work using the Cronus demo database that is available with all Business Central distributions and is installed by default when we install the Business Central demo system. The simplest way is to use the sandbox.

You can find up-to-date information on getting started with Business Central sandboxes on Microsoft Docs at https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-sandbox-overview.

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

 

Business Central 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, this 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 Business Central object type.

When we open Visual Studio, we need to create a new project folder. This can be done using the Command Palette via View | Command Palette... or Ctrl + Shift + P. Then, type AL:Go!:

The project folder will default to your Documents folder if you run this on a Windows machine. We will call our project WDTU:

 

Folder structure

A folder called WDTU is created with some default files and subfolders. The HelloWorld.al file can be deleted immediately:

 

launch.json

Inside a subfolder called .vscode, a file is created called launch.json that defines the connection to your Business Central sandbox:

  • name: For documentation purposes only. You can put the name of your project here. The content of this property does not affect the behavior.
  • server: This contains a URL to the development endpoint of your sandbox.
  • serverInstance: A server can have multiple instances.
  • authentication: This can be UserPassword, AAD, or Windows. The default is UserPassword.
  • startupObjectId: This option determines which object is executed when the project is published.
  • startupObjectType: This allows a switch between executing a table or a page upon publishing.
 

app.json

The app.json file contains properties about your extension, such as the name and version.

All properties are explained in the Microsoft Docs (https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-json-files). We will only populate the mandatory properties for now:

  • id: This is a unique ID for your extension and is autogenerated. Never change this value.
  • name: The name of your extension as it will be displayed to the user.
  • publisher: This usually contains the name of the company or individual who owns the intellectual property of the extension.
  • version: Your extensions can be versioned using this property. You can use this when you create a new version of the extension to determine if upgrade code needs to be executed.
  • idRange: This tells the compiler which object numbers are to be used for this extension. You must provide a range for application object IDs in the format "idRanges": [{"from": 50100,"to": 50200},{"from": 50202,"to": 50300}].
 

Symbol files

Before we can start creating our extension, we need to perform one more step, that is,downloading the symbol files. The compiler needs the symbol files to determine whether the dependencies are correct. The symbol files contain metadata about other extensions. To download the default symbol files from Business Central, we need to select Al: Download Symbols from the Visual Studio Command Palette:

When the symbol files are downloaded, they are placed in the ,/alpackages folder of your project.
 

Application tables

Table objects are the foundation of every Business Central 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 Business Central allows 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 Business Central 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 that the code resides in the table.

The Business Central online documentation recommends the following guidelines for placing 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 that are available to be scheduled.

First, create a new file in Visual Studio Code. Click on File | New and Visual Studio Code will create a new file and open the code editor window.

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, and City for the Customer table, and Description, Base Unit of Measure, and Unit Cost for the Item table).

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

Field names

Definitions

No.

20-character text (code)

Radio Show Type

10-character text (code)

Name

50-character text

Run Time

Duration

Host No.

20-character text (code)

Host Name

50-character text

Average Listeners

Decimal

Audience Share

Decimal

Advertising Revenue

Decimal

Royalty Cost

Decimal

 

In the preceding list, three of the fields are defined as Code fields, which are text fields that limit the alphanumeric characters to uppercase values. Code fields are used throughout Business Central 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 Business Central 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 that 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

The easiest way to create a table the easiest way is by using snippets. To use snippets, Visual Studio Code needs to understand that our file is written in the AL language. This is simply done by saving the file with the .al extension. We will save our newly created file using File | Save and using a name that makes sense later. Let's use Radio Show.al for now:

Now, we can use the snippet called ttable. If we type in the letters tta, IntelliSense will suggest this snippet:

This snippet creates content for our file and sets the cursor on the place where we need to define the object ID:

We will type 50100 and use Tab to go to the next field, object name, where we will type "Radio Show".

The snippet has already created a field with the default ID of 1. The field name is MyField and the type is Integer. We will change the name to "No." and the type to Code [20].

The next field can be field number 2. Sometimes, it is useful to leave large gaps (such as jumping from 80 to 200 or 500) when the next set of fields has a particular purpose that isn't associated with the prior set of fields.

The fields combining the primary key can use numbers up to nine since they are very unlikely to change. If this is changed at a later date, then a substantial amount of refactoring has to be done.

The Business Central online documentation says to not leave gaps in field numbers. Based on many years of experience, we disagree. Leaving numbering gaps will allow us to add additional fields between existing fields at a later date, 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 the previously defined fields should not be changed.

The following screenshot shows our new table definition in the table designer:

Note that you can remove anything you don't need from the snippet. In our case, we removed the DataClassification and keys sections, the variable declaration, and triggers.
 

Pages

Pages provide views of data or processes that are designed for on-screen display (or exposure as web services), and also allow 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 Business Central:

  • 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, and control properties. Data controls are generally 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 AL code within page or page control triggers, it is good practice to minimize the amount of code embedded within pages. Any data-related 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 you to enter or edit 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 that's visible to be controlled by the user at any time. 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 that 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 that contain 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 of a document page is the Sales Orders page that's shown in the following screenshot. In this example, the first tab and the last four tabs are in card page format, and show Sales Orders data fields that have a single occurrence on the page (in other words, they do not occur in a repeating column).

The second tab from the top is in a list part page format (all fields are in repeating columns) that shows the Sales Orders line items. Sales Orders line items may include products to be shipped, special charges, comments, and other pertinent order details. The information to the right of the data entry area is related to 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 Payment Journals 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 initally accesses any data table for the first time. The Business Central Development Environment has wizards (object generation tools) to help you 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 users.

Our first list page will be the basis for viewing our Radio Show master records. From Visual Studio Code, click on New, then click on File. A New Page screen will appear. Click on New, type in the name of the file to be saved, and then click on Save. Enter the name (Radio Show Page.al). Now, we can use the snippet for the list pages called tpage:

Now we will set ID to 50100 and the name to "Radio Show List" , and change the SourceTable to "Radio Show", as shown in the following screenshot:

After doing this, we can see that NameSource is highlighted as a problem, and the PROBLEMS window at the bottom of our screen tells us that NameSource does not exist in the context.

The reason why this problem is occurring is because of the combination of the table object and this page. We joined these objects by selecting the Radio Show table as SourceTable for this page. By joining them, the page object now has a dependency on the table object.

The next step will be to add the fields from the table to the page in the repeater. We will remove the NameSource field to do so.

We should also remove everything we do not need, such as FactBoxes and actions:

We can Preview the page by making a modification to the launch.json file. Change the startupObjectId to 50100 and select AL: Publish without debugging from the Command Palette, as shown in the following screenshot:

This will launch the Business Central application with our newly created page as the startup object:

Because our table does not contain any data, we will only see a header with the name of our page.

 

Creating a card page

Now, let's create a card page. The process for a card page is almost the same as for a list page, but using a different snippet. Our page number will be 50101 , and the name will be Radio Show Card:

You can copy and paste most of the definitions from the list page file, or even use File and Save As in Visual Studio Code if you find that faster or easier to use.

Let's change the launch.json file to this new page and publish the extension again. We can preview the page by making a modification to the launch.json file. Change the startupObjectId to 50101 and select AL: Publish without debugging from the Command Palette, as shown in the following screenshot:

 

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.

We will now revert the launch.json file to run the 50100 page, as originally defined, and then publish the extension. In the published window, we will click on New and see the following screen:

Enter the data shown in the following table so that we can see what the page looks like when it contains data. Later on, after we have added more capabilities to our table and pages, some fields will be 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:

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 Black

2 hours

RS008

TALK

Kristels Babytalks

KRIS

Kristel van Vugt

1 hour

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.
 

Creating a list report

To create a report, we will use the report snippet and create the 50000 Radio Shows report.

Open Object Designer, select Report, and click New. The Report Dataset Designer is empty when it is displayed, so we need to add a Data Source (table) to the first blank row.

Type 50000 or Radio Show into the Data Source column:

If we want users to be able to execute our report from Business Central, we also need to enable a search so that they can find our report. We will do that using the UsageCategory and ApplicationArea properties.

More information on ApplicationArea can be found in the Microsoft Docs at https://docs.microsoft.com/en-us/dynamics-nav/applicationarea-property.

UsageCategory will determine where the report will be listed, and ApplicationArea will determine the access level a user requires to be able to execute the report:

Microsoft Docs has a good up-to-date explanation of the UsageCategory options (https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-al-menusuite-functionality).

The SourceTableName for our report is the Radio Show table. The columns are the fields from this table. Spaces and special characters are not allowed in column names for reports.

After selecting the columns and removing any unnecessary elements from the snippet, our report code should look as follows:

 

Generating the layout

Now that we have defined our dataset, we can create the layout. Business Central supports both RDLC, which can be edited in Visual Studio, and SQL Report Builder, and it also supports Microsoft Word.

Both layouts can be added to the report definition using the WordLayout and RDLCLayout properties:

To generate the layout, we need to package our application, which can be done from the Command Palette:

This screenshot shows the generated RDLC, which is essentially to XML syntax:

Let's see if we can run our report. To do that, we will publish our extension without startupObjectId:

In the Business Central session, we will use the searchbox and type in the word radio , which will show our report:

When you click on the report and select Preview, you should see an empty layout.

 

Designing the layout

In this book, we will focus on Word reports, and we will go ahead and remove the RDLC file and associated property in the report. We will use the DefaultLayout property to make Word the default report format choice. Next, we will right-click on the RadioShows.docx file and open it in Microsoft Word:

In Microsoft Word, we need to locate the Developer tab, which might not be visible by default. Go to File | Options | Customize Ribbon and select Developer:

This will allow you to select XML Mapping Pane:

Let's create a simple list report by adding a table control to the report. We will select the middle row of the table control. Then, we will right-click on DataItemName and use Insert Content Control | Repeating:

The next step is to add the fields to the rows, add captions, and, for eye candy, add a style:

After saving the Microsoft Word document, we can publish our extension, search for the report, and select Preview:

There is much more to come. All we've done so far is scratch the surface. But by now, you should have a pretty good overview of the development process for Business Central.

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

Other Business Central object types

Let's finish up our introductory review of the Business Central object types.

 

TableExtension and PageExtension

Similar to the Table and Page objects, the table and page extension objects allow you to define fields in the database and display them to the user.

Table extensions are connected to existing tables and share the same primary key values. Fields defined in table extensions can be used on any existing page and report that uses the original table.

Page extensions allow developers to add new fields, tabs, actions, and FactBoxes to existing pages. You can also use this to hide controls.

 

Codeunits

A codeunit is a container for chunks of AL code to be called from other objects. These chunks of code are called procedures. Procedures can be called from any of the other Business Central object types that can contain AL code. Codeunits can also be exposed (published) as web services. This allows the procedures within a published codeunit to be invoked by external routines.

Codeunits are suited structurally to contain only procedures. Even though procedures could be placed in other object types, the other object types have superstructures that relate to their designed primary use, such as pages, and reports.

Codeunits act only as containers for AL coded procedures. They have no auxiliary procedures, no method of direct user interaction, and no predefined processing. Even if we are creating only one or two procedures and they are closely related to the primary activity of a particular object, and if these procedures are needed from both inside and outside of the report, the best practice is still to locate the procedures in a codeunit.

There are several codeunits being delivered as part of the standard Business Central product, which are really function libraries. These codeunits consist completely of utility routines, and are generally organized on some functional basis (for example, associated with dimensions, some aspect of manufacturing, or some aspect of warehouse management). Many of these can be found by filtering the codeunit names on the Management and Mgt strings (the same could be said for some of the tables with the Buffer string in their name). When we customize a system, we should create our own procedure library codeunits to consolidate our customizations and make software maintenance easier. Some developers create their own libraries of favorite special procedures, and include a procedure library codeunit in systems on which they work.

 

Queries

Queries are objects whose purpose is to create extracted sets of data from the Business Central database and do so very efficiently. Business Central queries translate directly into T-SQL query statements and run on the SQL Server side rather than on the Business Central Service Tier. A query can extract data from a single table or multiple tables. In the process of extracting data, a query can make different types of joins (inner join, outer join, or cross join), filter, calculate FlowFields (special Business Central calculations that are discussed in detail in Chapter 3, Data Types and Fields), sort, and create sums and averages. Queries obey the Business Central data structure business logic.

The output of a query can be a CSV file (useful for Excel charts), an XML file (for charts or external applications), or an Odata file for a web service. Queries can be published for web service access, similar to pages and codeunits. The results of a query can also be viewed by pages (as described in Chapter 5, Queries and Reports), but are especially powerful when output to charts. With a little creativity, a query can also be used to feed data to a page or report via the use of a temporary table to hold the query results.

 

XMLports

XMLports is a tool for importing and exporting data. XMLports handle both XML structured data and other external text data formats. XML (eXtensible Markup Language) is the de facto standard for exchanging data between dissimilar systems. For example, XMLports could be used to communicate between our Business Central ERP system and our accounting firm's financial analysis and tax preparation system.

XML is designed to be extensible, which means that we can create or extend the definition as long as we communicate the defined XML format to our correspondents. There is a standard set of syntax rules to which XML formats must conform. A lot of new software uses XML. For example, the new versions of Microsoft Office are quite XML friendly. All web services communications are in the form of an exchange of XML structured data.

The non-XML text data files handled by XMLports fall into two categories. One is known as comma-separated value or comma-delimited files (they usually have a .csv file extension). Of course, the delimiters don't have to be commas. The other category is fixed format, in which the length and relative position of each field is predefined.

XMLports can contain AL logic for any type of appropriate data manipulation, either when importing or exporting. Functions such as editing, validating, combining, and filtering can be applied to the data as it passes through an XMLport.

 

Control add-ins

A control add-in allows JavaScript developers to create custom controls using plain HTML5 or jQuery. In fact, anything that creates JavaScript can be loaded into the browser, although Microsoft officially does not support frameworks like Angular and React.

 

Development backups and documentation

As with any system where we can do development work, careful attention to documentation and backing up our work is very important. Visual Studio Code provides a variety of techniques for handling each of these tasks.

The first area we can place documentation is in line with modified AL code. Individual comment lines can be created by starting the line with double forward slashes, //. Whole sections of comments (or commented out code) can be created by starting and ending the section with a pair of curly braces { }. Depending on the type of object and the nature of the specific changes, we should generally annotate each change inline with forward slashes rather than with curly braces wherever the code is touched so that all the changes can be easily identified by the next developer.

The best documentation resides outside of our source code. Visual Studio Code has built-in support for Git, which means that we can use any source code control system supporting that, including, but not limited to, GitHub, GitLab, or Visual Studio Team Services.

There are some great resources on how to get started with GitHub online, like the ones we mentioned earlier in this chapter. A good explanation about Git in general can be found on YouTube (https://www.youtube.com/watch?v=tDlHCr70WUs).

In short, when doing development in Business Central Visual Studio Code, everything we have learned earlier about good documentation practices applies. This holds true, regardless of whether the development is new work or the modification of existing logic.

You can download the code from this book on GitHub at https://github.com/markbrummel/Programming-Microsoft-Dynamics-365-Business-Central.
 

Summary

In this chapter, we covered some basic definitions of terms related to Business Central and Visual Studio Code. We followed with an introduction to the 11 Business Central objects types (tables, table extensions, pages, page extensions, page customizations, profiles, reports, codeunits, queries, control add-ins, and XMLports). We introduced table, page, and report creation through review and hands-on use, and began a Business Central application for the programming management of the Radio Show WTDU. Finally, we looked briefly at the tools that we use to integrate with external entities and discussed how different types of backups and documentation are handled in Visual Studio Code. Now that we have covered the basics, we will dive into the detail of the primary object types in the next few chapters.

In the next chapter, we will focus on tables: the foundation of any Business Central system.

 

Questions

  1. An ERP system such as Business Central includes a number of functional areas. Which of the following are part of Business Central? Choose four:
    • Manufacturing
    • Order processing
    • Planning
    • Computer Aided Design (CAD)
    • General accounting
  1. Functionality in Business Central includes the following (choose three):
    • Tablet client
    • Drag and drop
    • Document emailing
    • Spellchecker
    • Mandatory fields
  1. Business Central development is done in the Visual Studio Code IDE or Visual Studio. True or false?
  2. Match the following table types and descriptions for Business Central:
    • Journal audit trail
    • Ledger validation process
    • Register invoice
    • Document transaction entries
    • Posting history
  1. With Business Central, iPads can be used to display the RTC. True or false?
  2. Which of the following describe Business Central? Choose two:
    • Customizable
    • Includes a storefront module
    • Object-based
    • C# IDE
    • Object-oriented
  1. What are the Business Central object types?
  2. All Business Central objects except XMLports can contain AL code. True or false?
  3. Business Central includes support for publishing objects as web services. True or false?
  4. The home page for a Business Central user is called what? Choose one:
    • Role Home
    • Home Center
    • Main Page
    • Role Center
  1. Codeunits can be used as startupObjectId. True or false?
  2. Microsoft Word is used in Business Central for what work? Choose one:
    • Report data definition
    • Report layout
    • Role Center design
    • Query processing
  1. Codeunits are the only Business Central objects that can contain procedures. True or false?
  2. Query output can be used as a data item for reports. True or false?
  3. AL and Visual Studio Code are required for Business Central development. True or false?
  4. Which object number range is available for assignment to customer-specific objects? Choose two:
    • 20 - 500
    • 50,000 - 60,000
    • 150,000 - 200,000
    • 50,000 - 99,999
    • 10,000 - 100,000
  1. XMLports can only process XML formatted data. True or false?
  2. The work date can only be changed by the system administrator. True or false?
  3. A design pattern is which of the following? Choose two:
    • Reusable code
    • Stripes and plaid together
    • A proven way to solve a common problem
    • UI guidelines
  1. Business Central reports are often generated automatically through the use of a wizard. True or false?
About the Authors
  • Marije Brummel

    Author, programmer, consultant, project manager, presenter, evangelist, sales person, and a trainer. It's next to impossible to find someone as experienced as Marije Brummel in the Business Central community. Marije received the Microsoft MVP and the NAVUG All-Star awards among several others. She has chaired the Dynamics Credentialing committee and has authored official Microsoft Exam materials. She's the go-to girl for performance troubleshooting and upgrade challenges. One of her biggest achievements was introducing Design Patterns into the Business Central community. Her books, blog articles, and YouTube videos have influenced almost everyone involved with Business Central. She enjoys the outdoors with her dog and loves spending time with her family.

    Browse publications by this author
  • David Studebaker

    David Studebaker has been designing and developing software since 1962 as a developer, consultant, manager, and business owner. In 1967, David coauthored the first general-purpose SPOOL system, an AT&T / IBM joint project. He has been a founding partner in several firms, most recently Studebaker Technology and Liberty Grove Software. David's publications include a decade of technical reviews for ACM Computing Reviews and a number of articles on shop floor data collection. David originated the Packt series of books on programming Dynamics Business Central (aka Dynamics NAV). He has a BS in mechanical engineering from Purdue University and an MBA from the University of Chicago. He is a life member of the Association for Computing Machinery.

    Browse publications by this author
  • Christopher D. Studebaker

    Chris Studebaker was a certified environmental consultant working with manufacturing facilities to meet national and state regulations before he started working with Navision in 1999. After working on regulatory reporting, data analysis, project management, and subcontractor oversight, Chris has used those skills to sell, develop, and implement NAV for the past 20 years. He has specialized in retail, manufacturing, job shop, and distribution implementations, mostly in high-user-count, high-data-volume applications. Chris acts in a consulting and training role for customers and for peer NAV professionals. He has a Bachelor of Science degree from Northern Illinois University and has done graduate work at Denmark Technical University.

    Browse publications by this author
Latest Reviews (8 reviews total)
Es una buena base para entender la nueva forma de desarrollo en Business Central, evidentemente no está acrulizadio con los últimos cambios
Awesome book, real time example give you more knowledge
Todo bien. Bastante Actualizado
Recommended For You
Mastering Microsoft Dynamics 365 Business Central

Develop customized business management solutions with the latest features of Microsoft Dynamics 365 Business Central

By Stefano Demiliani and 1 more
Microsoft Dynamics 365 Business Central Cookbook

Gain useful insights to help you efficiently build, test, and migrate customized solutions on Business Central cloud and on-premise platforms

By Michael Glue
Dynamics 365 Business Central Development Quick Start Guide

Understanding the new Microsoft Extension model for development

By Stefano Demiliani and 1 more
Automated Testing in Microsoft Dynamics 365 Business Central

Learn how to write automated tests for Dynamics 365 Business Central and see how to implement it in your daily work

By Luc van Vugt