Visual Studio Code Example Extension



-->

Writing a Visual Studio code extension in minutes. This will create the vscode-extension-example project complete with required files. STEP 2: Extension basics. Publish the extension to the Visual Studio Code Marketplace. Our VS Code extension can be published in the Visual Studio Code Marketplace to share it with the public. Refer to this documentation page for instructions on publishing the extension in the VS Code Marketplace. Sample extension source code. The mssql extension for Visual Studio Code lets you connect to a SQL Server, query with Transact-SQL (T-SQL), and view the results. In Visual Studio Code, select View Command Palette, or press Ctrl+Shift+P, or press F1 to open the Command Palette. In the Command Palette, select Extensions: Install Extensions from the dropdown.

This walkthrough will guide you through all the steps that you must follow to create a sample extension in AL. New objects and extension objects will be added to the base application for a simple reward feature for customers. Every section of this exercise includes code that serves for installing, customizing, or upgrading this sample extension. The final result can be published and installed on your tenants.

About this walkthrough

This walkthrough illustrates the following tasks:

  • Developing a sample extension with a table, a card page, and a list page.

  • Deploying the sample extension to your development sandbox environment.

  • Using the Dynamics 365 Business Central Designer to modify visual aspects of the extension.

  • Creating extension objects that can be used to modify page and table objects.

  • Initializing the database during the installation of the extension.

  • Upgrading and preserving data during the upgrade of the extension.

Prerequisites

To complete this walkthrough, you will need:

  • The Dynamics 365 Business Central tenant.

  • Visual Studio Code.

  • The AL Language extension for Visual Studio Code.

For more information on how to get started with your first extension for Dynamics 365 Business Central, see Getting Started.

Rewards extension overview

The extension enables the ability to assign one of three reward levels to customers: GOLD, SILVER, and BRONZE. Each reward level can be assigned a discount percentage. Different types of objects available within the AL development environment will build the foundation of the user interface, allowing the user to edit the information. If you look for another option to update the layout of a page, you can use the Designer drag-and-drop interface. Additionally, this exercise contains the install code that will create the base for the reward levels. The upgrade code is run to upgrade the extension to a newer version and it will change the BRONZE level to ALUMINUM. Following all the steps of this walkthrough allows you to publish the extension on your tenant and create a possible new feature for your customers.

Reward table object

The following code adds a new table 50100 Reward for storing the reward levels for customers. The table consists of three fields: Reward ID, Description, and Discount Percentage. For example, the Description field must contain a value of type text and it cannot exceed the limit of 250 characters. The second field contains three properties that are used to set the range of the discount percentage assigned to every customer. Properties can be created for every field, depending on the scope.

Tip

Type ttable followed by the Tab key. This snippet will create a basic layout for a table object.

For more information about table properties, see Table Properties.

Reward card page object

The following code adds a new page 50101 Reward Card for viewing and editing the different reward levels that are stored in the new Reward table. Pages are the primary object that a user will interact with and have a different behavior based on the type of page that you choose. The Reward Card page is of type Card and it is used to view and edit one record or entity from the Reward table.

Tip

Use the snippet tpage, Page to create the basic structure for the page object.

For more information about the types of pages in AL, see Pages Overview.

Reward list page object

The following code adds the 50102 Reward List page that enables users to view the contents of the Reward table and edit specific records by selecting them and viewing them in the Reward Card page.

Tip

Use the snippet tpage, Page of type list to create the basic structure for the page object.

After you have created the objects, update the startupObjectId in the launch.json file to 50102, the ID of the Reward List page and select the Ctrl+F5 shortcut to see the new page in your sandbox environment. You will be asked to sign in to your Business Central, if you have not already done so.

Tip

Information about your sandbox environment and other environments is stored as configurations in the launch.json file. For more information, see JSON Files.

Designer

Dynamics 365 Business Central Designer works in the browser and allows modifying the current page. It enables users to add existing table fields, move fields around, or remove fields from the page. Users can make changes to display the information they need, where they need it by using drag-and-drop components.
To show how the Designer changes the design of a page, you begin by adding two new fields to the Reward table. These fields will be used later on to exemplify the Designer's properties.

The Last Modified Date field requires constant changes to remain accurate. To keep it updated, triggers will be used. Triggers are predefined methods that are executed when certain actions happen. They are added by default when you use the ttable template, but you can also use the ttriger snippet to add them manually. Now you can add code to the triggers.

From this point, changes to the Reward Card page can be done either manually by adding the code below in Visual Studio Code or by using the Designer's functions to add the same fields. Both ways lead to the same results, but the Designer speeds up the process.

Using the F6 key shortcut in Visual Studio Code launches the browser and enters the Designer. You can also use the Designer from the Business Central client, by selecting Designer.

Note

Every time you start designing, you create a new extension and the changes you make in the Designer will apply to all users.

To add the same fields and customize the Reward Card page, follow the next steps:

  • Navigate to the Reward Card page by choosing + new.
  • Enter the Designer mode from the UI and select More from the Designer bar.
  • Select Field from the Designer bar to show the list of available fields.
  • Drag the Minimum Purchase and Last Modified Date fields from the list onto the page in the Reward group.
  • Choose the Reward in the group caption to enable the value to be edited. Change the caption to Info and press Enter.

After making these adjustments, finish up your design by choosing Stop Designing, which allows you to name the extension with an option to download code, and save the extension for the tenant. If you choose not to download the code at the end, you can still pull the changes via the Alt+F6 key shortcut from Visual Studio Code. You can also uninstall the extension by opening the Extension Management page.
For more information about Designer, see Designer.

Customer table extension object

The Customer table, like many other tables, is part of the Dynamics 365 Business Central service and it cannot be modified directly by developers. To add additional fields or to change properties on this table, developers must create a new type of object, a table extension.The following code creates a table extension for the Customer table and adds the Reward ID field.

Tip

Use the snippet ttableext to create a basic structure for the table extension object.

Customer card page extension object

A page extension object can be used to add new functionality to pages that are part of the Dynamics 365 Business Central service. The following page extension object extends the Customer Card page object by adding a field control, Reward ID, to the General group on the page. The field is added in the layout section, while in the actions section the code adds an action to open the Reward List page.

Tip

Use the shortcuts tpageext to create the basic structure for the page extension object.

At this point, reward levels can be created and assigned to customers. To do that, update the startupObjectId value in launch.json to 21 and select the Ctrl+F5 key to open the page.

Help links

This app is relatively straightforward, but we want users of your app to be able to get unblocked and learn more just like all other users of Business Central. First, configure your app to get context-sensitive links to Help, and then apply tooltips to the fields in your pages.

Configure context-sensitive links to Help

At an app level, you can specify where the Help for your functionality is published in the app.json file. Then, for each page in your app, you specify which Help file on that website is relevant for that particular page. For more information, see Configure Context-Sensitive Help.

Open the app.json file, and then change the value of the contextSensitiveHelpUrl property to point at the right location on your website. In this example, you publish Help for your app at https://mysite.com/documentation.

Next, you set the ContextSensitiveHelpPage property for the Reward Card and Reward List pages:

The following example illustrates the properties for the Reward List page after you have specified the context-sensitive Help page.

You can specify the same relative link for Reward Card, Reward List, and the customization of the Customer page, or you can specify different targets. For more information, see Page-level configuration.

Add tooltips

Even the best designed user interface can still be confusing to some. It can be difficult to predict specifically what users will find confusing, and that is why the base application includes tooltips for all controls and actions. For more information, see Help users get unblocked.

For the purposes of this walkthrough, add the following tooltip to the properties of the Reward ID field on all three pages:

The following example illustrates the tooltip:

If you now deploy the app, you will be able to read the tooltip text for the Reward ID field, and if you choose the Learn more link or press Ctrl+F1, a new browser tab opens the equivalent of https://mysite.com/documentation/sales-rewards.

Install code

After installing the extension, the Reward List page is empty. This is the result of the fact that the Reward table is also empty. Data can be entered manually into the Reward table by creating new records from the Reward List page. However, this task slows down the process, especially because the Reward table should be initialized with a standard number of reward levels when the extension is installed. To solve this, install codeunits can be used. A codeunit is an object that can be used to encapsulate a set of related functionality represented by procedures and variables. An install codeunit is a codeunit with the Subtype property set to Install. This codeunit provides a set of triggers that are executed when the extension is installed for the first time and when the same version is re-installed.

In this example, the following install codeunit initializes the Reward table with three records representing the 'GOLD', 'SILVER', and 'BRONZE' reward levels.

Tip

Use the shortcuts tcodeunit to create the basic structure for the codeunit.

For more information about install code, see Writing Extension Install Code.

Upgrade code

When you upgrade an extension to a newer version, if any modifications to the existing data are required to support the upgrade, you must write upgrade code in an upgrade codeunit. In this example, the following upgrade codeunit contains code that changes the BRONZE reward level to customer records to ALUMINUM. The upgrade codeunit will run when you run the Start-NAVAppDataUpgrade cmdlet.

Important

Remember to increase the version number of the extension in the app.json file.

For more information about writing and running upgrade code, see Upgrading Extension.

Instrumenting your app with telemetry

Business Central emits telemetry data for several operations that occur when extension code is run. Create an Application Insights resource in Azure if you don't have one. For more information, see Create an Application Insights resource. Now, add the Application Insights Key to the extension manifest (app.json file):

Replace <instrumenation key> with your key.

You can configure your extension to send this data to a specific Application Insights resource on Microsoft Azure. For more information, see Sending Extension Telemetry to Azure Application Insights.

Conclusion

This walkthrough demonstrated how an extension can be developed. The main AL objects and extension objects were used to store the reward levels, to view, and to edit them. The Designer was introduced as an alternative to modify visual aspects of page objects and to customize them from the web client instead of using code. Up to this point, the table and the page objects were empty, but the install codeunits were added and allowed to initialize the Reward table with a standard number of reward levels when the extension was installed. An upgrade code section was also included in this exercise to create a full picture of all processes involved when an extension is built. As a result, a user is enabled to assign one of the three reward levels to a customer and to change this scenario by upgrading the version of the extension.

Tip

To try building a more advanced Customer Rewards sample extension, see Building an Advanced Sample Extension.

See Also

Developing Extensions
Getting Started with AL
How to: Publish and Install an Extension
Converting Extensions V1 to Extensions V2
Configure Context-Sensitive Help
Sending Extension Telemetry to Azure Application Insights

  • Editing

Introduction

Since the beginning, editors are a strange beast. Some people defend their editor choice strenuously. In the Unix world you have those Emacs vs vi “wars”, and I kind of imagine why so much time is spend debating the advantages of one versus another.

I used tons of editors and IDEs in the past few years. I can remember TextMate, TextWrangler, Espresso, BBEdit, XCode, Coda, Brackets, Sublime Text, Atom, vim, PHPStorm. The difference between an IDE and an editor is mostly in the feature set, and complexity.

I largely prefer an editor over an IDE, as it’s faster and gets less in the way.

In the last 12 months I’ve been using VS Code, the Open Source editor from Microsoft, and it’s quickly become my favorite editor ever.

Visual studio code example extension pdf

Should I switch to VS Code? And why?

If you’re looking for suggestions for whether to use it or not, let me say yes, you should switch to it from whatever other editor you are using now.

This editor builds on top of decades of editor experience from Microsoft.

The code of the editor is completely Open Source, and there’s no payment required to use it.

It uses Electron as its base, which enables it to be cross platform and work on Mac, Windows and Linux. It’s built using Node.js, and you can extend it using JavaScript (which makes it a win for all us JavaScript developers).

It’s fast, easily the fastest editor I’ve used after Sublime Text.

It has won the enthusiasm of the community: there are thousands of extensions, some official, and some made by the community, and it’s winning surveys.

Microsoft releases an update every month. Frequent updates foster innovation and Microsoft is listening to its users, while keeping the platform as stable as possible (I should say I never had an issue with VS Code in 1 year of using it every day almost all day).

Getting started

The home page of Visual Studio Code on the internet is https://code.visualstudio.com/.

Go to that site to download the latest stable release of the editor.

The installation process depends on the platform, and you should be used to it.

When you start the editor for the first time you will see the welcome screen:

There is a toolbar on the left with 5 icons. That gives access to:

  • The File Explorer
  • Search
  • Source Control
  • The Debugger
  • The Extensions

Explorer

Let’s start the exploration with the explorer (pun intended).

Press the “Open Folder” button in the sidebar, or the Open folder... link in the Welcome page. Both will trigger the file picker view.

Choose one folder where you have source code, or even just text files, and open it.

VS Code will show that folder content in your view:

On the right, the empty view shows some commands to perform some quick operations, and their keyboard shortcut.

If you select a file on the left, that file will open on the main panel:

and if you start editing it, notice a dot will appear next to the file name in the tab, and in the sidebar as well:

Pressing CMD+P will show you a quick file picker to easily move in files on large projects:

You can hide the sidebar that hosts the file using the shortcut CMD+B.

Note: I’m using the Mac keyboard shortcuts. Most of the times, on Windows and Linux you just change CMT to CTRL and it works, but not always. Print your keyboard shortcuts reference.

Search

The second icon in the toolbar is “Search”. Clicking it shows the search interface:

You can click the icons to make the search case sensitive, to match whole words (not substrings), and to use a regular expression for the search string.

To perform the search, press enter.

Clicking the ▷ symbol on the left enables the search and replace tool.

Clicking the 3 dots shows a panel that lets you just include some specific kind of files, and exclude other files:

Source Control

The Source Control tab is enabled by clicking the third icon in the toolbar.

VS Code comes with Git support out of the box. In this case the folder we opened does not have source control initialized.

Clicking the first icon on top, with the Git logo, allows us to initialize the Git repository:

The U beside each file means that it’s been updated since the last commit (since we never did a commit in the first place, all files are updated).

Create the first commit by writing a text message and pressing Cmd-Enter, or clicking the ✔︎ icon on top.

I usually set this to automatically stage the changes when I commit them.

The 3 dots icon, when clicked, offers lots of options for interacting with Git:

Debugger

The fourth icon in the toolbar opens the JavaScript debugger. This deserves an article on its own. In the meantime check out the official docs.

Extensions

The fifth icon brings us to extensions.

Extensions are one killer feature of VS Code.

They can provide so much value that you’ll surely end up using tons of them.

I have lots of extensions installed.

One thing to remember is that every extension you install is going to impact (more or less) the performance of your editor.

You can disable an extension you install, and enable only when you need it.

You can also disable an extension for a specific workspace (we’ll talk about work workspaces later). For example, you don’t want to enable the JavaScript extensions in a Go project.

There is a list of recommended extensions, which include all the most popular tools.

Since I edit lots of markdown files for my blog, VS Code suggests me the markdownlint extension, which provides linting and syntax checking for Markdown files.

As an example, let’s install it.

First, I inspect the number of views. It’s 1.2M, so many! And the reviews are positive (4.55). Clicking the extension name opens the details on the right.

Pressing the green Install button starts the installation process, which is straightforward. It does everything for you, and you just need to click the “Reload” button to activate it, which basically reboots the editor window.

Done! Let’s test it by creating a markdown file with an error, like a missing alt attribute on an image. It successfully tells us so:

Down below I introduce some popular extensions you don’t want to miss, and the ones I use the most.

The Terminal

VS Code has an integrated terminal.

You can activate it from the menu View ➤ Integrated Terminal, or using CMD+` and it will open with your default shell.

This is very convenient because in modern web development you almost always have some npm or yarn process running in the background.

You can create more than one terminal tab, and show them one next to the other, and also stack them to the right rather than in the bottom of the window:

The Command Palette

The Command Palette is a very powerful tool. You enable it by clicking View ➤ Command Palette, or using CMD+SHIFT+P

A modal window will appear at the top, offering you various options, depending on which plugins you have installed, and which commands you used last.

Common operations I perform are:

  • Extensions: Install Extensions
  • Preferences: Color Theme to change the color theme (I sometimes change from night to day)
  • Format Document, which formats code automatically
  • Run Code, which is provided by Code Runner, and executes the highlighted lines of JavaScript

you can activate any of those by starting typing, and the autocomplete functionality will show you the one you want.

Remember when you typed CMD+P to see the list of files, before? That’s a shortcut to a specific feature of the Command Palette. There are others:

  • Ctrl-Shift-Tab shows you the active files
  • Ctrl-G opens the command palette to let you enter a line number to go to
  • CMD+SHIFT+O shows the list of symbols found in the current file

What symbols are depends on the file type. In JavaScript, those might be classes or functions. In Markdown, section titles.

Themes

Visual Studio Code Example Extension

You can switch the color theme used by clicking CMD-k + CMD-t, or by invoking the Preferences: Color Theme command.

This will show you the list of themes installed:

you can click one, or move with the keyboard, and VS Code will show you a preview. Click enter to apply the theme:

Themes are just extensions. You can install new themes by going to the extensions manager.

Probably the best thing for discoverability is to use the marketplace website.

My favorite theme is Ayu, which provides a great style for any time of the day, night, morning/evenings and afternoon.

Customization

Theme is just one customization you can make.

The sidebar icons that are assigned to a file are also a big part of a nice user experience.

You can change those by going to Preferences ➤ File Icon Theme. Ayu comes with its own icons theme, which perfectly matches the theme colors:

All those customizations we made so far, the theme and the icon theme, are saved to the user preferences.

Go to Preferences ➤ Settings (also reachable via CMD-,) to see them:

The view shows the default settings on the left, for an easy reference, and the overridden settings on the right. You can see the name of the theme and the icon theme we set up, in workbench.colorTheme and workbench.iconTheme.

I zoomed in using CMD-+, and this setting was saved as well to window.zoomLevel, so the next time VS Code starts up, it remembers my choice for zooming.

You can decide to apply some setting globally, in User Settings, or relative to a workspace, in Workspace settings.

Most of the times those settings are automatically added by extensions or by the VS Code itself, but in some cases you’ll directly edit them in this place.

Nice configuration options

Visual Studio Code Example Extension Pdf

VS Code has a lot of options. Everything is highly configurable, and it’s sometimes hard to make sense of it all.

You can open the configuration JSON file using the command palette, and select Open Settings (JSON).

Some nice configuration options I set in my code:

OptionDescription
'editor.minimap.enabled': falseRemove the minimap, which is shown at the right of the editor
'explorer.confirmDelete': falseStop asking me for confirmation when I want to remove a file (I have source control!)
'explorer.confirmDragAndDrop': falseDisable the confirmation for drag and drop
'editor.formatOnSave': trueFormat the code automatically when I save it
'editor.formatOnPaste': trueFormat the code automatically when I paste it in my code
'javascript.format.enable': trueEnable formatting for JavaScript code
'files.trimTrailingWhitespace': trueTrim whitespace in files
'editor.multiCursorModifier': 'alt'When clicking the Alt key and clicking with the mouse, I can select multiple lines
'editor.detectIndentation': trueAdapt to the file indentation, useful when editing other people code
'editor.quickSuggestionsDelay': 0Show the code suggestion immediately, not after some seconds

The best font for coding

I like Fira Code. It’s free, and has some very nice programming ligatures, which transform common constructs like ! and => to nicer symbols:

Enable it by installing the font and adding this to your configuration:

Workspaces

All User settings can be overridden in Workspace settings. They take precedence. They are useful for example when you use a project that has linting rules different from all the other projects you use, and you don’t want to edit your favorite settings just for it.

You create a workspace from an existing project by clicking the File ➤ Save Workspace as... menu.

The currently opened folder will be enabled as the workspace main folder.

The next time you open VS code, or you switch project, instead of opening a folder, you open a workspace, and that will automatically open the folder containing your code, and it will remember all the settings you set specific to that workspace.

In addition to having workspace-level settings, you can disable extensions for a specific workspace.

You can just work with folders until you have a specific reason for wanting a workspace.

One good reason is the ability to have multiple, separate root folders. You can use the File ➤ Add Folder to Workspace to add a new root folder, which can be located anywhere in the filesystem, but will be shown along with the other existing folder you had.

Editing

IntelliSense

When you edit in one of the supported languages (JavaScript, JSON, HTML, CSS, Less, Sass, C# and TypeScript) VS Code has IntelliSense, a technology that hints at autocompletion of functions and parameters, as you type them.

Code Formatting

Two handy commands (Format Document and Format Selection) are available on the Commands Palette to autoformat the code. VS Code by defaults supports automatic formatting for HTML, JavaScript, TypeScript and JSON.

Errors and warnings

When you open a file you will see on the right a bar with some colors. Those colors indicate some issues in your code. For example here’s what I see right now:

Those are al warnings or errors. You can try to find them in the code, where you see pieces underlined in red, or you can also press CMD-Shift-M (or choose View ➤ Problems)

Keyboard shortcuts

I showed you a lot of keyboard shortcuts up to now.

Free Visual Studio Code Examples

It’s starting to get complicated to remember them all, but they are a nice productivity aid. I suggest to print the official shortcuts cheat sheet, for Mac, Linux and Windows.

Keymaps

If you’re used to keyboard shortcuts from other editors, maybe because you worked with one editor for a long time, you can use a keymap.

The VS Code team provides keymaps for the most popular editors out of the box: vim, Sublime Text, Atom, IntelliJ, Eclipse and more. They are available as plugins. By opening the Preferences ➤ Keymaps Extensions menu.

Best Visual Studio Code Extension

Code snippets

Snippets are very cool.

For every language you might be developing in, there are extensions that provide ready-made snippets for you to use.

For JavaScript/React, one popular one is VS Code ES7 React/Redux/React-Native/JS snippets

You just type rfe, press TAB and this appears in your editor:

there are lots of these shortcuts, and they save a lot of time. Not just from typing, but also from looking up the correct syntax.

You can also define your own snippets. Click Preferences ➤ User Snippets and follow the instructions to create your own snippets file.

Visual Studio Code File Extensions

Extensions showcase

  • GitLens: visualize who made the last change to a line of your code, and when this happened
  • Git History visualize and search the Git history
  • CSS Peek lets you see and edit CSS definitions by inspecting the class of an HTML element. Very handy.
  • Code Runner lets you run bits of code that you select in the editor, and much more. Supports lots of languages.
  • Debugger for Chrome allows you to debug a JavaScript code running in the browser using the VS code debugger.
  • Bracket Pair Colorizer handy for visualizing brackets endings in your code.
  • Indent-Rainbow colors the indentation levels of your code.
  • Prettier check my Prettier guide
  • ESLint check my ESLint guide
  • IntelliSense for CSS improved autocompletion for CSS based on your workspace definitions
  • npm enables npm utility functions from the command palette
  • Auto Close Tag automatically close HTML/JSX/* tags
  • Auto Rename Tag automatically renames the closing tag when you change the opening one, and the opposite as well

The VS Code CLI command

Open the command palette and search for the install 'code' command in PATH command.

Press enter and the code command will be available globally in your command line.

This is very useful to start the editor and open a new window with the content of the current folder, with code ..

code -n will create a new window.

A useful thing that’s not always known is that VS Code can quickly show the diff between two files, with code --diff file1.js file2.js.

Solving high usage CPU issues

I ran into an issue of high CPU usage, and spinning fans, with a project with lots of files under node_modules. I added this configuration and things looked normal again:


C++ Visual Studio Code Example

More devtools tutorials:

Visual Studio Code Extensions






Comments are closed.