Home Business & Other Microsoft Dynamics 365 Business Central Cookbook

Microsoft Dynamics 365 Business Central Cookbook

By Michael Glue
books-svg-icon Book
eBook $35.99 $24.99
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $35.99 $24.99
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Let's Get the Basics out of the Way
About this book
Microsoft Dynamics 365 Business Central is a complete business management solution that can help you streamline business processes, connect individual departments in your company, and enhance customer interactions. Ok. That first part was really professional sounding, right? Now, let’s get into what this cookbook is going to do for you: put simply, it’s going to help you get things done. This book will help you get to grips with the latest development features and tools for building applications using Business Central. You’ll find recipes that will guide you in developing and testing applications that can be deployed to the cloud or on-premises. For the old-schoolers out there, you’ll also learn how to take your existing Dynamics NAV customizations and move them to the new AL language platform. Also, if you haven’t figured it out already, we’re going to be using very normal language throughout the book to keep things light. After all, developing applications is fun, so why not have fun learning as well!
Publication date:
August 2019
Publisher
Packt
Pages
380
ISBN
9781789958546

 

Let's Get the Basics out of the Way

Microsoft Dynamics 365 Business Central is a complete business application management system. With it comes an exciting new development platform and tools. Using AL, the primary development language, and Visual Studio Code, the primary development tool, you can create incredibly rich and feature-packed Business Central applications to fit the needs of virtually any customer.

In this chapter, we're going to go over the basics (yes, exactly like the title says!). Some of the recipes in this chapter are very simple, and you might wonder what the point of them is, but don't discount them. There is a reason behind each one, and I'll explain them along the way.

We will start this chapter with a recipe for setting up your development sandbox. After all, we can't build any applications without a place to test them! Once we have our sandbox in place, we will install and configure Visual Studio Code in order to connect it to the sandbox. We'll then move on through a set of recipes that will show you some of the basic components that almost every application you build will have.

In this chapter, we will cover the following recipes:

  • Setting up your development sandbox
  • Creating a new AL project
  • Creating basic entities
  • Creating new business logic
  • Classifying data
  • User permissions
  • Creating new reports
  • Adding help links
 

Technical requirements

In order to complete the recipes in this chapter (and this book, for that matter!), you need to install Visual Studio Code on your machine. You will use this to code your AL applications, but you can also use it for a myriad of other programming languages and scripts. You can read and obtain Visual Studio Code at https://code.visualstudio.com/.

If you plan on using a Docker container on your local machine, then you'll also need to install Docker. You're going to want to make sure you install the right edition, based on your OS:

If you have a Business Central license file, you should upload it somewhere that you can access it using a secure URL. For example, you can upload it to either an Azure Storage or Dropbox account. You must be able to get a secure URL for direct download.

Code samples and scripts are available on GitHub. Each of the recipes in this chapter builds on the previous recipe, so you can always download the previous recipe's code to get a quick jump on things if you don't want to work through them all in order. You can download everything you need from https://github.com/PacktPublishing/Microsoft-Dynamics-365-Business-Central-Cookbook/tree/master/ch1.

For the reporting recipe, you'll need to have Microsoft Report Builder installed. You can download that from Microsoft Download Center at https://go.microsoft.com/fwlink/?LinkID=734968.

 

Setting up your development sandbox

Well, we're kicking things off with a bang! Our first recipe is probably the longest recipe in this book, but that's because you have choices when it comes to setting up your development sandbox. Will you use a sandbox hosted in Business Central or will you set up your sandbox on a machine? Will that machine be hosted in Azure or on your local machine? Will you use a container or not? The choice is yours, and we'll go through each process in this recipe. By the end of this recipe, you will have a place to do all of your AL coding!

Getting ready

Depending on how you want to set up your development sandbox, you may need to do a few different things to prepare:

  • Sign up for or get access to a Business Central subscription
  • Sign up for or get access to an Azure subscription for which you can create virtual machines
  • Install Docker
  • Obtain the latest Business Central installation media

How to do it...

We have four different choices here. If you're super savvy, then by all means, try them all out, but really, you only need to do the one that fits you best.

Option 1 – Sandbox hosted in Business Central

If you want to set up your development sandbox to be hosted in Business Central—which, by the way, is the simplest of all the options—perform the following steps:

  1. Sign up for a Microsoft Dynamics 365 Business Central sandbox at https://aka.ms/getsandboxforbusinesscentral.
When you sign up for your sandbox, you cannot use a personal email address. You must use either a work or school account.
  1. Install the AL Language extension from the Visual Studio Code Marketplace at https://marketplace.visualstudio.com/items?itemName=ms-dynamics-smb.al:

There are just two steps to getting your sandbox! Once you go through the signup process, you'll be logged into your sandbox and will be greeted with a message similar to the following:

Option 2 – Azure-hosted sandbox

If you want to use a container hosted on a virtual machine in Azure, perform the following steps:

  1. If you have not already done so, you can sign up for an Azure subscription at https://azure.microsoft.com and start with a free account.
  2. Now that we have an Azure subscription, we need to create a virtual machine within that subscription. This virtual machine will host a Business Central environment inside a Docker container. To make this easy, there is an Azure Resource Manager (ARM) template available for you to use.

You can access the template at https://aka.ms/getbc. Make sure to use your Azure subscription login credentials.
The template contains a lot of options, but for our purposes, we're going to focus on just a few of them. Once you're familiar with the process, take a look at the other options and do things such as connecting your sandbox to an Office 365 account! See the options in the following table:

Option Comment
Resource Group Select Create new to create a new resource group for this virtual machine. You can name it whatever you like.
Location Choose the region closest to where you are connecting from. Selecting a region on the other side of the world from you will impact connection performance.
VM Name Give your machine a name – any name you want! Azure will make sure that the name you choose is acceptable.
Time zone Id Select the time zone you wish to work in.
Accept EULA You must accept the End User License Agreement (EULA) by selecting Yes for this option. The EULA can be found at https://go.microsoft.com/fwlink/?linkid=861843.
Remote Desktop Access Use this option to configure whether you are able to use Remote Desktop Protocol (RDP) to remotely log in to the virtual machine. Set this to an asterisk (*) if you want to connect to this machine from any machine.
VM Admin username You can leave this as the default value, vmadmin, or change it to one that suits you better. This login will be used to remote connect (via RDP) to the machine. This login is configured as the local administrator for the virtual machine.
BC Admin username You can leave this as the default value, admin, or change it to one that suits you better. You will use this login to launch the Business Central Web Client. This user is configured as a super user in the Business Central system.
Admin Password Set this to any password you want. This password applies to both the virtual machine and BC admin logins. Azure will ensure that the password you enter is strong enough.
BC Docker Image Here, you can configure the Docker image you wish to use. Set this option to microsoft/bcsandbox:xx, where :xx represents the country localization you want (for example, microsoft/bcsandbox:ca for Canada). For the list of countries available, see https://hub.docker.com/_/microsoft-businesscentral-sandbox.
License File URL If you uploaded a Business Central license to an online storage account, specify the secure URL to the file in this option. You can leave this option blank if you want to use a demo license.
You can get more information on each option in the template by using the '!' icon onscreen, which is directly to the right of each option name.
  1. Once you have filled in the ARM template, accept the terms and conditions at the bottom of the screen and then click the Purchase button.

Now, you can just sit back and relax, and if your template was configured properly, your virtual machine will be created. Go grab a coffee and check back later.

Make sure you wait at least one hour before logging into the virtual machine. Even after it is successfully created, the machine will go through a series of configurations to create and set up the container.
  1. To test the connection to your Azure virtual machine, you need to remotely connect to the machine to get some information from it. You need to use the Azure web portal (https://portal.azure.com) to find the address of your virtual machine:
    1. In the Azure web portal, click on Virtual Machines in the navigation pane on the left:
      • If you do not see Virtual Machines, press All Services and search for Virtual Machines to select it.
    2. Select the name of the virtual machine that you just created.
    3. Look for the DNS Name and take note of the address listed below it:
      • For example, myvirtualmachine.canadaeast.cloudapp.azure.com
  2. We can monitor the status of the virtual machine configuration by navigating to the virtual machine landing page:
    1. In your web browser, navigate to the DNS Name you noted previously.
    2. Click the View Installation Status link. Here, you can see when the virtual machine configuration is complete and is ready to use for development.

Once the virtual machine has been fully configured, the landing page will look similar to this:

  1. Now, we need to take note of a few pieces of information, for later.

At the bottom of the landing page is a section named Access the Dynamics 365 Business Central Sandbox Environment using Visual Studio Code. In this section, take note of the following values:

You can also download a remote connection file from the landing page in the event that you want to connect to and work directly within the server.
  1. Before we close the landing page, we need to install the security certificate so that we can connect to the sandbox:
    1. On the landing page, click the Download Certificate link and save the file to your local machine.
    2. Depending on which web browser you are using, click either the Windows (Edge/IE/Chrome) or the Windows (Firefox) link and follow the onscreen instructions to install the certificate.
  1. Let's check to make sure we can connect to the Business Central Web Client:
    1. Close your web browser and navigate to the landing page for your virtual machine.
    2. Click the Web Client link on the right-hand side of the page.

You should now be looking at the Business Central login page:

If you get an error about an unsecured connection, try restarting your web browser and/or reinstalling the security certificate.
  1. Install the AL Language extension from the Visual Studio Code Marketplace: https://marketplace.visualstudio.com/items?itemName=ms-dynamics-smb.al.

Option 3 – Sandbox in a local container

If you prefer to have your development sandbox in a container on your local machine, you must have Docker installed and working on your machine. It should be configured to run Windows containers, rather than the default Linux ones. Once you have that, you can perform the following steps:

  1. Download CreateSandboxContainer.ps1 from the GitHub repository.
  2. Run PowerShell ISE as an administrator and open CreateSandboxContainer.ps1.

Let's look at what the code does. The first line in the script installs NavContainerHelper, which is a PowerShell module that contains an entire toolbox of commands for interacting with Business Central containers:

$install-module navcontainerhelper -force
If you would like to read more about NavContainerHelper, there's a wonderful set of blogs about it at https://blogs.msdn.microsoft.com/freddyk/tag/navcontainerhelper/.
  1. We have the end-user license agreement. You must manually accept the agreement by setting $accept_eula = $true:
# set to $true to accept the eula (https://go.microsoft.com/fwlink/?linkid=861843)
$accept_eula = $false
  1. You need to assign your sandbox container a name:
# set the name of your container (must be 15 characters or less)
$containername = ''
Docker container names are case-sensitive, so I recommend using lowercase names.
  1. You need to define which Docker image will be used for the sandbox container. Refer to the link in the script for information on which images are available, as follows:
# set image to use to create container (see here for available images: https://hub.docker.com/_/microsoft-businesscentral-sandbox)
$bcdockerimage = 'mcr.microsoft.com/businesscentral/sandbox:us'
  1. Set your login credentials. The script will configure the container to be based on a user and password login, so here is where you can define what the username and password will be:
# the user you use to login to the Business Central client (is a SUPER user)
$userName = "admin"
$password = ConvertTo-SecureString -String "Pass@word1" -AsPlainText -Force

If you have a Business Central license, you can upload it to an online storage account and access it with a secure URL. You can put the URL in the script, as follows:

# set the secure URL to your Business Central license file (leave blank to use the demo license)
$licenseFileUri = ''
If you upload your license file, you must upload it to a storage account that allows direct download links.

The rest of the script is where the magic happens. First, the username and password that you defined will be converted into PowerShell credential objects, and then the New-NavContainer command does all the heavy lifting to create your sandbox:

$credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $userName, $password

New-NavContainer -accept_eula:$accept_eula `
-containername $containername `
-auth UserPassword `
-Credential $credential `
-licenseFile $licenseFileUri `
-includeCSide `
-alwaysPull `
-doNotExportObjectsToText `
-usessl:$false `
-updateHosts `
-assignPremiumPlan `
-shortcuts Desktop `
-imageName $bcdockerimage `
-useBestContainerOS
In order to execute the preceding script, you may need to configure the Execution Policy on your machine in order to allow it to run unsigned scripts. You can do that using the Set-ExecutionPolicy command-let. For more details, follow https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/set-executionpolicy?view=powershell-6.
  1. At this point, if you've filled in all the configuration in the script, you can run it by pressing F5. Then, sit back and relax while your container is created. The first thing that will happen is that the Docker image will be downloaded to your machine. This is the longest part of the process because the files are being downloaded, unpacked, and verified. A typical image will be around 10 - 20 GB.

Once that is finished, the container will be created and should be ready in under 10 minutes.

Do not close the PowerShell window yet!

  1. We need to take note of some important information that we're going to need later. In the PowerShell window, look for the following information and save it for later:
  1. To verify that your machine is working, open your web browser and navigate to the Web Client address that was listed in the PowerShell window (see the preceding example).
  2. Install the AL Language extension from the Visual Studio Code Marketplace: https://marketplace.visualstudio.com/items?itemName=ms-dynamics-smb.al.

Option 4 – Local sandbox using installation media

If you want to install Business Central onto your local machine using the installation media, you can do that by following these steps:

  1. From the installation media, run setup.exe.
  2. You must accept the licensing terms. Once you do that, click Advanced Installation Options.
  3. Here, you can choose between two setup options:
    • Install Demo: This installs a pre-configuration selection of components without manual intervention.
    • Choose an installation option: This allows you to choose which components to install and allows you to select some additional configuration options.
  4. Click the Choose an installation option so that we can select the components that we need to complete the recipes in this book.
  5. Click Customize... under the Developer option.
  6. Make sure that the following components are set to Run from My Computer:
    • AL Development Environment
    • Server Administration Tool
    • Server
    • SQL Server Database Components
    • SQL Server Database Components | Demo Database
    • Web Server Components
    • Dynamics NAV Client | Development Environment (C/SIDE)

Here is a screenshot for your reference:

  1. Click Next and you will see some additional installation parameters. For the purposes of the recipes in this book, you do not need to change anything here.
If you already have a compatible version of Microsoft SQL Server installed on your local machine, you can change the SQL Server and SQL Server Instance parameters to the corresponding ones so that the Business Central installation will use that instead of installing a new instance.
  1. Click Apply to perform the installation.
If the installation cannot find a compatible version of Microsoft SQL Server, then you will be notified that it will install a new instance. At the time of writing, Microsoft SQL Server 2016 Express is the version that will be installed.
  1. Once the installation has completed, click Close to close the installation wizard.
  2. You can verify the installation by opening the Business Central Web Client from the following URL: http://localhost:8080/BC130.
  3. Install the AL Language extension from the Visual Studio Code Marketplace at https://marketplace.visualstudio.com/items?itemName=ms-dynamics-smb.al.

How it works...

As you can see, you have a variety of ways you can configure your development sandbox. Personal preference may lead you to choose one way or another, but there are a few things to keep in mind when selecting which configuration to use:

  • Do you need offline access to your development sandbox? If so, then an Azure-hosted system might not be the right choice for you.
  • Do you need to build for the current Business Central SaaS version? If so, then you might want to consider setting up your development sandbox to be hosted in Business Central so that it is always on the current release.
  • Do you need to make sure your application will work on a future Business Central release? If so, you will want to take part in Microsoft's Ready to Go (http://aka.ms/readytogo) program so that you can gain access to future releases made available via Docker images.
  • Do you need to have multiple versions of Business Central on your local machine? If so, there's no easier way than using Docker containers to do that!

Each of the processes resulted in the same thing: a development system that will be used to build and test new Business Central applications. Whether it is hosted or not, or a container or local installation, the end result is the same: a development sandbox that you will build and publish your Business Central applications to.

See also

 

Creating a new AL project

In this recipe, we are going to create a quick and easy sample application. Of course, you can start from a blank slate, but we'll start with the built-in Hello World application. It's the easiest way to get your AL development up and running.

Getting ready

You need to have your development sandbox set up and know the address so that you can connect and log in to it. You should have also already installed the AL Language extension in Visual Studio Code. You're definitely going to need that!

How to do it...

  1. Open Visual Studio Code.
  2. Press Ctrl + Shift + P to open the Command Palette and type or select AL:Go! to create a sample Hello World application.
  3. When prompted, enter the path to where the new project will be stored. You can leave it as the default path or type in a new one. Press Enter to confirm the path.
  4. When prompted, you need to select the sandbox type based on what you are working with. You have two options:
    • Microsoft Cloud Sandbox: Select this option if you are hosting your development sandbox in Business Central (Option 1 in the Setting up your development sandbox section). When you select this option, you will be prompted to log in with your Microsoft account. Use the account under which you created the Business Central sandbox.
    • Your own server: Select this option if you chose to put your sandbox in an Azure virtual machine, or on your local machine using a container or the installation media (Options 2 - 4 in the Setting up your development sandbox section). When you select this option, you will be prompted to log in. Press Escape to cancel the login.
  5. This step is only required if you selected Your own server in the preceding step. Skip to the next step if you selected Microsoft Cloud Server.

Before we log in to our development sandbox, we need to make sure that we have the correct connection configuration.

This information is stored in the launch.json file in the .vscode folder. You can view the file's contents by selecting it in the Visual Studio Code Explorer.

There are three properties that we need to look at here and set based on how we set up our development sandbox:

server Here, you need to enter the connection URL into your sandbox. You can leave it at the default ("http://localhost") if you installed your sandbox using the installation media. If you hosted your sandbox on an Azure virtual machine, this will be the "server": value that you obtained from the virtual machine landing page. If you have your sandbox in a container on your local machine, this value will be the Dev. Server value you obtained from the PowerShell window.
serverInstance Here, you need to specify the name of your server instance (or service tier name). You can leave it at the default ("BC130") if you installed your sandbox using the installation media. If your sandbox is hosted on an Azure virtual machine, this will be the "serverInstance": value that you obtained from the virtual machine landing page. If you have your sandbox in a container on your local machine, this value will be the Dev. ServerInstance value you obtained from the PowerShell window.
authentication This defines the authentication method that will be used to connect to your sandbox. If you installed your sandbox using the installation media, you will set this value to "Windows". If you hosted your sandbox on an Azure virtual machine or it is in a container on your local machine, this value should be set to "UserPassword".
As you're poking around the launch.json file, if you press Enter to create a new line within the file, you can then press Ctrl + Space to see a list of other properties that are available for you to use.
  1. Now that we have our configuration set up, we need to download symbols. At this point, Visual Studio Code may have already been prompting you to do that.

Press Ctrl + Shift + P to open the Command Palette and type or select AL: Download Symbols to download the symbols.

This will prompt a connection to be made to your development sandbox, and the symbols will be downloaded to your local machine. They will be placed in a folder named .alpackages, which you will see in the Explorer.

The symbol files are required for you to do any sort of AL development. They contain metadata that describes all the entities that exist in your development sandbox, such as tables, functions, and pages.

Once the symbols have been downloaded, you will see two files in the .alpackages folder, similar to what you can see in the following screenshot:

  1. Now, it's time to build and publish our application.

To do that, you can simply press F5, which will build the application and then publish it to your development sandbox in debug mode. If you do not want to publish it in debug mode, you can press Ctrl + F5.

If you simply want to build your application but are not ready to publish it, you can do that by pressing Ctrl + Shift + B, and your application will be built in, but not published to, your development sandbox.

How it works...

Creating the sample application is the quickest way to begin a new AL project. Once you connect your project to your development sandbox and download the symbols, you will be ready to code your AL application.

There's more...

Before you begin creating your new AL application using the sample application, you will need to delete the HelloWorld.al file that is in the sample application.

 

Creating basic entities

Adding basic entities to your AL application is easy. We're going to take a look at two of them in this recipe: tables and pages. We'll create a new table to track television shows (come on, we need to have some fun with this, right!?) and an associated card and list page.

Getting ready

You're going to need an AL project to work in that's connected to a development sandbox. We will continue to build on the project that we started in this chapter. You can download it from the GitHub link at the start of this chapter.

How to do it...

  1. Open your AL project folder in Visual Studio Code. If you have not done so already, delete HelloWorld.al.
  2. In the Visual Studio Code Explorer, right-click and select New File. Name this file Television Show.al.

Repeat this process and create two more files:

    • Television Show List.al
    • Television Show Card.al
All files that contain AL code need to have an .al extension.
  1. Let's define the new table.
You can quickly add the basic structure for a table and field by using the ttable and tfield snippets. Do this by typing in your chosen snippet name and pressing Tab.

In Explorer, select Television Show.al. In the Editor tab, enter the following:

table 50100 "Television Show"
{
fields
{
field(1; Code; Code[20])
{
NotBlank = true;
}
field(2; Name; Text[80])
{
}
field(3; Synopsis; Text[250])
{
}
field(4; Status; Option)
{
OptionCaption = 'Active,Finished';
OptionMembers = Active,Finished;
}
field(5; "First Aired"; Date)
{
}
}

keys
{
key(PK; Code)
{
Clustered = true;
}
}
}

Make sure you save your changes.

  1. Now, let's create a card to display the detailed information for our Television Show records.
You can quickly add the basic structure for a card page by using the tpage snippet. There are multiple types of page snippets, so be sure to select the correct one.

In Explorer, select Television Show Card.al. In the Editor tab, enter the following:

page 50100 "Television Show Card"
{
PageType = Card;
SourceTable = "Television Show";
DelayedInsert = true;

layout
{
area(Content)
{
group(General)
{
field(Code; Code)
{
ApplicationArea = All;
}
field(Name; Name)
{
ApplicationArea = All;
}
field(Synopsis; Synopsis)
{
ApplicationArea = All;
}
field(Status; Status)
{
ApplicationArea = All;
}
field("First Aired"; "First Aired")
{
ApplicationArea = All;
}
}
}
}
}
  1. Now, we'll build a list page to display the records from our new table.
Only show the most relevant and frequently used information on your list pages.

In Explorer, select Television Show List.al. In the Editor tab, enter the following:

page 50101 "Television Show List"
{
PageType = List;
ApplicationArea = All;
UsageCategory = Lists;
Editable = false;
CardPageId = "Television Show Card";
SourceTable = "Television Show";

layout
{
area(Content)
{
repeater(Group)
{
field(Code; Code)
{
ApplicationArea = All;
}
field(Name; Name)
{
ApplicationArea = All;
}
field(Status; Status)
{
ApplicationArea = All;
}
}
}
}
}
In order to make your pages (and reports) searchable in the Business Central Web Client, you need to populate ApplicationArea and UsageCategory in the AL object file.
  1. Our basic application is ready to be published for testing. In the launch.json file, set the following properties:
"startupObjectId": 50101
"startupObjectType": "Page"
  1. Press F5 to publish the application to your development sandbox. Your web browser will open and, once you log in, you will be presented with your new Television Show List page:
  1. Of course, there is not much to see until you enter some records. Try that out by clicking the +New button in the ribbon; the Television Show Card should open:

How it works...

We created a basic Business Central application and published it to our development sandbox.

Creating a table allows us to define what data we will capture in our application. We can define a number of properties for each table and field.

In order to display the data in the table, we need to create pages. These allow the user to interact with the data in our application. A list page is the first page that the user will get to when they want to access the data. From this list, they can search, filter existing data, create new data, modify data, and even delete data. When more detailed information is required, the user can navigate from the list page to the card page, which is meant to show more detailed information and actions regarding the data.

See also

 

Creating new business logic

Adding a place to store data and interact with it is essential, but in all likelihood, you're going to need to manipulate the data or provide some logic for the user to interact with. In this recipe, we will create some business logic for our application.

Getting ready

We're going to need an AL project that's connected to a development sandbox to work in. We will continue to build on the project that we started in this chapter. You can download it from the GitHub link at the start of this chapter.

How to do it...

  1. Open your AL project folder in Visual Studio Code.
  2. In the Visual Studio Code Explorer, select the Television Show.al file. In the Editor tab, add two new fields named Last Aired and Created By, as follows:
field(6; "Last Aired"; Date)
{
}
field(7; "Created By"; Code[50])
{
Editable = false;
}
  1. When a new record is added to the Television Show table, we want to know who created it. We can do that by adding code to the OnInsert() trigger of the table so that our logic executes every time a record is inserted.

In the Television Show.al file, add the trigger and logic after the keys section. All we need to do is set the Created By field to the ID of the current user, as follows:

trigger OnInsert()
begin
"Created By" := UserId();
end;
You can use the trigger snippet to create a new trigger.
  1. Our next requirement is to make sure that if the user enters the Last Aired date, they choose a date that is not earlier than the First Aired date. This is simple logic, but it controls our data integrity.

This is done by adding code to the InValidate() trigger of both date fields, since either can be changed independently of the other.

Since we don't want to write the same code twice, we'll create a new procedure and call it from both fields. The new procedure will validate the dates.

Start by creating a new procedure. Add this new procedure after the OnInsert() trigger you added in the preceding step. The procedure will look like this:

local procedure VerifyDates()
var
FirstAiredDateCannotBeLaterErr: Label '%1 cannot be earlier
than %2';
begin
if "Last Aired" = 0D then
exit;

if "First Aired" > "Last Aired" then
Error(FirstAiredDateCannotBeLaterErr,
FieldCaption("Last Aired"),
FieldCaption("First Aired"));
end;

Like I said, it's simple logic, right?

Notice the Label variable. These are new to AL and take the place of text constants. You can read more about them at https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/methods-auto/label/label-data-type.
  1. Now that we have our new procedure, we need to call it from each of the date fields. We do that by adding a call to the procedure in the OnValidate() trigger of the First Aired and Last Aired fields. The trigger will look like this:
trigger onValidate()
begin
VerifyDates();
end;

Now that we have all of our logic in place, the Television Show.al file should look like this:

table 50100 "Television Show"
{
fields
{
field(1; Code; Code[20])
{
NotBlank = true;
}
field(2; Name; Text[80])
{
}
field(3; Synopsis; Text[250])
{
}
field(4; Status; Option)
{
OptionCaption = 'Active,Finished';
OptionMembers = Active,Finished;
}
field(5; "First Aired"; Date)
{
trigger onValidate()
begin
VerifyDates();
end;
}
field(6; "Last Aired"; Date)
{
trigger onValidate()
begin
VerifyDates();
end;
}
field(7; "Created By"; Code[50])
{
Editable = false;
}
}

keys
{
key(PK; Code)
{
Clustered = true;
}
}

trigger OnInsert()
begin
"Created By" := UserId();
end;

local procedure VerifyDates()
var
FirstAiredDateCannotBeLaterErr: Label '%1 cannot be
earlier than %2';
begin
if "Last Aired" = 0D then
exit;

if "First Aired" > "Last Aired" then
Error(FirstAiredDateCannotBeLaterErr,
FieldCaption("Last Aired"),
FieldCaption("First Aired"));
end;
}
  1. Before we can test our new logic, we need to add the Last Aired field to the Television Show Card.
    In Explorer, select Television Show Card.al and add the following code at the end of the group(General) section:
field("Last Aired"; "Last Aired")
{
ApplicationArea = All;
}
  1. We also need to add the Created By field to the Television Show List.

In Explorer, select Television Show List.al and add the following code at the end of the repeater(Group) section:

field("Created By"; "Created By")
{
ApplicationArea = All;
}
  1. Press F5 to build and deploy your application. Once your web browser opens and you log in to your sandbox, you will be on the Television Show List page.

Perform the following steps:

    1. Click +New to open the Television Show Card.
    2. Populate the Code field and press Tab.
    3. Select any date you want in the First Aired field.
    4. In the Last Aired field, select a date that is earlier than the date you selected in First Aired.
    5. Click on any other field on the page.

You should see the following error message:

  1. Close the Television Show Card. You will see that the Created By field has been populated for the new record that you just entered:

How it works...

Triggers are functions that happen based on when predetermined actions occur. When code is placed in these triggers, it is executed whenever the trigger is executed. It is important to note, however, that a trigger can be bypassed using business logic, so you cannot 100% guarantee that a trigger will fire.

The examples we looked at were table triggers that executed when a record was inserted into the table and any time a field was validated. There are many other triggers that are available for you to use in your AL coding. Each different AL object type has its own set of triggers.

See also

 

Classifying data

Data privacy is a huge concern for people today. With countless online systems collecting and tracking data from everyone in the world, people want to know that their data is safe and private, and that if they choose to remove their data from a system, it can be done.

Business Central contains features that help you build applications that are compliant with the regulatory requirements for the collecting and handling of personal information.

As an AL developer, you have the ability to identify the type of data that is stored in any new table or field that you create. We will look at how to do this in this recipe.

Getting ready

You're going to need an AL project to work in that's connected to a development sandbox. We will continue to build on the project that we started in this chapter. You can download it from the GitHub link at the start of this chapter.

How to do it...

  1. Open your AL project in Visual Studio Code and select the Television Show.al file in Explorer.
  2. For each field that we added to the Television Show table, we need to add the DataClassification property and assign it a value of CustomerContent, as follows:
DataClassification = CustomerContent;
In the event that a field has multiple properties, the order in which the properties are listed does not matter; however, the properties must be listed before any triggers that are defined.
  1. Define the same property to the overall table by adding the following to your AL file, before the fields section:
DataClassification = CustomerContent;

How it works...

By specifying the DataClassification property for the table and the fields within the table, we have now made our application compliant with data privacy regulations. There are multiple classifications that can be applied to data:

  • CustomerContent: Content created by users of the system
  • EndUserIdentifiableInformation: Data that can be used to identify an end user (for example, username and IP address)
  • AccountData: Data that is part of a customer's billing and payment information (for example, name, address, and email)
  • EndUsePseudonymousIdentifiers: An identifier that can be used in conjunction with other information to identify an end user (for example, user GUID and user SID)
  • OrganizationIdentifiableInformation: Data that can be used to find a tenant (for example, Tenant ID).
  • SystemMetadata: Data generated by the system that cannot be linked to a user or tenant

There's more...

Having the developer define the type of data that your tables and fields contain within the application is just the first step in maintaining data privacy. Business Central contains another feature that lets customers further define the sensitivity of the data in their system. The data sensitivity of a field can be set to one of the following levels:

  • Sensitive
  • Personal
  • Confidential
  • Normal

See also

 

User permissions

Remember that, when we deliver an application to a customer, we're trying to provide them with the best experience that we can. Nothing's worse than building the best application you can build and everything tests out great, but then you deploy it to the customer and nobody can run it because they don't have any permissions set up. This adds a layer of complexity for the customer that doesn't really need to be there, so the administrator needs to figure out what new entities were added so that they can update their permission sets.

In this recipe, you will see that, with your AL application, you can create a set of user permissions that will be installed when your application is deployed. Then, all an administrator has to do is assign those permissions to the appropriate users!

Getting ready

You're going to need an AL project to work in that's connected to a development sandbox. We will continue to build on the project that we started in this chapter. You can download it from the GitHub link at the start of this chapter.

How to do it...

  1. Open up your AL project in Visual Studio Code. Press Ctrl + Shift + P to open the Command Palette and type or select AL: Generate permission set containing current extension objects.

Wait... what? That's it? Yeah, it is that easy! When this command runs, it will create a file named extensionPermissionSet.xml.

This file will contain default permissions for every AL object file that you have created in your project:

    • Tables: Allow the user to run each table and have full read/write/modify access to the data in the table
    • Everything else: Allows the user to execute all other AL object types (such as pages, codeunits, and reports)

Your file should look similar to this:

<?xml version="1.0" encoding="utf-8"?>
<PermissionSets>
<PermissionSet RoleID="ALPROJECT1" RoleName="ALProject1">
<Permission>
<ObjectType>0</ObjectType>
<ObjectID>50100</ObjectID>
<ReadPermission>1</ReadPermission>
<InsertPermission>1</InsertPermission>
<ModifyPermission>1</ModifyPermission>
<DeletePermission>1</DeletePermission>
<ExecutePermission>0</ExecutePermission>
<SecurityFilter />
</Permission>
<Permission>
<ObjectType>1</ObjectType>
<ObjectID>50100</ObjectID>
<ReadPermission>0</ReadPermission>
<InsertPermission>0</InsertPermission>
<ModifyPermission>0</ModifyPermission>
<DeletePermission>0</DeletePermission>
<ExecutePermission>1</ExecutePermission>
<SecurityFilter />
</Permission>
<Permission>
<ObjectType>8</ObjectType>
<ObjectID>50101</ObjectID>
<ReadPermission>0</ReadPermission>
<InsertPermission>0</InsertPermission>
<ModifyPermission>0</ModifyPermission>
<DeletePermission>0</DeletePermission>
<ExecutePermission>1</ExecutePermission>
<SecurityFilter />
</Permission>
<Permission>
<ObjectType>8</ObjectType>
<ObjectID>50100</ObjectID>
<ReadPermission>0</ReadPermission>
<InsertPermission>0</InsertPermission>
<ModifyPermission>0</ModifyPermission>
<DeletePermission>0</DeletePermission>
<ExecutePermission>1</ExecutePermission>
<SecurityFilter />
</Permission>
</PermissionSet>
</PermissionSets>
If you make manual updates to the file that was generated by Visual Studio Code, and you run the command again to generate the XML file, your changes will be lost. You can avoid this by renaming the file that was generated so it doesn't get overwritten. Any manual changes need to be merged with the generated file.
  1. At this point, it's a really good idea to change the RoleID and RoleName values in the file. This makes it easier for the administrator who is assigning the permissions and trying to figure out what each permission set is for.

Set these properties to the following values:

RoleID="TVSHOW"
RoleName="Television Show"
If you prefer, you can also manually create a permission set file by creating an empty XML file, and then using the tpermsets and tpermset snippets to quickly build the structure of the file.
  1. Now, we can publish our application to make sure that our permission set gets installed properly.

In Visual Studio Code, press F5 to build and publish the application.

  1. When your browser opens up, log in to your sandbox and click the icon at the top-right of the window in order to open the Tell Me What You Want to Do search page. In the search box, type in permission sets and click the link to open the PERMISSION SETS page. In the list of available permission sets, you should see the TVSHOW set that you just created:
  1. Click on the TVSHOW permission set row, and on the ribbon at the top, click on More options | Navigate | Permissions | Permission Set to open up the permission set details. Here, you can see which permissions are included in the permission set. It should look like this:

As you can see, our permission set includes full access to the Television Show data, and access to run everything that is included in our application.

How it works...

When you create the XML file using the specific structure outlined previously, the AL compiler is able to automatically determine that the file contains permission sets and permissions, and it will automatically load the permission sets into Business Central when your application is installed. This way, the customer does not need to try and figure out what objects have been added, nor do they need to update any existing permission sets that they have already defined.

You can create multiple permission sets within your application, and you can define the permissions in as much detail as you like. For example, you could define two permission sets, where one has only read-only access to the data, and the other set has full access, thereby giving the customer the option of assigning different levels of user access.

There's more...

Once your permission sets have been installed, the last step is for the administrator to assign the permission sets to the applicable users. This can be done by either assigning the permission set directly to the user or by assigning the permission set to a user group. By doing this, all users within that group will inherit the new permission set.

See also

 

Creating new reports

In this recipe, we'll look at how you can add a report to your Business Central application. Just a basic report, though – this isn't a lesson on how to create report layouts, which is a whole other topic in itself.

Getting ready

You're going to need an AL project to work on that's connected to a development sandbox. We will continue to build on the project that we started in this chapter. You can download it from the GitHub link at the start of this chapter.

Make sure you have Microsoft Report Builder installed as well!

How to do it...

  1. Open up your AL project in Visual Studio Code. In the Explorer, right-click and select New File. Name the file Television Shows Report.al. This report will be a simple list to show the records from the Television Show table you added earlier.
  2. Now, we need to define the structure of our report dataset.
You can use the report snippet to quickly create the basic structure of a report.

Select the new file and, in the Editor tab, enter the following code:

report 50100 "Television Shows Report"
{
UsageCategory = ReportsAndAnalysis;
ApplicationArea = All;
DefaultLayout = RDLC;
RDLCLayout = 'Television Shows Report.rdl';

dataset
{
dataitem("Television Show"; "Television Show")
{
RequestFilterFields = Code, "First Aired", "Last
Aired", Status;

column(Code; Code)
{

}
column(Name; Name)
{

}
column(First_Aired; "First Aired")
{

}
column(Last_Aired; "Last Aired")
{

}
}
}
}

As you can see, in the preceding code, we have defined this report to have an RDLC layout:

DefaultLayout = RDLC;

We have also defined the name of the layout file:

RDLCLayout = 'Television Shows Report.rdl';
A report can be defined with both a Word and an RDLC layout; however, only one can be defined as the default layout. Adding a Word layout to the report would look like WordLayout = 'Television Shows Report.docx';.
  1. So, how do we create the layout file that we defined in the report AL object file? Of course, you could do it manually, but where's the magic in that? The AL Language extension is going to help you out here. When you build an AL project, if the report layout files that you've defined do not exist, it will create the files for you (with no content, of course – it's not going to do all the work for you!).

Press Ctrl + Shift + B to build your AL project.

Notice how in the Explorer, a new file named Television Shows Report.rdlc was created:

  1. The layout that was created for us has an .rdlc extension. This is not exactly what we want. By default, this file type will not open using SQL Report Builder, which—for this recipe, at least—is our reporting tool of choice.

Rename the Television Shows Report.rdlc layout file and change it to Television Shows Report.rdl. This now matches the layout name we defined in the RDLCLayout property, and it can now be opened using SQL Report Builder.

  1. Now that we have our empty report layout, what do we do next? Well, we need to actually create the layout in that file as it's empty right now. We're going to use Microsoft Report Builder to build a very simple list report layout.

Open Report Builder and click Open to open the RDL file that you created in your AL project:

Although the layout contents are completely empty, the RDL file does contain the dataset that you defined in the AL object file. You can see this by expanding Datasets | DataSet_Result in the Report Data pane:

  1. Now, we can add a simple table to display the data from the Television Show table. We're going to use the built-in wizard for this.

At the top of the Report Builder window, click on the Insert tab and then click on Table | Table Wizard... to open up the wizard:

  1. In the New Table or Matrix window, select Choose an existing dataset in this report or a shared dataset, and then select the DataSet_Result dataset:
  1. Click on Next; and you will see the list of available fields:
    1. Click and drag the Code field to the Row groups section.
    2. Click and drag the remaining fields (Name, First_Aired and Last_Aired) to the Values section.

The wizard should look similar to this:

  1. Click Next to choose the layout options. Uncheck both of the following options:
    • Show subtotals and grand totals
    • Expand/collapse groups

This is shown in the following screenshot:

  1. Click on Finish to close the wizard and add the table to the report layout. The report layout window should now look similar to this:

I know – this is not exactly the prettiest layout that's ever been created, but like I said, the point of this recipe is not to learn how to create beautiful reports. We just want to get a report built in our Business Central application.

  1. In Report Builder, click at the top left to save the report layout. You can now close the Report Builder.
  2. We've now created our dataset in an AL file and linked it to a new RDLC layout file. Now, it's time to check out our report.
    Press F5 to build and publish our application.
  3. Once your browser is open and you're logged in to the sandbox, use the icon at the top-right to search for Television Shows Report, and click the link to open the report.

Click Preview to run the report onscreen:

At this point, you'll see something such as the following (yes; at this point, you might be realizing that you need to add some Television Show entries):

How it works...

A report is made up of two parts:

  • Dataset: This is an AL file where you will define the tables, fields, filtering, and logic that applies to the report.
  • Layout: This will be either a Microsoft Word or an RDLC-formatted file and is where you define what the output of the report will look like.

The two parts are linked using properties in the AL file so that when the report is loaded into Business Central, the system knows which layout to use for which report.

There's more...

You can store up to two layouts (one RDLC layout and one for Microsoft Word) with an AL report object, which gives you the ability to deliver different, effectively built-in layout options to the customer. Once the report is installed in Business Central, however, the customer has the ability to further customize those layouts or create an entirely new layout by using the Custom Report Layouts feature of Business Central.

See also

 

Adding help links

You've built an amazing application, you've deployed it to the customer, and now they need help... what do you do? Wouldn't it be nice if you had a dedicated help website for your application? Wouldn't it be nice if, when the user clicked the help icon within your application, they would be taken to that dedicated help website? In this recipe, you'll see how you can make that happen.

Getting ready

You're going to need an AL project to work in that's connected to a development sandbox. We will continue to build on the project that we started in this chapter. You can download it from the GitHub link at the start of this chapter.

How to do it...

  1. Open your AL project in Visual Studio Code. In Explorer, select the Television Show List.al file and add the HelpLink page property, as highlighted in the following code:
PageType = List;
ApplicationArea = All;
UsageCategory = Lists;
Editable = false;
CardPageId = "Television Show Card";
SourceTable = "Television Show";
HelpLink = 'http://customhelpsite.com/televisionshows';
  1. Press F5 to build and publish your application.
  2. Once your browser opens and you log in to your sandbox, you will be on the Television Show List. Select the icon at the top right and select Help:

You will be directed to your new custom help link. The link does not point to a real page, as it is just to illustrate the point.

  1. Close the Television Show List and use the icon at the top right to search for items. Click the link to open the Items list. Select the icon at the top right and select Help. You will see that you're directed to the Microsoft online help website, and not your custom website.

How it works...

When you define a page's HelpLink and the user selects the Help link in Business Central while on that page, they will be directed to the custom link that's defined for the page. The rest of the pages in the system that are not part of your application will continue to go to the Microsoft online help website.

You can either define page-specific help links or direct all of your pages to a generic landing page. The choice is yours.

As an added bonus, you can also specify help links not only on pages, but also on report request pages and XMLports!

See also

About the Author
  • Michael Glue

    Michael Glue began his Dynamics journey in June 2001, when he became a certified Dynamics NAV developer. Starting with building custom solutions, he later became a product architect, where he focused solely on building repeatable vertical products. Today, Michael works with a talented research and development team as they continue to push their products forward on the Business Central platform. In 2018, Michael was given his first MVP award in Business Applications. Along with his wife, Jennifer, they have four amazing kids and four very active dogs. From coaching his daughters' baseball team, to playing video games with his boys, to watching a good movie with his wife, not a day goes by that is devoid of excitement. You can follow Michael on Twitter (@navbitsbytes).

    Browse publications by this author
Microsoft Dynamics 365 Business Central Cookbook
Unlock this book and the full library FREE for 7 days
Start now