Getting Started

To get started developing in Microsoft Dynamics NAV 2016, see the following topics.

To See

Learn about new features in Microsoft Dynamics NAV 2016.

  • What's New: Developer and IT Pro Changes for Microsoft Dynamics NAV

  • What’s New: Application Changes for Microsoft Dynamics NAV

Find documentation about developer or IT pro tasks.

Finding Information in Help

Learn about the Microsoft Dynamics NAV Windows client from the perspective of a developer.

Touring the RoleTailored Client for Developers

Learn about the Microsoft Dynamics NAV Web client from the perspective of a developer.

Microsoft Dynamics NAV Web Client

Learn about the Microsoft Dynamics NAV Tablet client from the perspective of a developer.

Developing for the Microsoft Dynamics NAV Universal App

Learn how to install, deploy, and configure Microsoft Dynamics NAV 2016.

Deployment

Learn how to upgrade from an earlier version to Microsoft Dynamics NAV 2016.

Upgrading to Microsoft Dynamics NAV 2016

Learn about development options for Microsoft Dynamics NAV 2016.

Development

Develop tables, codeunits, pages, reports, queries, XMLports, and MenuSuites in Microsoft Dynamics NAV 2016.

Objects

Learn about administration tools and processes for Microsoft Dynamics NAV 2016.

Administration

Read about application security.

Security and Protection

Find reference information, including C/AL functions, triggers, properties, development environment commands, and development environment windows.

Technical Reference

Watch videos to learn more about development and UI on the MSDN Dev Center for Microsoft Dynamics NAV.

Microsoft Dynamics NAV Dev Center

© 2015 Microsoft. All rights reserved.

Build Date:

2015-08-27


What's New: Developer and IT Pro Changes for Microsoft Dynamics NAV
See Also

Microsoft Dynamics NAV is a complete enterprise resource planning (ERP) software solution for mid-sized organizations that is fast to implement, easy to configure, and simple to use. Right from the start, simplicity has guided—and continues to guide—innovations in product design, development, implementation, and usability.

This document details new features and functionality that are available in Microsoft Dynamics NAV 2016 and have been added to the product since Microsoft Dynamics NAV 2015. It also describes features that have been deprecated since Microsoft Dynamics NAV 2015. For information about Microsoft Dynamics NAV 2015, see What's New: Developer and IT Pro Changes for Microsoft Dynamics NAV 2015 in the MSDN Library.

What's New for Developers, Administrators, and IT Pros in Microsoft Dynamics NAV 2016

Microsoft Dynamics NAV 2016 introduces changes to the upgrade, deployment, and development experiences compared to Microsoft Dynamics NAV 2015.

Redesigned C/AL Editor

The C/AL Editor in the Microsoft Dynamics NAV Development Environment has been redesigned to give you more coding capabilities. Coding in the new C/AL editor is like before except you benefit from new features such as IntelliSense, name completion, change tracking, improved syntax highlighting and colorization. The new design has a look-and-feel that resembles the Debugger regarding breakpoints.

Tip
You can use the old version of the C/AL Editor by running the Microsoft Dynamics NAV Development Environment from a command prompt and setting the useoldeditor parameter.

Event Channels on Microsoft Dynamics NAV Server Events

Microsoft Dynamics NAV 2016 introduces event channels on events that occur on Microsoft Dynamics NAV Server instances. Event channels provide a way to collect and view event data from a specific provider, which in this case in Microsoft Dynamics NAV Server, and for a specific type of event, such as admin, operational, or debug. The implementation of event channels offers the following enhancements to event logging and viewing:

  • In addition to the Windows Application log, Microsoft Dynamics NAV Server events are recorded in specific Microsoft Dynamics NAV Server logs in the Applications and Services Logs of Windows.

    This provides an advantage over the Windows Application log which contains events from several providers, not just the Microsoft Dynamics NAV Server. You also have the option to disable logging to the Windows Application log.

  • You can use Event Viewer to view trace events.

  • You can use FilterXpath parameter of the Get-WinEvent Windows PowerShell cmdlet to filter events for a specific Microsoft Dynamics NAV Server instance.

For more information, see Monitoring Microsoft Dynamics NAV Server Events.

Multiple Namespaces on XMLports

You can define multiple namespaces on XMLports that import or export data as XML. This improves the ability to create XMLports that are compatible with the XML schemas that are used by the systems that consume or provide the Microsoft Dynamics NAV data.

You define namespaces in the new Namespaces Property of the XMLport object. Each namespace is defined by a prefix and the namespace, which is typically a URI (uniform Resource Identifier). You then apply the prefix to specific elements of the XMLport by setting the new NamespacePrefix Property.

For more information, see Using Namespaces with XMLports.

Updating Custom Report Layouts by Using Upgrade Codeunits

You can update custom report layouts by creating upgrade codeunits to handle changes in report datasets that affect the report layouts. Upgrade codeunits enable you to programmatically update multiple custom report layouts in the database to changes in report datasets that cannot be resolved by users from the Microsoft Dynamics NAV client. For more information, see Updating Custom Report Layouts by Using Upgrade Codeunits.

Filter Pages for Filtering Tables

Microsoft Dynamics NAV 2016 includes the new C/AL data type FILTERPAGEBUILDER. You can use the FILTERPAGEBUILDER data type and its functions to create a filter page that enables users to set filters on one or more tables. A filter page contains one or more filter controls, where each filter control can be used to set filters on a specific table. Similar to report request pages in the Microsoft Dynamics NAV client, filter pages are generated at runtime and run in a modal dialog box.

For more information, see Creating Filter Pages for Filtering Tables and FilterPageBuilder Data Type.

C/AL Try Functions for Handling Errors

Try functions enable you to catch and handle errors that occur when running the application. You can use try functions to catch errors and exceptions that thrown by Microsoft Dynamics NAV or .NET Framework interoperability operations.

For more information, see Handling Errors by Using Try Functions.

HyperlinkHandler Function Type in Test Codeunits

You can write HyperlinkHandler functions in test codeunits to test hyperlink URLs that are passed to the HYPERLINK function. This is similar to other handler function types for handling UI interactions in application testing.

For more information, see How to: Create Handler Functions.

Object Metadata Virtual Tables

Microsoft Dynamics NAV 2016 includes the following virtual tables that contain metadata about Microsoft Dynamics NAV objects.

  • Codeunit Metadata virtual table

  • Page Metadata virtual table

  • Report Metadata virtual table

  • Table Metadata virtual table

For more information, see Virtual Tables

New CLIENTTYPE Options Added

With Microsoft Dynamics NAV the CLIENTTYPE function has been expanded to support Microsoft Dynamics NAV Tablet client, Microsoft Dynamics NAV Phone client and running the app in Microsoft Dynamics NAV Web client, which is Desktop mode. This allows showing, for example, pages differently depending on the display target. For more information, see CURRENTCLIENTTYPE Function and DEFAULTCLIENTTYPE Function.

Column Layout on Role Centers

The mechanism behind the column layout on the Role Center specifically for the Microsoft Dynamics NAV Web client has been changed. It is still possible to define groups as previously, and thereby keep the design of existing Role Centers. But when these Role Centers are displayed on larger screens, there is an automatic switch to a 4 column layout. When developing new Role Centers, it is now possible to not define any groups and let the dynamic layout handle the switch from 1 to 2 to 3 column layout, depending on the screen size.

When building Role Centers it is recommended to avoid using the Group type to group the parts that make up the Role Center, and instead create all parts directly underneath the Container type. This will optimize the layout to be more dynamic and thereby fit more display targets.

Camera and Location

With Microsoft Dynamics NAV an API for integrating to a camera and getting GPS coordinates is available. The camera option is implemented in the application as functionality available when using Incoming Documents on, which you can see on, for example, the Accounting Manager profile. For a code example of how to integrate with the camera option, see How to: Implement the Camera in C/AL. For a code example of how to get GPS coordinates, see How to: Implement Location in C/AL.

Sizing Settings for Control Add-ins

To control that the sizing of the control add-ins is always optimal on all display targets a number of new settings are available to you when writing the manifest code. For more information, see Manifest Overview.

Structure for Resource Files in Manifest

Microsoft Dynamics NAV supports resource files to be described in the manifest file with or without a relative path allowing you to organize and maintain resource files the way you prefer. For more information, see Manifest Overview.

Tooltips on Microsoft Dynamics NAV Web client

The ToolTip Property and the ToolTipML Property have been added on ActivityButtons and ActionContainers of the subtype HomeItems to support displaying descriptions in the navigation pane.

Additional Numeric Data Types Supported in Aggregations by Queries, FlowFields, and SIFT

In earlier versions of Microsoft Dynamics NAV, data aggregations (such as sum and average) on tables by Query objects, FlowFields, and SumIndexField Technology could only be done on Decimal data type fields. With Microsoft Dynamics NAV 2016 you can use Decimal, Integer, BigInteger, and Duration data types in aggregations.

For more information, see Understanding Query Totals and Grouping, FlowFields, and SumIndexField Technology (SIFT).

Timestamp Field Available in Tables

Each table in Microsoft Dynamics NAV includes a hidden timestamp field. The timestamp field contains row version numbers for records as maintained in SQL Server. In earlier versions of Microsoft Dynamics NAV, the timestamp field could not be used in tables. In Microsoft Dynamics NAV 2016, you can expose the timestamp field in tables, write code against it, add filters, and so on, similar to any other field in a table.

For more information, see How to: Use a Timestamp Field.

SQL Server Authentication

Microsoft Dynamics NAV 2016 supports SQL Server authentication between the Microsoft Dynamics NAV Server instance and the Microsoft Dynamics NAV database in SQL Server. Previously only Windows authentication was supported.

For more information, see How to: Configure SQL Server Authentication in Microsoft Dynamics NAV.

Automatic Deployment of Add-ins From the Database

Microsoft Dynamics NAV 2015 introduced the automatic deployment of Microsoft .NET Framework Interoperability and control add-in assemblies from the Microsoft Dynamics NAV Server to the Microsoft Dynamics NAV clients. Microsoft Dynamics NAV 2016 now makes it possible to automatically deploy add-in assemblies (including client control add-ins, .NET Framework interoperability, and language resources) directly from Microsoft Dynamics NAV database to the Microsoft Dynamics NAV Server instance or client as required. To accomplish this, you import the add-in files as a compressed (.zip) file into the database by using page 9820 Control Add-ins. The add-ins are then stored in system table 2000000069 Add-ins.

For more information, see How to: Install a Windows Client Control Add-in Assembly and How to: Set .NET Framework Types to Run on the Microsoft Dynamics NAV Windows Client or Microsoft Dynamics NAV Server Computers.

Running NAS Services with Administrator Rights

In earlier Microsoft Dynamics NAV versions, to run NAS services, the Microsoft Dynamics NAV Server service account had to be added as a user in Microsoft Dynamics NAV and assigned the required permissions to perform the operations. In Microsoft Dynamics NAV 2016, you can set up NAS services to run with administrator rights, which grants the NAS service the same permissions as the SUPER permission set without having to add the Microsoft Dynamics NAV Server service account as a user in Microsoft Dynamics NAV. This feature is supported for NAS services in a single tenant (non-multitenant) and multitenant Microsoft Dynamics NAV Server deployment.

For more information, see Configuring NAS Services.

Tenant Configurations Stored in Application Database

In a multitenant Microsoft Dynamics NAV Server deployment, the configuration information about the tenants that are mounted on a Microsoft Dynamics NAV Server instance is now stored in the application database (table dbo.$ndo$tenants) instead of a tenant.config file for the Microsoft Dynamics NAV Server instance.

This change is especially useful in application deployments where multiple Microsoft Dynamics NAV Server instances serve the same tenants. It is now easier to add Microsoft Dynamics NAV Server instances to load-balance or scale an application deployment. Instead of having to mount tenants manually, new server instances will automatically inherit the tenant configurations from the application database and mount tenants automatically. Also, when you want to mount or dismount a tenant, you only have to mount or dismount the tenant on one of the server instances for an application database because other server instances will automatically detect and apply the changes.

For more information, see Multitenant Deployment Architecture.

Loading Application Assemblies When Microsoft Dynamics NAV Server Instances Start

You can configure a Microsoft Dynamics NAV Server instance to compile all the business application assemblies and load them to cache memory when the server instance is started. The assemblies are then retrieved from memory when requested by a Microsoft Dynamics NAV client. This improves the response time after restarting a Microsoft Dynamics NAV Server instance.

For more information, see the Compile and Load Business Application setting in Configuring Microsoft Dynamics NAV Server.

Automatic Company Initialization During Data Upgrade

Previously, when upgrading data from an older version of Microsoft Dynamics NAV to the latest version, you had to manually run codeunit 2 Company Initialization on each company in the database. When upgrading data to Microsoft Dynamics NAV 2016, this task is automatically performed for you by the upgrade process.

For more information, see the Upgrading Data.

Microsoft Dynamics NAV Windows Client Available in 64-Bit Version

On a 64-bit Windows operating system, the Microsoft Dynamics NAV Windows client is available in 64-bit version and 32-bit version. By default, when you install the Microsoft Dynamics NAV Windows client, the 64-bit version is used. The 64-bit version is better when you have to run several large reports. However, there are some components, such as COM, which are not supported on 64-bit applications. Therefore, you can also run the 32-bit version of the Microsoft Dynamics NAV Windows client if it is required. For more information, see Running 32-Bit Microsoft Dynamics Windows Client on 64-Bit Windows.

Multilanguage Captions Compile as Unicode

When you compile application objects, Microsoft Dynamics NAV stores the objects in Unicode encoding. If the application objects contain multilanguage captions, Microsoft Dynamics NAV uses the code pages that are relevant for the languages that you have specified. For more information, see Developing Multilanguage-Enabled Applications.

Changes to C/AL Functions, Data Types, Properties, and Triggers in Microsoft Dynamics NAV 2016

For a list of changes to C/AL functions, data types, properties, and triggers, see Changes in C/AL Behavior and Support from Earlier Versions of Microsoft Dynamics NAV.

Changes to Microsoft Dynamics NAV 2016 Administration Shell and Microsoft Dynamics NAV 2016 Development Shell cmdlets

For a list of new, changed, or removed Windows PowerShell cmdlets, see Changes to Microsoft Dynamics NAV Cmdlets From Previous Release.

See Also

What’s New: Application Changes for Microsoft Dynamics NAV


Touring the RoleTailored Client for Developers

This section provides a visual overview of the generic RoleTailored client design, the Microsoft Dynamics NAV Development Environment, including a description of the different windows, pages, parts, and general terminology.

Note
The term RoleTailored client, which in Microsoft Dynamics NAV 2009 referred only to the Microsoft Dynamics NAV Windows client, now can designate either of the Microsoft Dynamics NAV clients.

In This Section

RoleTailored Client Design Principle

Touring the RoleTailored Client Windows

Touring the RoleTailored Client Pages


RoleTailored Client Design Principle

Design Principle

The RoleTailored clients have a customizable user interface that supports the job functions of different work roles in your organization. The RoleTailored clients are built around a navigation structure based on a user-centric design. The RoleTailored clients are comprised of a number of pages, similar to pages, which contain different information and tasks. The pages are combined in the RoleTailored clients and displayed in a series of windows

Note
The term RoleTailored client, which in Microsoft Dynamics NAV 2009 referred only to the Microsoft Dynamics NAV Windows client, now can designate either the Microsoft Dynamics NAV Windows client or the Microsoft Dynamics NAV Web client.

In a RoleTailored client, a user starts from a single navigational window called the Role Center that displays information pertinent to his or her role in the company. From the Role Center, the user can navigate to additional information and open separate windows for performing tasks and viewing data. For each role that you support, you can create a Role Center that displays key information and tasks that are required by that role.

See Also

Tasks

Touring the RoleTailored Client Pages
Touring the RoleTailored Client Windows


Touring the RoleTailored Client Windows

The RoleTailored clients use several windows to display information. Two of the key window types are the navigation window and task page window. The navigation window is the main window in which users find the information that they have to work with. The navigation window is used for the Role Center, List Places, and Departments, as described in this topic. A task page window opens separately from the navigation window when the user selects an action from the navigation window or from other task page windows. It is common for a user to have more than one task page window open at a time.

Role Center

The Role Center is the main entry point into Microsoft Dynamics NAV. The Role Center opens when the user starts the RoleTailored client. You design the Role Center based on the user's business role, taking into consideration the information and tasks relevant to the user during a typical work day. The following illustration shows the Role Center page.

RoleTailored client RoleCenter example

You create a Role Center by using a Role Center page. The Role Center page opens in the navigation window. Usually, there will only be a single navigation window open at a time. From there, users can open any number of task windows. The content area displays the Role Center page. The navigation pane includes a menu that links to List Places and Departments.

For more information, see the following.

To | See
Learn how to create a Role Center page | Walkthrough: Creating a Role Center
Get an overview of the parts on a Role Center page | Touring the RoleTailored Client Pages
Get an overview of the navigation window layout and its parts | Navigation Window

List Places

A List Place displays information from a table in a list format with rows and columns. Typical uses for List Places include displaying sale orders or customers. Similar to the Role Center, List Places display in the navigation window and include the navigation pane. The following illustration shows a List Place.

RoleTailored client List Place page example

List Places only open from the menu items in the navigation pane. To create a List Place, you create List type and then include the List Place in the navigation pane by adding actions to the Role Center page using the Action Designer to create the menu items in the navigation pane.

For more information, see the following.

To | See
See an example of how to create a List page Role Center page | Walkthrough: Creating a Customer List in Page Designer
Learn about List pages and parts, including FactBoxes | Touring the RoleTailored Client Pages
Get an overview of the navigation window layout and its parts | Navigation Window

Departments

The Departments item in the navigation pane only exists in the Microsoft Dynamics NAV Windows client. It provides links to all the pages of the Microsoft Dynamics NAV Windows client. The links and pages under Departments are generated automatically based on the menu suite of the Microsoft Dynamics NAV Windows client user. The following illustration shows the Department page.

RoleTailored client Departments example

To change Departments, you change the MenuSuite.

For more information, see the following.

To | See
Learn how to change the MenuSuite | MenuSuites
Get an overview of the navigation window layout and its parts | Navigation Window

Navigation Window Overview

The following illustration shows the parts of the navigation window that are used by Role Centers, List Places, and Departments.

RoleTailored client Navigation Window overview

Content Area

The content area displays the content of a Role Center page, List page, or Department.

For more information, see the following.

To | See
Learn how to create a page | How to: Create a Page
Get an overview of the pages | Touring the RoleTailored Client Pages

Navigation Pane

The navigation pane displays a menu that links different pages of the RoleTailored client. Menu items are arranged in a hierarchical structure that lets the user drill down through the different levels of menu items.

You use the navigation pane to link to the different List Places of the RoleTailored client. To create menu items in the navigation pane, you add actions to the Role Center page using the Action Designer. You can include menu items under Activity buttons (such as the Home button). You can also add more buttons, such as Posted Documents, and include the menu items there. The Departments button and its menu items are generated automatically based on the Microsoft Dynamics NAV MenuSuite.

For more information, see the following.

To | See
See an overview of actions | Actions Overview
Learn how to add actions to a page | How to: Add Actions to a Page
See an example of how to add an action to the navigation pane | Walkthrough: Creating a Role Center

Address Bar

The address bar displays the location of the current page in the navigation hierarchy of the application. The Address bar updates when the user moves to a different page.

Note
The Address bar is not configurable.

Status Bar

The status bar displays information about the current state of the Microsoft Dynamics NAV session, including the name of the company, the date and, the user's name or ID.

For users who work with more than one company, the status bar provides access to all the companies that they work with. By choosing the company name, the user can open a drop-down list which shows the companies available to them. Users can switch between companies.

Note
The status bar is not configurable.

Task Window

A Task window opens separately from the navigation window when a user chooses an action or menu item. A Task window typically shows a single object or element such as a task, list, or report. Common uses of Task pages include creating or editing sales orders, customer details, and items. The following illustration shows a Task window that displays a Card page for editing customers.

RoleTailored client Card page example

Task pages are similar in concept to the pop-up windows in Microsoft Office Outlook that show an e-mail, contact, or a task. It is typical for users to have multiple task pages open at the same time. Similar to the navigation window, a Task window includes a Command bar and ribbon. Unlike the navigation window, it does not include the navigation pane or status bar. The user can work with more than one Task window open at a time.

You create a Task window by creating a page and then linking the page to actions on other pages. The most common page types for Task windows are Card, Document, and List.

For more information, see the following.

To | See
Learn how to create a page | How to: Create a Page
Get an overview of the pages | Touring the RoleTailored Client Pages

See Also

Tasks

Touring the RoleTailored Client Pages


Touring the RoleTailored Client Pages

In Microsoft Dynamics NAV, pages are the main way to display and organize data in the RoleTailored client. You can create pages to offer users a visual experience that is closely aligned to Microsoft Office and Windows. There are different page types that you use for different situations. The page type that you choose depends on the application task that you want to support, the content that you want to display, and how you want to display it. For example, the Role Center page is the main page of the RoleTailored client and it displays when the RoleTailored client opens. The Role Center page is similar to a home page that helps users focus on their most important daily activities, by giving an overview of the information relevant to their tasks on one page. Other types of pages, such as List pages, display lists of customers or sales orders, while others such as Document task pages, focus on user tasks.

Note
The term RoleTailored client, which in Microsoft Dynamics NAV 2009 referred only to the Microsoft Dynamics NAV Windows client, now the RoleTailored client includes either the Microsoft Dynamics NAV Windows client or the Microsoft Dynamics NAV Web client.

You can choose from the following page types:

  • Role Center Page Type

  • Card Page Type

  • Card Part Page Type

  • ConfirmationDialog Page

  • Document Page Type

  • List Page Type

  • List Plus Page Type

  • List Part Page Type

  • Navigate Page Type for Wizards

  • StandardDialog Page Type

  • Worksheet Page

Designing Pages

You create page objects using Page Designer. In Page Designer, a page is basically an XML object comprised of a number of XML elements that determine the layout and the page content. The following illustration shows an example of Page Designer.

Page Designer overview

To add content to a page, you add containers that divide the page into separate areas which add different parts and content to the page. Each page type has a specific set of controls that can be used with that page type. For example, Cues can only be used on Role Center pages and FastTabs can only be used on Card and Document pages. The card page type shows a number of different controls used on one page type. It includes FastTabs, FactBoxes, Actions, and ribbon controls.

For more information, see the following.

To | See
Learn how to use Page Designer to create pages. | Pages

Role Center Page Type

The Role Center page is the main page of the RoleTailored client. You can customize the Role Center page for the individual user. The Role Center page provides the user with an overview of the day’s work, where the user can quickly access information and tasks on which to focus for the day. The following illustration shows a Role Center page.

RoleTailored client RoleCenter page type example

Important
Only system parts, card parts, and list parts are supported page types for the Role Center.

The Role Center page uses Cues and system parts, including My Notes and Recorder links.

For more information, see the following.

To | See
Learn how to create a page. | How to: Create a Page
Go through an example of how to create a Role Center page. | Walkthrough: Creating a Role Center
Get more information about Cues. | Cue

Card Page Type

A Card page is used to view and edit one record or entity from a table. The Card page displays selected fields from the table. An example of using a Card page is for editing a customer. The following illustration shows the Customer Card page.

RoleTailored client Card page example

You can group one or more fields in FastTabs. You can also include a FactBox that displays additional information about the record in the page.

For more information, see the following.

To | See
Learn how to create a page. | How to: Create a Page
Go through an example of how to create a card page. | Walkthrough: Creating a Customer Card Page in Page Designer
Get more information about FactBoxes. | Adding a FactBox to Page
Get more information about FastTabs. | FastTab

Card Part Page Type

A Card Part page is used in a FactBox on another page to view or edit additional fields associated with a selected entity in the page. The following illustration shows an example of using a Card Part page on a List page that displays sales orders. In the FactBox on the right, a Card Part page displays details about the customer that placed the selected sales order. The following illustration shows a FactBox.

RoleTailored client Card page example

For more information, see the following.

To | See
Learn how to create a page. | How to: Create a Page
Go through an example of how to use a card part on a Role Center page. | Walkthrough: Creating a Role Center
Go through an example of how to use a Card Part page in a FactBox. | How to: Create a CardPart Page For Displaying Customer Data in a FactBox
Get more information about FactBoxes. | How to: Add a FactBox to a Page
Get more information about FastTabs. | FastTab
See a Card Part page in Object Designer. | The page called Customer Details FactBox with ID 9084.

ConfirmationDialog Page

You use the ConfirmationDialog page to display messages or prompt users with a confirmation before they continue with the task that they are working on. For example, when filling out a sales order, a user can select a quantity for an item. This quantity might exceed the item's availability. Using a ConfirmationDialog page, you can display a message that indicates this condition to the user. The user can then choose to continue or cancel filling out the sales order. The following illustration shows a ConfirmationDialog page.

RoleTailored client Confirmed Dialog page example

To create a ConfirmationDialog, you define the message and table fields that you want displayed.

For more information, see the following.

To | See
Learn how to create a page. | How to: Create a Page
See a Confirmation page in Object Designer. | The page called Check Availability with ID 342.

Document Page Type

A Document page usually consists of two separate pages combined into one, with one page nested in the other. A Document page is suitable for use when you want to display data from two tables that are linked together. For example, this is the case with sales orders, which have two source tables: Sales Header and Sales Lines. The following illustration shows a sales order that is created using a Document page type. The following illustration shows a Document page.

RoleTailored client Document page example

A Document page displays a FastTab at the top of the page for showing fields, followed by another FastTab with line items for the selected item. Optionally, you can add additional FastTabs to display more details about a selected item.

For more information, see the following.

To | See
Learn how to create a page. | How to: Create a Page
Go through an example of how to create a Document page. | Walkthrough: Creating a Document Page
Get more information about FastTabs. | FastTab
See a Document page in Object Designer | The page called Sales Order with ID 42.

List Page Type

A List page displays content from a table in a list format. List pages can display as List Places (as part of the navigation layer) or in Task pages. The following illustration shows a List page.

RoleTailored client sales order List page example

You can also add a FactBox to display additional information about a selected item in the list.

For more information, see the following.

To | See
Learn how to create a page. | How to: Create a Page
Go through an example of how to create a List page. | Walkthrough: Creating a Customer List in Page Designer
Learn more about List Places. | Touring the RoleTailored Client Windows
Get more information about FactBoxes. | Adding a FactBox to Page
See a List page in Object Designer. | The page called Sales Order List with ID 9305.

List Plus Page Type

Similar to a List page, a List Plus page displays content from a table in a list format. The difference is that the List Plus page type can contain two lists in one page, and can be used as a two-dimensional matrix. The following illustration shows a List Plus page that is used for viewing a production forecast.

For more information, see the following.

The List Plus Page type

To | See
Learn how to create a page. | How to: Create a Page
Get more information about FactBoxes. | How to: Add a FactBox to a Page

List Part Page Type

Similar to a List page, a List Part page displays content from a table in a list format. The difference is that you use the List part page as another page in a FactBox or as a part of the Role Center page. The following illustration shows a List Part page that is used in the Role Center for viewing a list of the user's customers.

RoleTailored client ListPart page example

For more information, see the following.

To | See
Learn how to create a page. | How to: Create a Page
Get more information about FactBoxes. | Adding a FactBox to Page
See how a List Part page is used on a Role Center page. | The page called Order Processor Role Center with ID 9006.

Navigate Page Type for Wizards

You use a Navigate page type to create a wizard that leads the user through a sequence of steps for completing a task. The following illustration shows a Navigate page.

RoleTailored client Navigation pane wizard example

A wizard opens as a Task page.

For more information, see the following.

To | See
Learn how to create a page. | How to: Create a Page
Go through an example that creates a Navigate page. | Walkthrough: Creating a Wizard Page
Learn more about task pages. | Touring the RoleTailored Client Windows
See a Navigate page that is used as a wizard in Object Designer. | The page called Create To-do with ID 5097.

StandardDialog Page Type

The StandardDialog is a simple page type that you use when users only need to input data and do not need to perform other actions from the page. An example of a StandardDialog page type is page 511, Change Exchange Rate, in the CRONUS International Ltd. demonstration database. The following illustration shows the Change Exchange Rate StandardDialog page.

Currency Exchange Rate page

The StandardDialog page type has the following characteristics:

  • It does not contain a ribbon, FastTabs, or FactBoxes.

  • There is no customization of the page available from the RoleTailored client.

  • It is typically is not associated with a source table and gets its data based on a Card type page.

For more information, see the following.

To | See
Learn how to create a StandardDialog type page. | How to: Create a Page
See an example of a StandardDialog type page. | The page called Page 511, Change Exchange Rate.

Worksheet Page

You use a Worksheet page type for creating worksheet or journal task pages. The Worksheet page consists of a single grid in the content area and a section at the bottom with details about the selected grid line or totals for the grid. The following illustration shows a Worksheet page.

RoleTailored client navigation page example

You can optionally include a FactBox.

For more information, see the following.

To | See
Learn how to create a page. | How to: Create a Page
Go through an example that creates a Worksheet page. | Walkthrough: Creating a Worksheet Page
Get more information about FactBoxes. | Adding a FactBox to Page
See a Worksheet page. | The page called Standard Cost Worksheet with ID 5841.

Page Controls and Parts

Ribbon

The ribbon is located under the Command bar on task pages and list places and contains shortcuts to actions. Actions display as icons, which the user can choose to complete a task or view information. The following illustration shows the ribbon.

Action Pane clip from a Customer List page

To include an action in the ribbon, you use the Action Designer (available from the View menu when a Page Designer window is open) and promote the action. You should use the ribbon to display the tasks most frequently used by the user in the context of the page. For example, on a List page that displays sales orders, you should promote the action to process a sales order to the ribbon.

For more information, see the following.

To | See
Learn more about actions and navigation. | Adding Actions to Pages
Learn how to promote actions to the action page. | How to: Promote Actions to the Ribbon on Pages
See a page that promotes actions to the ribbon. | The page called Customer List with ID 22.

Cue

A Cue is an icon that provides a shortcut link to an underlying filtered list, such as invoices, sales orders, or credit memos. A Cue icon depicts a stack of papers on the page, where the height of the stack roughly indicates the number of entities in the underlying list. A number value on each Cue gives the precise count. The following illustration shows a Cue.

RoleTailored client cue example

A Cue can only be used on a Role Center page.

For more information, see the following.

To | See
Learn how to create a Cue. | Walkthrough: Creating a Cue Based on a FlowField
Go through an example that uses a Cue on the Role Center. | Walkthrough: Creating a Role Center
See a page that uses Cues. | The page called SO Processor Activities with ID 9060.

Chart Pane

The Chart pane displays data from a list in graphic form, giving the user a visual overview of the value distribution. Chart panes are only available on List page types. The following illustration shows the Chart pane.

RoleTailored client Chart part example

To view a chart pane, choose Customize on the page's command bar, and then select Chart Pane. To change the data that is displayed in a chart, choose Measures or Dimensions, and then select the fields that you want.

For more information, see the following.

To | See
See a chart pane on a List page. | The page called Sales Order List with ID 9305.

FactBox

A FactBox is an area that is located on the right side of a page which displays data related to information about an item on the page. For example, on a list page that shows sales orders, you can use a FactBox to show additional fields of a selected sales order in the list. The following illustration shows FactBoxes on the Customer Card page.

RoleTailored client FactBox example

You can set a FactBox to display a page, system part, or a chart. If you set the FactBox to display a page, you can display the following page types:

  • Card

  • List

  • List Plus

  • Document

  • Worksheet

  • Navigation

For more information, see the following.

To | See
Go through an example that uses a FactBox. | Walkthrough: Adding a FactBox to the Customer List Page
See a page that uses a FactBox. | The page called Sales Order List with ID 9305.

FastTabs

FastTabs enable you to place data in separate groups on a page, where each group has a header that expands and collapses the group when clicked. The header of the FastTab displays a name, such as "Prepayment" on the Sales Order shown. You can also promote fields included on the FastTab to the header. Promoting a field to the header enables you to present key information to the user when the FastTab is collapsed. The following illustration shows FastTabs on a Customer Card page.

RoleTailored client FastTab example

Organizing data using FastTabs helps users to find key information more quickly, while giving an overview of areas that otherwise would remain hidden.

For more information, see the following.

To | See
Learn how to add a FastTab to a page. | How to: Add FastTabs to a Customer Card Page
See a page that uses a FastTabs. | The page called Sales Order with ID 42.

Filter Pane

The Filter pane is found on List pages and enables the user to filter and sort the items displayed in the list based on a given criteria. The following illustration shows the Filter pane on the Customer List page.

RoleTailored client filter pane example

The Filter pane is automatically included on List pages and cannot be configured.

My Notifications

The My Notifications part allows users to view notifications that are assigned to them, similar to messenger service. The notifications are generated from a Notes control on a task page. For example, on a sales order page, the user can add a note and then target another user to receive the note. This note then shows up in the target user's My Notifications. The following illustration shows notifications from a Notes control on the Sales Orders page.

RoleTailored client MyNotifications part example

By double-clicking the link to the note in the notification, users can navigate directly to the relevant Task page to deal immediately and directly with the urgent issue or exceptions.

The My Notifications part is designed to be used on a Role Center page.

For more information, see the following.

To | See
Go through an example that uses My Notes. | Walkthrough: Creating a Role Center
See a page that uses the My Notifications part. | The page called Order Processor Role Center with ID 9006.

Notes

The Notes part allows the user to attach a note to an item on a Task page. For example, when creating a sales order, a user can add a note about the order. The note will appear with the item when it is viewed. If another user is targeted to be notified, then the note will appear in that user's Role Center in the My Notifications part. The following illustration shows a Note part

RoleTailored client Notes part example

You use Notes in a FactBox on a page.

For more information, see the following.

To | See
See a page that uses a Notes part. | The page called Sales Order with ID 42.

RecordLinks

The RecordLinks part allows the user to add links to files on items on a Task page. For example, when creating a sales order, users can add a link to the Microsoft Word document that pertains to the order. The links will appear with the item when it is viewed. When a user chooses a link, the target file opens. The following illustration shows a RecordLink part.

RoleTailored client recorded links example

You use RecordLinks in a FactBox on a page.

For more information, see the following.

To | See
See a page that uses a RecordLinks part. | The page called Sales Order with ID 42.

See Also

Tasks

Touring the RoleTailored Client Windows


Finding Information in Help

There are several ways to access Help information in Microsoft Dynamics NAV.

F1 Key

In the Microsoft Dynamics NAV Development Environment, when you press the F1 key, you get Help that pertains to where you have positioned the pointer. For example, if the pointer is in Report Dataset Designer, then you will get information about that specific designer.

In the Microsoft Dynamics NAV Windows client,

Help Menu

In the development environment, you can locate the Help options on the Help menu.

The Help menu in the development environment contains the following options.

Help option | Description
Developer and IT Pro Help | Opens a Compiled HTML Help (CHM) window that contains the Developer and IT Pro Help.
About Microsoft Dynamics NAV | Displays product information, including the version number of Microsoft Dynamics NAV. For more information, see About.

In the Microsoft Dynamics NAV Windows client, you can locate the Help options on the Application menu Application Menu button in menu bar.

The Help menu in the Microsoft Dynamics NAV Windows client contains the following options.

Help option | Description
Microsoft Dynamics NAV Help | Opens a topic related to the window or page that you are working in.
Page Notes | Opens the OneNote page that has been shared across a company. For more information, see How to: Set up OneNote Integration for a Group of Users.
About This Page | Provides information about all fields and values that are in the table on which a table or report is based. For more information, see How to: View All Table Fields for a Record.
About Microsoft Dynamics NAV | Displays product information, including the version number of Microsoft Dynamics NAV. For more information, see About.

Microsoft Dynamics NAV Help Server

When you access Help from the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client, Help opens in a browser that shows the content from the Microsoft Dynamics NAV Help Server. The Microsoft Dynamics NAV Help Server is a website with a high-level navigation in the left pane, and a Search box to help you find exactly what you are looking for.

The main pane shows the contents of the Help topic.

At the top of the Microsoft Dynamics NAV Help Server website, you can choose links that access the Microsoft Dynamics NAV Help on Microsoft Developer Network (MSDN) and other useful locations.

For more information, see Configuring Microsoft Dynamics NAV Help Server.

MSDN

The latest version of the Microsoft Dynamics NAV 2016 Developer and IT Pro Help is available in the MSDN Library.

See Also

Concepts

Getting Started
Configuring Microsoft Dynamics NAV Help Server
Deployment
Administration
Development


Copyright and Trademarks

Please refer to the following for information on notices and trademarks.

Notices

Complying with all applicable copyright laws is the responsibility of the user. Microsoft grants you the right to reproduce this documentation, in whole or in part, specifically and solely for your internal, reference purposes in connection with a validly licensed copy of the corresponding software.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, trade dress, copyrights, or other intellectual property. Unless otherwise noted, the companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted in examples herein are fictitious. No association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred.

© 2015 Microsoft. All rights reserved.

Trademarks

Microsoft, Microsoft Dynamics, Microsoft Dynamics NAV, Windows, Windows Server, and the other products listed on the trademarks page of the Microsoft website are trademarks of the Microsoft group of companies. All other trademarks are property of their respective owners.


Keyboard Shortcuts in the Development Environment

The following table provides an overview of shortcut key combinations in the Microsoft Dynamics NAV Development Environment.

Keyboard Shortcut | Action
Right Arrow | Move to the next field or character
Left Arrow | Move to the previous field or character
Up Arrow | Move to the field above in the same column
Down Arrow | Move to the field below in the same column
Delete | Clear selected text
Esc | Close the window or undo the data entry
End | Move to the last field on a line
Home | Move to the first field on a line
Arrow, Tab, Enter | Move to the next field on non-line FastTabs
F1 | Open Help
F10, Alt | Select the menu bar and display access keys
F6 | Drop-down or look up to view/select
Arrow, Shift+Tab | Move to the previous field
Ctrl+C | Copy
Ctrl+O or F12 | Open the company
Ctrl+V | Paste
Ctrl+X | Cut
Ctrl+Z | Undo
Ctrl+Home | Move to the first line in a list
Ctrl+End | Move to the last line in a list
Esc | Save and close window (equivalent to choosing the OK button)
F3 | Insert new line
Alt+F4 | Close window or close program

See Also

Keyboard Shortcuts

Concepts

C/AL Editor Keyboard Shortcuts


Product and Architecture Overview

The Microsoft Dynamics NAV 2016 architecture comprises three core components as well as various additional tools and components. Use Microsoft Dynamics NAV Setup to install all components.

The Microsoft Dynamics NAV Three-Tier Architecture

For every deployment of Microsoft Dynamics NAV 2016 you must install the core components, which are the three tiers that make up the Microsoft Dynamics NAV architecture.

  1. The RoleTailored client is the client tier, which includes a Microsoft Dynamics NAV Windows client and a Microsoft Dynamics NAV Web client.

    In addition to the RoleTailored client, Microsoft Dynamics NAV 2016 also supports additional client types, including web service clients and a NAS services client for programmatic access. For details on the various client types, see Client Types.

  2. Microsoft Dynamics NAV Server is the middle or server tier, managing all business logic and communication.

  3. SQL Server, augmented by Microsoft Dynamics NAV 2016 database components, is the data tier.

    If you deploy Microsoft Dynamics NAV in a multitenant deployment architecture, the data tier consists of an application database and one or more tenant databases.

Important
When you install Microsoft Dynamics NAV 2016, all components must be from the same version and build of Microsoft Dynamics NAV for the software to run correctly.

You can have multiple instances of any of the core components in a production environment. The following diagram shows a simple installation with two Microsoft Dynamics NAV Windows clients and a Microsoft Dynamics NAV Web client connecting to a single Microsoft Dynamics NAV Server computer, which in turn connects to a computer with SQL Server and the Microsoft Dynamics NAV database components.

The RoleTailored architecture.

Some common configurations are:

  • All three components on the same computer. This is the configuration for a demo install, and is also typical for a development environment, so that a developer can work on Microsoft Dynamics NAV applications without worrying about network connections and inter-component security. See Walkthrough: Installing the Demo Version.

  • RoleTailored client and Microsoft Dynamics NAV Server on the same computer, data tier on a separate computer. This scenario is described in Walkthrough: Installing the Three Tiers On Two Computers.

  • Each of the three tiers on a separate computer. This scenario is described in Walkthrough: Installing the Three Tiers on Three Computers.

Additional Components

In addition to the three core components, there are additional components that enhance or supplement the core components.

Component | Purpose
Microsoft Dynamics NAV Help Server | A website with the Help content for Microsoft Dynamics NAV in the languages that your version of Microsoft Dynamics NAV includes. You can deploy a single Help Server for all users, or customer-specific Help Servers, depending on your requirements.
Web Server Components. See How to: Install the Web Server Components. | The components that are needed to enable Microsoft Dynamics NAV Web clients to connect with a browser.
Microsoft Dynamics NAV Server Administration Tool | A tool for configuring and managing Microsoft Dynamics NAV Server and Microsoft Dynamics NAV sites.
Development Environment (C/SIDE) | The Development Environment for creating and modifying Microsoft Dynamics NAV applications in C/AL.
Microsoft Office Outlook Add-In | A component for synchronizing data, such as to-dos, contacts, and tasks, between Microsoft Dynamics NAV and Outlook.
Automated Data Capture System | A Microsoft Dynamics NAV tool for accurately capturing data for inbound, outbound, and internal documents, primarily in connection with warehouse activities. With ADCS, company employees use handheld devices and radio frequency technology to continuously validate warehouse inventories.
ClickOnce Installer Tools. See Deploying Microsoft Dynamics NAV Using ClickOnce. | A set of tools designed to create ClickOnce deployments for applications for the Microsoft Dynamics NAV Windows client.

See Also

Concepts

Deployment
Working with Microsoft Dynamics NAV Setup
Multitenant Deployment Architecture


Client Types

The following Microsoft Dynamics NAV clients interact with the Microsoft Dynamics NAV database through Microsoft Dynamics NAV Server:

  • Microsoft Dynamics NAV Windows client

  • Microsoft Dynamics NAV Web client

  • Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client

Of these client types, the Microsoft Dynamics NAV Windows client is the only one that you explicitly install and configure with Microsoft Dynamics NAV Setup.

Note
The term RoleTailored client, which in Microsoft Dynamics NAV 2009 referred only to the Microsoft Dynamics NAV Windows client, now can designate either the Microsoft Dynamics NAV Windows client or the Microsoft Dynamics NAV Web client.

In addition, the following service types also interact with the Microsoft Dynamics NAV database through Microsoft Dynamics NAV Server:

  • SOAP web services

  • OData web services

  • NAS services

You can configure a server instance for RoleTailored clients, SOAP and OData web services, and NAS connections using either the Microsoft Dynamics NAV Server Administration Tool or Microsoft Dynamics NAV Windows PowerShell Cmdlets.

Microsoft Dynamics NAV Windows client

The Microsoft Dynamics NAV Windows client is an intuitive and versatile Windows application that developers, partners, administrators, and super users can customize to support the job functions of a full range of work roles in an organization.

For each role, the Microsoft Certified Partner or developer creates a customizable Role Center that displays key information required for relevant employees and makes their day-to-day tasks easier to complete. Users run the RoleTailored client to find the information and data entry points that their jobs require.

The Microsoft Dynamics NAV Windows client is installed when you select the Demo Option, Client Option, or Developer Option in Microsoft Dynamics NAV Setup. The Microsoft Dynamics NAV Windows client is available in a 32-bit version and 64-bit version. The 32-bit version of the Microsoft Dynamics NAV Windows client can be run on either a 32-bit or 64-bit version of a Windows operating system. The 64-bit version of the Microsoft Dynamics NAV Windows client can only be run on a 64-bit version of a Windows operating system. On a 64-bit Windows operating system, the 64-bit version of the Microsoft Dynamics NAV Windows client is used by default, but you can to run the 32-bit version as well. For more information, see Running 32-Bit Microsoft Dynamics Windows Client on 64-Bit Windows.

Microsoft Dynamics NAV Web client

The Microsoft Dynamics NAV Web client is an alternative to the Microsoft Dynamics NAV Windows client that enables you to access Microsoft Dynamics NAV data over the Internet. From a web browser, you can view and edit data by using an interface that is similar to the Microsoft Dynamics NAV Windows client. Install the Web Server components to get the software that you need to set up a Microsoft Dynamics NAV Web client. For more information, see Microsoft Dynamics NAV Web Client.

Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client

The Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client allow users in small and medium sized businesses to access data from a tablet or a phone. Developing for Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client is very similar to developing for the Microsoft Dynamics NAV Web client using the Microsoft Dynamics NAV Development Environment. For more information, see Developing for the Microsoft Dynamics NAV Universal App.

SOAP Web Services

SOAP web services allow full flexibility for building operation-centric services. This includes industry standard interoperability, as well as channel and host plug-ability. For web services that must interoperate with Java or use channels other than HTTP, SOAP services are the only option. Windows Communication Framework (WCF) has supported SOAP services since its initial release in .NET Framework 3.0, and .NET Framework 4 adds additional support and default bindings to make it easier to build SOAP services using WCF. You define and publish Microsoft Dynamics NAV 2016 SOAP web services in the RoleTailored client, and manage them from the Microsoft Dynamics NAV Server Administration tool. See SOAP Web Services for further information.

OData Web Services

OData services are recommended for client applications that require a uniform, flexible, general purpose. They are less suited for applications that are primarily method-oriented or in which data operations are constrained to certain prescribed patterns. OData supports Representational State Transfer (REST)-based data services, which enable resources, identified using Uniform Resource Identifiers (URIs), and defined in an abstract data model (EDM), to be published and edited by web clients within corporate networks and across the Internet using simple Hypertext Transfer Protocol (HTTP) messages. OData services are lightweight, with functionality often referenced directly in the URI. You define and publish Microsoft Dynamics NAV 2016 OData web services in the RoleTailored client, and manage them from the Microsoft Dynamics NAV Server Administration tool. See OData Web Services for further information.

NAS Services

NAS services are a middle-tier server component that executes business logic without a user interface or user interaction. NAS services are intended for task scheduling, client offloading, and specialized integration scenarios. NAS services replace the NAV Application Server (NAS) available in earlier versions of Microsoft Dynamics NAV. You manage NAS services from the Microsoft Dynamics NAV Server Administration tool. See Configuring NAS Services for further information.

See Also

Concepts

Product and Architecture Overview
Web Service Alternatives: SOAP and OData
Microsoft Dynamics NAV Server Administration Tool

Other Resources

Installation Options


Microsoft Dynamics NAV Web Client

The Microsoft Dynamics NAV Web client gives users access to Microsoft Dynamics NAV data over a network, such as the Internet, by using a web browser. Users can view and modify data from a user-friendly interface that resembles the Microsoft Dynamics NAV Windows client, where the starting point is the Role Center. The Role Center can be customized to users individual needs based on their role, company, and daily tasks.

Unlike the Microsoft Dynamics NAV Windows client, you do not have to install any Microsoft Dynamics NAV components on devices that users will use to access Microsoft Dynamics NAV data. The Microsoft Dynamics NAV Web client does not replace the Microsoft Dynamics NAV Windows client but complements it by enabling scenarios that are not possible with the Microsoft Dynamics NAV Windows client. For a visual overview of the Microsoft Dynamics NAV Web client, see Touring the RoleTailored Client for Developers.

Deploying the Microsoft Dynamics NAV Web Client

To deploy Microsoft Dynamics NAV Web client, you install and configure the Microsoft Dynamics NAV Web Server components on a computer that is running Internet Information Services (IIS) and has a connection to a Microsoft Dynamics NAV Server and database. Microsoft Dynamics NAV users can access the Microsoft Dynamics NAV Web client from any supported device that has a supported internet browser and a TCP/IP network connection. For a list of supported devices and browsers, see System Requirements for Microsoft Dynamics NAV 2016.

For more information about how to deploy the Microsoft Dynamics NAV Web client, see Deploying the Microsoft Dynamics NAV Web Server Components.

Developing for the Microsoft Dynamics NAV Web Client

As a developer of Microsoft Dynamics NAV Web client applications, you will have the same experience as developing Microsoft Dynamics NAV Windows client applications. You use the Microsoft Dynamics NAV Development Environment to create objects, such as pages and reports, and implement the same business logic as you would for the Microsoft Dynamics NAV Windows client. The same page or report that is displayed in the Microsoft Dynamics NAV Windows client can also be displayed in the Microsoft Dynamics NAV Web client.

For more information about how to develop for the Microsoft Dynamics NAV Web client, see Developing for the Microsoft Dynamics NAV Web Client.

Administering Users of Microsoft Dynamics NAV Web Client

Like the Microsoft Dynamics NAV Web client, you control access to the Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV data by creating user accounts, permission sets, and profiles. You do not have to set up separate user accounts for the Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Windows client. The permissions that are granted to a specific user account apply to all RoleTailored clients.

For more information about how to manage users of the Microsoft Dynamics NAV Web client, see Administration in the Clients.

See Also

Tasks

How to: Install the Web Server Components

Concepts

Feature Limitations of the Microsoft Dynamics NAV Web Client
Microsoft Dynamics NAV Web Client Network Architecture
Accessibility Features of Microsoft Dynamics NAV Windows Client


Microsoft Dynamics NAV Web Client Network Architecture

The following illustration shows the four tiers of the network architecture in the Microsoft Dynamics NAV Web client.

NAV Web Client network architecture

The following table describes the components of each tier.

Tier | Description
Device | A computer or device that has access to the Internet with a browser. For a list of supported browsers, see System Requirements for Microsoft Dynamics NAV 2016.
Web server | A computer that is running Internet Information Services (IIS) at a minimum. Microsoft Dynamics NAV Web Server components are installed on a website on IIS. For more information, see How to: Install the Web Server Components.
Microsoft Dynamics NAV Server | A Microsoft .NET Framework-based Windows Service that manages communications and provides a security layer between clients and Microsoft Dynamics NAV databases in SQL Server. For more information, see Microsoft Dynamics NAV Server.
Database | A SQL Server database that contains Microsoft Dynamics NAV data. For more information, see SQL Server Database Components.


Feature Limitations of the Microsoft Dynamics NAV Web Client

Microsoft Dynamics NAV Web client supports most of the same Microsoft Dynamics NAV objects and features as Microsoft Dynamics NAV Windows client, but there are some small differences. This topic lists the features that are not supported or are partially supported by Microsoft Dynamics NAV Web client. These features are listed compared with the Microsoft Dynamics NAV Windows client. The topic is divided into the following sections:

  • General Features

  • Objects

  • Pages Features

  • Report Features

  • C/AL Functions

  • User Interface Features

Note
In this topic, partially supported means that the feature does not have all the capabilities as it does in Microsoft Dynamics NAV Windows client or it works differently than in Microsoft Dynamics NAV Windows client.

General Features

The following table lists general features that are not fully supported by Microsoft Dynamics NAV Web client.

Feature | Level of support | Remarks
COM and Automation | Not supported. | If a Microsoft Dynamics NAV object implements Automation (objects and servers), then an error occurs when the object is run in Microsoft Dynamics NAV Web client.
Departments and MenuSuite | Not supported. | The Departments button does not appear in the navigation pane of Role Center in the Microsoft Dynamics NAV Web client. Instead Page Search is available from an action in the navigation pane of the Role Center and on the top right corner of a page. MenuSuite is used to build the Departments page in Microsoft Dynamics NAV Windows client.
System Indicator | Not supported. | The Microsoft Dynamics NAV Web client always shows the name of the company that it connects to.
Microsoft .NET Framework Interoperability | Partially supported. | Microsoft .NET Framework interoperability objects that are configured to run on the client are not supported; objects that run on Microsoft Dynamics NAV Server are supported. For more information, see How to: Set .NET Framework Types to Run on the Microsoft Dynamics NAV Windows Client or Microsoft Dynamics NAV Server Computers.
Configuring the user interface for a profile | Partially supported. | You cannot perform configuration using the Microsoft Dynamics NAV Web client. Instead, you use the Microsoft Dynamics NAV Windows client. For more information, see Configuring and Personalizing the Microsoft Dynamics Web Client.

Objects

The following object types are not supported by Microsoft Dynamics NAV Web client.

Feature Level of support Remarks

XMLport

Partially supported.

Request pages are not supported. If you try to run an XMLport with a request page from the Microsoft Dynamics NAV Web client, then you receive an error that the XMLport page type is not supported.

To run an XMLport without using a request page, you can set the UseRequestPage Property of the XMLport in XML Designer to No. Or, if the XMLport is run from C/AL code by calling the RUN Function (XMLport), then you can set the ReqWindow parameter to false.

Pages Features

This section includes page features that are not fully supported by Microsoft Dynamics NAV Web client.

General Page Features

The following page features are not fully supported by Microsoft Dynamics NAV Web client.

Feature Level of support Remarks

Navigate page type

Not supported.

If you try to open a page of the NavigatePage type in the Microsoft Dynamics NAV Web client, then an error occurs. It is recommended to use Card page type instead, as shown in the Navigate page (244).

Note
If you have page that will display in the Microsoft Dynamics NAV Web client and the page includes an action that opens a page of the Navigate type, then you should consider removing or hiding the action. You can hide an action globally by setting the action's Visible Property to No. You can hide the action for a specific profile only by running the Microsoft Dynamics NAV Web client in the configuration mode, and then customizing the ribbon of the page. For more information, see Working with Role Centers.

GridLayout control for arranging page fields

Partially supported.

The RowSpan and ColumnSpan properties on fields in the grid layout are not supported.

Page Properties

The following page properties are not supported or are partially supported by Microsoft Dynamics NAV Web client.

Note
Properties that are not supported are ignored by Microsoft Dynamics NAV Web client.

Control | Property | Level of support | Remarks
Page object | RefreshOnActivate | Not supported. |
Group | ShowAsTree | Partially supported. | Columns will be indented but they will not be expandable or collapsible.
 | IndentationControls | Partially supported. | Only supports indentation on one column. If you specify more than one column in the IndentationControls property, only the first column is used.
Field | ColumnSpan | Not supported. |
 | RowSpan | Not supported. |
 | AssistEdit | Partially supported. | The AssistEdit button never appears on a field that has the data type Option.
Part | ChartPartID | Not supported. | If a page contains a Chart part, then the part is ignored and nothing appears for the part in the Microsoft Dynamics NAV Web client.
 | SystemPartID | Partially supported. | Microsoft Dynamics NAV Web client supports Notes and RecordLinks system parts, but not Outlook and MyNotes.
 | PartType | Partially supported. | The Chart option is not supported. If a page contains a Chart part or an unsupported System part, then the part is ignored and nothing appears for the part in the Microsoft Dynamics NAV Web client.

Report Features

The following table includes reports features that are not supported or are partially supported by Microsoft Dynamics NAV Web client.

Feature Level of support Remarks

Printing a report without using a request page by calling the Report.Run function

Partially supported.

If a report is run by calling the REPORT.RUN Function and the function call does not use a request page, then you must set up reports to print from Microsoft Dynamics NAV Server, otherwise you will get an error at runtime. Client-side printing is not supported in this scenario. For more information, see the following topics.

  • How to: Specify Printer Selection for Reports

  • STARTSESSION Function (Sessions)

  • Printing Reports from a Background Session

  • How to: Background Post with Job Queues

Filtering on request page of a report

Partially supported.

The only filters that are shown are filter fields that are set by the ReqFilterFields property or the SETRECFILTER function in C/AL code.

If you rerun a report, any filter values must be reentered. Filter values are not saved when a report has been run in the Microsoft Dynamics NAV Web client. There is a limit on the number of filters a user can set. The user can only specify one filter in addition to the number of filter fields that are set by the ReqFilterFields property.

Filter strings in a report URL

Not supported.

Unlike pages, you cannot filter a report by adding filter strings to the Internet address.

Document map in the report preview

Partially supported.

You can experience differences in the behavior between the Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client.

C/AL Triggers

This section lists the C/AL triggers that are not fully supported by Microsoft Dynamics NAV Web client. Triggers that are not supported are not invoked on an object at runtime.

Page Triggers

The following page triggers are not fully supported by Microsoft Dynamics NAV Web client.

Triggers | Level of support | Remarks
OnClosePage | Partially supported. | The OnClosePage trigger is invoked only when the Microsoft Dynamics NAV page is hosted in a modal popup dialog (MPO).
OnQueryClosePage | Partially supported. | The OnQueryClosePage trigger is invoked only when the Microsoft Dynamics NAV page is hosted in a modal popup dialog (MPO).

C/AL Functions

This section lists the C/AL functions that are not supported by Microsoft Dynamics NAV Web client. Except when indicated otherwise, if you use a function that is not supported, you will receive an error at runtime.

Data type Function Level of support Remarks

Debugger

ACTIVATE

Not supported.

An error occurs at runtime.

Dialog

UPDATE

Not supported.

The function is ignored.

Report

REPORT.RUN and REPORT.RUNMODAL

Partially supported.

If the ReqWindow parameter of the function is set to false, then you must set up reports to print from Microsoft Dynamics NAV Server, otherwise you will get an error at runtime. Client-side printing is not supported in this scenario. For more information, see How to: Specify Printer Selection for Reports and STARTSESSION Function (Sessions).

File

DOWNLOAD and DOWNLOADFROMSTREAM

Partially supported.

  • The DialogTitle, ToFolder, and ToFilter parameters are not supported.

UPLOAD and UPLOADINTOSTREAM

Partially supported.

  • The DialogTitle, FromFolder, and FromFile parameters are not supported.

  • Not supported on devices that run on Apple iOS, such as iPad. When you try upload a file, the dialog box for uploading a file appears in the Microsoft Dynamics NAV Web client, but it is disabled and you cannot select a file.

User Interface Features

The following end-user interface features are not supported by Microsoft Dynamics NAV Web client.

Feature Level of support Remarks

Buffering of keyboard input for heads-down data entry

Not supported.

System actions are default actions in the Application menu and ribbon on pages and reports. System actions include the following:

  • Copy Link to Page

  • Recipient as Attachment

  • Microsoft Word

  • Print Page

  • Show as List

  • OneNote

Not supported.

The actions are not available in the user interface.

Note
You can use the action Open in Excel on list places and transfer all data in the list to an Excel spreadsheet. You can use Internet Explorer functions to print a page and to create links on a page.

Actions related to a subpage in a part when the subpage is dynamically shown or hidden based on a user interaction

Partially supported.

The actions related to the subpage will always be present and active in the ribbon, even when the page is not shown. For an example, see page 5855.

FlowFilters on pages

Not supported.

Using Limit totals to is not supported. Use Filter on column instead.

Vertical resizing of controls

Not supported.

Vertical resizing of controls is not supported on the Microsoft Dynamics NAV Web client. A multiline textbox, for example, will not increase in vertical size when the user drags to increase the size of the page. This applies to all controls that can take advantage of vertical or horizontal resizing, such as charts, grids, multiline, textboxes, and control add-ins.

See Also

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Developing for the Microsoft Dynamics NAV Web Client


Browser Limitations with the Microsoft Dynamics NAV Web Client

The Microsoft Dynamics NAV Web client supports several browsers. There are some Microsoft Dynamics NAV features that are not supported by all browsers.

For a list of the supported browsers and versions, see System Requirements for Microsoft Dynamics NAV 2016.

Feature Limitations

The following table describes the feature limitations and known issues with the supported browsers.

Important
The Microsoft Dynamics NAV Web client is designed for keyboard and mouse usage. If you want to use a touch-enabled device, we recommend running the Microsoft Dynamics NAV Universal App.

Feature | Description | Browser | Remarks
Previewing a report | The Preview button does not appear on the request pages of reports. | Google Chrome Mozilla Firefox Safari |
Printing a report from the report preview | If you try to print a report from the report preview, then you will get a script error message. | Internet Explorer 10 (in the Windows 8-style UI mode) | This is because Windows 8-style UI does not support plugins. To print a report, open the report as a PDF, and then print the report from the PDF viewer.
Tooltips in the ribbon | Tooltips do not appear when you pause on an action with the pointer. | Safari |
Tooltips for error messages and icons on pages | Tooltips do not appear when you pause on an error message or an icon on a page with the pointer. | Internet Explorer 10 (on tablets that run Windows 8) Safari | To see the tooltip, you must tap the message or icon.
Dragging the cursor in a field | If you drag the cursor in a field, then the field becomes blocked and you cannot enter any data. | Safari | To make it possible to enter data, refresh the browser or start a new browser session.
Scrolling a list by using one finger | You cannot scroll a list by using a one finger scrolling gesture. | Safari | To scroll a list, use a two finger scrolling gesture.
Windows authentication | Validating user credentials by using Windows authentication is not supported. | Safari | For more information about authentication and credentials, see Users and Credential Types.

See Also

Tasks

How to: Open the Microsoft Dynamics NAV Web Client

Concepts

Feature Limitations of the Microsoft Dynamics NAV Web Client
Microsoft Dynamics NAV Web Client
Deploying the Microsoft Dynamics NAV Web Server Components
Developing for the Microsoft Dynamics NAV Web Client


Developing for the Microsoft Dynamics NAV Universal App

This section describes how to develop for the Microsoft Dynamics NAV Universal App.

In This Section

This section provides an overview of developing for the Microsoft Dynamics NAV Universal App.

  • Introducing the Microsoft Dynamics NAV Universal App

  • Deciding on Your Tablet and Phone Strategy

  • Getting Started Developing for the Microsoft Dynamics NAV Universal App

  • Designing for Different Screen Sizes on Tablet and Phone

  • Differences and Limitations When Developing Pages for the Microsoft Dynamics NAV Universal App

  • Using HTTPS and Certificates

  • How to: Implement the Camera in C/AL

  • How to: Implement Location in C/AL

  • How to: Display Data as Bricks on Phone

  • Defining Action Scope for Microsoft Dynamics NAV Pages

  • How to: Open the Microsoft Dynamics NAV Tablet or Phone Client from a Browser

  • Linking to the Microsoft Dynamics NAV Universal App

  • Walkthrough: Developing a Sales Rep Role Center for the Microsoft Dynamics NAV Tablet Client

  • Adding Help to the Microsoft Dynamics NAV Universal App

  • Troubleshooting the Microsoft Dynamics NAV Universal App


Introducing the Microsoft Dynamics NAV Universal App

The app displaying the Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client is targeted at users in small and medium sized businesses that want to access data from a tablet or a phone. Some of the advantages of offering this solution are portability and flexibility, when the user is away from the desk, on the train, between meetings, passing time and so on.

The tablet is lighter than a laptop, and thereby provides portability. Most tablets have an on-screen keyboard, but the keyboard plays a less central role on the tablet, and this forces you to have to consider the touch experience.

The phone is a very light device and has an even smaller screen than tablets, which is why the tasks that usually make sense to perform using the phone are brief and typically reading of data or very lightweight data entry, such as approving an invoice or getting an overview of the business. Designing for the Microsoft Dynamics NAV Tablet client you are used to optimizing for the touch experience; when you design for the Microsoft Dynamics NAV Phone client it is only about touch optimization.

Studies show that design for phone apps must cater for one-hand use; and in some cases, when switching to a panorama view, users will use both hands. The Microsoft Dynamics NAV Phone client layout is designed to support these needs, which allows the important data and buttons to be available within thumbs reach.

Having a Microsoft Dynamics NAV solution that runs on a smaller device brings it in the hands of many more users and your app is easy to distribute. Other advantages are that using a tablet or phone, you can capture data closer to the source, for example, at the customer site, and thereby improve accuracy and reduce end-to-end time.

The following illustration shows the intended use of the various Microsoft Dynamics NAV clients.

Illustrates the different NAV clients available

As illustrated, the Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client do not replace the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client. Instead, they offer a touch interface for a limited set of application scenarios compared to the Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client. The Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client support more complex business processes and heavier data entry than is possible on the Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client.

Microsoft Dynamics NAV Windows client is optimized for intensive use, and the user can have multiple windows open at the same time, for example, to compare sales orders, or do more things at a time. This is not possible in either Microsoft Dynamics NAV Web client or Microsoft Dynamics NAV Tablet client.

In the following documentation, you will see mentions of Microsoft Dynamics NAV Tablet client, Microsoft Dynamics NAV Phone client, and Microsoft Dynamics NAV Universal App. Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client describe the interface tailored to the category of mobile device, which is one of the tools available for developers for designing mobile solutions, whereas Microsoft Dynamics NAV Universal App is the common name for the app across all devices; the end result made with these tools.

Considering the User Scenarios

When you design your solution for the Microsoft Dynamics NAV Tablet client and the Microsoft Dynamics NAV Phone client, you must make sure that scenarios are simple enough to be meaningful and usable. The tablet and phone designs are meant for lighter tasks and useful, for example, for traveling salespeople or service technicians who need a portable, online, easy-to-use app that provides an overview, for example, of daily tasks and items in stock.

Depending on the scenarios that your tablet and phone solution will support, it will either make sense to create a new Role Center for tablet and phone only, or share the same Role Center across all of the client types. In some cases it can make sense to have a user sign in with two different profiles, one for a desktop client and one for mobile devices. In other cases, duplicating pages and designing specific duplicates to be device-oriented is the best solution.

If you have existing page objects that you want to make available on Microsoft Dynamics NAV Tablet client or Microsoft Dynamics NAV Phone client, we strongly recommend that you plan time to evaluate carefully which actions, sections, and fields will be needed for the user scenarios you want to enable. Fields and actions that are not needed should not be visible to users of your app. The UI must be simplified significantly to work well on a small device.

Supported Credential Types

Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client support the same credential types as Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client. For more information, see Users and Credential Types.

See Also

Concepts

Developing for the Microsoft Dynamics NAV Universal App
Getting Started Developing for the Microsoft Dynamics NAV Universal App
Differences and Limitations When Developing Pages for the Microsoft Dynamics NAV Universal App


Deciding on Your Tablet and Phone Strategy

To offer users a great mobile experience, you must decide on a strategy for how to accomplish this based on an analysis of your users’ needs. This topic explains the different options for developing for the Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client, but the documentation you will find in this section is primarily focused on the first of these scenarios.

Universal App Development Strategy

This section briefly describes some of the options that exist for Microsoft Dynamics NAV.

Development strategy Advantages What also to consider Examples For more information, see

Use the Microsoft Dynamics NAV Development Environment to modify and extend the Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client. This scenario resembles developing for Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client.

  • Extending and modifying Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client is useful for a minimal learning curve and a reduction of development costs; scenarios automatically work on multiple operating systems without having to worry about the maintenance.

  • Reusing existing investments in Microsoft Dynamics NAV page objects, business logic, and javascript-based client add-ins. Ideal for user scenarios which can be achieved by using simple application pages.

Microsoft Dynamics NAV only supports a specific number of page types, and this can be a limitation in some type of development projects.

  • For salespeople tracking customers, looking up item details, and capturing orders.

  • For technicians on the road using and re-ordering spare parts.

  • For simple approval scenarios.

Introducing the Microsoft Dynamics NAV Universal App

Getting Started Developing for the Microsoft Dynamics NAV Universal App

Based on OData web services or SOAP web services technologies, write an app that interacts with Microsoft Dynamics NAV. Visual Studio includes project templates for this kind of apps.

This strategy applies when you want to build a highly-custom app with your own UI design that takes advantage of all the rich features which native apps provide.

Cost to learn development tools and languages outside C/SIDE, preparing new development environments. Cost of licensing any one of these tools, and having to maintain code for different operating systems.

A simple touch interface for users to scan their access card for time registration.

Using OData Web Services to Modify Data

OData Web Services

SOAP Web Services

Web Services

Web Service Walkthroughs

Specifically for developers, use a browser for continuous development and test of the Microsoft Dynamics NAV Tablet client and the Microsoft Dynamics NAV Phone client solution that you are working on.

Switching to running in a browser is an easy and efficient way to test what new and modified pages look like.

Running the Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client in a browser is only recommended for development scenarios.

Testing a Role Center throughout the development process from a browser.

How to: Open the Microsoft Dynamics NAV Tablet or Phone Client from a Browser

See Also

Concepts

Developing for the Microsoft Dynamics NAV Universal App
Getting Started Developing for the Microsoft Dynamics NAV Universal App


Getting Started Developing for the Microsoft Dynamics NAV Universal App

The Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone clients are built on the same framework as the Microsoft Dynamics NAV Windows client and the Microsoft Dynamics NAV Web client. The Microsoft Dynamics NAV Tablet client and the Microsoft Dynamics NAV Phone client offer a framework for building an app based on Microsoft Dynamics NAV pages. Developing for Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client is not much different from developing pages for Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client using the Microsoft Dynamics NAV Development Environment.

Using the Microsoft Dynamics NAV Tablet client and the Microsoft Dynamics NAV Phone client you can develop content for the Microsoft Dynamics NAV Universal App that allow users in small and medium sized businesses to access Microsoft Dynamics NAV data from a tablet or a phone. Developing for tablets and phones provides flexibility for end-users who can perform their daily tasks from anywhere, outside the office, on the train, passing time and so on with just a tablet or phone available.

Microsoft Dynamics NAV Tablet and Phone Client Prerequisites

To be able to run Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client, the Microsoft Dynamics NAV Web Server components must be installed. For more information, see Deploying the Microsoft Dynamics NAV Web Server Components.

Steps for Developing for the Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client

The first step to take when you are developing for the Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client is to consider the design and implementation of the solution:

  • What is the business scenario that you want to support?

  • Do you want to extend your existing data model?

  • Should the solution work well on both a desktop computer, on the tablet and also on a phone?

  • What design should the Role Center that will be the central dashboard for the solution have?

Understanding the business scenario is important to build the best solution. Design your solution for users who are most typically occasional users who need an overview of their daily work status and perform relatively simple or light data entry. Many of these preparations resemble those for developing for Microsoft Dynamics NAV Web client, but in an even smaller scale. For more information, see Developing for the Microsoft Dynamics NAV Web Client.

Once the data model, users, permissions, and profiles are in place, you can start developing the Role Center. You have two options: You can either reuse an existing Role Center or create a new one. This will depend on the business scenario. The Microsoft Dynamics NAV Tablet client and the Microsoft Dynamics NAV Phone client are designed to be smart about laying out the same Role Center depending on the display target. Later in this section, you can read a walkthrough that illustrates how to create a new Role Center specifically for the Microsoft Dynamics NAV Tablet client. For more information, see Walkthrough: Developing a Sales Rep Role Center for the Microsoft Dynamics NAV Tablet Client. When developing for the Microsoft Dynamics NAV Phone client you want to continue similarly, but think even more about design and usability on a very small screen. On the phone the app will always by default start a page in view mode meaning that the user actively must switch to edit mode. This is based on the most common use, and avoids the accidental change of data.

There are some best practices and limitations to consider in particular caused by the smaller screen size and touch experience. For more information, see Differences and Limitations When Developing Pages for the Microsoft Dynamics NAV Universal App. On devices that have a camera and GPS capability and also run the Dynamics NAV Universal App you have a couple of additional options. For more information, see How to: Implement the Camera in C/AL and How to: Implement Location in C/AL.

The next steps are to consider how to deploy your solution and how to distribute it to your customers. After you have completed your solution, you can send an e-mail to the users to let them know that they can download Microsoft Dynamics NAV from the relevant store. In the e-mail, you can include the organization URL and sign-in information. For more information, see Linking to the Microsoft Dynamics NAV Universal App.

See Also

Tasks

Walkthrough: Developing a Sales Rep Role Center for the Microsoft Dynamics NAV Tablet Client

Concepts

Developing for the Microsoft Dynamics NAV Universal App
Deciding on Your Tablet and Phone Strategy
Differences and Limitations When Developing Pages for the Microsoft Dynamics NAV Universal App


How to: Open the Microsoft Dynamics NAV Tablet or Phone Client from a Browser

You can open the Microsoft Dynamics NAV Tablet client or the Microsoft Dynamics NAV Phone client by using a browser from a device that has a network connection. Opening the Microsoft Dynamics NAV Tablet client or the Microsoft Dynamics NAV Phone client in a browser can, for example, make it easier to test your solution during the design phase. You must know the name of the computer that is running the Microsoft Dynamics NAV Web Server components and the HTTP port that it is running on to be able to open the client in a browser.

Important
In early versions of Internet Explorer 11, prior to and 11.0.9600.16476, an issue with hardware acceleration can occur when the browser zoom is not set to 100%. This can cause some elements of the Microsoft Dynamics NAV Tablet client or Microsoft Dynamics NAV Phone client UI being rendered incorrectly. For example, the action pane appears displaced horizontally.

Important
The procedure in this article illustrates how you can open the Microsoft Dynamics NAV Tablet client in a browser. The syntax and options for opening Microsoft Dynamics NAV Phone client in a browser are the same; just replace tablet.aspx with phone.aspx in the examples later in this section.

To open Microsoft Dynamics NAV Tablet client in a browser

  1. Open the web browser.

  2. In the address box of the browser, type one of the following URLs.

    To open URL Example

    The Role Center for the default company

    http://ComputerName:Port/WebServerInstance/tablet.aspx

    Or (for multitenant deployments)

    http://ComputerName:Port/WebServerInstance/tablet.aspx?tenant=TenantID

    http://MyNAVWeb:8080/DynamicsNAV90/tablet.aspx

    The Role Center for a specific company

    http://ComputerName:Port/WebServerInstance/tablet.aspx?company=CompanyName

    Or

    http://ComputerName:Port/WebServerInstance/tablet.aspx?tenant=TenantID&company=CompanyName

    http://MyNAVWeb:8080/DynamicsNAV90/tablet.aspx?company=CRONUS%20International%20Ltd.

    A specific page

    http://ComputerName:Port/WebServerInstance/tablet.aspx?page=ID

    Or

    http://ComputerName:Port/WebServerInstance/tablet.aspx?tenant=TenantID&page=ID

    http://MyNAVWeb:8080/DynamicsNAV90/tablet.aspx?page=22

    A specific report

    http://ComputerName:Port/WebServerInstance/tablet.aspx?report=ID

    Or

    http://ComputerName:Port/WebServerInstance/tablet.aspx?tenant=TenantID&report=ID

    http://MyNAVWeb:8080/DynamicsNAV90/tablet.aspx?report=8

    A specific profile

    http://ComputerName:Port/WebServerInstance/tablet.aspx?profile=ProfileID

    Or

    http://ComputerName:Port/WebServerInstance/tablet.aspx?tenant=TenantID&profile=ProfileID

    http://MyNAVWeb:8080/DynamicsNAV90/tablet.aspx?profile=Small%20Business

    Substitute the following parameters:

    • http with https if SSL is configured for the Microsoft Dynamics NAV Tablet client or the Microsoft Dynamics NAV Phone client and the Microsoft Dynamics NAV Web Server is not configured to redirect HTTP requests to HTTPS.

    • ComputerName with the name of the computer that is running the Microsoft Dynamics NAV Web Server components.

    • Port with the port number that you configured for the Microsoft Dynamics NAV Web Server components during installation.

    • WebServerInstance with the virtual directory alias under which the Microsoft Dynamics NAV Tablet client or the Microsoft Dynamics NAV Phone client exists on the web server. For more information, see How to: Install the Web Server Components.

    • TenantID with the name of the tenant that you want to connect to. This parameter is only required when Microsoft Dynamics NAV is deployed in a multitenant architecture. The tenant that you specify must be mounted on the Microsoft Dynamics NAV Server instance that the Microsoft Dynamics NAV Web client connects to. For more information, see Multitenant Deployment Architecture.

    • CompanyName with the name of the company in Microsoft Dynamics NAV. This parameter is optional and is only needed if you want to open a different company than the one specified in My Settings.

    • ID with the ID that is assigned to the page or report in Microsoft Dynamics NAV.

    • ProfileID with the ID that is assigned to the profile in Microsoft Dynamics NAV.

See Also

Concepts

Developing for the Microsoft Dynamics NAV Universal App
Introducing the Microsoft Dynamics NAV Universal App


Walkthrough: Developing a Sales Rep Role Center for the Microsoft Dynamics NAV Tablet Client

In this walkthrough, you will learn how to create a new Role Center for the Microsoft Dynamics NAV Tablet client. Developing for the Microsoft Dynamics NAV Tablet client occurs in the Microsoft Dynamics NAV Development Environment and is not much different from developing for one of the other Microsoft Dynamics NAV clients. This walkthrough will concentrate on how to build a Role Center for a sales representative, which links to already existing page objects, but combined in a way so that it works well on the tablet.

About This Walkthrough

This walkthrough illustrates the following tasks:

  • Creating a Role Center page.

  • Adding existing pages to the Role Center.

  • Adding actions to pages from the Role Center.

  • Testing the Role Center page.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV installed with a developer license.

  • Microsoft Dynamics NAV Web Server components.

  • CRONUS International Ltd. demonstration database.

  • A supported browser. For more information, see System Requirements for Microsoft Dynamics NAV 2016.

Story

Simon is a partner developer working for CRONUS International Ltd. Nancy is a Sales Representative at Contoso Consulting. Simon has to build a new Role Center to support Nancy in her job. When at work, Nancy spends part of her time on the road with only her tablet available on customer visits. Nancy needs access to KPIs on the front page. She needs easy access to filter for the customers who she will visit. When at the customer site, she creates sales quotes. Simon wants to build a Role Center that can be used on a tablet and he wants to reuse as much code and as many page objects as possible.

Creating a Role Center Page

Simon starts by creating a new Role Center page using Page Designer. He starts by creating a new Role Center page, and then he will add relevant pages to the Role Center.

To create a Role Center Page

  1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Page, and then choose New. The New Page window opens.

  3. Choose Create a page using a wizard, choose RoleCenter, and then choose the OK button.

  4. On the first line, in the Name field, type RoleCenterContainer.

  5. On the File menu, choose Save. Set Name to Sales Rep Role Center, and set ID to 50006. Choose the OK button.

Adding Pages to the Role Center

Simon wants to add already existing pages to help Nancy access activities, customers, and charts to the Role Center that he just created.

To add pages to the role center

  1. In the development environment, choose Object Designer, and then choose the Role Center you created in the previous steps.

  2. In Page Designer, on the first empty line, set the Type field to Group.

  3. On the next line, set the Type field to Part, and set the SubType to Page.

  4. On the View menu, choose Properties.

  5. In the PagePartID property, use the Page List window to choose the Mini Activities page (1310).

  6. In the same way add a new line of the SubTypePage, which points to the My Customers (9150) page in the PagePartID property.

  7. On the next line, set the Type field to Group.

  8. Then, on the next line, set the Type field to Part, and set the SubType to Page.

  9. In the PagePartID property, use the Page List window to choose the Mini Generic Chart page (1390).

  10. Add another new line of the SubTypePage, which points to the Mini Trial Balance (1393) page in the PagePartID property.

  11. Close Page Designer, and choose Yes to save and compile the Sales Rep Role Center page.

Adding Actions to the Role Center

With the pages in place on the content area of the Role Center, Simon now adds actions that link to other pages, which Nancy uses in her daily work on the tablet. He adds the Sales Quote as an action item available from the action pane in the New group, the Customer and Item lists as Home items, which, on Microsoft Dynamics NAV Tablet client will display in the navigation pane.

To add actions to the role center

  1. In the development environment, choose Object Designer, and then choose the Role Center you created in the previous steps.

  2. On the View menu, choose Page Actions.

  3. In the Type field, choose ActionContainer.

  4. In the SubType field, choose ActionItems.

  5. On the next new line, in the Type field, choose ActionGroup and in the Caption property, enter New.

  6. On the next line, in the Type field, choose Action.

  7. In the Name property, enter Page Mini Sales Quote.

  8. In the RunObject property, choose Page Mini Sales Quote (1324).

  9. In the RunPageMode property, choose Create.

  10. In the Image property, choose the Quote image.

  11. In the Promoted property, choose Yes.

  12. The following table shows all of the actions you should have, including the one that you created during steps 1 through 11. Create the next actions following steps 6 through 11.

    Type SubType Name Properties

    ActionContainer

    ActionItems

    (default)

    (default)

    ActionGroup

    none

    (default)

    • Set Caption to New

    Action

    none

    <Page Mini Sales Quote>

    • Set RunPageMode to Create

    • Set Image to Quote

    • Set RunObject to Page Mini Sales Quote (1324)

    • Set Promoted to Yes

    ActionContainer

    HomeItems

    (default)

    (default)

    Action

    none

    Page Mini Customer List

    • Set Caption to Customers

    • Set PromotedCategory to New

    • Set RunObject to Page Mini Customer List (1301)

    • Set Promoted to Yes

    Action

    none

    Page Mini Item List

    • Set Caption to Items

    • Set PromotedCategory to New

    • Set RunObject to Page Mini Item List (1303)

    • Set Promoted to Yes

  13. Check the indentation of your page elements and adjust if it is required.

  14. Close Action Designer and then save and compile the Sales Rep Role Center page.

Simon now wants to test the Sales Rep Role Center that he created, and for testing purposes he uses a browser window. He enters a URL that specifically opens the page 50006 from tablet.aspx. His URL now resembles this: http://MyNAVWeb:8080/DynamicsNAV90/tablet.aspx?page=50006. For more information, see How to: Open the Microsoft Dynamics NAV Tablet or Phone Client from a Browser.

Next Steps

Nancy now has a Role Center that gives her access to most of the information that she needs when she is on the road. The next step for Simon is to refine the Sales Rep Role Center by adding more functionality, for example, the ability to retrieve more lists or making sure that Nancy can smoothly continue to work when she is back at the office on her desktop computer.

See Also

Concepts

Developing for the Microsoft Dynamics NAV Universal App
Designing for Different Screen Sizes on Tablet and Phone
Differences and Limitations When Developing Pages for the Microsoft Dynamics NAV Universal App


Differences and Limitations When Developing Pages for the Microsoft Dynamics NAV Universal App

Developing for the Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client is not much different from developing for the Microsoft Dynamics NAV Windows client, or Microsoft Dynamics NAV Web client. There are, however, some natural limitations on tablets and phones, such as not having a physical keyboard and mouse, as well as a smaller screen. In addition to this, there are some differences and limitations in developing pages for Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client. The differences and limitations listed are additional to the differences and limitations that exist on the Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client.

Differences and Limitations Overview

The following table describes some of the most common differences and limitations that you might experience when developing for Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client.

Concept On Tablet On Phone Example Recommendation

Activity buttons

Only the Home activity button is shown.

Only the Home activity button is shown.

Home, Departments, and Posted Documents on the Sales Order Processor Role Center.

Design pages to expose the workflows needed by the user. For example, configure the profile to show the important list pages under the Home activity button. Alternatively, consider designing a new Role Center if the activities for the activity button greatly vary from activities in other activity buttons.

Selecting multiple records in lists

Not available.

Not available.

Ctrl+A or Ctrl+Click on rows in a list using Microsoft Dynamics NAV Windows client.

Avoid scenarios requiring selecting multiple rows on a list. Also, try to minimize actions on lists.

Ribbon actions

Only Promoted actions are shown.

Only Promoted actions are shown.

On the Small Business Role Center.

Use the development environment to promote actions. Alternatively, configure the profile and add actions to the Home ribbon tab.

FactBoxes

Not shown on List pages or Worksheet pages.

Not shown on List pages or Worksheet pages.

Customer list on the Small Business Role Center.

Make sure the same information is visible on the corresponding card page of the given record.

Advanced filters

No column-specific filtering is available.

No column-specific filtering is available.

On the Customer list page.

Send data to Excel and do the complex filtering there.

Page search

Not available.

Not available.

On Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client.

Design pages to expose the workflows needed by the user. For example via list places, tiles or actions.

Cue and action tiles

The number of tiles that are shown is based on the size of the screen, no possibility to scroll.

The number of tiles on the phone is in theory unlimited because you can scroll.

On most Role Center pages.

Design Role Center pages to avoid having important tiles at the area end. Assume you have no control over how many tiles are displayed and consider that only the first few tiles will be made visible on the tablet.

Fields in fast tabs

Fields in fast tabs on list pages are not shown. Only the repeater control is shown in the content area of the page.

Not available.

Design List pages to avoid having important columns on the far right of the column list. Assume you have no control over how many columns are displayed and consider that only the first few columns will be made visible.

Links and Notes

Not available.

Not available.

On Sales Orders.

Similar to Factboxes, make sure the same information in the field group is visible on the corresponding card page of the given record.

Select from full list

Not available on lookups. Users are not able to run actions on a lookup page, and they cannot access the full set of records.

Not available on lookups. Users are not able to run actions on a lookup page, and they cannot access the full set of records.

On the Item Card when selecting the Base Units of Measure.

Make sure the appropriate columns are visible on the lookup. The user is still able to filter, scroll, and search through the lookup.

Search across list columns

Partly supported. Search will not include FlowFields.

Partly supported. Search will not include FlowFields.

On the Customer list page.

Report Viewer and CurrReport.PREVIEW

There is no Preview functionality available on the Microsoft Dynamics NAV Tablet client. CurrReport.PREVIEW cannot be reliably used to identify whether a report was run as a draft or as a final printed document.

There is no Preview functionality available on the Microsoft Dynamics NAV Phone client. CurrReport.PREVIEW cannot be reliably used to identify whether a report was run as a draft or as a final printed document.

See example in report 280.

Lookups

Available.

Available, with the difference that advanced and simple lookups behave similarly on the phone. The lookup will not bring up the card, show factboxes, or any field groups.

See examples on the Customer Card page.

Matrix controls

Not available.

Not available.

See example in G/L Budget.

File download

Available. Cannot download multiple files at the same time.

Available. Cannot download multiple files at the same time.

Trial Balance report in the Print to Excel check box.

Worksheet pages

Available.

Not available; an error message is displayed.

Sales Price Worksheet or Cash Flow Worksheet.

Run this type of page from the Microsoft Dynamics NAV Windows client, Microsoft Dynamics NAV Web client, or Microsoft Dynamics NAV Tablet client.

Lists

Available.

Available, with the difference that these are displayed in a brick layout with a number of differences and limitations. For an overview, see How to: Display Data as Bricks on Phone.

Customers or Sales Orders pages.

Indentation in repeater controls

Available.

Not available. The repeater control will be rendered as a regular flat brick layout.

Chart of Accounts and Contacts List pages.

Scope of actions

Available.

Available, but there are some behavioral differences regarding the Scope Property. Also, see Defining Action Scope for Microsoft Dynamics NAV Pages.

Use of camera and location

Available in the Microsoft Dynamics NAV Universal App on devices with a camera and GPS capabilities.

Note
Not available on Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client.

Available in the Microsoft Dynamics NAV Universal App on devices with a camera and GPS capabilities.

Note
Not available on Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client.

On the Accounting Manager profile, under Incoming Documents.

See Also

Tasks

How to: Display Data as Bricks on Phone
How to: Implement the Camera in C/AL
How to: Implement Location in C/AL

Concepts

Developing for the Microsoft Dynamics NAV Universal App
Developing for the Microsoft Dynamics NAV Web Client
Role Center Behaviors


Role Center Behaviors

This section describes in which areas the Role Center pages have a different behavior in the Microsoft Dynamics NAV Tablet client and the Microsoft Dynamics NAV Phone client than in the Microsoft Dynamics NAV Windows client and the Microsoft Dynamics NAV Web client. This behavior has influence on how you will build your Role Center pages. For information about pages on tablets and phones in general, see Differences and Limitations When Developing Pages for the Microsoft Dynamics NAV Universal App.

Behavioral Differences

Concept On Tablet/Phone

Tiles

The app bar will automatically show tiles in two or three columns depending on the total number of tiles. A Role Center with many tiles only displays the tiles that fit vertically on the screen; other tiles are not shown and will not be available.

On the phone, the Home page will automatically show tiles in one or two columns depending on the total number of tiles and these can be scrolled.

Actions

Actions that are added under an ActionContainer of the subtype HomeItems are always shown in the navigation pane.

Actions

Actions that are added under an ActionContainer of the subtype ActivityButtons are never shown, and cannot be accessed.

There is no ability to navigate to other Activity Buttons as you can do in Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client. Because Activity Buttons link to related functionality, the recommended workaround is to providing links to this functionality through their own Role Center as a separate entry point.

Actions

  • In the action pane, if the current profile has no configuration for the specific page, for example, if this was deleted, only promoted actions will be shown. If there are no promoted actions, any actions under NewDocumentItems will be shown. If there are no NewDocumentItems actions, an empty pane will be shown.

  • If a page configuration exists, the NewDocumentItems will be shown, together with any new groups that were created. Actions, even if they were renamed, which remain in their original group will not show until you move them to a custom group. This behavior differs from Microsoft Dynamics NAV Windows client which will always show them.

  • When you add actions to the Home tab, it corresponds to setting the actions to Promoted. However, you can only do this with the configuration tooling if there is at least one Promoted action. Otherwise, the Home tab will never be available for customization.

Parts

Available on the tablet.

On the phone, there is a limit to a total number of 5 parts that can be displayed. If you have multiple parts that contain cues, these are currently displayed as one part.

When building Role Centers it is recommended to avoid using the Group type to group the parts that make up the Role Center, and instead create all parts directly underneath the Container type. This will optimize the layout to dynamically switch from a 1 to 2 to 3 column layout and thereby fit more display targets.

See Also

Concepts

Developing for the Microsoft Dynamics NAV Universal App
Differences and Limitations When Developing Pages for the Microsoft Dynamics NAV Universal App


Designing for Different Screen Sizes on Tablet and Phone

When designing application pages for the Microsoft Dynamics NAV Tablet client and the Microsoft Dynamics NAV Phone client, it is best practice to consider the size of the tablets or phones that your end-users have access to. It is an advantage if the solution works well on both small screen sizes and also on larger screen sizes, but we also recommend that you consider thoroughly the most frequently used screen sizes for your end-user experience. Designing for small screens can be a challenge, because pages will show fewer fields, columns, and tiles.

In many cases, end-users will have access to a broad range of devices having different screen sizes and resolutions. End-users may have one device at work, and a different device at home, and expect the experience on both devices to be equally good. A good way to identify issues on how your application pages will look is to test on the smallest supported screen size. Currently tablet sizes start in the 7” range and phones range from 3” up to just below 7”. There are certain requirements for running the Microsoft Dynamics NAV Universal App on tablets and phones. For more information, see System Requirements for Microsoft Dynamics NAV 2016.

Various sizes of screens

Form Factor Considerations

Users can scroll the content area of the Microsoft Dynamics NAV Universal App on a tablet to access all data for a given page. However, some elements of the screen, for example, the app bar cannot be scrolled. The app bar is the blue area of Microsoft Dynamics NAV Universal App and it is designed to provide easy access to important information and tasks that the user should not lose sight of when scrolling. The static elements will display only as much data as they can reasonably fit on the screen. Developers should design to make sure that the important static elements are displayed first so that these will be shown even on the smallest, available devices.

On phones there is no app bar, and the Microsoft Dynamics NAV Universal App displays only one part at a time on the Role Center. On the Home page, the Activity tiles are always displayed first, and you navigate through the top menu to explore the content area.

Guidance for Page Element Types on Smallest Tablet Devices

The following table provides a list of non-scrollable elements in the page content or the app bar.

Page Type Displays on smallest tablet device

RoleCenter

4 tiles in 1 group, or 2 groups together with 2 tiles

List Pages

5 columns of type Text50 or 8 columns of type Text20

Card Pages

  • CardPage Factbox with up to 15 fields

  • 2 CardPage Factboxes with up to 6 fields each

  • Activities Factboxes with 4 tiles in 1 group, or 2 groups together with 2 tiles

Document Pages

  • CardPage Factbox with up to 15 fields

  • 2 CardPage Factboxes with up to 6 fields each

  • Activities Factboxes with 4 tiles in 1 group, or 2 groups together with 2 tiles

Testing Using a Browser

Using a browser you can test how your application pages will look on various device sizes. For more information, see How to: Open the Microsoft Dynamics NAV Tablet or Phone Client from a Browser. When running Microsoft Dynamics NAV Tablet client or Microsoft Dynamics NAV Phone client in a browser, you can use Microsoft Edge Developer Tools to emulate different screen sizes. For more information, see Using the F12 developer tools. Also, for more information see Troubleshooting: Client Returns Wrong CLIENTTYPE.

See Also

Concepts

Deciding on Your Tablet and Phone Strategy
Differences and Limitations When Developing Pages for the Microsoft Dynamics NAV Universal App


Using HTTPS and Certificates

The Microsoft Dynamics NAV Universal App can only run on an HTTPS protocol. To enable support for HTTPS on Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client, you must implement security certificates. Complete instructions are available from your certificate provider. We recommend that you secure the data that is transmitted over the Internet by enabling Secure Sockets Layer (SSL) on the connection to the Microsoft Dynamics NAV Universal App. For more information, see Digital Certificates.

The following table illustrates how SSL is enforced.

Mode | Credentials Type | Enforced SSL?
Microsoft Dynamics NAV Universal App | Windows authentication | Enforced
 | NavUserPassword | Enforced
Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client in a browser | Windows authentication | Not enforced Only credentials are encrypted, all other communication over the network is sent in clear text. Use SSL to help secure this.
 | NavUserPassword | Not enforced Credentials in addition to all other communication over the network are sent in clear text. Use SSL to help secure this.

Implementing Security Certificates

Microsoft Dynamics NAV Universal App only works using an HTTPS protocol. This means that you must configure a valid certificate on the server. If a trusted, valid, and signed certificate is configured on the Microsoft Dynamics NAV Server, the end-user does not have to do anything. If a self-signed certificate is configured on the Microsoft Dynamics NAV Server, the end-user must install a certificate on their device. The steps for implementing certificates will vary depending on the platform the user is using.

For more information, see How to: Implement Security Certificates in a Production Environment and How to: Create a Self-signed Security Certificate Using PowerShell Script.

Important
It is recommended to only use self-signed certificates for testing purposes and never in a production environment.

See Also

Concepts

Developing for the Microsoft Dynamics NAV Universal App
Getting Started Developing for the Microsoft Dynamics NAV Universal App


Adding Help to the Microsoft Dynamics NAV Universal App

To complete designing your Microsoft Dynamics NAV Universal App solution, you have to offer users Help. Although tablets and phones have a simpler interface than both the Microsoft Dynamics NAV Web client and the Microsoft Dynamics NAV Windows client, there can be times where the user needs help understanding the purpose of a page or a workflow.

Adding Help to a Microsoft Dynamics NAV Universal App solution is not different from adding Help to Microsoft Dynamics NAV in general.

Help is linked to the Microsoft Dynamics NAV Universal App using the same technology as for the Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client. Help is invoked on the Microsoft Dynamics NAV Universal App through an action on each page. The Help action is always the last action on the list. Because the same underlying technology applies to all clients, Help can be reused on all clients. The only difference is that field Help cannot be called directly from the Microsoft Dynamics NAV Universal App. Instead, users will be lead to the page Help and this should therefore be designed to guide users to relevant field topics.

Adding Help

Add Help to your solution by adding new HTML files, or modifying existing HTML files on your Help Server. Context-sensitivity is decided by topic names alone. Therefore naming is very important to get the Help call to work. Also, always make sure to work on an offline copy of a Help topic on the Help Server and then upload the topic(s) when you are finished.

For example, you can add a new topic to guide users who are using the Sales Rep Role Center created in Walkthrough: Developing a Sales Rep Role Center for the Microsoft Dynamics NAV Tablet Client. This topic will have to be named N_50006.htm, based on the page ID and prefixed with N_ which is the notation for pages. This topic must be put on your Help Server in the equivalent folder of C:\inetpub\wwwroot\DynamicsNAV90Help\help\en. In this topic, write text that guides the user and explains the processes and workflows associated with the Role Center page. Also, add direct links to Help topics on fields that you think the user will need guidance for. The notation for fields on tables is T_<table ID>_<field ID>, and the notation for page controls is N_<page ID>_<page control ID>. See more examples on your Help Server.

Important
The N_50006.htm file must adhere to the classic.css style sheet, which you can find on the Help Server.

See Also

Concepts

Developing for the Microsoft Dynamics NAV Universal App
Getting Started Developing for the Microsoft Dynamics NAV Universal App


Defining Action Scope for Microsoft Dynamics NAV Pages

When developing pages for Microsoft Dynamics NAV that include a repeater control, it is useful to be able to define whether the actions available on a page apply to the whole page or are related to the repeater control on the page.

The purpose of the Scope property is to enable developers to add row-specific actions to the shortcut menu which is available to the user on each line. This gives users a more direct way to invoke actions that relate to the selected row or line.

This is the case when you have, for example, Line Comments which are related to a line, but appear in the ribbon. You can specify the scope of the action by setting the Scope property on the page action to be either Page or Repeater.

Note
It is strongly recommended that the Scope property is always appropriately set when developing pages for the Microsoft Dynamics NAV Universal App.

For more information on how the settings are interpreted on the various clients, see Scope Property.

See Also

Reference

Scope Property


Linking to the Microsoft Dynamics NAV Universal App

The protocol handler for the Microsoft Dynamics NAV Universal App lets you construct a URL for starting the Microsoft Dynamics NAV Universal App on a device. You can then distribute this URL by e-mail or from a Web page to the users.

The ms-dynamicsnav scheme is registered automatically when the app is installed. From this point onward, invoking a URL based on this URI scheme will start the app with the provided parameters.

Constructing the URL

To enable starting the Microsoft Dynamics NAV Universal App from a link, construct a URL with the ms-dynamicsnav scheme pointing to your Microsoft Dynamics NAV Web server.

The structure of a Microsoft Dynamics NAV Universal App link is very similar to links for the Microsoft Dynamics NAV Web client and resembles this:

ms-dynamicsnav://<Server>:<Port>/<Instance>/[?tenant=<Tenant>&company=<Company>]/?profile=/?page=

Parameter | Description
Server | Optional. The public address for your Microsoft Dynamics NAV Web client server.
Port | Optional. The port number for your Microsoft Dynamics NAV Web client server. If not provided, the standard SSL port (443) is used.
Instance | Optional. The Microsoft Dynamics NAV Web client instance that you want to connect to.
Tenant | Optional. The tenant that you want to connect to. If not provided, the default tenant is used.
Company | Optional. The company that you want to connect to. If not provided, the default company is used.
Profile | Optional. The profile that you want to connect with. If not provided, the default profile is used.
Page | Optional. The ID of the page that you want to open directly.
Note
It is not possible to specify which client type to open up the URL in; the last used client will open up when clicking the URL.

Warning
The URL ms-dynamics:///?page=21 will open the server that you last connected to on the specified page.

URL Examples

The following examples demonstrate how to use the parameters from the table earlier in this section:

  • ms-dynamicsnav://myserver/myinstance/

  • ms-dynamicsnav://myserver:440/myinstance/

  • ms-dynamicsnav://myserver/myinstance/?company=MyOtherCompany

  • ms-dynamicsnav://myserver/myinstance/?tenant=myTenant2&company=MyCompany2

Important
The ms-dynamicsnav scheme only translates to a secure server connection. Therefore the Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client must be exposed through an https connection. For more information, see How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client.

Adding Username to the URL

The ms-dynamicsnav scheme also supports sending the user name in the URL for prefilling the user name. The password must be entered by the user. To send the user name, you must URL encode the value and prefix the server address by using <encoded username>@. Examples are as follows:

  • ms-dynamicsnav://demouser%40mycompany.com@myserver/myinstance/

  • ms-dynamicsnav://user1:@myserver/myinstance/

Security Note
We recommend that you do not share a user name in the URL. This technique should only be used in demonstration scenarios and other instances where the accidental sharing of a URL will not compromise the system.

See Also

Tasks

How to: Open the Microsoft Dynamics NAV Tablet or Phone Client from a Browser

Concepts

Developing for the Microsoft Dynamics NAV Universal App


Troubleshooting the Microsoft Dynamics NAV Universal App

This section contains information to help you resolve problems using the Microsoft Dynamics NAV Web client, the Microsoft Dynamics NAV Tablet client, and the Microsoft Dynamics NAV Phone client.

Troubleshooting Topics

Troubleshooting: Compression Option in IIS

Troubleshooting: The File that You Are Trying to Use Is Too Large

Troubleshooting: Icon Font Not Loaded

Troubleshooting: Device Date is Causing Connection Issues

Troubleshooting: Client Returns Wrong CLIENTTYPE

Troubleshooting: The Server Is Not Compatible


Troubleshooting: Compression Option in IIS

Users may experience slow mobile client responses especially noticeable when they are running with a slow network connection. The reason for the mobile client running slowly can be that the dynamic compression is not enabled on the IIS server.

Resolution

The IIS administrator must make sure that dynamic compression is enabled on the IIS. For more information, see Enable HTTP Compression of Dynamic Content

Note
Dynamic compression is enabled by the Microsoft Dynamics NAV installer when you install Microsoft Dynamics NAV Web Server components.

See Also

Troubleshooting Using Microsoft Dynamics NAV

Concepts

Troubleshooting the Microsoft Dynamics NAV Universal App


Troubleshooting: The File that You Are Trying to Use Is Too Large

If you are trying to upload a large image file that is larger than 30 MB, such as a high-resolution photo, Microsoft Dynamics NAV will give you an error message that says that the file that you are trying to upload is too large. This behavior can be changed by modifying the IIS configuration to support large file uploads.

Resolution

The IIS administrator should make the following changes in the Internet Information Services (IIS) Manager.

  1. Launch IIS Manager.

  2. In the left pane of IIS Manager, select the Microsoft Dynamics NAV web site, and choose Request Filtering.

  3. In the Actions pane of the Request Filtering window, choose Edit Feature Settings.

  4. Set the field Maximum allowed content length (Bytes) to an appropriate value, such as 100000000 and choose the OK button.

  5. In the left pane of IIS Manager, select the Microsoft Dynamics NAV web site, and choose Configuration Editor.

  6. In the Configuration Editor, make sure that the From field is set to Microsoft Dynamics NAV 2016 Web Client Web.config.

  7. Set the Section field to system.web/httpRuntime and now several properties will appear.

  8. Set maxRequestLength to an appropriate value, such as 100000 (kilobytes) and choose the Apply action on the right.

  9. Close IIS Manager.

The new settings should take effect immediately without refreshing the IIS or the site.

See Also

Troubleshooting Using Microsoft Dynamics NAV


Running 32-Bit Microsoft Dynamics Windows Client on 64-Bit Windows

On a 64-bit version of a Windows operating system, a 64-bit version of the Microsoft Dynamics NAV Windows client runs by default. The 64-bit version is suitable for most installations. It has an advantage over the 32-bit version because of its memory allocation capabilities, which is especially useful when running several large reports. However, if an application uses 32-bit components, such as COM technologies and 32-bit .NET Framework components, these components will not work in the 64-bit version of the Microsoft Dynamics NAV Windows client. In this case, you must run the 32-bit version of the Microsoft Dynamics NAV Windows client.

Run the 32-bit version of the Microsoft Dynamics NAV Windows client

By default, the Microsoft Dynamics NAV Windows client is started by running the Microsoft.Dynamics.Nav.Client.exe file. This file runs the 64-bit version of the Microsoft Dynamics NAV Windows client on a 64-bit Windows operating system and the 32-bit version of the Microsoft Dynamics NAV Windows client on a 32-bit Windows operating system. The file is installed by the Microsoft Dynamics NAV Setup, where the default location is C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client folder. In the same location, Microsoft Dynamics NAV Setup also installs the Microsoft.Dynamics.Nav.Client.x86.exe file, which you use to run the 32-bit version of the Microsoft Dynamics NAV Windows client.

To run the 32-bit version of the Microsoft Dynamics NAV Windows client, do any of the following:

  • Run the Microsoft.Dynamics.Nav.Client.x86.exe file directly from the installation folder or create a desktop shortcut.

  • Rename the Microsoft.Dynamics.Nav.Client.exe file to Microsoft.Dynamics.Nav.Client.X64.exe, and then rename the Microsoft.Dynamics.Nav.Client.X86.exe file to Microsoft.Dynamics.Nav.Client.exe.

    This sets up the 32-bit version to run from the Microsoft Dynamics NAV link in computer's Start menu and from the Microsoft Dynamics NAV Development Environment.

  • If you are installing the Microsoft Dynamics NAV Windows client on multiple computers and you want them all to run the 32-bit version, then on the Microsoft Dynamics NAV installation media (DVD), you can rename the .exe files as described in the previous bullet.

See Also

Concepts

Client Types


Microsoft Dynamics NAV Server

Microsoft Dynamics NAV Server is a .NET-based Windows Service application that manages communications between Microsoft Dynamics NAV clients and Microsoft Dynamics NAV databases in SQL Server. It uses the Windows Communication Framework (WCF) as its communication protocol.

Microsoft Dynamics NAV Server uses an ADO.NET interface, which is a managed data access layer that supports SQL Server connection pooling. This simplifies deployment of the Microsoft Dynamics NAV three-tier architecture for deployments where the three tiers are installed on separate computers. Specifically, administrators are not required to manually create service principal names (SPNs) or to set up delegation when the client, Microsoft Dynamics NAV Server, and SQL Server are on separate computers. For more details, see Data Access.

Microsoft Dynamics NAV Server supports a range of different client types. This includes the Microsoft Dynamics NAV Windows client and the Microsoft Dynamics NAV Web client and two types of web services. For more information, see Client Types. You administer Microsoft Dynamics NAV Server using either Microsoft Dynamics NAV Server Administration tool or Windows PowerShell cmdlets. For more information, see Microsoft Dynamics NAV Server Administration Tool or Microsoft Dynamics NAV Windows PowerShell Cmdlets.

Microsoft Dynamics NAV Server is installed when you select either the Server Option or the Developer Option in Microsoft Dynamics NAV Setup.

Note
Installing Microsoft Dynamics NAV Server on encrypted drives is not supported. You may experience issues if the server runs as a user that does not have access rights to the encrypted files.

Note
You can install Microsoft Dynamics NAV Server only on 64-bit operating systems.

See Also

Concepts

Server Option
System Requirements for Microsoft Dynamics NAV 2016
Configuring Microsoft Dynamics NAV Server
Enhancing Microsoft Dynamics NAV Server Security


Communicating with Microsoft Dynamics NAV Clients in Different Time Zones

Microsoft Dynamics NAV can interact with RoleTailored clients in different time zones.

RoleTailored Client Implementation

The following table provides an overview of how the time zone is determined for the different RoleTailored clients.

Client | Time zone
Microsoft Dynamics NAV Windows client | Determined by the date and time settings of the client computer.
Microsoft Dynamics NAV Web client | Determined by the time zone setting in the web.config file of the Microsoft Dynamics NAV Web client application. For more information, see Configuring Microsoft Dynamics NAV Web Client by Modifying the Web.config File.

DataTime Data Types

If RoleTailored client data contains data of the type DateTime, then upon receiving the data from the client, Microsoft Dynamics NAV Server converts this data into Coordinated Universal Time (UTC) based on the client time zone. When passing data of type DateTime back to the client, Microsoft Dynamics NAV Server converts the time back to the local time zone of the client before presenting the data to the end user.

Different countries and regions sometimes have different rules for determining when to start and end daylight saving time. If computers that run Microsoft Dynamics NAV Server are kept current with Windows updates, then changes to daylight saving time are managed automatically.

Note
There is limited support for reading and writing in UTC in the Microsoft Dynamics NAV Windows client. Specifically, the client evaluates and formats DateTime values in pages using format code 9. This format is UTC but can be difficult to read. For example, the date and time of January 1, 2008 with the long time format specifier, is displayed in the following format; 2008-01-01T10:22:00Z.

Date and Time Data Types

Date data type and Time data type are not affected by the time zone settings. The value that a user enters is the value that is saved to the Microsoft Dynamics NAV database.

Implementation for Web Services and NAS Services

The CustomSettings.config file, which is the configuration file for the Microsoft Dynamics NAV Server service instance, has a Services Default Time Zone setting. This setting is also implemented in the Microsoft Dynamics NAV Server Administration Tool and in the Microsoft Dynamics NAV Windows PowerShell Cmdlets.

You use this setting to define the time zone in which web service and NAS services calls are run. The following table describes the possible values for the Services Default Time Zone setting.

Value | Description
UTC | Specifies that all business logic for web services on the server runs in Coordinated Universal Time (UTC). This is the default value. This is how web services business logic was handled in Microsoft Dynamics NAV 2009 SP1 and Microsoft Dynamics NAV 2009.
Server Time Zone | Specifies that web services use the time zone of the computer that is running Microsoft Dynamics NAV Server.
ID of any Windows time zone | Specifies any Windows time zone as defined in the system registry under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones. For example, Romance Standard Time is a valid Windows time zone value.

When a web service writes data back to Microsoft Dynamics NAV, dates and times are based on the setting of the Services Default Time Zone setting. However, the web service consumer can override the setting and specify a different time zone.

Note
Microsoft Dynamics NAV Server stores dates and times as UTC. When a web service receives data from Microsoft Dynamics NAV Server, the time zone is UTC even if the Services Default Time Zone setting is set to a different time zone.

For example, if the Services Default Time Zone setting is set to UTC+3, the following table describes two scenarios where a web service consumer modifies Microsoft Dynamics NAV data and sends this back to Microsoft Dynamics NAV Server.

Web service changes the DateTime field to | Microsoft Dynamics NAV Server interprets the DateTime value as | Microsoft Dynamics NAV Server saves the DateTime value as
01/01/2014 17:00 UTC+1 | 01/01/2014 17:00 UTC+1 | 01/01/2014 16:00 UTC
01/01/2014 17:00 | 01/01/2014 17:00 UTC+3 | 01/01/2014 14:00 UTC

See Also

Concepts

Configuring the Windows Client
Dates and Times
Managing Time Zones with Web Services


Microsoft Dynamics NAV Server Administration Tool

The Microsoft Dynamics NAV Server Administration tool is a Microsoft Management Console (MMC) snap-in for creating and managing Microsoft Dynamics NAV Server instances. When you install the Server Option on a computer, the Microsoft Dynamics NAV Server Administration tool is one of the default features. The Microsoft Dynamics NAV Server Administration tool is also an option when you install the Client Option, although it is not one of the default components.

You typically run the Microsoft Dynamics NAV Server Administration tool by choosing Microsoft Dynamics NAV Administration from the Start menu. For some scenarios, however, you may need to open the MMC first and then add the Microsoft Dynamics NAV snap-in. For example, see How to: Administer Multiple Microsoft Dynamics NAV Server Computers. In this case, choose Run from the Start menu and then specify the Microsoft Management Console:

Copy Code
mmc
Security Note
Only members of the Administrator group on the computer are able to use the Microsoft Dynamics NAV Server Administration tool.

Security Note
The Microsoft Dynamics NAV Server Administration tool is not supported for multi-user environments.

To learn more about how to use Microsoft Dynamics NAV Server Administration tool, see one of the following topics:

To | See
Learn about the different tools and options for administering Microsoft Dynamics NAV 2016. | Administration
Administer a remote Microsoft Dynamics NAV Server computer. | How to: Administer a Remote Microsoft Dynamics NAV Server Computer
Administer multiple Microsoft Dynamics NAV Server computers from a single administrative console. | How to: Administer Multiple Microsoft Dynamics NAV Server Computers
Create a Microsoft Dynamics NAV Server instance. | How to: Create a Microsoft Dynamics NAV Server Instance
Mount a tenant on a Microsoft Dynamics NAV Server instance that is configured for multitenancy. | How to: Mount or Dismount a Tenant on a Microsoft Dynamics Server Instance
Manage Microsoft Dynamics NAV Server instances. | Managing Microsoft Dynamics NAV Server Instances
Manage settings for a Microsoft Dynamics NAV Server instance. | Microsoft Dynamics NAV Server Settings
Configure Microsoft Dynamics NAV Server settings. | Configuring Microsoft Dynamics NAV Server
Tip
You can also administrate your Microsoft Dynamics NAV deployment using Windows PowerShell cmdlets. For more information, see Microsoft Dynamics NAV Windows PowerShell Cmdlets.

Navigating the Microsoft Dynamics NAV Server Administration Tool

Microsoft Dynamics NAV Server Administration tool is divided into three panes:

  • The left pane shows a tree view that lists all Microsoft Dynamics NAV Server computers that you are administering from this computer and all Microsoft Dynamics NAV Server instances on those computers. The first time that you run Microsoft Dynamics NAV Server Administration tool, the view is collapsed. You only see the local server computer without any Microsoft Dynamics NAV Server instances listed.

    Admin Console Root collapsed

  • Choose Microsoft Dynamics NAV (Local), under Console Root, in the left pane of the Microsoft Dynamics NAV Server Administration tool, to display all Microsoft Dynamics NAV instances on the server computer in the center pane:

    Console root with two server instances

    For information about how to manage Microsoft Dynamics NAV Server instances, see Managing Microsoft Dynamics NAV Server Instances.

  • The center pane shows information about the item that you have selected in the left pane. When the selected item is a computer running Microsoft Dynamics NAV Server, the center pane shows a list of Microsoft Dynamics NAV Server instances on that computer and the status of each instance (running or stopped), and the name of the account the instance is running under.

    When the item selected in the left pane is a Microsoft Dynamics NAV Server instance, the center pane shows the settings for that instance. For information about how settings are organized in the center pane, see Microsoft Dynamics NAV Server Settings. For information about a specific setting, see Configuring Microsoft Dynamics NAV Server.

  • If the Microsoft Dynamics NAV Server is configured for multitenancy, then you can expand the Microsoft Dynamics NAV Server instance items in the left pane to display a Tenants item. Select the Tenants item to display all the tenants that are mounted on a Microsoft Dynamics NAV Server instance in the center pane. For more information, see Multitenant Deployment Architecture

  • The right pane displays available actions for the object that is selected in the left pane. These options differ depending on whether a Microsoft Dynamics NAV Server computer or a Microsoft Dynamics NAV Server instance is selected.

  • The Windows PowerShell History pane lists the Windows PowerShell commands that the equivalent of the tasks you perform in the Microsoft Dynamics NAV Server Administration tool. You can access the Windows PowerShell History pane from the Actions menu and from the right pane. To run a command that is shown in the Windows PowerShell History pane, you can copy the command and paste it into the Microsoft Dynamics NAV 2016 Administration Shell, for example.


Customer Experience Improvement Program and Microsoft Dynamics NAV Server

Microsoft Dynamics NAV Server supports the Customer Experience Improvement Program (CEIP), a tool that sends information to Microsoft about Microsoft Dynamics NAV Server usage and about the capacities of the computers where Microsoft Dynamics NAV Server is installed.

After Microsoft Dynamics NAV Server is installed, you can turn CEIP on or off on a per-server-instance basis with the Send Feedback parameter, which is on the General pane in the Microsoft Dynamics NAV Server Administration tool. See Configuring Microsoft Dynamics NAV Server. By default, CEIP is disabled.

Background on CEIP

Microsoft uses the information it collects through the Customer Experience Improvement Program to improve products. The information that is gathered contains no personally identifying information (such as passwords, IP addresses, or user IDs), no customer identifying information, and no customer data. CEIP helps Microsoft understand usage patterns and common computer configurations. It can also provide information that helps Microsoft diagnose software failures.

CEIP sends usage data to Microsoft at midnight every seven days counting from the midnight before when the server instance starts, and also when the service instance stops. If there is no opportunity to send data when the server instance stops, it is sent the next time that the server instance starts.

The Microsoft Dynamics NAV team uses CEIP information when trying to determine feature sets for upcoming releases and when deciding which issues to address in release updates. CEIP also allows the team to validate assumptions about design and customer usage.

Information Collected by the Customer Experience Improvement Program

When CEIP is enabled, Microsoft Dynamics NAV Server sends information about the configuration of the Microsoft Dynamics NAV Server computer:

  • Physical memory

  • Number of processors

  • Processor speed

  • Operating system

  • System language

In addition, information about Microsoft Dynamics NAV Server instance usage and configuration is sent:

  • Maximum number of connections per client type. See Client Types.

  • Maximum number of connections between Microsoft Dynamics NAV Server and the database.

  • Time since the Microsoft Dynamics NAV Server instance started.

  • Microsoft Dynamics NAV Server version information.

  • Is the RoleTailored client enabled for the server instance?

  • Are SOAP web services enabled for the server instance?

  • Are OData web services enabled for the server instance?

  • Are NAS services enabled for the server instance?

  • Is SSL enabled for the server instance?

See Also

Concepts

Provisioning the Microsoft Dynamics NAV Server Account

Other Resources

Corporate Customer Experience Improvement Program Client-to-Server Protocol Specification


SQL Server Database Components

SQL Server database components configure Microsoft SQL Server to work with Microsoft Dynamics NAV 2016.

If SQL Server is not present on the computer where you install the database components, then Setup automatically installs SQL Server Express 2014, which you can use for prototyping, developing, and testing. We recommend that you use SQL Server 2014 or SQL Server 2012 in production environments.

If you are installing the CRONUS International Ltd. demonstration database, Setup will automatically install SQL Server Express 2014 if it does not find an existing NAVDEMO instance in SQL Server. So if you intend to install the CRONUS database to an existing SQL Server installation, remember to create a NAVDEMO instance in SQL Server before you run Microsoft Dynamics NAV Setup.

In Microsoft Dynamics NAV Setup, SQL Server database components are a default component for the Developer Option. You can add the components to the Server Option or as part of a custom installation.

When you have installed the Microsoft Dynamics NAV SQL Server database components on a database server, you can create new Microsoft Dynamics NAV databases in the Microsoft Dynamics NAVdevelopment environment, by using the development environment commands, or by using the Microsoft Dynamics NAV Windows PowerShell cmdlets.

See Also

Concepts

Developer Option
Custom Option
Configuring Database Components
Microsoft Dynamics NAV Windows PowerShell Cmdlets
Development Environment Commands


Microsoft Dynamics NAV Web Services Overview

Web services are a lightweight, industry-standard way to make application functionality available to a variety of external systems and users. Microsoft Dynamics NAV 2016 supports creation and publishing of Microsoft Dynamics NAV functionality as web services. You can expose pages, codeunits, or queries as web services, and even enhance a page web service by using an extension codeunit. When you publish Microsoft Dynamics NAV objects as web services, they are immediately available on the network.

Developers can publish two types of web services from Microsoft Dynamics NAV objects:

  • SOAP Web Services. You can publish either Microsoft Dynamics NAV pages or codeunits as SOAP services.

  • OData Web Services. You can publish either pages or queries as OData services.

Microsoft Dynamics NAV 2016 web services are stateless and do not preserve the values of global variables or single-instance codeunits between calls.

Web Service Protocols

The following table shows the types of web service applications that you can create for the web service protocols supported in Microsoft Dynamics NAV 2016.

 | SOAP web services | OData web services
Pages | Yes: Create, Read, Update, and Delete operations (CRUD) | Yes: Create, Read, Update, and Delete operations (CRUD)
Codeunits | Yes | No
Queries | No | Yes: Read-only

For more information about the difference between these protocols, see Web Service Alternatives: SOAP and OData.

Page Web Services

When you expose a page as an OData web service, you can query that data to return a service metadata (EDMX) document, an AtomPub document, or a JavaScript Object Notation (JSON) document. You can also write back to the database if the exposed page is writable. For more information, see OData Web Services.

When you expose a page as a SOAP web service, you expose a default set of operations that you can use to manage common operations such as Create, Read, Update, and Delete. Page-based web services offer built-in optimistic concurrency management. Each operation call in a page-based web service is managed as a single transaction.

For SOAP services, you can also use extension codeunits to extend the default set of operations that are available on a page. Adding an extension codeunit to a page is useful if you want to perform operations other than the standard Create, Read, Update, and Delete operations. The benefit of adding an extension codeunit to a page is that you can make the web service complete by adding operations that are logical to that service. Those operations can use the same object identification principle as the basic page operations. For an example of how to implement an extension codeunit, see Walkthrough: Creating a Web Service using Extension Codeunits (SOAP).

Codeunit Web Services

For SOAP services only, codeunit web services provide you with the most control and flexibility. When a codeunit is exposed as a web service, all functions defined in the codeunit are exposed as operations.

Query Web Services

When you expose a Microsoft Dynamics NAV query as an OData web service, you can query that data to return a service metadata (EDMX) document or an AtomPub document. For more information about how to create and use Microsoft Dynamics NAV queries, see Queries.

Web Services and Regional Settings

Data is formatted according to the value of the Services Language setting for the relevant Microsoft Dynamics NAV Server instance. The default value is en-us. This means that Microsoft Dynamics NAV Server interprets all incoming data as the specified culture, such as dates and amounts.

If you know that the Services Language setting is always en-us, for example, your code can be based on that assumption. In a multilanguage environment, you will see more predictable transformations of data if data that is transmitted through web services is in a consistent culture.

However, you can choose to use the culture that is specified in the regional settings for the user who reads the data. To enforce this, add the following entry to the CustomSettings.config file for the relevant Microsoft Dynamics NAV Server instances:

Copy Code
<add key="ServicesCultureDefaultUserPersonalization" value="true"/>

If you set this key to true, web services override the Services Language setting and look up the Language ID for the current user in the User Personalization table.

Web Services in Multitenant Deployments

If your Microsoft Dynamics NAV solution is used in a multitenant deployment architecture, you must make sure that any code that generates or consumes a web service specifies the relevant tenant. Web services are set up in the application, but typically you want to consume company-specific and tenant-specific data.

If you use the GETURL function, the generated URL will automatically apply to the user’s tenant ID. For more information, see GETURL Function.

The URL for accessing a web service in a multitenant deployment must specify the tenant ID in one of two ways: As a query parameter, or as a host name. If you use host names for tenants, the host name must be specified as an alternative ID.

For example, the following URL consumes the Customer ODATA web service for a specific tenant:

Copy Code
http://localhost:7048/DynamicsNAV/OData/Company('CRONUS%20International%20Ltd.')/Customer?Tenant=Tenant1

For more information, see Multitenant Deployment Architecture.

See Also

Tasks

How to: Publish a Web Service
How to: Use SystemService to Find Companies

Concepts

Web Service Alternatives: SOAP and OData
SOAP Web Service URIs
Basic Page Operations
Web Services Best Practices
Configuring Microsoft Dynamics NAV Server


Development Environment (C/SIDE)

You use the Microsoft Dynamics NAV Development Environment to develop Microsoft Dynamics NAV applications. In earlier versions of Microsoft Dynamics NAV, this component was also an end-user client, but this changed in Microsoft Dynamics NAV 2013.

The administrator who installs Microsoft Dynamics NAV 2016 automatically has access to the Microsoft Dynamics NAV database in the development environment. To grant another user permission to work with a particular Microsoft Dynamics NAV database with development environment, grant that user db_owner role on the database in SQL Server Management Studio. To grant another user permission to create new databases in development environment, grant that user the dbcreator and securityadmin Server Roles for the Microsoft Dynamics NAV SQL Server instance in SQL Server Management Studio. For information about how to grant these roles, see Setting Database Owner and Security Administration Permissions.

Warning
If you install the development environment on a 64-bit computer and you do not install any other Microsoft Dynamics NAV components, you may receive the following message:

The program cannot start because MSVCP100.dll is missing.

If you see this error message, download and install the Microsoft Visual C++ 2010 Redistributable Package (x86). You can then run the development environment.

Object Designer

When you open the development environment, you can open Object Designer, which gives you access to Microsoft Dynamics NAV objects. You use Object Designer to modify the application or to create new application areas. For more information, see Object Designer.

If you migrate your solution to a multitenant deployment architecture, Microsoft Dynamics NAV Development Environment can only access the application database. For more information, see Multitenant Deployment Architecture.

Debugging with the Microsoft Dynamics NAV Development Environment

If you use the development environment for debugging and want to be able to set breakpoints, the following must be true:

  • You must be a Microsoft Dynamics NAV user. See How to: Create Microsoft Dynamics NAV Users.

  • You must have a Login for the Microsoft Dynamics NAV database. You must also assign that Login the db_owner database role. Use SQL Server Management Studio to create logins and assign roles. See Setting Database Owner and Security Administration Permissions for detailed information.

There are additional requirements exist if you are using NavUserPassword or AccessControlService authentication:

  • Your Login for the Microsoft Dynamics NAV database must match your User Name in Microsoft Dynamics NAV.

  • You must connect to the database using Database Authentication.

See Users and Credential Types for an overview of authentication options for Microsoft Dynamics NAV.

Other Uses

You use the development environment to create and manage Microsoft Dynamics NAV databases and to upload or change Microsoft Dynamics NAV licenses. However, you cannot use the Microsoft Dynamics NAV Development Environment to administrate your solution. Instead, you use the Microsoft Dynamics NAV Server Administration tool or the Microsoft Dynamics NAV Windows PowerShell cmdlets.

See Also

Tasks

Walkthrough: Debugging the Microsoft Dynamics NAV Windows Client

Concepts

Microsoft Dynamics NAV Server Administration Tool
Administration in the Development Environment
Setting Database Owner and Security Administration Permissions
License Types
Breakpoints


Microsoft Dynamics NAV Help Server

Microsoft Dynamics NAV Help deploys to a Microsoft Dynamics NAV Help Server, which is a website that installs on the specified server. The website includes Search and other navigation, and it provides context-sensitive Help for Microsoft Dynamics NAV Web client in addition to Microsoft Dynamics NAV Windows client. Depending on your deployment architecture, you can choose to set up a dedicated Help Server that all clients connect to, or you can choose to deploy customer-specific Help Servers.

Accessing Microsoft Dynamics NAV Help

When you have deployed a Microsoft Dynamics NAV Help Server, users in the Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client can access Help by pressing F1 or choosing a Help icon.

Tip
In the Microsoft Dynamics NAV Web client, if you want to access context-sensitive Help for a field, for example, choose the caption of the field. This is equivalent to pressing F1 in the Microsoft Dynamics NAV Windows client.

If you want to access the Microsoft Dynamics NAV Help in a browser, enter the address for the Help Server, such as http://MyServer:49000/main.aspx?lang=en&content=conGettingStarted.htm. You can save the URL as a favorite in your browser, and you can save links to individual Help topics such as http://MyServer:49000/Main.aspx?lang=en&content=conWorkingWithNav.htm.

For example, if there is a complicated task that you have to do periodically, you can find the topic that describes how to do that task, and you can save the URL to the topic to your desktop or your favorites.

The URL to a Help topic contains two query parameters as described in the following table.

Name | Description | Example
lang | Specifies the locale. Microsoft Dynamics NAV defaults to the Help content in the non-locale-specific version if the client locale cannot be found. | da-dk
content | Specifies the HTML file that contains the relevant Help content. | conGettingStarted.htm

In the standard Help, most Help topics have easily recognizable file names, such as conGettingStarted.htm for the conceptual overview that is called Getting Started. Similarly, the Help content for field 1 on table 3 is in the T_3_1.htm file.

In the standard Help for Microsoft Dynamics NAV, many file names for topics have a prefix that identifies the type of content that the topic contains. The following table describes the prefixes for file names.

Name | Description
con | The topic contains a conceptual overview.
B_ | The topic contains reference content for a batch job.
N_ | The topic contains reference content for a page.
ori | The topic is an orientation topic that provides an overview of a group of topics.
R_ | The topic contains reference content for a report.
ref | The topic contains reference content for the Microsoft Dynamics NAV Development Environment.
S_ | The topic contains reference content for a system window or dialog.
T_ | The topic contains reference content for a table or a field on a table.
tsk | The topic is a task topic and contains procedures.
wlk | The topic contains a walkthrough.

See Also

Concepts

Configuring Microsoft Dynamics NAV Help Server
Upgrading Your Existing Help Content
Help Table of Contents
Finding Information in Help
Product and Architecture Overview


Additional Components

The components listed in this section extend the capabilities Microsoft Dynamics NAV 2016 in various ways.

Components

The following components can also be installed with Microsoft Dynamics NAV 2016 Setup:

  • Automated Data Capture System

  • Microsoft Office Outlook Add-In

  • Microsoft Dynamics NAV Web Client

  • Microsoft Dynamics NAV Help Server

  • Deploying Microsoft Dynamics NAV Using ClickOnce

See Also

Concepts

Working with Microsoft Dynamics NAV Setup


Automated Data Capture System

The Automated Data Capture System (ADCS) is a Microsoft Dynamics NAV tool that lets you accurately capture data for inbound, outbound, and internal documents, primarily for warehouse activities. With ADCS, company employees use handheld devices and radio frequency technology to continuously validate warehouse inventories.

Installing ADCS

To install ADCS, you must customize the list of installation components to include ADCS, which is not included in one of the predefined Installation Options. For more information, see How to: Choose Components to Install.

For more information about configuring ADCS, see Configuring Automated Data Capture System.

See Also

Tasks

How to: Run Setup

Concepts

ADCS Overview
Configuring Automated Data Capture System


Microsoft Office Outlook Add-In

Use the Microsoft Office Outlook Add-In component to synchronize data, such as to-dos, contacts, and tasks, between Microsoft Dynamics NAV and Outlook. The Microsoft Office Outlook Add-In uses Microsoft Dynamics NAV web services.

Installing Microsoft Office Outlook Add-In

You must install the Microsoft Office Outlook Add-In and other components before you set up Microsoft Office Outlook Integration. The following lists show which components and subcomponents you must select in Microsoft Dynamics NAV Setup.

These components are not all available with any of the pre-configured Installation Options. To install the add-in, choose Custom on the Choose an Installation Option pane in Setup and then select components. See How to: Choose Components to Install.

It is not necessary to install all listed components on a single computer. But if you install different Microsoft Dynamics NAV components on different computers, then you must configure the components so that they can communicate. For more information, see Installation and Configuration Walkthroughs. The following table lists the components that need to be installed and configured.

Required components | Required option
Client | Not applicable
Server | Microsoft Office Outlook Integration
SQL Server Database Components | Demo Database
Microsoft Office Outlook Add-In | Not applicable

See Also

Tasks

Walkthrough: Setting Up Outlook Synchronization

Concepts

Web Services

Other Resources

Installation and Configuration Walkthroughs
Installation Options


Multitenant Deployment Architecture

Microsoft Dynamics NAV supports deployments where several different companies access a centrally maintained Microsoft Dynamics NAV application. By using this multitenancy support, you can add new customers to your solution easily, and you can roll out updates quickly with limited downtime for your customers.

Important
You do not have to turn your Microsoft Dynamics NAV solution into a multitenant deployment. You can install and run Microsoft Dynamics NAV as a classic one-server-one-database deployment.

In a multitenant deployment, information about the Microsoft Dynamics NAV application is stored in a separate application database. Your customers’ data is stored in separate business databases, each of which is a tenant in your deployment. By separating application from data, you can deploy the same solution to many customers with centralized maintenance of the application and isolation of each tenant. The application database contains the tables that define an application, such as the Object table and other system tables.

For example, if your current solution contains 10 companies in the Microsoft Dynamics NAV database, you can choose to create separate Microsoft Dynamics NAV databases to store each company’s business data. The knowledge about the shared application is then stored in a dedicated application database. Microsoft Dynamics NAV includes Windows PowerShell cmdlets that create an application database, and other cmdlets that enable you to create and administer tenant-specific databases.

You can choose to upgrade to Microsoft Dynamics NAV and not change your deployment so that you still have a single database that has one or more companies in it. You can also choose to extract the application tables to an application database but still have one business data database that has one or more companies in it. In both scenarios you have not migrated to multitenancy, but in the second scenario you have prepared your solution so that you can move to multitenancy at a later point.

Tenants, Companies, and Databases

A tenant is an entity that uses your solution and stores data in a business database. This is often either a business or a group of legal entities whose data can be stored in one database. In practical terms, a tenant is a database that stores business data for one or more Microsoft Dynamics NAV companies. Each tenant is connected to a Microsoft Dynamics NAV Server instance, but the Microsoft Dynamics NAV Server instance can support multiple tenants.

When you deploy and maintain a Microsoft Dynamics NAV 2016 solution, you must activate the relationship between the Microsoft Dynamics NAV Server instance by mounting the tenant to the Microsoft Dynamics NAV Server instance. You can do this by using the Microsoft Dynamics NAV Server Administration tool or by running the Mount-NAVTenant and Sync-NAVTenant cmdlets from the Microsoft Dynamics NAV 2016 Administration Shell. Similarly, to disconnect a tenant, you can use the Microsoft Dynamics NAV Server Administration tool or run the Dismount-NAVTenant cmdlet. For more information, see How to: Mount or Dismount a Tenant on a Microsoft Dynamics Server Instance.

When tenants are mounted, the tenant configurations are stored in the dbo.$ndo$tenants table of the application database that is connected to the Microsoft Dynamics NAV Server instance. If you connect additional Microsoft Dynamics NAV Server instances to the same application database, the added server instances will automatically inherit the tenant configurations from the application database. This means that existing tenants will be automatically mounted to the new server instance. In addition, if you must mount or dismount a tenant, you only have to perform the operation on one of the Microsoft Dynamics NAV Server instances. The other server instances will automatically detect and update to the changes.

When you refer to a tenant, you refer to it by the tenant ID. The first tenant that is mounted against a Microsoft Dynamics NAV Server instance has the tenant ID default. However, you can choose to set up host names for the tenants in your deployment. For example, if you want a tenant to access Microsoft Dynamics NAV through a URL, you can set up a tenant-specific subdomain. The users in that tenant will then access Microsoft Dynamics NAV through a URL such as https://mytenant.myservice.com. The tenant host name, mytenant.myservice.com, must be specified as an alternative ID in the tenant configuration. You can specify alternative IDs for a tenant by using the Mount-NAVTenant Windows PowerShell cmdlet.

Companies

A tenant database can contain one or more Microsoft Dynamics NAV companies. It is not the number of companies in a database that determines whether you are running a multitenant environment. The deciding factor is whether you have created an application database, and if you have more than one tenant database connected to the application database.

Databases

When information about the application is stored in a separate application database, you maintain the application centrally without affecting the various tenants that use the application. Each tenant database contains the business data for one or more specific companies and does not contain all of the application metadata.

For example, if you want to modify a report, and your solution is used by 25 customers, you modify the report in the application database. When each customer then accesses the report, they see the modified report.

Deployment Scenarios Supported in Microsoft Dynamics NAV 2016

The following table compares deployment scenarios.

Includes application database | No. of business databases per application database | No. of companies in business database | Multitenant deployment
No | 1 | 1 | No
Yes | 1 | 1 | No
Yes | 2 | 2 | Yes
Yes | 2 | 1 | Yes
Yes | 2 | 2 | Yes

In the table, the number of companies and business databases are shown as either 1 or 2. But most of the time there are either 1 or more than 2.

The table describes different deployments of a Microsoft Dynamics NAV solution. For example, a deployment with one database and a single company versus a deployment with two or more business databases for each application database. Of those two scenarios, only the second is a multitenant deployment because it connects multiple tenant databases (the business databases) with a single application database. The table also illustrates that you can have multiple companies in a business database. Finally, you can have an application database and a single business database that contains multiple companies. This is a single-tenant deployment.

The Application in Multitenant Deployments

In a Microsoft Dynamics NAV application that is used in a multitenant deployment, some areas require you to set up web services. Since web services are created in the application database, you must create at least one tenant that has write access to the application database. This setting is determined by the Allow application database writes parameter when you mount a tenant against a Microsoft Dynamics NAV Server instance. For more information, see How to: Mount or Dismount a Tenant on a Microsoft Dynamics Server Instance.

For example, you can create a dedicated administration tenant that you mount against the Microsoft Dynamics NAV Server instance when you create web services for an application.

If you have an existing Microsoft Dynamics NAV application that you want to use in a multitenant deployment, there are a number of changes that you have to make. This includes setting up the permission sets in a way that supports all tenants that use that application.

URLs and Tenants

In multitenant deployments, URLs must specify the tenant that the URL applies to. If you have C/AL code that constructs URLs, you must update the code to include the tenant. Alternatively, update your code with the GETURL Function to get the URLs calculated for you. The same applies to hyperlinks in report objects, for example.

The URL can specify the tenant ID or the tenant host name if you specify host names as alternative IDs for tenants. For example, the following URL consumes the Customer ODATA web service for a specific tenant:

Copy Code
http://localhost:7048/DynamicsNAV/OData/Company('CRONUS%20International%20Ltd.')/Customer?Tenant=Tenant1

If the mytenant.myservice.com host name has been specified as an alternative ID for the tenant Tenant1, then the following URL returns the same ODATA web service:

Copy Code
http://mytenant.myservice.com:7048/DynamicsNAV/OData/Company('CRONUS%20International%20Ltd.')/Customer

See Also

Tasks

How to: Mount or Dismount a Tenant on a Microsoft Dynamics Server Instance

Concepts

Migrating to Multitenancy
Microsoft Dynamics NAV Windows PowerShell Cmdlets

Other Resources

Upgrading to Microsoft Dynamics NAV 2016


Accessibility

This section contains information about the available accessibility features in Microsoft Dynamics NAV 2016. For more information, see the following topics:

Accessibility Features of Microsoft Dynamics NAV Windows Client

Accessibility Features of Microsoft Dynamics NAV Web Client

See Also

Concepts

Development


Accessibility Features of Microsoft Dynamics NAV Windows Client

Microsoft is committed to making its products and services easier for everyone to use. This topic provides information about features of the Microsoft Dynamics NAV that makes the product more accessible for people with disabilities.

Keyboard Shortcuts

Instead of using a mouse or another pointing device, the keyboard can sometimes be a faster way to perform a task. For a list of the keyboard shortcuts that can be used in the Microsoft Dynamics NAV, see Keyboard Shortcuts.

Assistive technologies

Microsoft Dynamics NAV supports various assistive technologies such as screen readers and voice recognition software.

Ribbon

With the introduction of the ribbon in Microsoft Dynamics NAV, the navigation through menus and actions has now become easier using the keyboard. Use the F6 key to navigate through the different frames in Microsoft Dynamics NAV; use Shift+F6 to navigate backwards. To display all the access keys in the ribbon, press the Alt key.

Help

Microsoft Dynamics NAV Help offers features that make help more accessible. For more information, see Microsoft Accessibility.

For more accessibility information

You can find additional information about accessibility with Microsoft products and assistive technologies on the Microsoft Accessibility.


Accessibility Features of Microsoft Dynamics NAV Web Client

This topic provides information about the features of the Microsoft Dynamics NAV Web client that make Microsoft Dynamics NAV content readily available to people with disabilities. The Microsoft Dynamics NAV Web client supports the following accessibility features:

  • Keyboard Shortcuts

  • Navigation

  • Headings

  • Image and Links

  • Assistive Technologies

Keyboard Shortcuts

Microsoft Dynamics NAV Web client supports the keyboard shortcuts that are supported by most web browsers.

To do this | Press
To move focus to the next or previous control or element on a page, such as buttons, fields, or items in a list. | Tab, Shift+Tab
To enable or access the element or control that is in focus. | Enter
To scroll items up and down in a list. | Up Arrow, Down Arrow
To scroll columns of an item left and right in a list. | Left Arrow, Right Arrow
To open a drop-down list or look up a value for a field. | Alt+Down Arrow

Navigation

You can navigate between the tabs and actions in the ribbon, elements in the navigation pane, and other controls on Microsoft Dynamics NAV pages and reports using the keyboard. To move the focus from one tab, action, or control to another, press the Tab key to move forward. Press Shift+Tab to move backward.

By using the tab order, you can also switch between the main browser window and dialog boxes that request confirmation, for example, or the login window.

Headings

The HTML source for Microsoft Dynamics NAV content uses tags to help users of assistive technology to understand the structure and content of the page. For example, on list pages, the columns are defined in TH tags and the column headings are set with TITLE attribute inside the tag. Captions for elements, such as FastTabs, FactBoxes, and fields are included in heading tags (H1, H2, H3, and H4).

Image and Links

A descriptive text for images is set with the ALT attribute inside the IMG tag. A descriptive text for hyperlinks is set with the title attribute inside the A tag.

Assistive Technologies

The Microsoft Dynamics NAV Web client supports various assistive technologies, such as high contrast, screen readers, and voice recognition software. Some assistive technologies may not work well with certain elements on Microsoft Dynamics NAV content.

Additional Accessibility Information

For additional information about accessibility with Microsoft products and assistive technologies, see the Microsoft Accessibility web site.

See Also

Tasks

How to: Install the Web Server Components

Concepts

Microsoft Dynamics NAV Web Client
Deploying the Microsoft Dynamics NAV Web Server Components


License Types

When you create a user in Microsoft Dynamics NAV 2016, you must specify a license type. This topic provides an overview of the license types.

Note
Licenses are specific to the Microsoft Dynamics NAV version and are not forward or backward compatible. This means that a license from an earlier Microsoft Dynamics NAV version will not work with Microsoft Dynamics NAV 2016, and vice versa.

For additional information about the types of user licenses and the license restrictions regarding user licenses, see the Microsoft Dynamics NAV 2015 Licensing Guide located at http://go.microsoft.com/fwlink/?LinkId=518623 (requires PartnerSource login).

  • Full User

    Full User licenses provide users full read and full write capabilities to all of the licensed solution functionality through any and all modes of access, including the Microsoft Dynamics NAV Windows client, the Microsoft Dynamics NAV Web client, or any other mode of access including web services. Full User licenses are for users requiring unlimited read and write access. As long as the number of users needing simultaneous access to the solution does not exceed the number of Full User licenses you have acquired, these users are properly licensed for full read and write access to the complete solution functionality.

  • Limited User

    Limited User licenses provide users full read, but limited write, capabilities to all of the licensed solution functionality through any and all modes of access including the Microsoft Dynamics NAV Windows client. The Limited User license is designed to give customers a lower-cost alternative for extending ERP to users who only require limited access to the Microsoft Dynamics NAV application:

    • Read access to data contained in the solution through any client accessing the application, including but not limited to the Microsoft Dynamics NAV Windows client, the Microsoft Dynamics NAV Web client, and web services.

    • Write access to a maximum of three application tables in the object range 0 - 99,999,999 other than the General Ledger Entry table, through any client accessing the application. Access to the General Ledger Entry Table requires a Full User license.

    For more information, see the Microsoft Dynamics NAV 2015 Licensing Guide.

  • Device Only User

    Device-only licenses enable a user to connect, provided there is an enabled device available to use. Devices can be full or limited. Device users have either full or limited access, as determined by the device.

  • Windows Group

    Use this license type to create a Microsoft Dynamics NAV user account that is based on a Windows group and has explicit permissions in Microsoft Dynamics NAV. Individual members of the Windows group will then inherit the permissions for this user.

    Important
    For each member of the Windows group, you create a Microsoft Dynamics NAV user account, which does not explicitly have any permissions. Users then log on by using their Microsoft Dynamics NAV user account credentials.

    Windows Group licensing is a form of license multiplexing. Multiplexing does not reduce the number of user licenses required to access a Microsoft Dynamics NAV solution.

  • External User

    As described in the Microsoft Software License Terms that apply to Microsoft Dynamics NAV 2016, external users are the customers of customers. This license type is specific to individual users of Microsoft Dynamics NAV 2016. External user licenses must not be shared with other individual users. You do not need concurrent user CALs for external users. External users must not use any clients provided by the Microsoft Dynamics NAV 2016 Application Programming Interface (API), such as the Microsoft Dynamics NAV Windows client or the Microsoft Dynamics NAV Web client. External user licenses must not be used for business process outsourcing purposes.

See Also

Tasks

How to: Specify When UI Elements Are Removed
How to: Upload the License File

Concepts

Properties of the Demo License

Other Resources

Microsoft Dynamics NAV 2015 Licensing Guide


Deployment

The topics in the Deployment node are intended to help an administrator install and configure Microsoft Dynamics NAV 2016 software.

Key Features of Setup

With Microsoft Dynamics NAV 2016 Setup, you can:

  • Install different components on different computers.

  • Choose from a selection of predefined Installation Options or create your own custom list of components and options to install. For more information, see How to: Choose Components to Install.

  • Preconfigure components before installation. For more information, see How to: Preconfigure Components.

  • Create, save, or load Setup configuration files that capture your selection of components and configuration information. For more information, see How to: Create or Load a Setup Configuration File.

You use Setup to install software and to create custom deployments that you can distribute to different users across a company.

Installation Notes

  • Before installing Microsoft Dynamics NAV 2016 components on a computer, you must remove (uninstall) any previous versions.

  • All RoleTailored components must be from the same version and build of Microsoft Dynamics NAV for the software to run correctly.

  • If you have either SQL Server 2000 or Microsoft SQL Server Desktop Engine (MSDE) installed on a computer where you want to install Microsoft Dynamics NAV, then you must remove it before you begin installing. The presence of either of these database products causes a Setup error.

See Also

Concepts

Product and Architecture Overview
System Requirements for Microsoft Dynamics NAV 2016
Working with Microsoft Dynamics NAV Setup
Configuring Microsoft Dynamics NAV

Other Resources

Installation Options


System Requirements for Microsoft Dynamics NAV 2016

Microsoft Dynamics NAV Documentation
System Requirements for Microsoft Dynamics NAV 2016

The following sections list the minimum hardware and software requirements to install and run Microsoft Dynamics NAV 2016. Minimum means that later versions (such as SP1, SP2, or R2 versions) of a required software product are also supported. For the latest version of the system requirements, see the MSDN Library.

Client components

  • Microsoft Dynamics NAV Windows Client Requirements

  • Microsoft Dynamics NAV Development Environment Requirements

  • Microsoft Dynamics NAV Web Client Requirements

  • Microsoft Dynamics NAV Tablet Client and Phone Client (in a Browser) Requirements

  • Microsoft Dynamics NAV Universal App Requirements

Server components

  • Microsoft Dynamics NAV Server Requirements

  • Microsoft Dynamics NAV Web Server Components Requirements

  • Microsoft Dynamics NAV Database Components for SQL Server Requirements

  • Microsoft Dynamics NAV Help Server Requirements

Additional components and features

  • Microsoft Dynamics NAV as an App for SharePoint Requirements

  • Automated Data Capture System Requirements

  • Microsoft Office Outlook Add-In Requirements

  • Microsoft Dynamics CRM Integration Requirements

  • Automated Deployment on Microsoft Azure Requirements

Note
Microsoft Dynamics NAV 2016 Setup installs some software if it is not already present in the target computer. For more information, see the "Additional Information" section for each component.

Microsoft Dynamics NAV Windows Client Requirements

The following table shows the minimum system requirements for the Microsoft Dynamics NAV Windows client.

Supported operating systems

  • Windows 10 Pro, Enterprise, or Education (32-bit and 64-bit editions).

  • Windows 8.1 Professional or Enterprise (32-bit and 64-bit editions).

  • Windows 8 Professional or Enterprise (32-bit and 64-bit editions).

  • Windows 7 Service Pack 1 Professional, Ultimate, or Enterprise (32-bit and 64-bit editions).

  • Windows Server 2012 R2 Standard or Essentials (64-bit edition).

  • Windows Server 2012 Standard or Essentials (64-bit edition).

Hardware resources

  • Hard disk space: 200 MB.

  • Memory: 1 GB.

Reports

  • Microsoft Report Viewer 2015 to run reports that use RDLC report layouts.

  • SQL Server Report Builder 3.0 for Microsoft SQL Server 2014, Microsoft SQL Server 2012 SP1, or Microsoft SQL Server 2012 to edit RDLC report layouts.

  • Microsoft Word 2013 to edit the layouts.

Instant messaging and Telephony API

  • Microsoft Lync 2013 or Microsoft Lync 2010.

Outlook client integration and mail merge

  • Microsoft Office 2013 Service Pack 1 (SP1) or Microsoft Office 2010 Service Pack 2 (SP2).

Import and export with Microsoft Excel and Office XML, and SharePoint links

  • Microsoft Office 2013 SP1, Microsoft Office 2010 SP2, or Microsoft Office 365.

OneNote integration

  • Microsoft Office 2013 SP1or Microsoft Office 2010 SP2.

Email logging

  • Active Directory and Microsoft Exchange Server 2010 or Microsoft Exchange Server 2013.

  • Microsoft Exchange Online, or Exchange Online as part of an Office 365 subscription.

Additional software

  • Microsoft .NET Framework 4.5.2.

Additional information

  • Microsoft Dynamics NAV 2016 Setup installs the following software if it is not already present in the target computer:

    • Microsoft .NET Framework 4.5.2.

    • Microsoft Report Viewer 2015.

  • The Microsoft Dynamics NAV Windows client is available in a 32-bit version and 64-bit version. On a 32-bit Windows operating system, the 32-bit version is run. On a 64-bit Windows operating system, the 64-bit version is run by default; however, you can also run the 32-bit version if it is required.

  • Microsoft Dynamics NAV 2016 Setup can only install the Excel Add-in if Excel is present on the target computer.

  • Outlook synchronization is not supported on 64-bit versions of Office.

Microsoft Dynamics NAV Development Environment Requirements

The following table shows the minimum system requirements for the Microsoft Dynamics NAV Development Environment.

Supported operating systems

  • Windows 10 Pro, Enterprise, or Education (32-bit and 64-bit editions).

  • Windows 8.1 Professional or Enterprise (32-bit and 64-bit editions).

  • Windows 8 Professional or Enterprise (32-bit and 64-bit editions).

  • Windows 7 Service Pack 1 Professional, Ultimate, or Enterprise (32-bit and 64-bit editions).

  • Windows Server 2012 R2 Standard or Essentials (64-bit edition).

  • Windows Server 2012 Standard or Essentials (64-bit edition).

Hardware resources

  • Hard disk space: 200 MB.

  • Memory: 1 GB.

Reports

  • Microsoft Report Viewer 2015 to run reports that use RDLC report layouts.

  • Microsoft Visual Studio or SQL Server Report Builder for creating and editing RDLC report layouts. The following versions and editions are supported:

    • Microsoft Visual Studio 2012 Professional, Premium, or Ultimate edition.

    • Microsoft Visual Studio 2013 Professional, Premium, or Ultimate edition.

    • SQL Server Report Builder 3.0 for Microsoft SQL Server 2014, Microsoft SQL Server 2012 SP1, or Microsoft SQL Server 2012.

  • SQL Server Report Builder 3.0 for Microsoft SQL Server 2014, Microsoft SQL Server 2012 SP1, or Microsoft SQL Server 2012 to upgrade reports.

  • Word 2013 to create Word report layouts.

Additional software

  • Microsoft .NET Framework 4.5.2.

Additional information

  • Microsoft Dynamics NAV 2016 Setup installs the following software if it is not already present in the target computer:

    • Microsoft .NET Framework 4.5.2.

    • SQL Server Native Client 11.0.

    • Microsoft Report Viewer 2015.

    • SQL Server Report Builder 3.0 for Microsoft SQL Server 2014. This is not installed if a version of SQL Server Report Builder or Microsoft Visual Studio is already present on the target computer

  • If the development environment and Microsoft Dynamics NAV Server are on the same computer, then only a 64-bit operating system is supported.

Microsoft Dynamics NAV Web Client Requirements

The following table shows the minimum system requirements for the Microsoft Dynamics NAV 2016 Web client.

Supported browsers

  • Microsoft Edge.

  • Internet Explorer 10 or Internet Explorer 11.

  • Google Chrome 44.0 for Windows.

  • Mozilla Firefox 40.0 for Windows.

  • Safari 8.4 on iOS (iPad).

  • Safari 8.0.8 on OSX.

For a list of browser limitations, see Browser Limitations with the Microsoft Dynamics NAV Web Client.

Sending data to Excel

  • Microsoft Office 2013 SP1, Microsoft Office 2010 SP2, or Microsoft Office 365.

SharePoint Online links

  • Microsoft Office 2013 SP1, Microsoft Office 2010 SP2, or Microsoft Office 365.

Printing reports to Excel or Word

  • Microsoft Office 2013 SP1, Microsoft Office 2010 SP2, or Microsoft Office 365.

Additional information

  • The browser must be able to install the Report Viewer ActiveX control to be able to print.

  • If you experience problems using the Microsoft Dynamics NAV Web client, you can try to turn off browser tools, such as translator tools that may run in the background.

Microsoft Dynamics NAV Tablet Client and Phone Client (in a Browser) Requirements

The following table shows the minimum system requirements for the Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client running in a browser when used for development and testing purposes.

Server component

Identical to the Microsoft Dynamics NAV 2016 Web client.

Supported browsers

The following desktop browsers are supported:

  • Microsoft Edge

  • Internet Explorer 11 (build 11.0.9600.17239) for Windows 8.1 (32-bit and 64-bit versions) and for Windows 10.

  • Google Chrome 44.0 for Windows.

Microsoft Dynamics NAV Universal App Requirements

The following table shows the minimum system requirements for the Microsoft Dynamics NAV Universal App. For the latest information, see Dynamics NAV for Windows, Dynamics NAV for iPad and iPhone, and Dynamics NAV for Android tablet and Android phone.

Supported operating systems

  • Windows 10 Home, Pro, Enterprise, or Education (32-bit and 64-bit editions).

  • Windows 8.1 with Internet Explorer 11 (build 11.0.9600.17239) (32-bit and 64-bit versions including RT) and Windows Phone 8.1.

  • Android 4.4.3.

  • iOS 8.4.

Additional hardware

  • 1 GB RAM for Android and Windows.

Additional software

  • A third-party telephony or VoIP app such as Skype or Lync is required for placing calls from Microsoft Dynamics NAV.

  • A third-party email program such as Outlook is required for sending emails from Microsoft Dynamics NAV.

  • Microsoft Office 2013 SP1 or Microsoft Office 365 is required for sending data to Microsoft Excel or to Microsoft Word.

Additional information

  • Device diagonal screen size 7” for tablets.

  • Screen resolution 960 × 510 for tablets.

  • Device diagonal screen size 4” for phones.

  • Screen resolution 854 x 480 for phones.

Microsoft Dynamics NAV Server Requirements

The following table shows the minimum system requirements for Microsoft Dynamics NAV Server.

Supported operating systems

  • Windows 10 Pro, Enterprise, or Education (64-bit edition).

  • Windows 8.1 Professional or Enterprise (64-bit edition).

  • Windows 8 Professional or Enterprise (64-bit edition).

  • Windows 7 Service Pack 1 Professional, Ultimate, or Enterprise (64-bit edition).

  • Windows Server 2012 R2 Standard or Essentials (64-bit edition).

  • Windows Server 2012 Standard or Essentials (64-bit edition).

Hardware resources

  • Hard disk space: 500 MB.

  • Memory: 2 GB.

Reports

  • Microsoft Report Viewer 2015 for Save as Excel, Save as PDF, and Save as Word functionality.

Microsoft Dynamics CRM integration

  • Windows Identity Framework.

    For a list of supported Microsoft Dynamics CRM versions, see Microsoft Dynamics CRM Integration Requirements.

Additional software

  • Microsoft .NET Framework 4.5.2.

  • Windows PowerShell 3.0.

Additional information

  • Microsoft Dynamics NAV 2016 Setup installs the following software if it is not already present on the target computer:

    • Microsoft .NET Framework 4.5.2.

    • Microsoft Report Viewer 2015.

    • Windows Identity Framework.

Microsoft Dynamics NAV Web Server Components Requirements

Supported operating systems

  • Windows 10 Pro, Enterprise, or Education (64-bit edition).

  • Windows 8.1 Professional or Enterprise (64-bit edition).

  • Windows 8 Professional or Enterprise (64-bit edition).

  • Windows 7 Service Pack 1 Professional, Ultimate, or Enterprise (64-bit edition).

  • Windows Server 2012 R2 Standard or Essentials (64-bit edition).

  • Windows Server 2012 Standard or Essentials (64-bit edition).

Web server

  • Internet Information Server 7.5, Internet Information Server 8.0, Internet Information Server 8.5, or Internet Information Server 10 with the following features enabled:

    • .NET Extensibility 4.5.2.

    • ASP .NET 4.5.2.

    • ISAPI Extensions.

    • ISAPI Filters.

    • Request Filtering.

    • Windows Authentication.

    • Static Content.

    • HTTP Activation.

Reports

  • Microsoft Report Viewer 2015 to run reports that use RDLC report layouts.

Additional software

  • Microsoft .NET Framework 4.5.2.

  • Windows PowerShell 3.0.

Additional information

  • Microsoft Dynamics NAV 2016 Setup installs the following software if it is not already present on the target computer.

    • Microsoft .NET Framework 4.5.2.

    • Internet Information Server 7.5, Internet Information Server 8.0, Internet Information Server 8.5, or Internet Information Server 10 depending in the operating system, with the required features enabled.

  • For more information about installing IIS, see How to: Install Internet Information Services for Microsoft Dynamics NAV Web Client

  • To avoid crashes on the IIS server with many concurrent users, download and install the update from here Update for the .NET Framework 4.5 in Windows 8, Windows RT, and Windows Server 2012.

Microsoft Dynamics NAV Database Components for SQL Server Requirements

The following table shows the minimum system requirements for Microsoft Dynamics NAV 2016 database components for SQL Server.

Supported operating systems

  • Windows 10 Pro, Enterprise, or Education (64-bit edition).

  • Windows 8.1 Professional or Enterprise (64-bit edition).

  • Windows 8 Professional or Enterprise (64-bit edition).

  • Windows 7 Service Pack 1 Professional, Ultimate, or Enterprise (64-bit edition).

  • Windows Server 2012 R2 Standard or Essentials (64-bit edition).

  • Windows Server 2012 Standard or Essentials (64-bit edition).

For more information, see Hardware and Software Requirements for Installing SQL Server 2014. From this page, you can access requirements for other versions of SQL Server.

Hardware resources

  • Hard disk space: 500 MB.

  • Memory: 2 GB.

SQL Server

  • Microsoft SQL Server 2014 Express, Standard or Enterprise.

  • Microsoft SQL Server 2012 Service Pack 2 Express, Standard, or Enterprise (64-bit editions only).

  • Azure SQL Database V12 Standard and Premium service tiers.

For more information, see Installation Considerations for Microsoft SQL Server.

Additional information

  • Microsoft Dynamics NAV 2016 Setup installs the following software if it is not already present on the target computer.

    • SQL Server 2012 SP2 Express (64-bit edition).

  • If the operating system on the target computer does not support SQL Server 2012 SP2 Express, Setup displays a pre-requisite warning. In this case you should exit Setup and then update the operating system on the computer to one that does support SQL Server 2012 SP2 Express. Then run Setup again.

Microsoft Dynamics NAV Help Server Requirements

The following table shows the minimum system requirements for the Microsoft Dynamics NAV 2016 Help Server.

Supported operating systems

  • Windows 10 Pro, Enterprise, or Education (64-bit editions).

  • Windows 8.1 Professional or Enterprise (64-bit edition).

  • Windows 8 Professional or Enterprise (64-bit edition).

  • Windows 7 Service Pack 1 Professional, Ultimate, or Enterprise (64-bit edition).

  • Windows Server 2012.

  • Windows Server 2012 Essentials.

Hardware resource

  • Hard disk space: 500 MB.

  • Memory: 2 GB.

Web server

  • Internet Information Server 7.5, Internet Information Server 8.0, Internet Information Server 8.5, or Internet Information Server 10. The following features must be enabled:

    • .NET Extensibility 4.5.2.

    • ASP .NET 4.5.

    • ISAPI Extensions.

    • ISAPI Filters.

    • Request Filtering.

    • Windows Authentication.

    • Static Content.

    • HTTP Activation.

Additional software

  • Microsoft .NET Framework 4.5.2.

Additional information

  • Microsoft Dynamics NAV 2016 Setup installs the following software if it is not already present on the target computer.

    • Microsoft .NET Framework 4.5.2.

    • Internet Information Server 7.5, Internet Information Server 8.0, Internet Information Server 8.5, or Internet Information Server 10, depending on the operating system, with the required features enabled.

  • For more information about installing IIS, see How to: Install Internet Information Services for Microsoft Dynamics NAV Web Client

  • Windows Search must be enabled on the computer that you install the Microsoft Dynamics NAV Help Server on. If you install on Windows Server 2012, and Windows Search is not enabled as a file service, Microsoft Dynamics NAV 2016 Setup adds the service. However, the changes do not take effect until the computer has restarted.

Automated Data Capture System Requirements

The following table shows the minimum system requirements for Automated Data Capture System (ADCS) for Microsoft Dynamics NAV 2016.

Additional software

  • MSXML version 6.0.

  • Telnet or Microsoft Windows HyperTerminal.

  • VT100 Plug-in for each computer on which you install ADCS.

  • Microsoft Loopback Adapter.

Additional information

  • HyperTerminal is no longer included with Windows. For more information, see What happened to HyperTerminal? in the Windows Help.

  • VT100 Plug-in acts as a virtual Telnet server.

Microsoft Office Outlook Add-In Requirements

The following table shows the system requirements for the Microsoft Office Outlook Add-In.

Additional software

Microsoft Office 2013 SP1 or Microsoft Office 2010 SP2 (32-bit edition).

Microsoft Dynamics CRM Integration Requirements

The following table shows the system requirements for integrating Microsoft Dynamics NAV with Microsoft Dynamics CRM.

Additional software

Microsoft Dynamics CRM Online 2015 Update, Microsoft Dynamics CRM Online 2015 Update 1, or Microsoft Dynamics CRM 2015.

Microsoft Dynamics NAV as an App for SharePoint Requirements

The following table shows the minimum system requirements for Microsoft Dynamics NAV as an App for SharePoint.

Supported operating systems

  • Windows Server 2012 R2 Standard or Datacenter (64-bit edition).

  • Windows Server 2012 Standard or Datacenter (64-bit edition).

Additional software

  • SharePoint 2013 Service Pack 1.

  • SharePoint Online.

Automated Deployment on Microsoft Azure Requirements

Automated deployment of Microsoft Dynamics NAV 2016 on Microsoft Azure by using the provisioning tools is only supported on Azure virtual machines that are running Windows Server 2012. For additional requirements for specific Microsoft Dynamics NAV components, refer to the other sections in this topic.


Installation Options

When you run Microsoft Dynamics NAV 2016 Setup, you can select from a list of predefined installation options, which are logical collections of Microsoft Dynamics NAV components.

Review and accept the Microsoft Software License Terms in Setup and then choose Next. On the next page, you are presented with two options: Install Demo and Choose an installation option. Choose the latter option to see the other available installation options.

In This Section

Demo Option

Client Option

Server Option

Developer Option

Custom Option

Related Sections

System Requirements for Microsoft Dynamics NAV 2016

Working with Microsoft Dynamics NAV Setup


Demo Option

The Install Demo option is available on the first page after you accept the Microsoft Software License Terms in Microsoft Dynamics NAV 2016 Setup. When you choose Install Demo, Setup installs all three tiers of the Product and Architecture Overview on the local computer.

The Demo Install is intended for users who want to try the features of Microsoft Dynamics NAV. We do not recommend this as the foundation for an actual production environment.

Warning
You must install the Demo on a computer that uses a 64-bit Windows operating system.

Demo Install Option Notes

  • When you choose Demo Install, Setup begins to copy files. After this, you have no additional interaction with Setup. Choose Close to exit Setup when it is finished copying files.

  • Setup installs SQL Server 2012 Express, creates a SQL Server instance, NAVDEMO, and installs the Demo Database NAV (9-0) in this instance. Previous versions of Microsoft Dynamics NAV installed the Demo database in the default SQL Server instance.

    The first time that you install Microsoft Dynamics NAV 2016, the new SQL Server instance and Demo database are created automatically. If you subsequently delete Microsoft Dynamics NAV 2016 and then run Setup to install the Demo version again, Setup prompts you to replace the existing database:

    The SQL Server Instance “NAVDEMO” already has an instanced named ‘Demo Database NAV (9-0)’. Would you like to replace this database?

    You can choose OK or Cancel.

  • Setup cannot install the data file for a database, an .mdf file, to the local computer if the destination folder or drive is compressed.

Installed Components

When you choose the Demo Install option, Setup installs the following components:

  • Microsoft Dynamics NAV Windows client.

    For more information, see Client Types.

  • Microsoft Dynamics NAV Server.

  • Development Environment (C/SIDE).

  • Microsoft Office Excel Add-In.

  • SQL Server Express 2012, a smaller-scale version of SQL Server. If a valid version of SQL Server is already present on the computer where you are installing the Demo version, Setup does not install SQL Server Express 2012.

  • SQL Server Database Components.

  • CRONUS International Ltd. demonstration database, with a demo license. For information about what you can do with this license, see Properties of the Demo License.

Note
By default, the Install Demo option does not install the Microsoft Dynamics NAV Help Server or the Microsoft Dynamics NAV Web Server components. If you want these options, you can run the installation program again, choose the Custom option, and then choose the option that you want.

See Also

Concepts

System Requirements for Microsoft Dynamics NAV 2016
Properties of the Demo License
Client Types
Installation Considerations for Microsoft SQL Server
Custom Option


Properties of the Demo License

The demo license is automatically installed when you install the Demo Option. The demo license works with the CRONUS International Ltd. demonstration database, has serial number 000, and includes granule 540. The license allows access to the entire base application and limited access to the development system.

Properties of the Demo License

When the demo license is installed, you can:

  • Start up to two simultaneous client sessions on any platform.

  • Create up to two companies.

  • Support an unlimited number of web users.

  • Run in any supported language.

  • Use all application functionality, including add-on products, local extensions and customizations in current and previous versions. This means that you can run, but not modify, all object types within the range 1 to 99,999,999.

  • Run and modify table 18, pages 21 and 22, report 101, and XMLports 99,008,503 and 99,008,510.

  • Run, modify, and create fields 99,990 to 99,999, page 99,999, report 99,999, and MenuSuite 90.

Limitations of the Demo License

The demo license does not allow you to:

  • Import objects in text format, except for page and report ID 99,999.

  • Enter dates in months other than November, December, January, and February.

Important
The demo license can only be used with demonstration companies such as CRONUS International Ltd..

Country/Region Versions

When you run a country/region version of Microsoft Dynamics NAV, the license must correspond with the country/region version that you have installed.

Any license can be available in different country/region versions.

See Also

Tasks

Walkthrough: Installing the Demo Version

Concepts

Demo Option


Client Option

The Client option is available on the Choose an installation option page in Microsoft Dynamics NAV 2016 Setup.

Installed Components

When you choose the Client option, Microsoft Dynamics NAV Setup installs the following components:

  • Microsoft Dynamics NAV Windows client

    For more information, see Client Types.

  • Microsoft Office Excel Add-In

    With the Microsoft Office Excel Add-In, you can update the data in your Excel document with fresh data from Microsoft Dynamics NAV. However, if your company configures Microsoft Dynamics NAV to integrate with Office 365, documents will open in the installed version of Excel and not in the Excel Web App.

The Microsoft Dynamics NAV Windows client constitutes tier one in the Microsoft Dynamics NAV three-tier Product and Architecture Overview. Microsoft Dynamics NAV Server is tier two, and SQL Server Database Components, together with SQL Server or SQL Server Express, is tier three.

You can configure the Client option to add or remove components by choosing Customize under the Client option on the Choose an installation option pane. You can configure the Client option to add or remove components on the Customize the installation page.

Additional components available under the Client option include the Microsoft Dynamics NAV Development Environment, and the Microsoft Office Outlook Add-In.

You must provide some initial configuration information to enable the Microsoft Dynamics NAV Windows client to establish a connection with an instance of Microsoft Dynamics NAV Server.

Configuring the Microsoft Dynamics NAV Windows client in Setup

When you choose the Client option, the Specify parameters pane is displayed in Setup. You must specify certain parameters in order to install the Microsoft Dynamics NAV Windows client so that the client can connect to the relevant Microsoft Dynamics NAV Server instance. Each parameter is described in the Setup window. The following list provides a high-level description of the required parameters.

Section/ Parameter Description

Installation location for 32-bit components

Specifies the folder destination for Microsoft Dynamics NAV Windows client files.

Microsoft Dynamics NAV Server server name, service instance name, and the listening TCP port or the computer running Microsoft Dynamics NAV Server for this client.

If you are not sure which Microsoft Dynamics NAV Server computer to specify, enter a temporary value, such as TBD, so you can complete Setup. Then edit the Microsoft Dynamics NAV Windows client configuration file later to identify the actual server. You will not be able to run the Microsoft Dynamics NAV Windows client without a valid Microsoft Dynamics NAV Server connection.

If you specify a server name, instance name or server port in Setup that is not valid, then the Microsoft Dynamics NAV Windows client cannot connect to Microsoft Dynamics NAV Server. You will receive the following message when you attempt to open the Microsoft Dynamics NAV Windows client:

The program could not create a connection to the server. Do you want to try again?

If you choose No, then the Select Server window opens. Correct the port number by typing a string in this format in the Server Name field:

Copy Code
servername:port/ServerInstance

If your deployment uses a multitenant architecture, the string must identify the tenant database that the client connects to. The format changes to the following: servername:port/ServerInstance/tenant

Add rule to Firewall

Specifies whether Microsoft Dynamics NAV Setup adds a rule to Windows Firewall to allow the Microsoft Dynamics NAV Windows client to communicate with a Microsoft Dynamics NAV Server instance on another computer, through the specified Server Port.

The default value is Yes for the Client or Server installation options, where the assumption is that Microsoft Dynamics NAV Server is installed on a different computer from the client, and No for the Demo and Developer options, where the assumption is that Microsoft Dynamics NAV Server is installed on the same computer as the client.

If the target computer uses a firewall other than Windows Firewall, or if networking is not configured on the target computer, then this option must be set to No or Setup will not be able to complete successfully.

Credential Type

Microsoft Dynamics NAV supports different credential authorization mechanisms for users. When you create a user, you provide different information depending on the credential type that you are using in the current Microsoft Dynamics NAV Server instance. The credential type that is configured for a user must match the credential type that is configured for the Microsoft Dynamics NAV Server instance that the user connects to. For more information, see Users and Credential Types.

Help Server and Help Server port

Specifies the name and port of the server that hosts the Microsoft Dynamics NAV Help Server.

This can be a public website or a local computer.

For more information, see Configuring Microsoft Dynamics NAV Help Server.

Choose Apply when you have finished entering values on the Specify parameters page in Setup. If you want to change the configuration after installation, you can modify the ClientUserSettings.config file for each client. For more information, see Configuring the Windows Client.

See Also

Tasks

How to: Choose Components to Install

Concepts

Working with Microsoft Dynamics NAV Setup
Configuring the Windows Client
Configuring Microsoft Dynamics NAV Server
Configuring Microsoft Dynamics NAV Help Server
Users and Credential Types
Microsoft Dynamics NAV Server Administration Tool

Other Resources

Installation Options


Server Option

The Server option is available on the Choose an installation option page in Microsoft Dynamics NAV 2016 Setup.

Important
You can only install the Server option on a computer that is running a 64-bit Windows operating system.

Installed Components

When you choose the Server option, Microsoft Dynamics NAV Setup installs the following components:

  • Microsoft Dynamics NAV Server. For more information, see Microsoft Dynamics NAV Server.

  • The Microsoft Dynamics NAV Server Administration tool. For more information, see Microsoft Dynamics NAV Server Administration Tool.

  • Microsoft Office Outlook integration. For more information, see Outlook Add-in/Microsoft Dynamics NAV Synchronization Add-in.

  • SharePoint Online integration. For more information, see Integrating with Microsoft Office.

Microsoft Dynamics NAV Server represents the middle tier in the Microsoft Dynamics NAV three-tier Product and Architecture Overview. The Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client is tier one, and SQL Server Database Components, together with SQL Server or SQL Server Express, is tier three.

You can configure the Server option to add or remove components by choosing Customize under the Server option on the Choose an installation option pane. You can configure the Server option to add or remove components on the Customize the installation page.

You may want to consider adding the following components to a Microsoft Dynamics NAV Server installation:

  • SQL Server Database Components, to which you can add the Demo database.

  • Automated Data Capture System.

  • Web Server Components. For more information, see Microsoft Dynamics NAV Web Client.

  • The Microsoft Dynamics NAV Help Server. This adds a separate website that displays the Help for Microsoft Dynamics NAV. For more information, see Configuring Microsoft Dynamics NAV Help Server.

Configuring Microsoft Dynamics NAV Server in Setup

When you choose the Server option, the Specify parameters pane is displayed in Setup. You must specify certain parameters in order to install Microsoft Dynamics NAV Server so that clients can connect to the Microsoft Dynamics NAV Server instance. Each parameter is described in the Setup window. The following list provides a high-level description of the required parameters.

Category/Parameter Description

Installation location for 32-bit and 64-bit components

Specifies the destination folder where Microsoft Dynamics NAV Server will be installed.

You cannot install Microsoft Dynamics NAV Server on computers that are running 32-bit editions of Windows. However, the Server option includes 32-bit components.

The name of the Microsoft Dynamics NAV Server service instance name, the service account, and the listening TCP ports for clients and services

The instance name must not include spaces. For more information, see How to: Create a Microsoft Dynamics NAV Server Instance.

You must specify an account that the Microsoft Dynamics NAV Server instance uses as credentials.

The ports for the various services have default values, but you can specify other ports. The valid range is between 1 and 65535.

Add a rule to the Windows Firewall

Specifies whether Microsoft Dynamics NAV Setup adds a rule to Windows Firewall to allow Microsoft Dynamics NAV Server instances on the target computer to communicate with clients on other computers, through the specified Client Services Port.

The default value is Yes for the Client or Server installation options, where the assumption is that Microsoft Dynamics NAV Server is installed on a different computer from the RoleTailored client. The default value is No for the Demo and Developer options, where the assumption is that the Microsoft Dynamics NAV Server is installed on the same computer as the RoleTailored client.

If the target computer uses a firewall other than Windows Firewall, or if networking is not configured on the target computer, then this option must be set to No or Setup will not be able to complete successfully.

SQL Server database components

Specifies the computer that is running SQL Server, an instance of SQL Server, and the database.

If you do not specify an instance of SQL Server, Microsoft Dynamics NAV Server connects to the default instance of SQL Server.

Important
If you are installing the CRONUS International Ltd. demonstration database, Microsoft Dynamics NAV 2016 Setup may automatically install SQL Server 2012 Express even if there is already a valid version of SQL Server on the target computer, unless you create an instance named NAVDEMO in SQL Server before you run Microsoft Dynamics NAV Setup. For more information, see Installation Considerations for Microsoft SQL Server.

Public URLs for web services and client services

Optionally, specifies the root of the URLs that are used to access web services and client services. For example, you can change the value if you want to change the externally facing endpoint.

For more information, see How to: Copy the URL to Open a Page or Report.

Help Server and Help Server port

Specifies the name and port of the server that hosts the Microsoft Dynamics NAV Help Server.

This can be a public website or a local computer.

For more information, see Configuring Microsoft Dynamics NAV Help Server.

Choose Apply when you have finished entering values to return to the Specify parameters page in Setup.

After you finish running Setup, you can modify Microsoft Dynamics NAV Server using the Microsoft Dynamics NAV Server Administration tool, the Microsoft Dynamics NAV Windows PowerShell cmdlets, or by modifying the server configuration files. For more information, see Configuring Microsoft Dynamics NAV Server.

See Also

Integrating with Microsoft Office

Tasks

How to: Create a Microsoft Dynamics NAV Server Instance

Concepts

Configuring Microsoft Dynamics NAV Server
SQL Server Database Components
Microsoft Dynamics NAV Web Client
Configuring Microsoft Dynamics NAV Help Server
Automated Data Capture System


Developer Option

The Developer option is available on the Choose an installation option page in Microsoft Dynamics NAV 2016 Setup.

The set of components installed with the Developer option includes components a developer would typically use in designing Microsoft Dynamics NAV applications for a customer company.

Warning
The Developer option includes database components and the demo database. Setup cannot install the data file for a database, an .mdf file, if the destination folder or drive is compressed.

Installed Components

When you choose the Developer Environment option, Setup installs the following components:

  • Microsoft Dynamics NAV Windows client

    For more information, see Client Types.

  • Development Environment (C/SIDE).

  • Microsoft Dynamics NAV Server.

  • SQL Server Database Components, to which you can add the Demo database.

  • Web Server Components. For more information, see Microsoft Dynamics NAV Web Client.

  • ClickOnce Installer Tools. For more information, see Deploying Microsoft Dynamics NAV Using ClickOnce.

  • Microsoft Dynamics NAV 2016 Development Shell. For more information, see Comparing and Merging Application Object Source Files.

You can configure the Developer option to add or remove components by choose the Customize link under the Developer option on the Choose an installation option pane.

Other components that you many want to consider installing include:

  • The Microsoft Dynamics NAV Help Server. For more information, see Configuring Microsoft Dynamics NAV Help Server.

  • Automated Data Capture System

  • Microsoft Office Outlook Add-In

See Also

Tasks

How to: Choose Components to Install

Concepts

Client Types


Custom Option

The Custom option is available on the Choose an installation option page in Microsoft Dynamics NAV 2016 Setup.

Installed Components

The Custom option offers the full list of Microsoft Dynamics NAV components from which you can select individual components to install. In this way, it differs from the other installation options that are available on the Choose an installation option page, which are subsets of available components for a particular type of user or configuration. For more information, see How to: Choose Components to Install. You can use this list to design your own installation option.

Component Description Additional options

Client

Microsoft Dynamics NAV Windows client

  • Microsoft Dynamics NAV Development Environment

  • Microsoft Office Excel Add-In

Administration Tool

Microsoft Dynamics NAV Server Administration tool

Not applicable

Server

Microsoft Dynamics NAV Server

  • Microsoft Office Outlook Integration

  • Page Testability

SQL Server Database Components

Microsoft SQL Server

  • Demo Database

Microsoft Office Outlook Add-in

Adds a toolbar to Microsoft Outlook to enable synchronization of contacts, appointments, and tasks.

Not applicable

Automated Data Capture System

Enables the tracking of movements within a warehouse.

Not applicable

Web Server Components

Enables web clients to connect to a web browser.

Not applicable

Help Server

Installs a website that hosts the Microsoft Dynamics NAV Help content.

Not applicable

ClickOnce Installer Tools

Installs tools to facilitate with ClickOnce deployments.

Not applicable

See Also

Tasks

How to: Preconfigure Components
How to: Create or Load a Setup Configuration File


Provisioning the Microsoft Dynamics NAV Server Account

The Microsoft Dynamics NAV Server account is used by Microsoft Dynamics NAV clients to log on to the Microsoft Dynamics NAV Server instance. The Microsoft Dynamics NAV Server then uses the service account to log on to the Microsoft Dynamics NAV database. When you install Microsoft Dynamics NAV Server, you identify an Active Directory account to provide credentials for the server. By default, Setup runs Microsoft Dynamics NAV Server under the Network Service account, a predefined local account used by the service control manager. This account has minimum privileges on the local computer and acts as the computer on the network.

We recommend that you create a domain user account for running Microsoft Dynamics NAV Server. The Network Service account is considered less secure because it is a shared account that can be used by other unrelated network services. Any users who have rights to this account have rights to all services that are running on this account. If you create a domain user account to run Microsoft Dynamics NAV Server, you can use the same account to run SQL Server, whether or not SQL Server is on the same computer.

Note
Because Microsoft Dynamics NAV Setup and the New-NavDatabase cmdlet configure the required permissions for the Microsoft Dynamics NAV Server account, you will typically use the procedures in this topic when you change the Microsoft Dynamics NAV Server account for an existing installation.

To provision a Microsoft Dynamics NAV Server account, complete the following procedures as described in this topic:

  • Provisioning a Domain User Account

  • Provisioning the Network Service Account

Provisioning a Domain User Account

If you are running the Microsoft Dynamics NAV Server under a domain user account, you must:

  • Enable the account to log in as a service

  • Enable the account to register an SPN on itself

  • Give the account necessary database privileges in SQL Server

Enabling the account to log in as a service

Depending on various factors, the account may or may not already have this ability. For example, if you have already installed SQL Server and configured it to run under the same account, SQL Server will have modified the account to log in as a service.

Instructions for enabling an account to log in as a service are available on TechNet. See Add the Log on as a service Right to an Account. The instructions are for Windows Server 2008. For Windows 7, use this version of the procedure: Add the Log on as a service right to an account.

When this permission is lacking, Microsoft Dynamics NAV Server server instances may not be able to start.

Enabling the account to register an SPN on itself

To enable secure mutual authentication between clients and Microsoft Dynamics NAV Server, you must configure the Microsoft Dynamics NAV Server account to self-register Service Principal Names (SPNs). Mutual authentication is recommended in a production environment but may not be necessary in a testing or staging environment. The following procedure assumes a computer running Windows Server 2008 or Windows Server 2008 R2. On Windows 7 or Windows Vista you would need to install the Remote Server Administration Tools first.

To enable the Microsoft Dynamics NAV Server account to register an SPN on itself

  1. Start the Active Directory Users and Computers snap-in in Microsoft Management Console (MMC):

    1. Choose Run on the Start menu, type mmc on the command line, and the choose OK.

    2. When the console opens, select Add/Remove Snap-In from the File menu, select Active Directory Users and Computers, and choose Add.

      If you do not see Active Directory Users and Computers in the list of available snap-ins, you may need to use Server Manager to install the Active Directory Domain Services role on your server computer.

  2. In MMC, select Active Directory Users and Computers in the tree view and choose Advanced Features from the View menu.

  3. Expand the domain node in the tree view and choose Users.

  4. Right-click the service account, select Properties, and then choose to display the Security tab.

  5. Choose SELF in the Group or user names list.

  6. Under Permissions for SELF, in the lower part of the panel, scroll down to Write public information and select the Allow column.

  7. Choose OK to exit the Properties panel, and close Active Directory Users and Computers.

Giving the account necessary database privileges in SQL Server

The Microsoft Dynamics NAV Server account must be a member of the db_owner database role on the Microsoft Dynamics NAV database. When you install the Microsoft Dynamics NAV database by using Microsoft Dynamics NAV Setup or the New-NAVDatabase PowerShell cmdlet, you can specify the Microsoft Dynamics NAV Server account. In these cases, the server account that you specify should already have the necessary privileges in SQL Server. If you change the Microsoft Dynamics NAV Server account for an existing installation, then you should verify the account has the required privileges in SQL Server.

To verify database privileges after you create your Microsoft Dynamics NAV database, use SQL Server Management Studio and, if necessary, modify database privileges. If you have installed SQL Server with the guidelines in Installation Considerations for Microsoft SQL Server, then SQL Server Management Studio is already installed on your computer. Otherwise, update your SQL Server installation to include the Management Tools - Complete option for SQL Server.

Note
If you installed the Demo option in Microsoft Dynamics NAV Setup, then the Network Service account already has the necessary database privileges.

To assign necessary database privileges for the Microsoft Dynamics NAV Server account

  1. Start SQL Server Management Studio and connect to the instance where the Microsoft Dynamics NAV database is installed.

  2. Create a login for the Microsoft Dynamics NAV Server account.

    1. Navigate the tree view: Security, Logins

    2. Right-click Logins and choose New Login.

    3. Choose Search, and use the Select User or Group dialog box to identify the Microsoft Dynamics NAV Server account.

    4. Choose OK to exit the New Login dialog box.

  3. Add the login as a user on the master database.

    1. Navigate the tree view: Databases, System Databases, master, Security, Users.

    2. Right-click Users and choose New User.

    3. Choose the ellipse button at the far right of the second line in the Database User - New dialog box.

    4. In the Select Login dialog box, enter or browse for the login you created for the Microsoft Dynamics NAV Server account.

    5. Enter a name in the User name field (the first line in the Database User - New dialog box).

    6. Choose OK to exit the Database User - New dialog box.

  4. Grant the Microsoft Dynamics NAV Server login permissions on the master database. In the tree view, right-click master and choose Properties. Then do the following in the Database Properties - master dialog box.

    1. Under Select a Page, choose Permissions.

    2. Under Name, choose the login you created for the Microsoft Dynamics NAV Server account name.

    3. Under Permissions for <username>, on the Explicit tab, scroll down to down to the Select line, and select the check box in the Grant column.

    4. Choose OK to exit the Database Properties - master dialog box.

    5. Navigate the tree view: Databases, System Databases, master, Tables, System Tables.

    6. Right-click the dbo.$ndo$srvproperty table and choose Properties.

    7. Under Select a Page, choose Permissions.

    8. Choose Search, and use the Select User or Group dialog box to identify the login for the Microsoft Dynamics NAV Server account.

    9. Under Permissions for <username>, on the Explicit tab, scroll down to down to the Select line, and select the check box in the Grant column.

    10. Choose OK to exit the Table Properties - dbo.$ndo$srvproperty dialog box.

  5. Grant the login the necessary database roles on the Microsoft Dynamics NAV database.

    1. Navigate the tree view: Databases, <your Microsoft Dynamics NAV database>, Security, Users.

    2. Right-click Users and choose New User.

    3. In the Database User - New dialog box, choose the ellipse button at the far right of the second line.

    4. Select the login you created for the Microsoft Dynamics NAV Server account name and choose OK.

    5. Under Database role membership, select the db_owner check boxe.

    6. Choose OK to exit the Database User - New dialog box.

    7. Right-click your Microsoft Dynamics NAV database and choose Properties.

    8. Under Select a Page, choose Permissions.

    9. Choose Search, and use the Select User or Group dialog box to identify login you created for the Microsoft Dynamics NAV Server account.

    10. Under Permissions for <username>, on the Explicit tab, scroll down to down to the View database state line, and select the check box in the Grant column.

    11. Choose OK to exit the Database Properties dialog box for your Microsoft Dynamics NAV database.

It is also possible to script these steps in SQL Server Management Studio:

Copy Code
USE [master]
GO
CREATE LOGIN [domain\accountname] FROM WINDOWS
CREATE USER [domain\accountname] FOR LOGIN [domain\accountname]
GRANT SELECT ON [master].[dbo].[$ndo$srvproperty] TO [domain\accountname]
GO
USE [Microsoft Dynamics NAV Database]
GO
CREATE USER [domain\accountname] FOR LOGIN [domain\accountname]
ALTER ROLE [db_owner] ADD MEMBER [domain\accountname]
GRANT VIEW DATABASE STATE TO [domain\accountname]

Provisioning the Network Service Account

The only circumstance where it is necessary to take any action with regard to the Network Service account is when change the Microsoft Dynamics NAV Server account on an existing installation from a domain account to the Network Service. In this situation you must verify that the account has the necessary database privileges in SQL Server, as per Giving the account necessary database privileges in SQL Server, above.


Installation Considerations for Microsoft SQL Server

This topic describes the requirements for installing and configuring Microsoft SQL Server to work with Microsoft Dynamics NAV 2016.

SQL Server Components to Install

For a list of supported editions of SQL Server, see Microsoft Dynamics NAV Database Components for SQL Server Requirements.

SQL Server Components

If you are installing SQL Server to use with Microsoft Dynamics NAV, then install the following components:

  • Database Engine Services

  • Client Tools Connectivity

  • Management Tools - Complete

Setup Options for Microsoft SQL Server

When you are running Microsoft SQL Server Setup, you must provide additional information. Your responses can affect how you use SQL Server with Microsoft Dynamics NAV 2016.

Instance Configuration

If you plan on installing the Microsoft Dynamics NAV Demo database with Microsoft Dynamics NAV 2016, and you want Microsoft Dynamics NAV Setup to use an already installed version of SQL Server (and not to install SQL Server 2012 Express) you must create a SQL Server instance named NAVDEMO in SQL Server before you install Microsoft Dynamics NAV 2016. Otherwise, Microsoft Dynamics NAV Setup will install SQL Server 2012 Express automatically, even if there is a valid version of SQL Server already on the computer. If you do not plan to install the Demo database, or if you have no objection to using SQL Server 2012 Express, you are free to use the default instance and Instance ID on the Instance Configuration page, or to specify any instance name.

Server Configuration

We recommend that you use a dedicated domain user account that you create specifically for your Microsoft Dynamics NAV Server instances and for your Microsoft Dynamics NAV instance on SQL Server, instead of a Local System account or the Network Service account.

Data Encryption Between Microsoft Dynamics NAV Server and SQL Server

When SQL Server and Microsoft Dynamics NAV Server are running on different computers, you can make this data channel more secure by encrypting the connection with IPSec. (Other encryption options are not supported.) For information on how to do this, see Encrypting Connections to SQL Server, which is part of SQL Server 2008 Books Online in MSDN library.

See Also

Concepts

Data Access
Configuring Microsoft SQL Server
Troubleshooting: SQL Server Connection Problems
Deployment


Working with Microsoft Dynamics NAV Setup
Note
Before installing Microsoft Dynamics NAV 2016, you must uninstall any prior version of Microsoft Dynamics NAV.

Key Concepts for Microsoft Dynamics NAV 2016 Setup

Before you install Microsoft Dynamics NAV, you should understand the following concepts about Setup.

Installation Options

Microsoft Dynamics NAV 2016 Setup offers installation options that are designed for a typical use or type of user. For more information, see Installation Options.

Setup Configuration Files

In addition to using Setup to actually install software, you can use it to capture a set of Setup decisions to a Setup configuration file which you can then save and distribute. When you load a Setup configuration file with Microsoft Dynamics NAV Setup, previously saved options and configurations are applied.

Required Security Configuration

After you install Microsoft Dynamics NAV, you must then set up security. For more information, see Security Overview.

RapidStart Services for Microsoft Dynamics NAV

For assistance with setting up companies in Microsoft Dynamics NAV, see Set Up a Company With RapidStart Services for Microsoft Dynamics NAV.

In This Section

How to: Run Setup

Microsoft Software License Terms

Install Demo or Choose an Installation Option

How to: Choose Components to Install

How to: Preconfigure Components

How to: Create or Load a Setup Configuration File

Modifying, Uninstalling, or Repairing Microsoft Dynamics NAV

Running Setup on the Command Line

How to: Install C/SIDE Development Environment

How to: Upload the License File

Installation and Configuration Walkthroughs

Related Sections

Configuring Microsoft Dynamics NAV

Security Overview

System Requirements for Microsoft Dynamics NAV 2016


How to: Run Setup

You use Microsoft Dynamics NAV 2016 Setup to install software or to capture a set of custom setup settings to save in a setup configuration file. In this procedure, you run Microsoft Dynamics NAV 2016 Setup without any customization or configuration. Opportunities for customization and configuration are described throughout the procedure.

Note
You must be an administrator on the computer where you run Setup.

Running Setup to Install an Installation Option

Note
Before installing Microsoft Dynamics NAV 2016 on a computer, you must uninstall any other version of Microsoft Dynamics NAV.

To run Microsoft Dynamics NAV 2016 Setup

  1. Verify that the target computer meets the hardware and software requirements for the selected installation option. For more information, see System Requirements for Microsoft Dynamics NAV 2016.

  2. Insert the Microsoft Dynamics NAV installation media or locate the Microsoft Dynamics NAV 2016 Setup.exe file, and then double-click the Setup.exe file.

  3. Choose Next.

  4. To accept the license terms, choose I accept.

  5. Choose either Install Demo or Choose an installation option.

    If you choose Install Demo, Setup immediately begins to copy software and runs without requiring additional input. For more information, see Demo Option. If you choose Choose an installation option, you open the Choose an installation option page.

  6. On the Choose an installation option page, choose the larger text that defines the name of an installation option: Client Option, Server Option, or Developer Option.

    You can also choose Customize that appears below any of the three installation options to modify the list of components before you install. For more information, see How to: Choose Components to Install.

  7. On the Customize the Installation page, choose Next to open the Specify parameters page. Any parameter that has an asterisk (*) in front of the text box is a required parameter. Setup cannot complete unless you provide values for these parameters. In some cases, you may not know the correct value when you run Setup. You can add a temporary value. You can then modify the setting after you have finished running Setup by editing the appropriate configuration file. For more information, see Configuring Microsoft Dynamics NAV.

    For information about how to configure components in Setup, see How to: Preconfigure Components.

  8. After you configure components, choose Install to start to install the software.

  9. When Setup is finished, choose Close.

Canceling Setup

Setup does not provide a Cancel button on all pages, but you can cancel an installation from any page by choosing the Close button in the upper-right corner. All Microsoft Dynamics NAV components are removed from the computer. The only software that Setup installs but cannot remove are:

  • Database files, such as the Demo database.

  • Prerequisites for Microsoft Dynamics NAV components that Setup can install, such as the .NET Framework.

See Also

Tasks

How to: Choose Components to Install
How to: Preconfigure Components
How to: Create or Load a Setup Configuration File


Microsoft Software License Terms

The Microsoft Software License Terms page in Microsoft Dynamics NAV 2016 Setup defines the legal conditions under which you can use the Microsoft Dynamics NAV 2016 software. To continue with the installation, choose I accept after reading the terms.

To print the software license terms, choose Print.

See Also

Tasks

How to: Upload the License File


Install Demo or Choose an Installation Option

After you accept the software license terms and choose Next, you come to the Microsoft Dynamics NAV Setup page. This page presents the following options:

  • Install Demo

    When you choose this option, Setup immediately begins copying files. After this, you have no further interaction with Setup except to choose Close to exit Setup after it is finished copying files.

    The Demo Install is intended for users who want to try out the features of Microsoft Dynamics NAV 2016. It is not intended as the foundation for a production environment.

    Important
    Because Microsoft Dynamics NAV Server requires a 64-bit Windows operating system, you can only install the Demo version of Microsoft Dynamics NAV on a computer running a 64-bit Windows operating system.

  • Choose an Installation Option

    When you choose this option, Setup moves to the Choose an Installation Option page, where you select from a set of predefined installation configurations.

See Also

Tasks

How to: Run Setup

Concepts

Demo Option
Working with Microsoft Dynamics NAV Setup

Other Resources

Installation Options


How to: Choose Components to Install

When you run Microsoft Dynamics NAV 2016 Setup, you can install a predefined component package. These packages are called Installation Options. If you have to modify the set of components that are included in an existing installation option, then you can choose Customize under any installation option. If you want to install components that are not all available in a predefined installation option, then you can choose Custom Components.

Important
You can customize the component list for the Client, Server, or Developer installation options. However, only with the Developer Option can you choose from the complete set of Microsoft Dynamics NAV components. The range of available components for the other two installation options is limited to components that are relevant for that option.

Choosing Components to Install

In this procedure, you use the Component Selection page to select what to install.

To identify the components that you want to install

  1. In Setup, on the Choose an installation option page, decide which Installation Option you want to customize, and then choose Customize below the name of the installation option.

    This opens the Customize the installation page with one or more components already selected.

    You can also choose Custom Components on the Choose an installation option pane. This opens the Customize the installation pane without preselected components.

    Note
    To install Microsoft Dynamics NAV to a location other than the default location, on the Customize the installation page, choose Destination folder.

  2. Select the components that you want to install on the Customize the installation page.

    Options are presented in a tree view. The tree has three levels of hierarchy:

    • The top level shows only a single node, which is Microsoft Dynamics NAV.

    • The second level shows additional nodes that each identify a component such as Client and Server. Some second-level nodes have a plus sign on the left. You can choose the plus sign to display the third level of the hierarchy.

    • The third level shows subcomponents for the selected second-level component.

    Each node has one of three statuses as indicated by its appearance.

    Component node Description
    White Node

    The component and all its subcomponents are selected for installation.

    Gray node

    The component is selected for installation. Some or none but not all of the subcomponents are also selected. Only items on the top or second level can be gray because only these nodes can have subcomponents.

    Red node

    Neither the component nor any of its subcomponents is selected for installation.

  3. Choose a component to open a menu of options for that component. You must click in the box. The following options are available.

    Node option Description

    Run from My Computer

    Select this component for installation.

    Run all from My Computer

    Select this component and all subcomponents for installation.

    Not Available

    Cancel installation of this component and all subcomponents.

    For second-level nodes without subcomponents and third-level nodes, the only options are Run from My Computer and Not Available.

  4. After you have selected the set of components and subcomponents that you want to install, choose Next to continue to the Specify parameters page. For more information, see How to: Preconfigure Components.

See Also

Tasks

How to: Run Setup

Concepts

Custom Option
Configuring Microsoft Dynamics NAV Server
Configuring Microsoft Dynamics NAV Help Server

Other Resources

Installation and Configuration Walkthroughs


How to: Preconfigure Components

You can preconfigure components before you install Microsoft Dynamics NAV so that you do not have to configure them after. You can also configure Setup components and then save them to Setup configuration files before you deploy them to users. For more information, see How to: Create or Load a Setup Configuration File.

To associate configuration settings with a component before installing

  1. In Setup, on the Specify parameters pane, supply all settings for the listed components.

    Two settings that you see on the Specify parameters pane are not related to a particular component:

    • The Destination Folder (x86) setting specifies where Setup installs 32-bit Microsoft Dynamics NAV components such as the Microsoft Dynamics NAV Windows client.

    • The Destination Folder setting specifies where Setup installs 64-bit Microsoft Dynamics NAV components such as Microsoft Dynamics NAV Server.

  2. For information about parameters for a configurable component, see one of the following:

    • Configuring Microsoft Dynamics NAV Server

    • Configuring the Windows Client

    • Configuring Database Components

    • Configuring Microsoft Dynamics NAV Help Server

  3. When you have finished configuring a component, choose Apply to validate your settings. If there are issues with the settings that you have selected, then information about these issues is displayed on the Problems were identified for this configuration pane.

See Also

Tasks

How to: Create or Load a Setup Configuration File
How to: Install the Web Server Components

Concepts

Custom Option


How to: Create or Load a Setup Configuration File

You can customize the list of components to install or configure settings for individual components. For more information, see How to: Choose Components to Install and How to: Preconfigure Components.

After you finished customization and configuration, you can save this information to a Setup configuration file. You can use this file with Setup, either when you or another user runs Setup or when you run a silent installation. For more information about silent installation, see Running Setup on the Command Line.

In these procedures, you save and load a configuration file.

Saving Setup Configuration Files

You can create a new setup configuration file or save a modified setup configuration file on the Specify parameters page in Microsoft Dynamics NAV Setup. This page is available when you run Setup unless you select Install Demo, which skips all other Setup pages.

To save a setup configuration file

  1. In the Specify parameters page, choose Save.

  2. Type a file name for the configuration file. An .xml extension is added automatically.

  3. Choose Save.

    You now return to the Specify parameters page, where you can continue with installing software. You can also close Setup if you only have to create a Setup configuration file.

Loading a Setup Configuration File

The option to load a Setup configuration file is on the Choose an installation option page in Microsoft Dynamics NAV Setup. This option is also available with a command-line install. For more information, see Running Setup on the Command Line.

Important
A Setup configuration file contains information about which components to install and which settings to apply to each component. Therefore, you should not customize the list of components or configure components in Setup before you load a Setup configuration file because loading the configuration overwrites all prior customization and configuration.

To load a Setup configuration file in Setup

  1. In the Choose an installation option page, choose Load Configuration.

    This option is located under Custom Components.

  2. In the Open dialog box, select or browse to the Setup configuration file that you want to open, and then double-click the file.

    Setup now shows the Customize the installation page that has been modified according to the component selection in the loaded Setup configuration file.

  3. Modify the list of components to install or choose Next to proceed to the Specify parameters page, where settings from the Setup configuration file are shown.

  4. Configure these settings or choose Apply to accept these values and continue.

See Also

Concepts

Editing a Setup Configuration File


Editing a Setup Configuration File

You create or load Setup configuration files using Microsoft Dynamics NAV 2016 Setup. You can directly edit these XML files.

Setup configuration files contain two types of settings.

Setting type Purpose

Component

For each component, there are three separate values, all displayed on a single line:

  • ShowOptionNode

    Specifies whether the component should be displayed in Setup. For silent installs, this parameter is not relevant.

  • State

    There are two possible values: Local, indicates that the component is included in the install, and Absent indicates that the component is not included.

  • Id

    Identifies the component

You can change value for State or ShowOptionNode, but not for Id. Also, you cannot add or remove a component.

Parameter

These settings contain configuration information for components. As with Components, you can modify a parameter’s Value, but not its Id.

For information about values for pre-configuring Microsoft Dynamics NAV components using a Setup configuration file, see Configuring Microsoft Dynamics NAV.

Tip
Microsoft Dynamics NAV Setup is primarily a tool for installing software, but you can also use it as an editor for creating and modifying Setup configuration files. When you want to edit a Setup configuration file, you have the following options:

  • You can edit the file using an XML editor.

  • You can load it into Setup, make the desired modifications, and then save it. You do not need to install any software during this process.

See Also

Tasks

How to: Choose Components to Install
How to: Preconfigure Components
How to: Create or Load a Setup Configuration File


Modifying, Uninstalling, or Repairing Microsoft Dynamics NAV

If you run Microsoft Dynamics NAV 2016 Setup on a computer where any Microsoft Dynamics NAV 2016 components are already installed, you see the following options:

  • Add or Remove Components

    Select this option to navigate directly to the Customize the installation pane in Setup, where you can specify additional components to install on the local computer, or to remove from the local computer.

    On the Customize the installation page, click within the box of a component to open a menu of options for that component. The following options are available.

    Node option Behavior

    Run from My Computer

    Adds this component to the current installation.

    Run all from My Computer

    Adds this component and all subcomponents to the current installation.

    Not Available

    Removes this component and all subcomponents from the current installation.

    After you finish selecting components, choose Next to proceed to the Specify parameters pane. See How to: Preconfigure Components for details.

  • Repair

    Select this option to repair any Microsoft Dynamics NAV components on the local computer that have become corrupted.

    Important
    If the Microsoft Dynamics NAV Web Server components are installed, see Repairing Microsoft Dynamics NAV Web Server Components before running Repair.

  • Uninstall

    Select this option to remove Microsoft Dynamics NAV 2016 components from the local computer.

    Note
    After you choose Repair or Uninstall, Setup runs to completion with no further interaction. Your next option is to close Microsoft Dynamics NAV 2016 Setup.

Removing the Demo Database

Setup does not remove the Microsoft Dynamics NAV Demo database. After you use Setup to remove Microsoft Dynamics NAV software from your computer, you must manually remove the demo database.

With SQL Server

Use SQL Server Management Studio to remove the Microsoft Dynamics NAV demo database, which is called Demo Database (7-1). By default, the database is installed to the NAVDEMO SQL Server instance.

If you have installed SQL Server with the guidelines in Installation Considerations for Microsoft SQL Server, then SQL Server Management Studio is already installed on your computer. Otherwise, update your SQL Server installation to include the Management Tools - Complete option for SQL Server.

With SQL Server Express

If you did not have SQL Server on your computer when you installed the demo database, then Microsoft Dynamics NAV Setup installed SQL Server 2012 Express Edition to host the database. To remove the demo database, follow these steps:

  1. From the Microsoft Download Center, download and install Microsoft SQL Server 2012 Management Studio Express.

  2. Use SQL Server Management Studio Express to remove the Microsoft Dynamics NAV demo database, which is called Demo Database (7-1). By default, the database is installed to the NAVDEMO SQL Server instance.

Repairing Microsoft Dynamics NAV Web Server Components

You can use Microsoft Dynamics NAV Setup to install the Microsoft Dynamics NAV Web Server components. Setup installs a default web server instance on IIS for the Microsoft Dynamics NAV Web client. After the initial installation, you can add and configure additional web server instances by using the cmdlets that are provided in the Microsoft Dynamics NAV Administration Shell. If you run the Repair option in Microsoft Dynamics NAV Setup, then Setup re-creates the initial default environment, which includes a default web server instance, and removes any web server instances that have been added.

To ensure that you can easily re-create the web server instances after you run the Repair option, we recommend that you create Windows PowerShell scripts that add and configure the web server instances.

See Also

Tasks

How to: Choose Components to Install
How to: Run Setup

Concepts

Working with Microsoft Dynamics NAV Setup


Running Setup on the Command Line

You can run Microsoft Dynamics NAV 2016 Setup at a command prompt. On the Microsoft Dynamics NAV installation media, Setup.exe is in the root directory.

After installation, the typical location for Setup.exe on the target computer is:

Copy Code
C:\Program Files (x86)\Common Files\Microsoft Dynamics NAV\90\Setup

You can use the following options with Setup.exe.

Setup option | Description
/config <Setup config file> | Specifies path and file name information for a Microsoft Dynamics NAV 2016 Setup configuration file to load. This is the only required option.
/help | Displays Help about Setup.exe options.
/log <log path> | Specifies path and file name information for a Setup log file to be created by Setup. The file must not exist before you run Setup.
/quiet | Specifies that Setup does not display anything on the screen. All configuration information is taken from the specified configuration file.
/repair | Repairs the current installation of Microsoft Dynamics NAV 2016.
/uninstall | Removes the current installation Microsoft Dynamics NAV 2016.

See Also

Tasks

How to: Create or Load a Setup Configuration File

Concepts

Working with Microsoft Dynamics NAV Setup
Editing a Setup Configuration File


How to: Install C/SIDE Development Environment

Developers and administrators use the Microsoft Dynamics NAV Development Environment to develop and manage Microsoft Dynamics NAV applications. Developers use development environment to create objects, such as pages, reports, and tables, for displaying and handling data in the Microsoft Dynamics NAV Windows client and the Microsoft Dynamics NAV Web client. Administrators can use the Microsoft Dynamics NAV Development Environment for the administrative tasks, such as managing licenses, and adding and managing databases.

The development environment can be included as part of the different installation options.

Installation option | Development environment status
Demo Option | Installed automatically
Client Option installation | Not pre-selected for installation but can be added
Developer Option installation | Pre-selected for installation but can be removed

In this procedure, you install the development environment

To install the development environment

  1. Insert the Microsoft Dynamics NAV installation media in the drive of your computer, or navigate to the directory that contains the Microsoft Dynamics NAV 2016 Setup program.

  2. Double-click the Setup.exe file to start the Microsoft Dynamics NAV Setup wizard.

    If you have already installed one or more Microsoft Dynamics NAV components on the computer, you will see the Maintenance page instead of the Welcome page. In this case, choose Add or remove components, and then go to step 7.

  3. Choose Next.

  4. To accept the license terms, choose I accept.

  5. On the Microsoft Dynamics NAV Setup page, choose Choose an installation option.

  6. On the Choose an Installation Option page, choose Custom.

  7. On the Customize the Installation page, choose the plus sign (+) to expand the Client option.

  8. Choose Development Environment (C/SIDE), and then choose Run from My Computer. You must click in the rectangle, and not on the text: Click in the box and select Run from My Computer

  9. Choose Next to go to the Specify Parameters page.

  10. Specify a name and a port for Microsoft Dynamics NAV Server.

    You must have a valid Microsoft Dynamics NAV Server connection to successfully work with the Microsoft Dynamics NAV database.

  11. Choose Install.

  12. When Setup is finished, choose Close.

See Also

Tasks

How to: Choose Components to Install
How to: Upload the License File
How to: Create Microsoft Dynamics NAV Users

Concepts

Development
Administration in the Development Environment


Saving Setup Parameters in the Zup File

Setup parameters for running the Microsoft Dynamics NAV Development Environment are stored in a .zup file. By default, the file is named fin.zup and is located at C:\users\<user name>\AppData\Roaming\. To change the name and location of the .zup file, run the development environment at a command prompt and specify the path and ID in the id parameter. For more information, see Using the Development Environment from the Command Prompt.

You can create multiple .zup files by using the id parameter. For example, you may want different users to run the development environment with different setup parameters by using the id parameter and specifying different .zup files.

The information that is stored in the .zup file includes:

  • Database name.

  • Database server name.

  • The parameters that are available in the Options window.

  • User-specified personalization of development environment windows, such as window size, window position, column order, column visibility, and column width.

When a user closes the development environment, any setup changes the user has made are saved to the .zup file.

To return to the original setup parameters, you can run the development environment at a command prompt without specifying the id parameter so that the fin.zup file is used instead of a customized <id>.zup file. If you have made changes to the fin.zup file but want to return to the original fin.zup settings, then delete the fin.zup file and run the development environment at a command prompt without specifying the id parameter. A new fin.zup file is created that has the original setup parameters.


Deploying the Microsoft Dynamics NAV Web Server Components

This section contains information about the deployment of the Microsoft Dynamics NAV Web Server components. It is important to understand the Microsoft Dynamics NAV Web Server components environment and consider the factors that will affect the installation and configuration, such as network architecture and infrastructure, users, security, and the deployment phase.

When you deploy the Microsoft Dynamics NAV Web Server components, you get both the Microsoft Dynamics NAV Web client and the Microsoft Dynamics NAV Tablet client.

Network Architecture and Topology

The following illustration shows the Microsoft Dynamics NAV Web Server components environment.

NAV Web Client network architecture

You can deploy the components on one computer or on separate computers. For example, you can install the Microsoft Dynamics NAV Web Server components on one computer and the Microsoft Dynamics NAV Server and SQL Server database on another computer. The topology that you choose depends on the network resources and the infrastructure of the Microsoft Dynamics NAV components. The installation and configuration process is different for each scenario.

For information about the common deployment scenarios, see Deployment Scenarios for the Microsoft Dynamics NAV Web Server Components.

Microsoft Dynamics NAV Web Server Components Installation on IIS

To deploy the Microsoft Dynamics NAV Web client, you install Microsoft Dynamics NAV Web Server components on a computer that is running Internet Information Services (IIS). For more information about how to install the Microsoft Dynamics NAV Web Server components and IIS, see How to: Install the Web Server Components and How to: Install and Configure Internet Information Services for Microsoft Dynamics NAV Web Client.

When you install Microsoft Dynamics NAV Web Server components, a web server instance is added on IIS for the Microsoft Dynamics NAV Web client. The web server instance consists of a virtual directory and application. The following illustration shows the structure in Internet Information Services Manager. For more information about these elements in IIS, see IIS Manager UI.

The NAV Web client structure on IIS

The following table includes the default settings for each element of the website structure.

Website

Setting | Value
Name | Microsoft Dynamics NAV 2016 Web Client
Binding | Type: http or https (if you configure SSL on the Microsoft Dynamics NAV Web Server components) Port: Port number you assigned the Microsoft Dynamics NAV Web client (default 8080)
Application pool | DefaultAppPool
Application pool identity | ApplicationPoolIdentity
Physical path | %systemroot%\inetpub\wwwroot\NavWebApplicationContainer
Authentication | Windows Authentication

Virtual directory

Setting | Value
Physical path | %systemroot%\inetpub\wwwroot\DynamicsNAV90
Virtual path/Alias | /DynamicsNAV90 By default, this name matches the name of the Microsoft Dynamics NAV Server instance that the Microsoft Dynamics NAV Web Server components connects to.

Web application

Setting Value

Application pool

Microsoft Dynamics NAV 2016 Web Client Application Pool

Application pool identity

ApplicationPoolIdentity

Physical path

%systemroot%\inetpub\wwwroot\DynamicsNAV90\WebClient

Note
This folder is a symbolic link that targets the %systemroot%\Program Files\Microsoft Dynamics NAV\90\Web Client folder.

Virtual path/Alias

/DynamicsNAV90/WebClient

Protocol

http

Authentication

Windows Authentication, Forms authentication, Anonymous Authentication, and ASP.NET Impersonation.

Deployment Phases

Typically, you will deploy the Microsoft Dynamics NAV Web client in phases, which can influence the network topology and security settings that you deploy. For example, in the development phase, you develop, test, and fine-tune the application. In this phase, you might consider deploying the Microsoft Dynamics NAV Web client in a single-computer scenario. When you move to the production phase, you deploy the Microsoft Dynamics NAV Web client in the full network infrastructure.

Security

User Authentication

Microsoft Dynamics NAV supports four methods for authenticating users who try to access the Microsoft Dynamics NAV Web client: Windows, UserName, NavUserPassword, and AccessControlService. Windows authentication is configured by default. For more information, see Users and Credential Types and How to: Configure User Authentication for the Microsoft Dynamics NAV Web Client.

Service Account for Microsoft Dynamics NAV Server and Microsoft Dynamics NAV Database Access

When you install Microsoft Dynamics NAV Server and Microsoft Dynamics NAV database components, you must identify an Active Directory account to provide credentials for the servers. By default, Microsoft Dynamics NAV 2016 Setup runs Microsoft Dynamics NAV Server and the Microsoft Dynamics NAV database under the Network Service account, a predefined local account that is used by the service control manager.

Tip
We recommend that you create and use a domain user account for running Microsoft Dynamics NAV Server and accessing the Microsoft Dynamics NAV database. The Network Service account is considered less secure because it is a shared account that can be used by other unrelated network services.

For more information, see Provisioning the Microsoft Dynamics NAV Server Account.

Securing the Connection to Microsoft Dynamics NAV Web Client With SSL

You can help secure Microsoft Dynamics NAV data that is transmitted over the Internet by enabling Secure Sockets Layer (SSL) on the connection to the Microsoft Dynamics NAV Web client. You can configure SSL when you install the Microsoft Dynamics NAV Web Server components or after the installation.

For more information, see How to: Install the Web Server Components and How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client.

See Also

Tasks

How to: Install the Web Server Components

Concepts

Microsoft Dynamics NAV Web Client


Deployment Scenarios for the Microsoft Dynamics NAV Web Server Components

This section describes how to install and configure the Microsoft Dynamics NAV Web Server components in different network topologies.

NAV Web Client network architecture

Deployment Scenarios

The following table includes the deployment scenarios that are discussed in this section.

Scenario | Description
Deploying the Microsoft Dynamics NAV Web Server Components in a Demonstration Environment | Installs the Microsoft Dynamics NAV Web client, Microsoft Dynamics NAV Tablet client, Microsoft Dynamics NAV Windows client, Microsoft Dynamics NAV Development Environment, and the CRONUS International Ltd. demonstration database and company on a single computer. The scenario lets you install and test the Microsoft Dynamics NAV Web client features and behavior in a simple network topology by using the default settings of Microsoft Dynamics NAV Setup. The installation requires minimal preparation and hardware resources.
Deploying the Microsoft Dynamics NAV Web Server Components in a Single Computer Environment | Installs the Microsoft Dynamics NAV Web Server components, Microsoft Dynamics NAV Server, and the SQL Server database components on the same computer.
Deploying the Microsoft Dynamics NAV Web Server Components in a Two Computer Environment | Installs the Microsoft Dynamics NAV Web Server components on a computer separate than Microsoft Dynamics NAV Server and the SQL Server database components.
Deploying the Microsoft Dynamics NAV Web Server Components in a Three Computer Environment | Installs the Microsoft Dynamics NAV Web Server components, Microsoft Dynamics NAV Server, and the SQL Server database components on three separate computers.

See Also

Tasks

How to: Install the Web Server Components


Deploying the Microsoft Dynamics NAV Web Server Components in a Demonstration Environment

In this scenario, you install the major components of the Microsoft Dynamics NAV 2016 on a single computer. The scenario enables you to install Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Tablet client in an environment where you can test its features and behavior, compare it to the Microsoft Dynamics NAV Windows client, and start developing your own applications. The installation requires minimal hardware resources, preparation, and configuration.

Note
Microsoft Dynamics NAV Windows client is not required to run the Microsoft Dynamics NAV Web client or Microsoft Dynamics NAV Tablet client. In this scenario, Microsoft Dynamics NAV Windows client is installed for demonstration only.

Installed Components and Configuration

Components

This scenario installs the following components:

  • Microsoft Dynamics NAV Web Server components

  • Microsoft Dynamics NAV Windows client

  • Microsoft Dynamics NAV Server

  • SQL Server Database Components

  • Microsoft Dynamics NAV Server Administration Tool

  • Development Environment (C/SIDE)

  • CRONUS International Ltd. demonstration database, including a demo license.

    For information about what you can do with this license, see Properties of the Demo License.

Configuration

This scenario uses the default setting of the Microsoft Dynamics NAV Setup program, which includes the following:

  • Windows authentication is configured for authenticating users who try to open the Microsoft Dynamics NAV Web client.

  • Microsoft Dynamics NAV Server configuration:

    • Service instance: DynamicsNAV90

    • Client service port: 7046

    • SOAP web services port: 7047

    • OData web services port: 7048

  • Microsoft Dynamics NAV database components configuration:

    • Service instance: NAVDEMO

    • Database: Demo Database NAV (9-0)

  • NETWORK SERVICE account is used as the service account for Microsoft Dynamics NAV Server and Microsoft Dynamics NAV database.

Installing the Microsoft Dynamics NAV Web Server Components

To install the Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Tablet client in this scenario, you will run Microsoft Dynamics NAV Setup two times. The first time, you will choose the Install Demo option, which installs the Microsoft Dynamics NAV Windows client, development environment, and the CRONUS International Ltd. demonstration database. The second time that you run Setup, you will choose the Web Server Components option, which installs a website for Microsoft Dynamics NAV Web client on the Internet Information Services.

Prepare for the Microsoft Dynamics NAV Web client installation

  1. Get access to the Microsoft Dynamics NAV installation media. For example, this could be a DVD or network drive that contains the Microsoft Dynamics NAV installation files.

  2. Make sure that the computer meets the hardware and software requirements.

    For more information, see System Requirements for Microsoft Dynamics NAV 2016.

  3. Install Internet Information Services 7.0 or Internet Information Services 8.0.

    For more information, see How to: Install and Configure Internet Information Services for Microsoft Dynamics NAV Web Client.

    Note
    Instead of installing and configuring Internet Information Services (IIS) manually, you can use Microsoft Dynamics NAV Setup to install IIS and enable the required features. If IIS is already installed, then Setup will enable any required features that are not currently enabled.

  4. Determine which HTTP port to use for the Microsoft Dynamics NAV Web client connection and create an inbound for the port in Windows Firewall according to the following guidelines:

    • Microsoft Dynamics NAV Setup will create a website on IIS for the Microsoft Dynamics NAV Web client. During Setup, you will have to choose the port to use for the site. The default port that is used in Microsoft Dynamics NAV Setup is port 8080. If you are not sure of which port to use, then use the default port.

    • If your computer is running Windows 7 or Windows 8, then you have to create an inbound rule that allows communication on the port.

      For information about how to create an inbound rule, see How to: Create an Inbound Rule in Windows Firewall for the Port of Microsoft Dynamics NAV Web Client.

    • If your computer is running Windows Server 2012, then an inbound rule is already created and no action is required.

Run Microsoft Dynamics NAV Setup

  1. From the Microsoft Dynamics NAV 2016 installation media, run the setup.exe file to start Microsoft Dynamics NAV Setup Wizard.

  2. On the Welcome to Microsoft Dynamics NAV 2016 Setup page, choose the Next button, and then choose I accept to accept the license terms.

  3. On the Microsoft Dynamics NAV Setup page, choose Install Demo.

    The installation starts. This can take several minutes.

  4. When the installation is complete, choose the Close button.

  5. Run the setup.exe to start the Microsoft Dynamics NAV Setup Wizard again.

  6. On the Maintenance page, choose Add or remove components.

  7. On the Customize the Installation page, choose the box next to Web Server Components, choose Run from My Computer, and then choose Next.

  8. On the Specify Parameters page, under Web Server Components, set the Port parameter to the TCP/IP port to use for the Microsoft Dynamics NAV Web client connection or use the default port 8080.

  9. Set the Install IIS prerequisites parameter to Install.

    This enables the IIS features that are required for the Microsoft Dynamics NAV Web client on the computer. For more information about this parameter, see Using Microsoft Dynamics NAV Setup to Install IIS Features.

  10. Choose the Apply button.

    The installation starts.

  11. When the installation is complete, choose the Close button.

The following elements of the Microsoft Dynamics NAV Web client have been added to your computer:

  • A Microsoft Dynamics NAV Web client button on the Start menu.

  • A web server instance for the Microsoft Dynamics NAV Web client is installed on IIS. The web server instance includes a virtual directory and application for the Microsoft Dynamics NAV Web client that has the alias DynamicsNav90\WebClient.

    Note
    The DynamicsNAV90 alias matches the name of the Microsoft Dynamics NAV Server instance that was also created.

Open the Microsoft Dynamics NAV Web client

  • To open the Microsoft Dynamics NAV Web client from the computer where you installed Microsoft Dynamics NAV 2016, on the Start menu, choose All Programs, and then choose Microsoft Dynamics NAV 2016 Web Client.

  • To open the Microsoft Dynamics NAV Web client from other devices on the network, open an Internet browser, and type the following URL in the address box:

    Copy Code
    http://ComputerName:PortNumber/DynamicsNAV90/WebClient
    • Substitute ComputerName with the name of the computer where you installed Microsoft Dynamics NAV. If you are working on the computer where you installed Microsoft Dynamics NAV, then you can use localhost.

    • Substitute PortNumber with the port that you configured for the Microsoft Dynamics NAV Web Server components during Setup.

      For example, if the Microsoft Dynamics NAV Web Server components is installed on port 8080, then you can use the following URL:

      Copy Code
      http://ComputerName:PortNumber/DynamicsNAV90/WebClient

    For a list of supported devices and browsers, see System Requirements for Microsoft Dynamics NAV 2016.

Note
If you get an error and the Microsoft Dynamics NAV Web client does not open, then see Troubleshooting the Microsoft Dynamics NAV Web Client Installation to try to resolve the problem.

See Also

Tasks

How to: Install the Web Server Components

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components


Deploying the Microsoft Dynamics NAV Web Server Components in a Single Computer Environment

In this scenario, you install the Microsoft Dynamics NAV Web Server components, Microsoft Dynamics NAV Server, and the SQL Server database components on the same computer.

NAV Web Client installation on one computer

Tip
For a step-by-step example that describes how to deploy this scenario, see Walkthrough: Installing the Microsoft Dynamics NAV Web Server Components on a Single Computer.

Deployment Tasks

To deploy the Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Tablet client in this scenario, complete the following tasks.

Pre-Installation Tasks

The following table includes tasks to perform before you install the Microsoft Dynamics NAV Web Server components.

Task Description For more information, see

Make sure that system requirements are met.

Verify that the computer has the required hardware and software installed.

System Requirements for Microsoft Dynamics NAV 2016

Install Internet Information Services 7.0 or Internet Information Services 8.0.

When you install the Microsoft Dynamics NAV Web Server components, Microsoft Dynamics NAV Setup creates a website for the Microsoft Dynamics NAV Web client on IIS. If IIS is already installed, then make sure that the required features are enabled.

Note
Instead of installing and configuring IIS manually, you can use Microsoft Dynamics NAV Setup to install IIS and enable the required features.

How to: Install and Configure Internet Information Services for Microsoft Dynamics NAV Web Client

Determine the TCP port for the Microsoft Dynamics NAV Web client and allow communication on the port through Windows Firewall.

Microsoft Dynamics NAV Setup creates a website on IIS for the Microsoft Dynamics NAV Web client. During Setup, you will have to choose the port to use for the site. The default port that is used in Microsoft Dynamics NAV Setup is port 8080. If you are not sure of which port to use, then use the default port.

If the computer is running Windows 7 or Windows 8 with Windows Firewall enabled, then you have to create an inbound rule that allows communication on the port.

How to: Create an Inbound Rule in Windows Firewall for the Port of Microsoft Dynamics NAV Web Client

Set up the service account for Microsoft Dynamics NAV Server and the SQL Server database.

Optional. When you install Microsoft Dynamics NAV Server, you can specify a user account that will be used to log on to the Microsoft Dynamics NAV Server instance and Microsoft Dynamics NAV database. The default service account is Network Service. If you want to use Network Service, then no action is required for this task.

Provisioning the Microsoft Dynamics NAV Server Account.

Obtain and install an SSL certificate.

Optional. If you want to configure SSL on the connection to Microsoft Dynamics NAV Web client, then complete the following procedures:

  • Obtain an SSL certificate.

  • Import the certificate into the local computer store of the computer on which you will install the Microsoft Dynamics NAV Web Server components.

  • Obtain the certificate's thumbprint.

Note
You can also configure SSL after you have installed the Microsoft Dynamics NAV Web client. For more information, see Post-installation Tasks.

The following sections in the Walkthrough: Configuring Web Services to Use SSL (SOAP and OData) topic:

  • Obtaining an SSL Certificate

  • Importing the SSL Certificate into the Local Computer Store of the Microsoft Dynamics NAV Server computer

  • Obtaining the Certificate's Thumbprint

Installation Tasks

The following table includes tasks for installing the Microsoft Dynamics NAV Web Server components.

Task | Description | For more information, see
Install Microsoft Dynamics NAV Web Server components, Microsoft Dynamics NAV Server, and Microsoft Dynamics NAV database components. | Run the Microsoft Dynamics NAV 2016 setup.exe file, choose the Custom installation option, and then choose the SQL Server Database Components, Server, and NAV Web Server Components options. | How to: Run Setup How to: Install the Web Server Components

Post-installation Tasks

The following table includes tasks that configure the Microsoft Dynamics NAV Web Server components after installation. These tasks are optional depending on your organizational and network requirements.

Task | Description | For more information, see
Configure Report Viewer. | To display reports, Microsoft Report Viewer must be configured on a website of the Microsoft Dynamics NAV Web client. Report Viewer includes an option that lets users save a report as a Microsoft Excel, Microsoft Word, or PDF file. By default, this option is disabled. You configure Microsoft Report Viewer in the web.config file for the Microsoft Dynamics NAV Web client website. | How to: Configure Microsoft Report Viewer for the Microsoft Dynamics NAV Web Client
Change the user authentication method. | The Microsoft Dynamics NAV Web client supports the same authentication methods as the Microsoft Dynamics NAV Windows client, which include Windows, UserName, NavUserPassword, and AccessControlService. By default, the Microsoft Dynamics NAV Web client uses Windows authentication. | How to: Configure User Authentication for the Microsoft Dynamics NAV Web Client
Secure the connection to the Microsoft Dynamics NAV Web client with SSL. | You can help secure Microsoft Dynamics NAV data that is transmitted over the Internet by enabling Secure Sockets Layer (SSL) on the connection to the Microsoft Dynamics NAV Web client. | How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client
Change Microsoft Dynamics NAV settings of the Microsoft Dynamics NAV Web client. | There are several parameters in the web.config file for the website that is running Microsoft Dynamics NAV Web Server components that you can modify to change the behavior of the Microsoft Dynamics NAV Web client. Some of the more common parameters include the Microsoft Dynamics NAV Server instance, company, language, time zone, regional settings, session time out, and online Help URL. | Configuring Microsoft Dynamics NAV Web Client by Modifying the Web.config File
Set up multiple Microsoft Dynamics NAV Web client applications on a website. | You can set up multiple web server instances for the Microsoft Dynamics NAV Web client on the existing website. The web server instances will use the same address (URL) except with an alias that specifies the specific application. | How to: Set Up Multiple Web Server Instances for the Microsoft Dynamics NAV Web Client
Configure web browsers on devices. | The Microsoft Dynamics NAV Web client supports several different web browsers. To access the Microsoft Dynamics NAV Web client, the web browser must be enabled on a device with cookies and JavaScript. | Configuring the Web Browser for the Microsoft Dynamics NAV Web Client

See Also

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Deploying the Microsoft Dynamics NAV Web Server Components in a Two Computer Environment
Deploying the Microsoft Dynamics NAV Web Server Components in a Three Computer Environment


Walkthrough: Installing the Microsoft Dynamics NAV Web Server Components on a Single Computer

In this walkthrough, you will install the tiers of Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Tablet client in a production environment on one computer.

NAV Web Client installation on one computer

About This Walkthrough

After completing this walkthrough, you will have a functioning four-tier installation on one computer. The installation uses the CRONUS International Ltd. demonstration database, which contains the CRONUS International Ltd. company. Windows authentication is used for authenticating users who try to access the Microsoft Dynamics NAV Web client.

This walkthrough illustrates the following tasks:

  • Using a domain user account as the service account for Microsoft Dynamics NAV Server and the Microsoft Dynamics NAV database.

  • Installing the Microsoft Dynamics NAV Database Components and Microsoft Dynamics NAV Server

  • Allowing Inbound Communication to the Microsoft Dynamics NAV Web Client Through the Windows Firewall

  • Opening the <token xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">nav_web</token>

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 installation media. For example, this could be a DVD or network drive that contains the Microsoft Dynamics NAV 2016 installation files.

  • A computer that is installed with the following software:

    • A supported operating system. For more information, see System Requirements for Microsoft Dynamics NAV 2016.

    • A supported version of Microsoft SQL Server. For more information, see System Requirements for Microsoft Dynamics NAV 2016

      If a supported SQL Server product is not already installed on the target computer, then Microsoft Dynamics NAV Setup automatically installs a 64-bit edition of SQL Server Express.

      For more information, see Installation Considerations for Microsoft SQL Server.

    • Internet Information Services 7 or Internet Information Services 8.

      You must enable IIS with the required features for the Microsoft Dynamics NAV Web client. For more information, see How to: Install and Configure Internet Information Services for Microsoft Dynamics NAV Web Client.

      Note
      Instead of installing and configuring IIS manually, you can use Microsoft Dynamics NAV Setup to install IIS and enable the required features, as described in this walkthrough.

  • A device with a network connection and a supported web browser.

    For a list of supported browsers, see System Requirements for Microsoft Dynamics NAV 2016.

  • Optionally, a domain user account for accessing Microsoft Dynamics NAV Server and Microsoft Dynamics NAV database on the Microsoft SQL Server. The user account must have the following permissions:

    • Permission to log on as a service on the computer where you will install Microsoft Dynamics NAV Server and the computer that is running SQL Server.

    • Permission to register Service Principal Names (SPNs) on itself.

    For information about how to create a domain user account, see Create a New User Account. For information about how to enable permission to log on as a service and register SPNs, see Provisioning the Microsoft Dynamics NAV Server Account.

    Note
    By default, Microsoft Dynamics NAV Setup uses NETWORK SERVICE as the service account. You can use NETWORK SERVICE instead of a domain user account, but this is considered less secure. If you want to use NETWORK SERVICE, then you do not need this prerequisite.

Story

Viktor is a Microsoft Certified Partner working for CRONUS International Ltd. He has been tasked with deploying Microsoft Dynamics NAV Web client for a customer. To meet the customer's requirements, Viktor has decided to deploy the Microsoft Dynamics NAV Web client as follows:

  • Install the Microsoft Dynamics NAV Web Server components, Microsoft Dynamics NAV Server, and SQL server with Microsoft Dynamics NAV database components on one computer.

  • Install the Microsoft Dynamics NAV Web Server components on HTTP port 8080.

  • Use a domain user account instead of the Network Service account as the service account for Microsoft Dynamics NAV Server.

  • Use Windows Authentication to authenticate users.

Installing the Microsoft Dynamics NAV Components

In this procedure, you run Microsoft Dynamics NAV 2016 Setup to install the SQL Server Database components for Microsoft Dynamics NAV, including the CRONUS International Ltd. demonstration database, Microsoft Dynamics NAV Server, and the Microsoft Dynamics NAV Web Server components. During setup, you will assign the domain user account as the service account for the database.

Note
You can also use this procedure to connect to an existing Microsoft Dynamics NAV Server and Microsoft Dynamics NAV database.

To install the Microsoft Dynamics NAV components

  1. From the Microsoft Dynamics NAV installation media, run the setup.exe file to start the Microsoft Dynamics NAV Setup Wizard.

  2. On the Welcome to Microsoft Dynamics NAV 2016 Setup page, choose the Next button.

  3. To accept the license terms, choose I accept.

  4. On the Microsoft Dynamics NAV Setup page, choose Choose an installation option.

  5. On the Choose an Installation Option page, choose Custom.

  6. On the Customize the installation page, to install the Microsoft Dynamics NAV database, select the SQL Server Database Components box, and then select Run from My Computer or Run all from my computer.

    If you choose Run all from my computer, Setup installs the CRONUS International Ltd. demonstration database.

  7. To install the Microsoft Dynamics NAV Server, select the Server box, and then choose Run from My Computer.

  8. To install the Microsoft Dynamics NAV Web client, select the Web Server Components box, and then choose Run from My Computer.

  9. Choose Next to open to the Specify Parameters page.

  10. In the Server section, set the Server account field to the domain user account that you created for access to the Microsoft Dynamics NAV Server, and in the Service Account Password field, type the password for the user account.

  11. In the SQL Server Database Components section, in the SQL Database field, type a name for the Microsoft Dynamics NAV database.

    For this walkthrough, type Demo Database NAV (9-0).

  12. In the Web Server Components section, set the Port field to 8080.

  13. Set the Install IIS prerequisites parameter to Install.

    This enables the IIS features that are required for the Microsoft Dynamics NAV Web client on the computer. For more information about this parameter, see Using Microsoft Dynamics NAV Setup to Install IIS Features.

  14. Choose Apply to complete the installation.

  15. When Setup is complete, choose the Close button.

A website that has the name Microsoft Dynamics NAV 2016 Web Client has been installed on IIS. The website uses port 8080. A website that has the name Microsoft Dynamics NAV 2016 Web Client has been installed on IIS. The website includes a web server instance for Microsoft Dynamics NAV Web client that has the name DynamicsNAV90. The default physical path of the web server instance is C:\inetpub\wwwroot\DynamicsNAV90\.

Allowing Inbound Communication on the Microsoft Dynamics NAV Web Client Port Through the Windows Firewall

Viktor chose to install the Microsoft Dynamics NAV Web Server components on port 8080 of the computer. This port is typically blocked by Windows Firewall. To allow communication to the port from client devices, he must create an inbound rule on the port 8080 in the Windows Firewall setup.

Note
You do not have to perform this task if the computer is running Windows Server 2012.

To create an inbound rule on the port that is used by Microsoft Dynamics NAV Web client

  1. On the Start menu, choose Control Panel, choose System and Security, and then choose Windows Firewall.

  2. In the navigation pane, choose Advanced settings.

  3. In the Windows Firewall with Advanced Settings window, in the navigation pane, choose Inbound Rules, and then in the Actions pane, choose New Rule.

  4. On the Rule Type page, choose Port, and then choose Next.

  5. On the Protocol and Ports page, choose Specific local ports, and then type the port number in the box. For example, type 8080 for the default port of the Microsoft Dynamics NAV Web client.

  6. Choose Next.

  7. On the Action page, choose Allow the connection, and then choose Next.

  8. On the Profile page, choose the profiles, and then choose Next.

  9. On the Name page, type a name for the rule, and then choose Finish.

Opening the Microsoft Dynamics NAV Web client

You can open the Microsoft Dynamics NAV Web client from any device with a supported web browser.

To open the Microsoft Dynamics NAV Web client

  1. Open the web browser.

  2. In the address box, type the following URL:

    http://ComputerName:PortNumber/DynamicsNAV90/WebClient/Default.aspx

    • Substitute ComputerName with the name of the computer that is running the Microsoft Dynamics NAV Web Server components. If you are working on the computer where you installed Microsoft Dynamics NAV Web Server components, then you can use localhost.

    • Substitute PortNumber with the port that you configured for the Microsoft Dynamics NAV Web Server components during Setup.

    • Substitute DynamicsNAV90 with the name of the Microsoft Dynamics NAV Server instance that you configured during Setup. DynamicsNAV90 is the default value.

    For example, if the Microsoft Dynamics NAV Web Server components is installed on port 8080 and the computer has the name NavWeb, then you can use the following URL:

    http://NavWeb:8080/DynamicsNAV90/WebClient/Default.aspx

Troubleshooting

If you are cannot connect the Microsoft Dynamics NAV Web client or you are experiencing problems, see Troubleshooting the Microsoft Dynamics NAV Web Client Installation.

Next Steps

The following is a list of typical tasks to perform after you install Microsoft Dynamics NAV Web Server components.

  • Upload your license. For more information, see How to: Upload the License File.

  • Create users and integrate them into the Microsoft Dynamics NAV security system. For more information, see Managing Users.

See Also

Tasks

Walkthrough: Installing the Microsoft Dynamics NAV Web Server Components on a Single Computer
Walkthrough: Installing the Microsoft Dynamics NAV Web Server Components on Two Computers

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Deploying the Microsoft Dynamics NAV Web Server Components in a Three Computer Environment
Microsoft Dynamics NAV Web Client Network Architecture
Configuring Microsoft SQL Server
Configuring Microsoft Dynamics NAV Server


Deploying the Microsoft Dynamics NAV Web Server Components in a Two Computer Environment

In this scenario, you install the Microsoft Dynamics NAV Web Server components on a computer separate than Microsoft Dynamics NAV Server and the SQL Server database components.

NAV Web client installation on two computers

Tip
For a step-by-step example that describes how to deploy this scenario, see Walkthrough: Installing the Microsoft Dynamics NAV Web Server Components on Two Computers.

Deployment Tasks

To deploy the Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Tablet client in this scenario, complete the following tasks.

Pre-Installation Tasks

The following table includes tasks to perform before you install the Microsoft Dynamics NAV Web Server components.

Task Description For more information, see

Make sure that system requirements are met.

Verify that the computer has the required hardware and software installed.

System Requirements for Microsoft Dynamics NAV 2016

Install Internet Information Services 7.0 or Internet Information Services 8.0.

When you install the Microsoft Dynamics NAV Web Server components, Microsoft Dynamics NAV Setup creates a website for the Microsoft Dynamics NAV Web client on IIS. If IIS is already installed, then make sure that the required features are enabled.

Note
Instead of installing and configuring IIS manually, you can use Microsoft Dynamics NAV Setup to install IIS and enable the required features.

How to: Install and Configure Internet Information Services for Microsoft Dynamics NAV Web Client

Determine the TCP port for the Microsoft Dynamics NAV Web client and allow communication on the port through Windows Firewall.

Microsoft Dynamics NAV Setup creates a website on IIS for the Microsoft Dynamics NAV Web client. During Setup, you will have to choose the port to use for the site. The default port that is used in Microsoft Dynamics NAV Setup is port 8080. If you are not sure of which port to use, then use the default port.

If the computer is running Windows 7 or Windows 8 with Windows Firewall enabled, then you have to create an inbound rule that allows communication on the port.

How to: Create an Inbound Rule in Windows Firewall for the Port of Microsoft Dynamics NAV Web Client

Set up the service account for Microsoft Dynamics NAV Server and the SQL Server database.

Optional. When you install Microsoft Dynamics NAV Server, you can specify a user account that will be used to log on to the Microsoft Dynamics NAV Server instance and Microsoft Dynamics NAV database. The default service account is Network Service. If you want to use Network Service, then no action is required for this task.

Provisioning the Microsoft Dynamics NAV Server Account.

Obtain and install an SSL certificate.

Optional. If you want to configure SSL on the connection to Microsoft Dynamics NAV Web client, then complete the following procedures:

  • Obtain an SSL certificate.

  • Import the certificate into the local computer store of the computer on which you will install the Microsoft Dynamics NAV Web Server components.

  • Obtain the certificate's thumbprint.

Note
You can also configure SSL after you have installed the Microsoft Dynamics NAV Web client. For more information, see Post-installation Tasks.

The following sections in the Walkthrough: Configuring Web Services to Use SSL (SOAP and OData) topic:

  • Obtaining an SSL Certificate

  • Importing the SSL Certificate into the Local Computer Store of the Microsoft Dynamics NAV Server computer

  • Obtaining the Certificate's Thumbprint

Installation Tasks

The following table includes tasks for installing the Microsoft Dynamics NAV Web Server components.

Task | Description | For more information, see
Install Microsoft Dynamics NAV Server and Microsoft Dynamics NAV database components. | On the computer designated for the Microsoft Dynamics NAV Server and the Microsoft Dynamics NAV database, run Microsoft Dynamics NAV Setup. During Setup, choose the Choose an installation option, and then choose the Server and the SQL Server Database Components options. | How to: Run Setup
Install the Microsoft Dynamics NAV Web Server components. | On the web server computer, run Microsoft Dynamics NAV Setup and choose the Web Server Components option. | How to: Install the Web Server Components
Configure delegation from the web server to Microsoft Dynamics NAV Server. | Because Microsoft Dynamics NAV Server is running on a different computer than the Microsoft Dynamics NAV Web Server components, you must configure the computer that is running Microsoft Dynamics NAV Web Server components to delegate its access to Microsoft Dynamics NAV Server on behalf of the device trying to access the Microsoft Dynamics NAV Web client. | How to: Configure Delegation for Microsoft Dynamics NAV Web Client

Post-installation Tasks

The following table includes tasks to configure the Microsoft Dynamics NAV Web Server components after installation. These tasks are optional depending on your organizational and network requirements.

Task | Description | For more information, see
Configure Report Viewer. | To display reports, Microsoft Report Viewer must be configured on website of the Microsoft Dynamics NAV Web client. Report Viewer includes an option that lets users save a report as a Microsoft Excel, Microsoft Word, or PDF file. By default, this option is disabled. You configure Microsoft Report Viewer in the web.config file for the Microsoft Dynamics NAV Web client website. | How to: Configure Microsoft Report Viewer for the Microsoft Dynamics NAV Web Client
Change the user authentication method. | The Microsoft Dynamics NAV Web client supports the same authentication methods as the Microsoft Dynamics NAV Windows client, which include Windows, UserName, NavUserPassword, and AccessControlService. By default, the Microsoft Dynamics NAV Web client uses Windows authentication. | How to: Configure User Authentication for the Microsoft Dynamics NAV Web Client
Secure the connection to the Microsoft Dynamics NAV Web client with SSL. | You can help secure Microsoft Dynamics NAV data that is transmitted over the Internet by enabling Secure Sockets Layer (SSL) on the connection to the Microsoft Dynamics NAV Web client. | How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client
Change Microsoft Dynamics NAV settings of the Microsoft Dynamics NAV Web client. | There are several parameters in the web.config file for the website that is running Microsoft Dynamics NAV Web Server components that you can modify to change the behavior of the Microsoft Dynamics NAV Web client. Some of the more common parameters include the Microsoft Dynamics NAV Server instance, company, language, time zone, regional settings, session time out, and online Help URL. | Configuring Microsoft Dynamics NAV Web Client by Modifying the Web.config File
Set up multiple Microsoft Dynamics NAV Web client applications on a website. | You can set up multiple web server instances for the Microsoft Dynamics NAV Web client on the existing website. The web server instances will use the same address (URL) except with an alias that specifies the specific application. | How to: Set Up Multiple Web Server Instances for the Microsoft Dynamics NAV Web Client
Configure web browsers on devices. | The Microsoft Dynamics NAV Web client supports several different web browsers. To access the Microsoft Dynamics NAV Web client, the web browser must be enabled on a device with cookies and JavaScript. | Configuring the Web Browser for the Microsoft Dynamics NAV Web Client

See Also

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Deploying the Microsoft Dynamics NAV Web Server Components in a Single Computer Environment
Deploying the Microsoft Dynamics NAV Web Server Components in a Three Computer Environment


Walkthrough: Installing the Microsoft Dynamics NAV Web Server Components on Two Computers

In this walkthrough, you will install the tiers of the Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Tablet client in a production environment, where the Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Tablet client is on one computer and Microsoft Dynamics NAV Server and Microsoft SQL Server with Microsoft Dynamics NAV database components are on another computer.

NAV Web client install on two computers

The following table describes the components in this scenario.

Computer Installed operating system and software

NAVSRV-SQL

A supported operating system with the 64-bit edition of a supported version of SQL Server installed.

You will install Microsoft Dynamics NAV database components and Microsoft Dynamics NAV Server on this computer.

Note
If a supported SQL Server product is not already installed on the target computer, then Microsoft Dynamics NAV Setup automatically installs a 64-bit edition of SQL Server 2012 Express.

NAVWEB

A supported operating system.

Internet Information Services 7 or Internet Information Services 8.

Note
Microsoft Dynamics NAV Setup can automatically enable IIS and the IIS features that are required for the Microsoft Dynamics NAV Web client.

You will install the Microsoft Dynamics NAV Web Server components on this computer.

DEVICE

A device with an Internet connection and a web browser.

Note
For a complete list of supported hardware and software, see System Requirements for Microsoft Dynamics NAV 2016.

The key characteristic of this walkthrough is that the Microsoft Dynamics NAV Web Server components and Microsoft Dynamics NAV Server are installed on separate computers. Because of the multiple computers involved when a device tries to access the Microsoft Dynamics NAV Web client over the Internet to manage Microsoft Dynamics NAV data, additional configuration is required to set up this environment compared to an environment where all components are on a single computer.

About This Walkthrough

After completing this walkthrough, you will have a functioning four-tier installation on two computers. The installation uses the CRONUS International Ltd. demonstration database, which contains the CRONUS International Ltd. company. Windows authentication is used for authenticating users who try to access the Microsoft Dynamics NAV Web client.

This walkthrough illustrates the following tasks:

  • Using a domain user account as the service account for Microsoft Dynamics NAV Server and the Microsoft Dynamics NAV database.

  • Installing the Microsoft Dynamics NAV Database Components and Microsoft Dynamics NAV Server

  • Installing the Microsoft Dynamics NAV Web Server Components

  • Configuring Constrained Delegation from the Microsoft Dynamics NAV Web Client to Microsoft Dynamics NAV Server

  • Allowing Inbound Communication to the Microsoft Dynamics NAV Web Client Through the Windows Firewall

  • Opening to the Microsoft Dynamics NAV Web Client

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 installation media. For example, this can be a DVD or a network drive that contains the Microsoft Dynamics NAV 2016 installation files.

  • Two computers that are configured as described in the introduction.

    On the NAVWEB computer, you must enable IIS with the required features for the Microsoft Dynamics NAV Web client. For instructions about how to install Internet Information Services, see How to: Install and Configure Internet Information Services for Microsoft Dynamics NAV Web Client.

    Note
    Instead of installing and configuring IIS manually, you can use Microsoft Dynamics NAV Setup to install IIS and enable the required features, as described in this walkthrough.

  • A domain user account for accessing Microsoft Dynamics NAV Server and Microsoft Dynamics NAV database on the Microsoft SQL Server. The user account must have the following permissions:

    • Permission to log on as a service on the computer where you will install Microsoft Dynamics NAV Server and the computer that is running SQL Server.

    • Permission to register Service Principal Names (SPNs) on itself.

      If the user account does not have this permission, then you must register SPNs for the account manually.

    For information about how to create a domain user account, see Create a New User Account in the TechNet Library. For information about how to enable permission to log on as a service and register SPNs, see Provisioning the Microsoft Dynamics NAV Server Account

    Note
    By default, Microsoft Dynamics NAV Setup uses NETWORK SERVICE as the service account. You can use NETWORK SERVICE instead of a domain user account, but this is considered less secure. If you want to use NETWORK SERVICE, then you do not need this prerequisite.

Story

Viktor is a Microsoft Certified Partner working for CRONUS International Ltd. He has been tasked with deploying Microsoft Dynamics NAV Web client for a customer. Viktor is a Microsoft Certified Partner working for CRONUS International Ltd. He has been tasked with deploying Microsoft Dynamics NAV Web client for customer. To meet the customer's requirements, Viktor has decided to deploy the Microsoft Dynamics NAV Web client as follows:

  • Install the Microsoft Dynamics NAV Web Server components on one computer, and install Microsoft Dynamics NAV Server and SQL server with Microsoft Dynamics NAV database components on another computer.

  • Install the Microsoft Dynamics NAV Web Server components on HTTP port 8080.

  • Use a domain user account instead of the Network Service account as the service account for Microsoft Dynamics NAV Server.

  • Use Windows Authentication to authenticate users.

Installing the Microsoft Dynamics NAV Database Components and Microsoft Dynamics NAV Server

In this procedure, you run Microsoft Dynamics NAV 2016 Setup to install the SQL Server Database components for Microsoft Dynamics NAV, including the CRONUS International Ltd. demonstration database, and Microsoft Dynamics NAV Server. During setup, you will assign the domain user account as the service account for the database.

Note
If you already have an existing Microsoft Dynamics NAV Server and Microsoft Dynamics NAV database that you want to use for the Microsoft Dynamics NAV Web client, you can skip this procedure.

To install the Microsoft Dynamics NAV database components and Microsoft Dynamics NAV Server

  1. On the NAVSRV-SQL computer, access the Microsoft Dynamics NAV installation media.

  2. Run the setup.exe file to start the Microsoft Dynamics NAV Setup wizard.

  3. On the Welcome to Microsoft Dynamics NAV 2016 Setup page, choose the Next button.

  4. To accept the license terms, choose I accept.

  5. On the Microsoft Dynamics NAV Setup page, choose Choose an installation option.

  6. On the Choose an installation option page, under the Server option, choose Customize.

  7. On the Customize the installation page, select SQL Server Database Components, and then select Run all from my computer.

    This specifies that you want to install this component and all subcomponents. In this case, there is a single subcomponent, which is the CRONUS International Ltd. demonstration database.

    Note
    The Server option, which installs Microsoft Dynamics NAV Server, is automatically chosen.

  8. Choose the Next button to proceed to the Specify parameters page.

    The Specify parameters page contains many parameters that you can configure, but default parameters are provided for all except Server Account and SQL Server.

  9. Set the Server account to the domain user account that you created for the Microsoft Dynamics NAV database and Microsoft Dynamics NAV Server.

  10. In the SQL Server box, type localhost to specify the computer that you are working on.

  11. If you have an existing database for Microsoft Dynamics NAV on the computer, and you want to replace it with the CRONUS International Ltd. demonstration database, then set the Replace Existing Database box to Yes.

  12. Choose the Apply button.

    Setup installs the components.

  13. After the installation is complete, choose the Close button.

Installing the Microsoft Dynamics NAV Web Server Components

In this procedure, you use Microsoft Dynamics NAV 2016 Setup to install the Microsoft Dynamics NAV Web Server components on the NAVWEB computer.

To install Microsoft Dynamics NAV Web Server components by using Setup

  1. On the NAVWEB computer, access the Microsoft Dynamics NAV installation media.

  2. Run the setup.exe file to start the Microsoft Dynamics NAV Setup wizard.

  3. Choose the Next button.

  4. To accept the license terms, choose I accept.

  5. On the Microsoft Dynamics NAV Setup page, choose Choose an installation option.

  6. On the Choose an Installation Option page, choose Custom.

  7. On the Customize the Installation page, select NAV Web Server Components, and then choose Run from My Computer.

  8. Choose the Next button to go to the Specify Parameters page.

  9. On the Specify parameters page, in the Server Name box, type the name of the computer that is running Microsoft Dynamics NAV Server, in this case, NAVSRV.

  10. In the Web Server Components section, set the Port field to 8080.

  11. Set the Install IIS prerequisites parameter to Install.

    This enables the IIS features that are required for the Microsoft Dynamics NAV Web client on the computer. For more information about this parameter, see Using Microsoft Dynamics NAV Setup to Install IIS Features.

  12. Choose the Apply button to complete the installation.

  13. When Setup is finished, choose the Close button.

A website that has the name Microsoft Dynamics NAV 2016 Web Client has been installed on IIS. The website uses port 8080. A website that has the name Microsoft Dynamics NAV 2016 Web Client has been installed on IIS. The website includes a web server instance for Microsoft Dynamics NAV Web client that has the name DynamicsNAV90. The default physical path of the web server instance is C:\inetpub\wwwroot\DynamicsNAV90\.

Configuring Constrained Delegation from the Microsoft Dynamics NAV Web Client to Microsoft Dynamics NAV Server

When the client device, Microsoft Dynamics NAV Web Server components, and Microsoft Dynamics NAV Server are on separate computers, the client device interacts with Microsoft Dynamics NAV Server through the computer that is running Microsoft Dynamics NAV Web Server components. The computer that is running Microsoft Dynamics NAV Web Server components is performing actions on the client device's behalf. This process is known as impersonation. Impersonation cannot be used across multiple computers, so you must set up delegation from the computer that is running Microsoft Dynamics NAV Web Server components to Microsoft Dynamics NAV Server.

To configure delegation, you must perform two tasks. First, you delegate access from the computer that is running Microsoft Dynamics NAV Web client to the computer that is running Microsoft Dynamics NAV Server. Second, you configure the kernel mode authentication for the Microsoft Dynamics NAV Web client.

Delegating Access from the Web Server to Microsoft Dynamics NAV Server

Configuring delegation means explicitly configuring the computer that is running Microsoft Dynamics NAV Web Server components (NAVWEB) to delegate its access to the Microsoft Dynamics NAV Server (NAVSRV-SQL) on behalf of the device (DEVICE) that is trying to connect to Microsoft Dynamics NAV. To make the access more secure, you specify delegation to a specific service on a specific server. This is known as constrained delegation.

Note
You must run the following procedure on a domain controller computer or a computer that is installed with Active Directory Domain Services tools.

To delegate access to Microsoft Dynamics NAV Server

  1. On the domain controller computer for your network, or a computer that is installed with Active Directory Domain Services tools, choose Start, and then choose Run.

  2. In the Open field, type dsa.msc.

    This opens the Active Directory Users and Computers utility.

  3. Expand the node for the domain where you have installed the Microsoft Dynamics NAV environment. For this example, the domain in the walkthrough is Corp.

  4. Select the Computers node, right-click the NAVWEB computer, and then choose Properties.

  5. On the Delegation tab, choose Trust this user for delegation to specified services only, and then choose Use Kerberos only.

  6. You must add the following service entries for the computer that is running Microsoft Dynamics NAV Server, which in this walkthrough is NAVSRV-SQL.

    Service type User or computer Port

    DynamicsNAV

    NAVSRV-SQL

    7046

    DynamicsNAV

    NAVSRV-SQL.corp

    7046

    HOST

    NAVSRV-SQL

    HOST

    NAVSRV-SQL.corp

  7. To add the services, select Expanded, and then choose Add.

  8. In the Add Services window, choose Users or Computers.

  9. In the Enter the object names to select box, type the name of the computer that is running Microsoft Dynamics NAV Server, in this case NAVSRV-SQL, and then choose the OK button.

  10. In the list of available services, press and hold the Ctrl key, select DynamicsNAV for port 7046 and HOST, and then choose the OK button.

  11. Choose the OK button to close the dialog box.

Configuring Kernel Mode Authentication

By default, Windows authentication in IIS is set to use kernel mode authentication. Kernel-mode authentication improves authentication performance. However, when you use delegation with Kerberos, you must either disable kernel mode or configure it to use the credentials of the application pool of Microsoft Dynamics NAV Web client. Otherwise, authentication will fail and Microsoft Dynamics NAV Web client will not be able to connect to Microsoft Dynamics NAV Server. This is because kernel mode authentication runs under the computer account of the computer that is running Microsoft Dynamics NAV Web Server components, while the Microsoft Dynamics NAV Web client runs under the user account of the user trying to access Microsoft Dynamics NAV.

As a best practice, you should configure kernel mode authentication to use the application pool credentials as described in this walkthrough.

To configure kernel mode authentication to use the application pool credentials

  1. On the NAVWEB computer, using a text editor such as Notepad, open the applicationHost.config file for IIS. By default, the file is located in the c:\Windows\System32\inetsrv folder.

  2. Locate the <location path="Microsoft Dynamics NAV 2013 Web Client"> element.

  3. Change the <windowsAuthentication enabled="true"> element to the following.

    Copy Code
    <windowsAuthentication enabled="true" useAppPoolCredentials="true" />

  4. Save the file.

  5. Restart IIS. To restart IIS in a command prompt, do the following:

    1. On the Start menu, choose Run.

    2. In the Open box, type cmd, and then choose the OK button.

    3. At the command prompt, type iisreset, and then press Enter.

    Tip
    You can also restart IIS using Internet Information Services Manager, if you have it installed.

Allowing Inbound Communication on the Microsoft Dynamics NAV Web Client Port Through the Windows Firewall

By default, the Microsoft Dynamics NAV Web client is configured for communication on port 8080 of the computer. This port is typically blocked by Windows Firewall. To allow communication to the Microsoft Dynamics NAV Web client from client devices, you must create an inbound rule on the port 8080 in the Windows Firewall setup.

Note
You do not have to perform this task if the computer is running Windows Server 2012 because communication on the port is automatically allowed by Windows Firewall.

To create an inbound rule on the port that is used by Microsoft Dynamics NAV Web client

  1. On the NAVWEB computer, on the Start menu, choose Control Panel, choose System and Security, and then choose Windows Firewall.

  2. In the navigation pane, choose Advanced settings.

  3. In the Windows Firewall with Advanced Settings window, in the navigation pane, choose Inbound Rules, and then in the Actions pane, choose New Rule.

  4. On the Rule Type page, choose Port, and then choose the Next button.

  5. On the Protocol and Ports page, choose Specific local ports, and then type a port number in the box. For example, type 8080 for the default port of the Microsoft Dynamics NAV Web client.

  6. Choose the Next button.

  7. On the Action page, choose Allow the connection, and then choose the Next button.

  8. On the Profile page, choose the profiles, and then choose the Next button.

  9. On the Name page, type a name for the rule, and then choose the Finish button.

Opening the Microsoft Dynamics NAV Web client

You can open the Microsoft Dynamics NAV Web client from a device with a supported web browser.

To open the Microsoft Dynamics NAV Web client

  1. Open the web browser.

  2. In the address box, type the following URL:

    http://ComputerName:PortNumber/DynamicsNAV90/WebClient/Default.aspx

    • Substitute ComputerName with the name of the computer that is running the Microsoft Dynamics NAV Web Server components.

    • Substitute PortNumber with the port that you configured for the Microsoft Dynamics NAV Web Server components during Setup.

    • Substitute DynamicsNAV90 with the name of the Microsoft Dynamics NAV Server instance that you configured during Setup. DynamicsNAV90 is the default value.

    For this walkthrough, you would use the following URL:

    Copy Code
    http://navweb:8080/DynamicsNAV90/WebClient/Default.aspx

Troubleshooting

If you are cannot connect the Microsoft Dynamics NAV Web client or you are experiencing problems, see Troubleshooting the Microsoft Dynamics NAV Web Client Installation.

Next Steps

The following is a list of typical tasks to perform after you install Microsoft Dynamics NAV Web client.

  • Secure the connection to Microsoft Dynamics NAV Web client using SSL. For more information, see How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client.

  • Upload your license. For more information, see How to: Upload the License File.

  • Create users and integrate them into the Microsoft Dynamics NAV security system. For more information, see Managing Users.

See Also

Tasks

Walkthrough: Installing the Microsoft Dynamics NAV Web Server Components on Three Computers
Walkthrough: Installing the Microsoft Dynamics NAV Web Server Components on a Single Computer

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Deploying the Microsoft Dynamics NAV Web Server Components in a Two Computer Environment
Microsoft Dynamics NAV Web Client Network Architecture
Configuring Microsoft SQL Server
Configuring Microsoft Dynamics NAV Server


Deploying the Microsoft Dynamics NAV Web Server Components in a Three Computer Environment

In this scenario, you install the Microsoft Dynamics NAV Web Server components, Microsoft Dynamics NAV Server, and the SQL Server database components on separate computers.

NAV Web client installation on three computers

Tip
For a step-by-step example that describes how to deploy this scenario, see Walkthrough: Installing the Microsoft Dynamics NAV Web Server Components on Three Computers.

Deployment Tasks

To deploy the Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Tablet client in this scenario, complete the following tasks.

Pre-Installation Tasks

The following table includes tasks to perform before you install the Microsoft Dynamics NAV Web Server components.

Task Description For more information, see

Make sure that system requirements are met.

Verify that the computer has the required hardware and software installed.

System Requirements for Microsoft Dynamics NAV 2016

Install Internet Information Services 7.0 or Internet Information Services 8.0.

When you install the Microsoft Dynamics NAV Web Server components, Microsoft Dynamics NAV Setup creates a website for the Microsoft Dynamics NAV Web client on IIS. If IIS is already installed, then make sure that the required features are enabled.

Note
Instead of installing and configuring IIS manually, you can use Microsoft Dynamics NAV Setup to install IIS and enable the required features.

How to: Install and Configure Internet Information Services for Microsoft Dynamics NAV Web Client

Determine the TCP port for the Microsoft Dynamics NAV Web client and allow communication on the port through Windows Firewall.

Microsoft Dynamics NAV Setup creates a website on IIS for the Microsoft Dynamics NAV Web client. During Setup, you will have to choose the port to use for the site. The default port that is used in Microsoft Dynamics NAV Setup is port 8080. If you are not sure of which port to use, then use the default port.

If the computer is running Windows 7 or Windows 8 with Windows Firewall enabled, then you have to create an inbound rule that allows communication on the port.

How to: Create an Inbound Rule in Windows Firewall for the Port of Microsoft Dynamics NAV Web Client

Set up the service account for Microsoft Dynamics NAV Server and the SQL Server database.

Optional. When you install Microsoft Dynamics NAV Server, you can specify a user account that will be used to log on to the Microsoft Dynamics NAV Server instance and Microsoft Dynamics NAV database. The default service account is Network Service. If you want to use Network Service, then no action is required for this task.

Provisioning the Microsoft Dynamics NAV Server Account.

Obtain and install an SSL certificate.

Optional. If you want to configure SSL on the connection to Microsoft Dynamics NAV Web client, then complete the following procedures:

  • Obtain an SSL certificate.

  • Import the certificate into the local computer store of the computer on which you will install the Microsoft Dynamics NAV Web Server components.

  • Obtain the certificate's thumbprint.

Note
You can also configure SSL after you have installed the Microsoft Dynamics NAV Web client. For more information, see Post-installation Tasks.

The following sections in the Walkthrough: Configuring Web Services to Use SSL (SOAP and OData) topic:

  • Obtaining an SSL Certificate

  • Importing the SSL Certificate into the Local Computer Store of the Microsoft Dynamics NAV Server computer

  • Obtaining the Certificate's Thumbprint

Installation Tasks

The following table includes tasks for installing the Microsoft Dynamics NAV Web client.

Task | Description | For more information, see
Install the Microsoft Dynamics NAV database components. | On the computer designated for SQL Server, run Microsoft Dynamics NAV Setup and choose the SQL Server Database Components option. | How to: Run Setup
Start the SQL Server Browser Service on the SQL Server computer. | This task is only required if you are using a named database instance for Microsoft Dynamics NAV. By default, Microsoft Dynamics NAV uses the database instance named NAVDEMO. The SQL Server Browser Service is required so that the database instance can be discovered by the Microsoft Dynamics NAV Server instance, which in this scenario, is another computer. To start the SQL Server, use SQL Server Configuration Manager. | How to: Start SQL Browser Service
Install Microsoft Dynamics NAV Server. | On the computer designated for the Microsoft Dynamics NAV Server, run Microsoft Dynamics NAV Setup and choose the Server option. | How to: Run Setup
Install the Microsoft Dynamics NAV Web Server components. | On the web server computer, run Microsoft Dynamics NAV Setup and choose the Web Server Components option. | How to: Install the Web Server Components
Configure delegation from the web server to Microsoft Dynamics NAV Server. | Because Microsoft Dynamics NAV Server is running on a different computer than the Microsoft Dynamics NAV Web Server components, you must configure computer running Microsoft Dynamics NAV Web Server components to delegate its access to Microsoft Dynamics NAV Server on behalf of the device trying to access the Microsoft Dynamics NAV Web client. | How to: Configure Delegation for Microsoft Dynamics NAV Web Client

Post-installation Tasks

The following table includes tasks that configure the Microsoft Dynamics NAV Web Server components after installation. These tasks are optional depending on your organizational and network requirements.

Task | Description | For more information, see
Configure Report Viewer. | To display reports, Microsoft Report Viewer must be configured on a website of the Microsoft Dynamics NAV Web client. Report Viewer includes an option that lets users save a report as a Microsoft Excel, Microsoft Word, or PDF file. By default, this option is disabled. You configure Microsoft Report Viewer in the web.config file for the Microsoft Dynamics NAV Web client website. | How to: Configure Microsoft Report Viewer for the Microsoft Dynamics NAV Web Client
Change the user authentication method. | The Microsoft Dynamics NAV Web client supports the same authentication methods as the Microsoft Dynamics NAV Windows client, which include Windows, UserName, NavUserPassword, and AccessControlService. By default, the Microsoft Dynamics NAV Web client uses Windows authentication. | How to: Configure User Authentication for the Microsoft Dynamics NAV Web Client
Secure the connection to the Microsoft Dynamics NAV Web client with SSL. | You can help secure Microsoft Dynamics NAV data that is transmitted over the Internet by enabling Secure Sockets Layer (SSL) on the connection to the Microsoft Dynamics NAV Web client. | How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client
Change Microsoft Dynamics NAV settings of the Microsoft Dynamics NAV Web client. | There are several parameters in the web.config file for the website that is running Microsoft Dynamics NAV Web Server components that you can modify to change the behavior of the Microsoft Dynamics NAV Web client. Some of the more common parameters include the Microsoft Dynamics NAV Server instance, company, language, time zone, regional settings, session time out, and online Help URL. | Configuring Microsoft Dynamics NAV Web Client by Modifying the Web.config File
Set up multiple Microsoft Dynamics NAV Web client applications on a website. | You can set up multiple web server instances for the Microsoft Dynamics NAV Web client on the existing website. The web server instances will use the same address (URL) except with an alias that specifies the specific application. | How to: Set Up Multiple Web Server Instances for the Microsoft Dynamics NAV Web Client
Configure web browsers on devices. | The Microsoft Dynamics NAV Web client supports several different web browsers. To access the Microsoft Dynamics NAV Web client, the web browser must be enabled on a device with cookies and JavaScript. | Configuring the Web Browser for the Microsoft Dynamics NAV Web Client

See Also

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Deploying the Microsoft Dynamics NAV Web Server Components in a Single Computer Environment
Deploying the Microsoft Dynamics NAV Web Server Components in a Two Computer Environment


Walkthrough: Installing the Microsoft Dynamics NAV Web Server Components on Three Computers

In this walkthrough, you will install Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Tablet client in a four tier production environment, with the Microsoft Dynamics NAV Web client, Microsoft Dynamics NAV Server, and Microsoft SQL Server with Microsoft Dynamics NAV database components on three separate computers as shown in the following illustration.

NAV Web client setup on four tiers

Computer Installed operating system and software

NAVSQL

A supported operating system with the 64-bit edition of a supported version of SQL Server installed.

You will install Microsoft Dynamics NAV database components on this computer.

Note
If SQL Server is not present, then Setup automatically installs the 64-bit edition of SQL Server Express 2012, which you can use for prototyping, developing, and testing. We recommend that you use SQL Server 2008 R2 in production environments. For more information, see Installation Considerations for Microsoft SQL Server.

NAVSERVER

A supported operating system.

You will install Microsoft Dynamics NAV Server on this computer.

NAVWEB

A supported operating system.

Internet Information Services 7 or Internet Information Services 8.

Note
Microsoft Dynamics NAV Setup can automatically enable IIS and the IIS features that are required for the Microsoft Dynamics NAV Web client.

You will install the Microsoft Dynamics NAV Web Server components on this computer.

DEVICE

A device with an Internet connection and a supported browser. For a list of supported browsers, see System Requirements for Microsoft Dynamics NAV 2016.

Note
For a complete list of supported hardware and software, see System Requirements for Microsoft Dynamics NAV 2016.

The key characteristic of this walkthrough is that the Microsoft Dynamics NAV Web Server components and Microsoft Dynamics NAV Server are installed on separate computers. Because of the multiple computers involved when a device tries to access the Microsoft Dynamics NAV Web client over the Internet to manage Microsoft Dynamics NAV data, additional configuration is required to set up this environment compared to an environment where all components are on a single computer.

About This Walkthrough

After completing this walkthrough, you will have a functioning four-tier installation on three computers. The installation uses the CRONUS International Ltd. demonstration database, which contains the CRONUS International Ltd. company. Windows authentication is used for authenticating users who try to access the Microsoft Dynamics NAV Web client.

This walkthrough illustrates the following tasks:

  • Using a domain user account as the service account for Microsoft Dynamics NAV Server and the Microsoft Dynamics NAV database.

  • Installing the Microsoft Dynamics NAV Database Components

  • Starting the SQL Server Browser Service on the SQL Server

  • Installing Microsoft Dynamics NAV Server

  • Installing the Microsoft Dynamics NAV Web Server Components

  • Configuring Constrained Delegation from the Microsoft Dynamics NAV Web Client to Microsoft Dynamics NAV Server

  • Allowing Inbound Communication on the Microsoft Dynamics NAV Web Client Port Through the Windows Firewall

  • Opening the <token xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">nav_web</token>

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 installation media. For example, this can be a DVD or a network drive that contains the Microsoft Dynamics NAV 2016 installation files.

  • Three computers that are configured as described in the introduction.

    On the NAVWEB computer, you must enable IIS with the required features for the Microsoft Dynamics NAV Web client. For instructions about how to install Internet Information Services, see How to: Install and Configure Internet Information Services for Microsoft Dynamics NAV Web Client.

    Note
    Instead of installing and configuring IIS manually, you can use Microsoft Dynamics NAV Setup to install IIS and enable the required features, as described in this walkthrough.

  • A domain user account for accessing Microsoft Dynamics NAV Server and Microsoft Dynamics NAV database on the Microsoft SQL Server. The user account must have the following permissions:

    • Permission to log on as a service on the computer where you will install Microsoft Dynamics NAV Server and the computer that is running SQL Server.

    • Permission to register Service Principal Names (SPNs) on itself.

      If the user account does not have this permission, then you must register SPNs for the account manually.

    For information about how to create a domain user account, see Create a New User Account in the TechNet Library. For information about how to enable permission to log on as a service and register SPNs, see Provisioning the Microsoft Dynamics NAV Server Account.

    Note
    By default, Microsoft Dynamics NAV Setup uses NETWORK SERVICE as the service account. You can use NETWORK SERVICE instead of a domain user account, but this is considered less secure. If you want to use NETWORK SERVICE, then you do not need this prerequisite.

Story

Viktor is a Microsoft Certified Partner working for CRONUS International Ltd. He has been tasked with deploying Microsoft Dynamics NAV Web client for customer. To meet the customer's network needs and requirements, Viktor will install the Microsoft Dynamics NAV Web client, Microsoft Dynamics NAV Server, and SQL server with Microsoft Dynamics NAV database components on separate computers. For security reasons, he will use a domain user account instead of the Network Service account as the service account for Microsoft Dynamics NAV Server. He will configure the environment to authenticate users who are using Windows Authentication.

Installing the Microsoft Dynamics NAV Database Components

In this procedure, you run Microsoft Dynamics NAV 2016 Setup to install the SQL Server Database components for Microsoft Dynamics NAV, including the CRONUS International Ltd. demonstration database. During setup, you will assign the domain user account as the service account for the database.

Note
If you already have an existing Microsoft Dynamics NAV database that you want to use, you can skip this procedure.

To install the Microsoft Dynamics NAV database components and the demo database

  1. On the NAVSQL computer, access the Microsoft Dynamics NAV installation media.

  2. Double-click the setup.exe file to start the Microsoft Dynamics NAV Setup wizard.

  3. On the Welcome to Microsoft Dynamics NAV 2016 Setup page, choose Next.

  4. To accept the license terms, choose I accept.

  5. On the Microsoft Dynamics NAV Setup page, choose Choose an installation option.

  6. On the Choose an installation option page, choose Custom.

  7. On the Customize the installation page, select SQL Server Database Components box, and then select Run all from my computer.

    This specifies that you want to install this component and all subcomponents. In this case, there is a single subcomponent, which is the CRONUS International Ltd. demonstration database.

  8. Choose Next.

  9. On the Specify parameters page, set the Server account to the domain user account that you created for and the Microsoft Dynamics NAV database and Microsoft Dynamics NAV Server.

  10. In the SQL Database box, type a name for the Microsoft Dynamics NAV database. For this walkthrough, type Demo Database NAV (9-0).

    You can keep the default values for the other parameters.

  11. Choose Apply.

    Setup installs the database components.

  12. After the installation is complete, choose Close.

A database instance that is named NAVDEMO has been created on the SQL Server. The database instance includes the Demo Database NAV (9-0) database.

Starting the SQL Server Browser Service on the SQL Server

When you installed the Microsoft Dynamics NAV database components, the CRONUS International Ltd. demonstration database was installed on a database instance named NAVDEMO. Because you are using a named database instance and Microsoft Dynamics NAV Server is on a separate computer, you must enable and run the SQL Server Browser Service on the SQL Server to ensure the Microsoft Dynamics NAV Server can connect to the database instance.

To start SQL Server Browser Service

  1. On the NAVSQL computer, to run the SQL Server Configuration Manage, do the following.

    1. Open SQL Server Configuration Manager.

  2. In SQL Server Configuration Manager, in the navigation pane on the left side, choose SQL Server Service.

  3. Right-click SQL Server Browser, and then choose Properties.

  4. On the Services tab of the SQL Server Browser dialog box, set the Start mode to Automatic.

  5. Choose OK to return to the SQL Server Configuration Manager main page.

  6. Right-click SQL Server Browser again, and then choose Start.

Installing Microsoft Dynamics NAV Server

In this procedure, you use Microsoft Dynamics NAV 2016 Setup to install Microsoft Dynamics NAV Server on the NAVSERVER computer. During setup, you will assign the domain user account as the service account for Microsoft Dynamics NAV Server.

Note
If you already have a Microsoft Dynamics NAV Server that you want to connect to, you can skip this procedure.

To install Microsoft Dynamics NAV Server

  1. On the NAVSERVER computer, access the Microsoft Dynamics NAV installation media.

  2. Double-click the setup.exe file to start the Microsoft Dynamics NAV Setup wizard.

  3. On the Welcome to Microsoft Dynamics NAV 2016 Setup page, choose Next.

  4. To accept the license terms, choose I accept.

  5. On the Microsoft Dynamics NAV Setup page, choose Choose an installation option.

  6. On the Choose an installation option page, choose Server.

  7. On the Specify parameters page, in the Server section, set the Server Account parameter to the domain user account that you created for Microsoft Dynamics NAV Server.

  8. In the Account password parameter, type the password for the domain user account.

  9. In the SQL Server Database Components section, set the following parameters for the Microsoft Dynamics NAV database.

    Parameter Value

    SQL Server

    NAVSQL

    SQL Server Instance

    NAVDEMO

    SQL Database

    Demo Database NAV (9-0)

    Note
    Substitute the values in the table with the values for your installation as needed.

  10. Default values are sufficient for all other parameters. Choose Apply to save your setting information. Setup installs the components.

  11. After the installation is complete, choose Close.

Installing the Microsoft Dynamics NAV Web Server Components

In this procedure, you use Microsoft Dynamics NAV 2016 Setup to install the Microsoft Dynamics NAV Web Server components to the NAVWEB computer.

To install Microsoft Dynamics NAV Web Server Components with Setup

  1. On the NAVWEB computer, access the Microsoft Dynamics NAV installation media.

  2. Double-click the setup.exe file to start the Microsoft Dynamics NAV Setup wizard.

  3. Choose Next.

  4. To accept the license terms, choose I accept.

  5. On the Microsoft Dynamics NAV Setup page, choose Choose an installation option.

  6. On the Choose an Installation Option page, choose Custom.

  7. On the Customize the Installation page, select NAV Web Server Components, and then select Run from My Computer.

  8. Choose Next to go to the Specify Parameters page.

  9. On the Specify parameters page, in the Server Name box, type the name of the computer that is running Microsoft Dynamics NAV Server, in this case, NAVSRV.

  10. In the Web Server Components section, set the Port field to 8080.

  11. Set the Install IIS prerequisites parameter to Install.

    This enables the IIS features that are required for the Microsoft Dynamics NAV Web client on the computer. For more information about this parameter, see Using Microsoft Dynamics NAV Setup to Install IIS Features.

  12. Choose Apply to complete the installation.

  13. When Setup is finished, choose Close.

    A website that has the name Microsoft Dynamics NAV 2016 Web Client has been installed on IIS. The website uses port 8080. A website that has the name Microsoft Dynamics NAV 2016 Web Client has been installed on IIS. The website includes a web server instance for Microsoft Dynamics NAV Web client that has the name DynamicsNAV90. The default physical path of the web server instance is C:\inetpub\wwwroot\DynamicsNAV90\.

Configuring Constrained Delegation from the Microsoft Dynamics NAV Web Client to Microsoft Dynamics NAV Server

When the client device, Microsoft Dynamics NAV Web Server components, and Microsoft Dynamics NAV Server are on separate computers, the client device interacts with Microsoft Dynamics NAV Server through the computer that is running Microsoft Dynamics NAV Web client. The computer that is running Microsoft Dynamics NAV Web Server components is performing actions on the client device's behalf. This process is known as impersonation. Impersonation cannot be used across multiple computers, so you must set up delegation from the computer that is running Microsoft Dynamics NAV Web Server components to Microsoft Dynamics NAV Server.

To configure delegation, you must perform two tasks. First, you delegate access from the computer that is running Microsoft Dynamics NAV Web client to the computer that is running Microsoft Dynamics NAV Server. Second, you configure the kernel mode authentication for the Microsoft Dynamics NAV Web client.

Delegating Access from the Web Server to Microsoft Dynamics NAV Server

Configuring delegation means explicitly configuring the computer that is running Microsoft Dynamics NAV Web Server components (NAVWEB) to delegate its access to the Microsoft Dynamics NAV Server (NAVSERVER) on behalf of the device (CLIENT) that is trying to connect to Microsoft Dynamics NAV. To make the access more secure, you specify delegation to a specific service on a specific server. In this walkthrough, you specify delegation on the DynamicsNAV90 service on NAVSERVER. This is known as constrained delegation.

Note
You must run the following procedure on a domain controller computer or a computer that is installed with Active Directory Domain Services tools.

To delegate access to Microsoft Dynamics NAV Server

  1. On the domain controller computer for your network, or a computer that is installed with Active Directory Domain Services tools, choose Start, and then choose Run.

  2. In the Open field, type dsa.msc.

    This opens the Active Directory Users and Computers utility.

  3. Expand the node for the domain where you have installed the Microsoft Dynamics NAV environment. For this example, the domain in the walkthrough is Corp.

  4. Select the Computers node, right-click the NAVWEB computer, and then choose Properties.

  5. On the Delegation tab, choose Trust this user for delegation to specified services only, and then choose Use Kerberos only.

  6. You must add the following service entries for the computer that is running Microsoft Dynamics NAV Server, which in this walkthrough is NAVSERVER.

    Service type User or computer Port

    DynamicsNAV

    NAVSERVER

    7046

    DynamicsNAV

    NAVSERVER.corp

    7046

    HOST

    NAVSERVER

    HOST

    NAVSERVER.corp

  7. To add the HOST service, select Expanded, and then choose Add.

  8. In the Add Services window, choose Users or Computers.

  9. In the Enter the object names to select box, type the name of the computer that is running Microsoft Dynamics NAV Server, in this case NAVSERVER, and then choose the OK button.

  10. In the list of available services, select HOST, and then choose the OK button.

  11. To add the DynamicsNAV service, select Expanded, and then choose Add.

  12. In the Enter the object names to select box, type the name of the user that is running the Microsoft Dynamics NAV Server, and then choose the OK button.

  13. Choose the OK button to close the dialog box.

Configuring Kernel Mode Authentication

By default, Windows authentication on the Microsoft Dynamics NAV Web client in IIS is set to use kernel mode authentication. Kernel-mode authentication improves authentication performance. However, when you use delegation with Kerberos, you must either disable kernel mode or configure it to use the credentials of the application pool of Microsoft Dynamics NAV Web client. Otherwise, authentication will fail and Microsoft Dynamics NAV Web client will not be able to connect to Microsoft Dynamics NAV Server. This is because kernel mode authentication runs under the computer account of the computer that is running Microsoft Dynamics NAV Web Server components, while the Microsoft Dynamics NAV Web client runs under the user account of the user trying to access Microsoft Dynamics NAV.

As best practice, you should configure kernel mode authentication to use the application pool credentials, as described in this walkthrough.

To configure kernel mode authentication to use the application pool credentials

  1. On the NAVWEB computer, using a text editor such as Notepad, open the applicationHost.config file for IIS. By default, the file is located in the c:\Windows\System32\inetsrv folder.

  2. Locate the <location path="Microsoft Dynamics NAV 2016 Web Client"> element.

  3. Change the <windowsAuthentication enabled="true"> element to the following.

    Copy Code
    <windowsAuthentication enabled="true" useAppPoolCredentials="true" />

  4. Save the file.

  5. Restart IIS. To restart IIS in a command prompt, do the following:

    1. On the Start menu, choose Run.

    2. In the Open box, type cmd, and then choose the OK button.

    3. At the command prompt, type iisreset, and then press Enter.

    Tip
    You can also restart IIS using Internet Information Services Manager, if you have it installed.

Allowing Inbound Communication on the Microsoft Dynamics NAV Web Client Port Through the Windows Firewall

By default, the Microsoft Dynamics NAV Web client is configured for communication on port 8080 of the computer. This port is typically blocked by Windows Firewall. To allow communication to the Microsoft Dynamics NAV Web client from client devices, you must create an inbound rule on the port 8080 in the Windows Firewall setup.

Note
You do not have to perform this task if the computer is running Windows Server 2012 because communication on the port is automatically allowed by Windows Firewall.

To create an inbound rule on port that is used by Microsoft Dynamics NAV Web client

  1. On the NAVWEB computer, on the Start menu, choose Control Panel, choose System and Security, and then choose Windows Firewall.

  2. In the navigation pane, choose Advanced settings.

  3. In the Windows Firewall with Advanced Settings window, in the navigation pane, choose Inbound Rules, and then in the Actions pane, choose New Rule.

  4. On the Rule Type page, choose Port, and then choose Next.

  5. On the Protocol and Ports page, choose Specific local ports, and then type a port number in the box. For example, type 8080 for the default port of the Microsoft Dynamics NAV Web client.

  6. Choose Next.

  7. On the Action page, choose Allow the connection, and then choose Next.

  8. On the Profile page, choose the profiles, and then choose Next.

  9. On the Name page, type a name for the rule, and then choose Finish.

Opening the Microsoft Dynamics NAV Web client

You can open the Microsoft Dynamics NAV Web client on a device with a supported web browser.

To open the Microsoft Dynamics NAV Web client

  1. Open the web browser.

  2. In the address box, type the following URL:

    http://ComputerName:PortNumber/DynamicsNAV90/WebClient/Default.aspx

    • Substitute ComputerName with the name of the computer that is running the Microsoft Dynamics NAV Web Server components.

    • Substitute PortNumber with the port that you configured for the Microsoft Dynamics NAV Web Server components during Setup.

    • Substitute DynamicsNAV90 with the name of the Microsoft Dynamics NAV Server instance that you configured during Setup. DynamicsNAV90 is the default value.

    For this walkthrough, you would use the following URL:

    Copy Code
    http://navweb:8080/DynamicsNAV90/WebClient/Default.aspx

Troubleshooting

If you are cannot connect the Microsoft Dynamics NAV Web client or you are experiencing problems, see Troubleshooting the Microsoft Dynamics NAV Web Client Installation.

Next Steps

The following is a list of typical tasks to perform after you install Microsoft Dynamics NAV Web client.

  • Secure the connection to Microsoft Dynamics NAV Web client using SSL. For more information, see How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client.

  • Upload your license. For more information, see How to: Upload the License File.

  • Create users and integrate them into the Microsoft Dynamics NAV security system. For more information, see Managing Users.

See Also

Tasks

Walkthrough: Installing the Microsoft Dynamics NAV Web Server Components on a Single Computer

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Deploying the Microsoft Dynamics NAV Web Server Components in a Three Computer Environment
Microsoft Dynamics NAV Web Client Network Architecture
Configuring Microsoft SQL Server
Configuring Microsoft Dynamics NAV Server


How to: Install the Web Server Components

To deploy the Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Tablet client, you install the Microsoft Dynamics NAV Web Server components on a computer that is running Internet Information Services (IIS). To access the Microsoft Dynamics NAV Web client, you must have a web browser and a network connection to a Microsoft Dynamics NAV Server instance that connects to a Microsoft Dynamics NAV database. The following illustration shows the components involved in the setup.

Install NAV Web client on same computer as server

You can install Microsoft Dynamics NAV Web Server components on the same computer as the Microsoft Dynamics NAV Server or on a separate computer.

Note
You do not need a Microsoft Dynamics NAV Server instance or SQL Server database to install the Microsoft Dynamics NAV Web Server components. You can install these components separately and then later configure the Microsoft Dynamics NAV Web Server components to use them.

Prerequisites

  • Microsoft Dynamics NAV 2016 installation media. For example, this could be a DVD or network drive that contains the Microsoft Dynamics NAV 2016 installation files.

  • Verify that the system requirements are met on the computer that you want to install Microsoft Dynamics NAV Web Server components. For more information, see System Requirements for Microsoft Dynamics NAV 2016.

  • Install Internet Information Services 7.0 at a minimum.

    Make sure that the required features are enabled. For more information, see How to: Install and Configure Internet Information Services for Microsoft Dynamics NAV Web Client

    Instead of installing and configuring IIS manually, you can use Microsoft Dynamics NAV Setup to install IIS and enable the required features. If IIS is already installed, then Setup will enable any required features that are not currently enabled.

  • If you want to configure SSL on the connection to Microsoft Dynamics NAV Web client, then complete the following procedures:

    • Obtain an SSL certificate.

    • Import the certificate into the local computer store of the computer on which you will install the Microsoft Dynamics NAV Web Server components.

    • Obtain the certificate's thumbprint.

    For more information about these procedures, see Walkthrough: Configuring Web Services to Use SSL (SOAP and OData).

    Note
    If you do not want to configure SSL when you install the Microsoft Dynamics NAV Web Server components, you can configure it after installation. For more information, see How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client.

Installing the Microsoft Dynamics NAV Web Server

To install the Microsoft Dynamics NAV Web client, you run Microsoft Dynamics NAV Setup on a computer that is running IIS, and then choose the Microsoft Dynamics NAV Web Server components option.

To install Microsoft Dynamics NAV Web Server components using the Microsoft Dynamics NAV Setup Wizard

  1. On the computer that is running IIS, open the Microsoft Dynamics NAV 2016 installation media.

  2. Double-click the setup.exe file to start the Microsoft Dynamics NAV Setup Wizard.

    If you have already installed one or more Microsoft Dynamics NAV components on the computer, you will see the Maintenance page instead of the Welcome page. In this case, choose Add or remove components, and then go to step 7.

  3. Choose the Next button.

  4. To accept the license terms, choose I accept.

  5. On the Microsoft Dynamics NAV Setup page, choose Choose an installation option.

  6. On the Choose an Installation Option page, choose Custom.

  7. On the Customize the Installation page, select the NAV Web Server Components check box, and then choose Run from My Computer.

  8. Choose the Next button to go to the Specify Parameters page.

  9. In the Server section, set the following parameters to configure the Microsoft Dynamics NAV Server instance.

    Parameter Description

    Server Name

    Specifies the name of the computer that is running Microsoft Dynamics NAV Server for this client.

    Client Services Port

    The listening TCP port for the computer that is running Microsoft Dynamics NAV Server.

    Service Name

    The name of the Microsoft Dynamics NAV Server instance to connect to.

    Note
    If you currently do not know the Microsoft Dynamics NAV Server instance or you want set up the Microsoft Dynamics NAV Server later, then use the default values.

  10. In the Web Server Components section, set the Port parameter to the TCP port to use for the Microsoft Dynamics NAV Web client website.

  11. If you want to add an item on the Start menu for opening the Microsoft Dynamics NAV Web client, set the Add link to Start menu parameter to Yes.

  12. Set the Install IIS prerequisites parameter to one of the following values.

    Value Description

    Install

    Setup enables IIS and the required features for the Microsoft Dynamics NAV Web client and installs the Microsoft Dynamics NAV Web Server components. If IIS is already enabled on the computer, then Setup enables any required features that are not currently enabled.

    Detect

    Setup detects whether IIS and the required features for the Microsoft Dynamics NAV Web client are enabled on the computer, and then does the following:

    • If the required IIS features are enabled, then Setup installs the Microsoft Dynamics NAV Web Server components.

    • If any IIS features are not enabled, then Setup does not install the Microsoft Dynamics NAV Web Server components and an error report is generated that lists the required features. You must enable the required features, and then run Setup again to install the Microsoft Dynamics NAV Web Server components.

    Skip

    Setup installs the Microsoft Dynamics NAV Web Server components without detecting whether IIS or the required features are enabled. Setup does not change the IIS setup.

  13. Verify the parameters, and then choose Apply to complete the installation.

  14. When Setup is complete, choose the Close button.

A website called Microsoft Dynamics NAV 2016 Web Client is added on the IIS. The website includes a web application that has the name WebClient. The physical path of the web application is C:\inetpub\wwwroot\DynamicsNav90\WebClient.

The Microsoft Dynamics NAV Web Server components are also installed in the %systemroot%\Program Files\Microsoft Dynamics NAV\90\Web Client folder of the computer.

For more information about the Microsoft Dynamics NAV Web client installation on IIS, see Deploying the Microsoft Dynamics NAV Web Server Components.

To open the Microsoft Dynamics NAV Web client

  • To open the Microsoft Dynamics NAV Web client from the computer on which you installed the Microsoft Dynamics NAV Web Server components, use one of the following procedures:

    • Choose Start, in the Search box, type Microsoft Dynamics NAV 2016 Web Client, and then choose the related link

    • Open a web browser, and then in the address box, type http://localhost:port/DynamicsNAV90/WebClient. Replace port with the TCP port number that you chose during Setup.

    For more information, see How to: Open the Microsoft Dynamics NAV Web Client. If you get an error when trying to open the Microsoft Dynamics NAV Web client, see Troubleshooting the Microsoft Dynamics NAV Web Client Installation for information about resolving the problem.

Next Steps

  • If Microsoft Dynamics NAV Web Server components was installed on Windows 7, create an inbound rule in the Windows Firewall to allow communication on the TCP port that you chose during Setup.

    For more information, see How to: Create an Inbound Rule in Windows Firewall for the Port of Microsoft Dynamics NAV Web Client.

  • If the Microsoft Dynamics NAV Web client is installed on a different computer than Microsoft Dynamics NAV Server, set up delegation on Microsoft Dynamics NAV Server from the Microsoft Dynamics NAV Web client.

    For more information, see How to: Configure Delegation for Microsoft Dynamics NAV Web Client.

  • If you want to change the Microsoft Dynamics NAV Server instance that the Microsoft Dynamics NAV Web client connects to, then modify the web.config file for the Microsoft Dynamics NAV Web client website.

    For more information, see How to: Change the Microsoft Dynamics NAV Server for the Microsoft NAV Web Client.

  • If you want to help secure the communication with the Microsoft Dynamics NAV Web client, configure SSL.

    For more information, see How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client.

See Also

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Troubleshooting the Microsoft Dynamics NAV Web Client Installation


How to: Install and Configure Internet Information Services for Microsoft Dynamics NAV Web Client

This topic describes how to install and configure Internet Information Service (IIS) for the Microsoft Dynamics NAV Web client. To deploy the Microsoft Dynamics NAV Web client, you install the Microsoft Dynamics NAV Web Server components on a computer that running IIS 7.0 or IIS 8.0. A website for Microsoft Dynamics NAV Web client is installed on the IIS.

IIS must have the following features enabled:

  • .NET Extensibility (on Windows 7 and Windows Server 2008) or .NET Extensibility 4.5 (on Windows 8 and Windows Server 2012)

  • ASP.NET (on Windows 7 and Windows Server 2008) or ASP.NET 4.5 (on Windows 8 and Windows Server 2012)

  • ISAPI Extensions

  • ISAPI Filters

  • Request Filtering

  • Windows Authentication

  • Static Content

  • HTTP Activation

The procedure is slightly different for the different versions of Windows. For more information, see the following sections:

  • Installing IIS Features on Windows 7

  • Installing IIS Features on Windows Server 2008 and Windows Server 2008 R2

  • Installing IIS Features on Windows 8

  • Installing IIS Features on Windows Server 2012

Note
Instead of manually installing IIS, you can use the Microsoft Dynamics NAV Setup wizard to install and enable the IIS features. For more information, see Using Microsoft Dynamics NAV Setup to Install IIS Features.

Installing IIS Features on Windows 7

The following procedure describes how to install IIS and the required features for the Microsoft Dynamics NAV Web client, including HTTP activation, on Windows 7.

To install IIS features on Windows 7

  1. On the Start menu, choose Control Panel, and then choose Programs.

  2. Under Programs and Features, choose Turn Windows features on or off.

  3. In the Windows features list, expand Internet Information Services, and then expand World Wide Web Services.

  4. Expand Application Development Features, and select the following features:

    • .NET Extensibility

    • ASP.NET

    • ISAPI Extensions

    • ISAPI Filters

  5. Expand Security, and then select the following features:

    • Request Filtering

    • Windows Authentication

  6. Expand Common HTTP Features, and then select the Static Content feature.

  7. To install Internet Information Service (IIS) Manager, under Internet Information Services, expand Web Management Tools, and then select IIS Management Console.

    This step is optional. You use Internet Information Service IIS Manager to manage local and remote web servers and sites.

  8. Choose the OK button to complete the installation.

  9. In the Windows features list, expand Microsoft .NET Framework, and then select Windows Communication Foundation HTTP Activation.

  10. To verify that the web server has been installed correctly, start your browser, and then type http://localhost in the address.

    The default web site opens and should display an IIS 7 image. If the IIS 7 image does not appear, then verify that you have configured static content on IIS, as described in step 6.

    Note
    To open Internet Information Services (IIS) Manager, on the Start menu, in the Search Programs and Files box, type inetmgr, and then press Enter.

Installing IIS Features on Windows Server 2008 and Windows Server 2008 R2

The following procedure describes how to install IIS and the required features for the Microsoft Dynamics NAV Web client on Windows Server 2008 and Windows Server 2008 R2.

To install IIS features on Windows Server 2008 and Windows Server 2008 R2

  1. On the Start menu, choose All Programs, choose Administrative Tools, and then choose Server Manager.

  2. In the navigation pane, choose Roles, and then choose Add Roles.

  3. In the Before You Begin window, choose the Next button.

  4. In the Select Server Roles window, select Web Server (IIS), and then choose Next, and then choose Next again.

  5. In the Select Role Service window, expand Common HTTP Features, and then select Static Content. Other features that are selected by default can remain selected.

  6. Expand Application Development Features, and select the following features:

    • ASP.NET

      Note
      If a message displays asking to add role services for ASP.NET, choose Add Required Role Services.

    • .NET Extensibility

    • ISAPI Extensions

    • ISAPI Filters

    Note
    If a message displays asking you to confirm ASP.NET, choose Allow to continue.

  7. Expand Security, and then select the following features:

    • Windows Authentication

    • Request Filtering

  8. Expand Management Tools, and then choose IIS Management Console.

    This step is optional. You use Internet Information Service IIS Manager to manage local and remote web servers and sites.

  9. Choose Next, confirm your selections, and then choose Install to complete the installation.

  10. When the installation is complete, choose the Close button.

  11. To verify that the web server has been installed correctly, start your browser, and then type http://localhost in the address.

    The default website opens and should display an IIS 7 image. If the IIS 7 image does not appear, then verify that you have configured static content on IIS, as described in step 5.

    Note
    Internet Information Services Manager was also installed. To verify the installation, on the Start menu, choose Administrative Tools, and then choose Internet Information Service (IIS) Manager.

To enable HTTP Activation

  1. In the Server Manager window, in the navigation pane, choose Features, and then choose Add Features.

  2. In the Select Features window, expand .NET Framework 3.5 Features, and then expand WCF Activation.

  3. Select HTTP Activation window, expand Common HTTP Features, and then select Static Content. Other features that are selected by default can remain selected.

    If a dialog box appears that prompts you to add features required for HTTP activation, then choose Add Required Features.

  4. Choose Next, confirm your selections, and then choose Install to complete the installation.

  5. When the installation is complete, choose the Close button.

Installing IIS Features on Windows 8

The following procedure describes how to install IIS and the required features for the Microsoft Dynamics NAV Web client on Windows 8.

To install IIS features on Windows 8

  1. On the Start page, choose Control Panel, and then choose Programs.

  2. Under Programs and Features, choose Turn Windows features on or off.

  3. In the Windows features dialog box, expand .NET Framework 4.5 Advanced Services, and then select ASP.NET 4.5.

  4. Expand WCF Services, and then select HTTP Activation.

  5. If the .NET Framework 3.50 is installed, then expand Microsoft .NET Framework 3.5 (including .NET 2.0 and 3.0), and then select Windows Communication Foundation HTTP Activation.

  6. In the Windows features list, expand Internet Information Services, and then expand World Wide Web Services.

  7. Expand Application Development Features, and select the following features:

    • .NET Extensibility 3.5 (if .NET Framework 3.5 is installed)

    • .NET Extensibility 4.5

    • ASP.NET 3.5 (if .NET Framework 3.5 is installed)

    • ASP.NET 4.5

    • ISAPI Extensions

    • ISAPI Filters

  8. Expand Common HTTP Features, and then select the Static Content feature.

  9. Expand Security, and then select the following features:

    • Request Filtering

    • Windows Authentication

  10. To install Internet Information Service (IIS) Manager, under Internet Information Services, expand Web Management Tools, and then select IIS Management Console.

    This step is optional. You use Internet Information Service IIS Manager to manage local and remote web servers and sites.

  11. Choose the OK button to complete the installation.

  12. To verify that the web server has been installed correctly, start your browser, and then type http://localhost in the address.

    The default web site opens and should display an IIS 8 image.

Installing IIS Features on Windows Server 2012

The following procedure describes how to install IIS and the required features for the Microsoft Dynamics NAV Web client on Windows Server 2012.

To install IIS features on Windows Server 2012

  1. On the Start page, choose Server Manager.

  2. In the navigation pane, choose Dashboard, and then choose Add roles and features.

  3. In the Add Roles and Features Wizard, in the Before You Begin page, choose the Next button.

  4. On the Select installation type page, select Role-based or feature-based installation, and then choose the Next button.

  5. On the Select destination server page, select Select a server from the server pool, select your server from Server Pool list, and then choose the Next button.

  6. In the Select Server Roles window, select Web Server (IIS), and then choose the Next button.

  7. If the Add features that are required for Web Server (IIS) dialog box appears, then choose Add Features.

    Note
    If you do not want to install the IIS Management Console, clear the Include management tools check box, and then choose the Continue button.

  8. On the Select features page, expand .NET Framework 4.5, and then select ASP.NET 4.5.

  9. Expand WCF Services, and then select HTTP Activation.

  10. In the Add features that are required for ASP.NET 4.5? dialog box, choose the Add Features button.

    The following additional features are added.

    • ASP.NET 4.5

    • ISAPI Extensions

    • ISAPI Filters

    • .NET Extensibility 4.5

  11. If .NET Framework 3.5 is installed, then do the following:

    1. Expand the .NET Framework 3.5 Features node.

    2. Select HTTP Activate.

    3. If the Add features that are required for ASP.NET 3.5 dialog box appears, choose the Add Features button.

      The following additional features are added.

      • .NET Framework 3.5 (including .NET 2.0 and 3.0)

      • .NET Extensibility 3.5

  12. On the Select Features page, choose the Next button.

  13. On the Web Server Role (IIS) page, choose the Next button.

  14. On the Select role services page, verify that the following role services are selected at a minimum.

    • Common HTTP Features

      • Static Content

    • Security

      • Request Filtering

      • Windows Authentication

    • Application Development

      • .NET Extensibility 3.5 (if .NET Framework 3.5 is installed)

      • .NET Extensibility 4.5

      • ASP.NET 3.5 (if .NET Framework 3.5 is installed)

      • ASP.NET 4.5

      • ISAPI Extensions

      • ISAPI Filters

    • Management Tools (optional)

      • IIS Management Console (optional)

    Note
    You can leave other role services that are selected by default as selected.

  15. Choose the Next button

  16. On the Confirm installation selections page, choose the Install button.

  17. On the Installation progress page, confirm that your installation completed successfully, and then choose the Close button.

  18. To verify that the web server has been installed correctly, start your browser, and then type http://localhost in the address.

    The default website opens and should display an IIS 8 image.

See Also

Tasks

How to: Install the Web Server Components

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components


Using Microsoft Dynamics NAV Setup to Install IIS Features

When you install the Microsoft Dynamics NAV Web Server components, you can use the Microsoft Dynamics NAV Setup wizard to enable Internet Information Services (IIS) and the IIS features that are required to run the Microsoft Dynamics NAV Web client. If IIS is already enabled on the computer and you do not want Setup to change the configuration, then you can use Setup to detect which required features are not enabled. Afterward, you can manually enable the features, and then install the Microsoft Dynamics NAV Web Server components.

IIS Installation Options

To install or detect the IIS features on the computer where you are installing the Microsoft Dynamics NAV Web Server components, you set the Install IIS prerequisites parameter on Specify Parameters page of the Setup wizard. The parameter has the following options.

Value Description

Install

Setup enables IIS and the required features for the Microsoft Dynamics NAV Web client and installs the Microsoft Dynamics NAV Web Server components. If IIS is already enabled on the computer, then Setup enables any required features that are not currently enabled.

Detect

Setup detects whether IIS and the required features for the Microsoft Dynamics NAV Web client are enabled on the computer, and then does the following:

  • If the required IIS features are enabled, then Setup installs the Microsoft Dynamics NAV Web Server components.

  • If any IIS features are not enabled, then Setup does not install the Microsoft Dynamics NAV Web Server components and an error report is generated that lists the required features. You must enable the required features, and then run Setup again to install the Microsoft Dynamics NAV Web Server components.

Skip

Setup installs the Microsoft Dynamics NAV Web Server components without detecting whether IIS or the required features are enabled. Setup does not change the IIS setup.

For more information about how to run the Microsoft Dynamics NAV setup wizard to install the Microsoft Dynamics NAV Web Server components, see How to: Install the Web Server Components.

IIS Features That are Enabled by Setup

Microsoft Dynamics NAV Setup enables IIS and the following features:

  • HTTP Activation (Windows Communication Foundation)

  • .NET Extensibility (on Windows 7 and Windows Server 2008) or .NET Extensibility 4.5 (on Windows 8 and Windows Server 2012)

  • ASP.NET (on Windows 7 and Windows Server 2008) or ASP.NET 4.5 (on Windows 8 and Windows Server 2012)

  • ISAPI Extensions

  • ISAPI Filters

  • Request Filtering

  • Windows Authentication

  • Static Content

  • Default Document

  • Directory Browsing

  • HTTP Errors

  • HTTP Logging

  • Request Monitoring

  • Static Content Compression

  • IIS Management Console

See Also

Tasks

How to: Install the Web Server Components
How to: Install and Configure Internet Information Services for Microsoft Dynamics NAV Web Client

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components


How to: Create an Inbound Rule in Windows Firewall for the Port of Microsoft Dynamics NAV Web Client

This procedure describes how to modify Windows Firewall to allow inbound communication on the port that is used by the Microsoft Dynamics NAV Web client. By default, the port is 8080. You use this procedure after you install the Microsoft Dynamics NAV Web Server components on a computer that is running Windows 7 or if you change the Microsoft Dynamics NAV Web client port to a port other than 8080.

To create an inbound rule

  1. On the computer that is running the Microsoft Dynamics NAV Web Server components, on the Start menu, choose Control Panel, choose System and Security, and then choose Windows Firewall.

  2. In the navigation pane, choose Advanced settings.

  3. In the Windows Firewall with Advanced Settings window, in the navigation pane, choose Inbound Rules, and then in the Actions pane, choose New Rule.

  4. On the Rule Type page, choose Port, and then choose the Next button.

  5. On the Protocol and Ports page, choose Specific local ports, and then enter the port number. For example, enter 8080 for the default port of the Microsoft Dynamics NAV Web client.

  6. Choose the Next button.

  7. On the Action page, choose Allow the connection, and then choose the Next button.

  8. On the Profile page, choose the profiles, and then choose the Next button.

  9. On the Name page, type a name for the rule, and then choose the Finish button.

See Also

Tasks

How to: Install the Web Server Components

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components


How to: Open the Microsoft Dynamics NAV Web Client

You open the Microsoft Dynamics NAV Web client by using a web browser from a device that has a network connection. To open the Microsoft Dynamics NAV Web client, you must know the name of the computer that is running the Microsoft Dynamics NAV Web Server components and the HTTP port that it is running on.

For a list of supported browsers, see System Requirements for Microsoft Dynamics NAV 2016. For more specific parameters, see Opening a Page in the Microsoft Dynamics NAV Web Client by Using a URL

To open Microsoft Dynamics NAV Web client

  1. Open the web browser.

  2. In the address box of the browser, type one of the following URLs.

    To open URL Example

    The Role Center for the default company

    http://ComputerName:Port/WebServerInstance/WebClient

    Or (for multitenant deployments)

    http://ComputerName:Port/WebServerInstance/WebClient/default.aspx?tenant=TenantID

    http://MyNAVWeb:8080/DynamicsNAV90/WebClient

    The Role Center for a specific company

    http://ComputerName:Port/WebServerInstance/WebClient/default.aspx?company=CompanyName

    Or

    http://ComputerName:Port/WebServerInstance/WebClient/default.aspx?tenant=TenantID&company=CompanyName

    http://MyNAVWeb:8080/DynamicsNAV90/WebClient/default.aspx?company=CRONUS%20International%20Ltd.

    A specific page

    http://ComputerName:Port/WebServerInstance/WebClient/default.aspx?page=ID

    Or

    http://ComputerName:Port/WebServerInstance/WebClient/default.aspx?tenant=TenantID&page=ID

    http://MyNAVWeb:8080/DynamicsNAV90/WebClient/default.aspx?page=22

    A specific report

    http://ComputerName:Port/WebServerInstance/WebClient/default.aspx?report=ID

    Or

    http://ComputerName:Port/WebServerInstance/WebClient/default.aspx?tenant=TenantID&report=ID

    http://MyNAVWeb:8080/DynamicsNAV90/WebClient/default.aspx?report=5

    A specific profile

    http://ComputerName:Port/WebServerInstance/WebClient/?profile=ID

    Or

    http://ComputerName:Port/WebServerInstance/WebClient/?profile=ID

    http://MyNAVWeb:8080/DynamicsNAV90/WebClient/?profile=Small%20Business

    Substitute the following parameters:

    • http with https if SSL is configured for the Microsoft Dynamics NAV Web client and the Microsoft Dynamics NAV Web Server is not configured to redirect HTTP requests to HTTPS.

    • ComputerName with the name of the computer that is running the Microsoft Dynamics NAV Web Server components.

    • Port with the port number that you configured for the Microsoft Dynamics NAV Web Server components during installation.

    • WebServerInstance with the virtual directory alias under which the Microsoft Dynamics NAV Web client application exists on the web server. For more information, see Installing Microsoft Dynamics NAV Web Server Components on IIS.

    • TenantID with the name of the tenant that you want to connect to. This parameter is only required when Microsoft Dynamics NAV is deployed in a multitenant architecture. The tenant that you specify must be mounted on the Microsoft Dynamics NAV Server instance that the Microsoft Dynamics NAV Web client connects to. For more information, see Multitenant Deployment Architecture.

    • CompanyName with the name of the company in Microsoft Dynamics NAV. This parameter is optional and is only needed if you want to open a different company than the one specified in My Settings.

    • ID with the ID that is assigned to the page or report object in Microsoft Dynamics NAV.

    Tip
    After you open the Microsoft Dynamics NAV Web client, you can choose the Search for Page or Report icon to find pages and reports. The Search for Page or Report button in the ribbon.

For more information about the URLs to open pages and reports, see Opening a Page in the Microsoft Dynamics NAV Web Client by Using a URL and Opening a Report in the Microsoft Dynamics NAV Web Client by Using a URL.

See Also

Tasks

How to: Install the Web Server Components
How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client
How to: Open the Microsoft Dynamics NAV Tablet or Phone Client from a Browser

Concepts

Developing for the Microsoft Dynamics NAV Web Client


Opening a Page in the Microsoft Dynamics NAV Web Client by Using a URL

You can open a specific page in the Microsoft Dynamics NAV Web client by typing the page's URL in the address of a web browser. You can use the URL as a hyperlink to the page, which you can include in other sources, such as emails or Word documents, or you can it send to other users.

Important
Certain data in the URL, such as company name, could be considered sensitive information. Use discretion if you distribute URLs that contain the company name, or if it is possible, exclude this information from the address.

This topic includes the following sections:

  • Example

  • Page Address Syntax

  • Building the Page Address

  • URL Parameters

  • Filtering Data on the Page

Example

The following URL displays page 9305 Sales Order List for the CRONUS International Ltd. company. The page is displayed in a Microsoft Dynamics NAV Web client that is running on port 8080 of a computer that has the name MyWebServer.

Copy Code
http://MyWebServer:8080/DynamicsNAV90/WebClient/default.aspx?company=CRONUS%20International%20Ltd.&page=9305

There are several parameters that define the address for the page. These parameters are described in the URL Parameters section of this topic. You can also filter the data on specific fields of the page. For information about how to filter the data, see Filtering Data on the Page.

Page Address Syntax

The address to open a page in the Microsoft Dynamics NAV Web client has the following syntax.

Copy Code
<http|https>://<webserver>[:<port>]/<webserverinstance>/WebClient/<default|blank>.aspx?<page>=<ID>&[tenant=<tenantID>]&[company=<companyname>]&[mode=<View|Edit|Create>]

The URL consists of two parts, the web server part and the Microsoft Dynamics NAV content part. The web server part targets a specific site on the computer that is running Microsoft Dynamics NAV Web Server components and includes the following syntax.

Copy Code
<http|https>://<webserver>[:<port>]/<webserverinstance>/WebClient

The Microsoft Dynamics NAV content part includes the rest of the address after /WebClient/. This part of the address is composed of an active server page extended (ASPX) file and a query string that specifies the page to display.

Syntax Key

The following table describes the notation that is used to indicate address syntax.

Notation | Description
Text without brackets | Parameters that you must type as shown.
<> | A placeholder for values that you must supply. Do not include the brackets in the address.
[ ] | Optional parameters. Do not include the brackets in the address.
| | A set of values from which to choose. Use one of the options and do not include | in the address.

Building the Page Address

Use the following guidelines to write page URL syntax and create a URL:

  • Place parameters in any order after aspx? because the order is not important. For example, the following URLs will yield the same results.

    Copy Code
    http://MyWebServer:8080/DynamicsNAV90/WebClient/default.aspx?company=CRONUS%20International%20Ltd.&page=9305&mode=View
    Copy Code
    http://MyWebServer:8080/DynamicsNAV90/WebClient/default.aspx?page=9305&mode=View&company=CRONUS%20International%20Ltd.
  • Separate parameters after aspx? with the ampersand symbol (&).

  • Use %20 for any spaces in values and names.

  • Enclose values in single quotation marks ('').

URL Parameters

The following table describes the parameters of the URL for displaying a page.

Parameter Description

http|https

Specifies the Internet protocol to use. Valid options are http and https.

The https protocol helps secure the Microsoft Dynamics NAV data that is transmitted over the Internet. To use https, Secure Sockets Layer (SSL) must be enabled on the connection to Microsoft Dynamics NAV Web client. For more information, see How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client.

webserver

Specifies the name of the computer that is running Microsoft Dynamics NAV Web client.

port

Specifies the server port on which the Microsoft Dynamics NAV Web client is running. The default port is 8080.

webserverinstance

Specifies the name of the web server instance for the Microsoft Dynamics NAV Web client. On IIS, this is the alias of the virtual directory of the web server instance.

When you install the Microsoft Dynamics NAV Web client using Microsoft Dynamics NAV Setup, the web server instance is given the same name as the Microsoft Dynamics NAV Server instance that it connects to. If you use the New-NAVWebServerInstance cmdlet to add Microsoft Dynamics NAV Web client instances, then you specify the web server instance name. For more information, see How to: Set Up Multiple Web Server Instances for the Microsoft Dynamics NAV Web Client.

default|blank

Specifies the name of the active server page file to use to display the page. You can use either of the following types, regardless what the page type is: default or, blank.

The type that you set is not important because the Microsoft Dynamics NAV Web client will automatically redirect to the appropriate page.

Important
You cannot use blank to open a RoleCenter type page. Use default instead.

company

The name of the company in Microsoft Dynamics NAV for which you want to display the page.

If you do not choose a company, then Microsoft Dynamics NAV Web client uses the company that is defined in its web.config file. If no company is defined in the web.config file, then the company last opened by the user is used.

bookmark

Specifies a record in the underlying table of the page. The value of a bookmark is an alphanumeric string of characters, for example, 27%3bEgAAAAJ7CDAAMQA5ADAANQA4ADkAMw%3d%3.

For the page types Card, CardPart, and Document, the bookmark specifies the record that is shown in the page. For page types List, ListPart, and Worksheet, the bookmark specifies the record that is selected in the list on the page.

Important
Bookmarks are generated automatically. You can only determine a value for the bookmark by displaying the page in the Microsoft Dynamics NAV Web client and looking at its address. Therefore, a bookmark is only relevant when the address you are working with has been copied from another instance of the page in the Microsoft Dynamics NAV Web client.

ID

The ID of the page in Microsoft Dynamics NAV.

Important
Microsoft Dynamics NAV Web client does not support the NavigatePage page type. If you try to display a page of the type NavigatePage, then you will get an error.

mode

Specifies the mode in which to display the page.

  • View

    The page can only be viewed. The user cannot change data on the page.

    Note
    Worksheet page types only display in the edit mode, even if the value is set to View.

  • Edit

    The user can change data on the page.

    Note
    To use the edit mode, the Editable Property of the page in Page Designer must be set to Yes.

    This mode is not supported for pages of the type List, RoleCenter, and CardPart. If you set the value to Edit, pages of these types still display in the view mode.

    For List type pages, the user can modify the list by choosing Edit List in the ribbon of the page in Microsoft Dynamics NAV Web client.

  • Create

    Opens a blank page that enables the user to create a new item.

    Note
    This mode is not supported for pages of the type CardPart, List, ListPart, RoleCenter, and Worksheet. For pages of the type CardPart, List, and ListPart, the page displays in the view mode.

    Do not use this mode for Worksheet pages; otherwise you will get an error when you try to open the page.

showribbon

Specifies whether or not to show the ribbon when the specified page opens. The default value, if the parameter is not specified, is 1 which displays the ribbon. Use the value 0 to not show the ribbon.

Note
This parameter only works for pages of the list page type.

shownavigation

Specifies whether or not to show the navigation page when the specified page opens. The default value, if the parameter is not specified, is 1 which displays the navigation pane. Use the value 0 to not show the navigation pane.

Note
This parameter only works for pages of the list page type.

showuiparts

Specifies whether or not to show UI parts when the specified page opens. The default value, if the parameter is not specified, is 1 which displays the UI parts. Use the value 0 to not show UI parts.

Note
This parameter only works for pages of the list page type.

tenant

Specifies the ID of the tenant to connect to. You must provide this parameter when Microsoft Dynamics NAV is deployed in multitenant architecture. The tenant that you specify must be mounted on the Microsoft Dynamics NAV Server instance that the Microsoft Dynamics NAV Web client connects to. For more information, see Multitenant Deployment Architecture.

profile

Specifies the ID of the profile to open in Microsoft Dynamics NAV. For more information, see How to: Open the Microsoft Dynamics NAV Web Client.

captionhelpdisabled

Specifies that the ability to look up Help by clicking a field caption is disabled. By default Help is always available from field captions. Set captionhelpdisabled=1 to have this parameter take effect.

Note
The parameter needs to be added at the first request when the user logs on to take effect, adding the parameter on an existing session has no effect.

For more information about framing the Web client, see Embedding Microsoft Dynamics NAV Web Client Pages in Other Websites.

Filtering Data on the Page

You can filter the data that is displayed in the page by using the filter parameter in the address. The filter parameter enables you to display only records from the underlying table of the page that have specific values for one or more fields.

Example

The following address displays data in page 9305 only for the customer who has the Sell-to Customer No. 10000 and the Location Code Blue.

Copy Code
http://MyWebServer:8080/nav_server_instance/WebClient/default.aspx?company=CRONUS%20International%20Ltd.&page=9305&filter='Sell-to%20Customer%20No.'%20IS%20'10000'%20AND%20'Location%20Code'%20IS%20'BLUE'

Filter Syntax

The filter has the following syntax.

Copy Code
&filter='<field>'%20IS%20'<value>'[%20AND%20'<field>'%20IS%20'<value>']

You can add the filter anywhere in the address after .aspx?.

Tip
The filter syntax for a page in the Microsoft Dynamics NAV Web client is the same as a page in the Microsoft Dynamics NAV Windows client, which you can see by choosing the Copy Link to Page action on the Application menu in the Microsoft Dynamics NAV Windows client.

Filter Parameters

The following table describes the filter parameters.

Parameter | Description
field | The name of the table field on which to filter.
%20IS%20 | Specifies the equal operator.
value | The value of the table field on which to filter.
%20AND%20 | Use this parameter to specify more than one filter. It specifies an “and” operator for adding additional filters. Place %20AND%20 between each additional filter. To be included in the page data, the table record must match values for all fields in the filter.

See Also

Tasks

How to: Install the Web Server Components
How to: Open the Microsoft Dynamics NAV Web Client

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Developing for the Microsoft Dynamics NAV Web Client


Opening a Report in the Microsoft Dynamics NAV Web Client by Using a URL

You can open a specific report in the Microsoft Dynamics NAV Web client by typing the report's URL in the address of a web browser. After you have the URL of a report, you can use it as a hyperlink to the report, which you can include in other sources, such as emails or Word documents, or send to other users.

Important
Certain data in the URL, such as company name, could be considered sensitive information. Use discretion if you distribute URLs that contain the company name, or if it is possible, exclude this information from the URL.

This topic includes the following sections:

  • Example

  • Report Address Syntax

  • Building the Report Address

  • Report Address Parameters

Example

The following address displays report 5 Receivables - Payables for the CRONUS International Ltd. company. The page is displayed in a Microsoft Dynamics NAV Web client that is running on port 8080 of a computer that has the name MyWebServer.

Copy Code
http://MyWebServer:8080/DynamicsNAV90/WebClient/default.aspx?report=5&company=CRONUS%20International%20Ltd.

There are several parameters that define the URL for the report. These parameters are described in the URL Parameters section of this topic.

Note
Unlike pages, you cannot filter the data in a report using the URL.

Report Address Syntax

The address for opening a report in the Microsoft Dynamics NAV Web client has the following syntax.

Copy Code
<http|https>://<webserver>[:<port>]/<webserverinstance>/WebClient/default.aspx?report=<ID>&[tenant=<tenantID>]&[company=<companyname>]

Syntax Key

The following table describes the notation that is used to indicate address syntax.

Notation | Description
Text without brackets | Parameters that you must type as shown.
<> | A placeholder for values that you must supply. Do not include the brackets in the address.
[ ] | Optional parameters. Do not include the brackets in the address.
| | A set of values from which to choose. Use one of the options and do not include | in the address.

Building the Report Address

Use the following guidelines to write report URL syntax and create a URL:

  • Place parameters in any order after .aspx? because the order is not important. For example, default.aspx?company=CRONUS%20International%20Ltd.&report=5 yields the same as default.aspx? report=5&company=CRONUS%20International%20Ltd..

  • Separate parameters after aspx? with the ampersand symbol (&).

  • Use %20 for any spaces in values and names.

Report Address Parameters

The following table describes the parameters of the URL for displaying a report.

Parameter Description

http|https

Specifies the Internet protocol to use. Valid options are http and https.

The https protocol helps secure the Microsoft Dynamics NAV data that is transmitted over the Internet. To use https, Secure Sockets Layer (SSL) must be enabled on the connection to Microsoft Dynamics NAV Web client. For more information, see How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client.

webserver

Specifies the name of the computer that is running Microsoft Dynamics NAV Web client.

port

Specifies the server port on which the Microsoft Dynamics NAV Web client is running. The default port is 8080.

webserverinstance

Specifies the name of the web server instance for the Microsoft Dynamics NAV Web client. On IIS, this is the alias of the virtual directory of the web server instance.

When you install the Microsoft Dynamics NAV Web client using Microsoft Dynamics NAV Setup, the web server instance is given the same name as the Microsoft Dynamics NAV Server instance that it connects to. If you use the New-NAVWebServerInstance cmdlet to add Microsoft Dynamics NAV Web client instances, then you specify the web server instance name. For more information, see How to: Set Up Multiple Web Server Instances for the Microsoft Dynamics NAV Web Client.

default.aspx

Specifies the name of the active server page (.aspx) file to use to display the report.

ID

The ID of the report in Microsoft Dynamics NAV.

tenant

Specifies the ID of the tenant to connect to. You must provide this parameter when Microsoft Dynamics NAV is deployed in multitenant architecture. The tenant that you specify must be mounted on the Microsoft Dynamics NAV Server instance that the Microsoft Dynamics NAV Web client connects to. For more information, see Multitenant Deployment Architecture.

company

The name of the company in Microsoft Dynamics NAV for which you want to display the page.

If you do not choose a company, then Microsoft Dynamics NAV Web client uses the company that is defined in the web.config file. If no company is defined in the web.config file, then the last company opened by the user is displayed.

See Also

Tasks

How to: Install the Web Server Components
How to: Open the Microsoft Dynamics NAV Web Client

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Developing for the Microsoft Dynamics NAV Web Client


Embedding Microsoft Dynamics NAV Web Client Pages in Other Websites

The Microsoft Dynamics NAV Web client can be deployed as an independent website. In some cases, it is useful to embed parts of the Microsoft Dynamics NAV Web client in other websites, for example, in order to build an internal company portal that not only contains data from Microsoft Dynamics NAV, but also contains news feeds, document handling, and so on

You can do this by adding an iframe element on the embedding website, such as: <iframe src=”http://MyWebServer/DynamicsNAV90/WebClient/default.aspx?...” />. The Microsoft Dynamics NAV Web client will display the ribbon, the navigation pane, and other UI parts inside the frame. You can update the Microsoft Dynamics NAV Web client to hide the ribbon, the navigation pane, or any UI parts, and only display the core part of the list inside the frame.

Note
In Microsoft Dynamics NAV, only list pages are supported as framed pages.

Important
Certain data in the URL, such as company name, could be considered sensitive information. Use discretion if you distribute URLs that contain the company name, or if it is possible, exclude this information from the address.

Example

The following URL displays page 22 Customers for the CRONUS International Ltd. Company. The page is displayed in a Microsoft Dynamics NAV Web client that is running on a computer that has the name MyWebServer. The page is displayed without the ribbon, the navigation pane, and any UI parts.

Copy Code
http://MyWebServer/DynamicsNAV90/WebClient/default.aspx?company=CRONUS%20International%20Ltd.&page=22&showribbon=0&shownavigation=0&showuiparts=0

For more information about the page address syntax, see Opening a Page in the Microsoft Dynamics NAV Web Client by Using a URL.

iframe Parameters

The following table describes the parameters of the URL for displaying a list page in an iframe.

Parameter Description

http|https

Specifies the Internet protocol to use. Valid options are http and https.

The https protocol helps secure the Microsoft Dynamics NAV data that is transmitted over the Internet. To use https, Secure Sockets Layer (SSL) must be enabled on the connection to the Microsoft Dynamics NAV Web client. For more information, see How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client.

webserver

Specifies the name of the computer that is running the Microsoft Dynamics NAV Web client.

webserverinstance

Specifies the name of the web server instance for the Microsoft Dynamics NAV Web client.

On IIS, this is the alias of the virtual directory of the web server instance. When you install the Microsoft Dynamics NAV Web client using Microsoft Dynamics NAV Setup, the web server instance is given the same name as the Microsoft Dynamics NAV Server instance that it connects to. If you use the New-NAVWebServerInstance cmdlet to add Microsoft Dynamics NAV Web client instances, then you specify the web server instance name. For more information, see How to: Set Up Multiple Web Server Instances for the Microsoft Dynamics NAV Web Client.

default|blank

Specifies the name of the active server page file to use to display the page. You can use either of the following types, regardless of the page type: default, blank.

company

The name of the company in Microsoft Dynamics NAV for which you want to display the page. If you do not select a company, then Microsoft Dynamics NAV Web client uses the company that is defined in the web.config file. If no company is defined in the web.config file, then the last company opened by the user is displayed.

mode

Specifies the mode in which to display the page.

  • View

    The page can only be viewed. The user cannot change data on the page.

  • Edit

    The user can change data on the page.

  • Create

    Opens a blank page that enables the user to create a new item.

showribbon

Specifies whether to show the ribbon when the specified page opens. The default value, if the parameter is not specified, is 1, which displays the ribbon. Use the value 0 if you do not want to show the ribbon.

Important
The showribbon parameter cannot be used to hide the app bar, use the isembedded parameter instead.

shownavigation

Specifies whether to show the navigation page when the specified page opens. The default value, if the parameter is not specified, is 1, which displays the navigation pane. Use the value 0 if you do not want to show the navigation pane.

showuiparts

Specifies whether to show UI parts when the specified page opens. The default value, if the parameter is not specified, is 1, which displays the UI parts. Use the value 0 if you do not want to show UI parts.

isembedded

Specifies the navigational behavior of the Microsoft Dynamics NAV Web client. If the Microsoft Dynamics NAV Web client is run as part of an external web site, the isembedded parameter can be used to specify that the Microsoft Dynamics NAV Web client opens in full screen mode when activated.

Use the Back button on the web browser to return from a list. If a card was activated, the original web site is rendered when the card is dismissed.

The default value, if the parameter is not specified, is 0, which displays the Microsoft Dynamics NAV Web client in a non-embedded manner. Use the value 1 if you want to show the Microsoft Dynamics NAV Web client embedded and in full screen mode, when activated.

Important
Specifying the value 1 for isembedded will also hide the app bar.

pagesize

Specifies the number of lines to display in a grid control, which is useful when embedding the Microsoft Dynamics NAV Web client.

The default value, if the parameter is not specified, is 20.

Embedding the Microsoft Dynamics NAV Web Client in a Website on Another Web Server

By default, the Microsoft Dynamics NAV Web client will not allow a website to display the web client inside an iframe unless the website is hosted on the same web server. This is enforced by having the default value of X-FRAME-OPTIONS in the web.config file set to SAMEORIGIN.

Copy Code
<httpProtocol>
      <customHeaders>
        <!-- SAMEORIGIN: allows framing of the Microsoft Dynamics NAV Web client in another website only if the other website is on the same host. Remove this to enable cross-site framing of the Microsoft Dynamics NAV Web client, but be aware of the increased risk of clickjacking, which could deceive a legitimate user into taking unintended actions on behalf of the attacker. -->
        <add name="X-FRAME-OPTIONS" value="SAMEORIGIN" />
      </customHeaders>
    </httpProtocol>

In order to show a list page in an HTML site on a different host, the Microsoft Dynamics NAV Web client web.config file has to be configured by removing the <add name="X-FRAME-OPTIONS" value="SAMEORIGIN" /> line from the web.config file.

Warning
Be aware that if you remove the <add name="X-FRAME-OPTIONS" value="SAMEORIGIN" /> line from the web.config file, it can pose a potential security risk.

See Also

Tasks

How to: Open the Microsoft Dynamics NAV Web Client


Troubleshooting the Microsoft Dynamics NAV Web Client Installation

This section contains information to help you resolve problems with Microsoft Dynamics NAV Web client installation.

Troubleshooting Topics

You can find help about the following problems:

  • Troubleshooting: Microsoft Dynamics NAV Web Client does have styles and images are missing

  • Troubleshooting: Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel...'

  • Troubleshooting: 401 - Unauthorized: Access is denied due to invalid credentials.

  • Troubleshooting: HTTP Error 500 (or 500.21) - Internal Server Error Handler

  • Troubleshooting: HTTP 500.13 - The request cannot be processed because the amount of traffic exceeds the Web site's configured capacity

  • Troubleshooting: Server Error in '/' Application. Access Denied

  • Troubleshooting: Internet Explorer cannot display the webpage

  • Troubleshooting: A server error occurred and the content cannot be displayed

  • Troubleshooting: A fatal error occurred. The connection to SQL server cannot be established

  • Troubleshooting: Reports that are saved as Excel or Word files are blank

See Also

Tasks

How to: Install the Web Server Components

Concepts

Microsoft Dynamics NAV Web Client
Deploying the Microsoft Dynamics NAV Web Server Components


Troubleshooting: Microsoft Dynamics NAV Web Client does have styles and images are missing

The Microsoft Dynamics NAV Web client does not render properly. Text displays with no style or formatting, and images are missing.

Resolution

This error can occur if Internet Information Services (IIS) is not configured for static content. To resolve this issue, configure the static content feature in IIS. For information about configuring IIS, see How to: Install and Configure Internet Information Services for Microsoft Dynamics NAV Web Client.


Troubleshooting: Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel...'

When you try to access the Microsoft Dynamics NAV Web client, you get the following error.

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

This error can occur when there are multiple versions of the .NET Framework on the computer that is running IIS, and IIS was installed after .NET Framework 4.0 or before the Service Model in Windows Communication Foundation was registered.

Resolution

For Windows 7 and Windows Server 2008, use the ASP.NET IIS Registration Tool (aspnet_regiis.exe,) to register the correct version of ASP.NET. For more information about the aspnet_regiis.exe, see ASP.NET IIS Registration Tool.

To register the correct version of ASP.NET

  1. On the computer that is running Microsoft Dynamics NAV Web Server components, open a command prompt as an administrator as follows:

    1. From the Start menu, choose All Programs, and then choose Accessories.

    2. Right-click Command Prompt, and then choose Run as administrator.

  2. At the command prompt, type the following command to change to the Microsoft.NET\Framework64\v4.0.30319 folder, and then press Enter.

    Copy Code
    cd\Windows\Microsoft.NET\Framework64\v4.0.30319

  3. At the command prompt, type the following command, and then press Enter.

    Copy Code
    aspnet_regiis.exe -iru

  4. At the command prompt, type the following command, and then press Enter.

    Copy Code
    iisreset

See Also

Tasks

How to: Install the Web Server Components

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components


Troubleshooting: 401 - Unauthorized: Access is denied due to invalid credentials.

When you try to access the Microsoft Dynamics NAV Web client, you get the following error:

401 - Unauthorized: Access is denied due to invalid credentials. You do not have permission to view this directory or page using the credentials that you supplied.

Resolution

This error typically occurs when authentication is not configured correctly for the Microsoft Dynamics NAV Web client. To resolve this error, verify that the following conditions are met:

  • The credential type to use for authenticating users is configured correctly in the web.config file of the Microsoft Dynamics NAV Web client and on Microsoft Dynamics NAV Server.

  • The correct authentication method is enabled on the Microsoft Dynamics NAV Web client site in IIS.

  • For Windows authentication, the correct authentication providers are configured on the Microsoft Dynamics NAV Web client site in IIS.

For more information about how to enable authentication in the Microsoft Dynamics NAV Web client, see the Configuring the Credential Type on the Microsoft Dynamics NAV Web Client Website.

See Also

Tasks

How to: Install the Web Server Components

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Troubleshooting the Microsoft Dynamics NAV Web Client Installation


Troubleshooting: HTTP Error 500 (or 500.21) - Internal Server Error Handler

When you try to access the Microsoft Dynamics NAV Web client, you get an error message that is similar to one of the following:

HTTP Error 500 - Internal Server Error Handler

HTTP Error 500.21 - Internal Server Error Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list.

Resolution

This error occurs because the Microsoft .NET Framework 4.0 configuration for ASP .NET has been damaged, which can occur if Microsoft Visual Studio 2012 was installed before Visual Studio 2010 or Microsoft SQL Server 2008.

To resolve this error, you must repair the .NET Framework 4.0.30319 version. However, the Microsoft .NET Framework 4.0 installation and configuration can vary depending on your system. You can try to repair the .NET Framework 4.0.30319 version from a command prompt (as described in the following procedure) or use the Microsoft .NET Framework Repair Tool that is available at http://support.microsoft.com/kb/2698555.

To repair the .NET Framework

  1. On the computer that is running Microsoft Dynamics NAV Web Server components, open a Command Prompt window as an administrator as follows:

    1. From the Start menu, choose All Programs, and then choose Accessories.

    2. Right-click Command Prompt, and then choose Run as administrator.

  2. At the command prompt, do the following.

    • If the computer is running the full Microsoft .NET Framework, enter the following commands to change to the Microsoft.NET\Framework64\v4.0.30319\SetupCache folder, and then run setup.exe:

      Copy Code
      cd\Windows\Microsoft.NET\Framework64\v4.0.30319\SetupCache
      Copy Code
      setup.exe /repair /x86 /x64 /ia64 /norestart
    • If the computer is running the Microsoft .NET Framework client profile, enter the following commands to change to the Microsoft.NET\Framework64\v4.0.30319\SetupCache\Client folder, and then run the setup.exe:

      Copy Code
      cd\Windows\Microsoft.NET\Framework64\v4.0.30319\SetupCache\Client
      Copy Code
      setup.exe /repair /x86 /x64 /ia64 /parameterfolder Client /norestart

  3. At the command prompt, type the following command, and then press Enter:

    Copy Code
    iisreset

See Also

Tasks

How to: Install the Web Server Components

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Troubleshooting the Microsoft Dynamics NAV Web Client Installation


Troubleshooting: HTTP 500.13 - The request cannot be processed because the amount of traffic exceeds the Web site's configured capacity

When you try to preview a report or open a report as a PDF from the Microsoft Dynamics NAV Web client, you get an error message that is similar the following:

HTTP Error 500.13 - Internal Server Error

The request cannot be processed because the amount of traffic exceeds the Web site's configured capacity.

Resolution

This error can occur when too many users are running reports at the same time. By default, there is a limit of 50 concurrent report sessions. If this limit is exceeded, then an error occurs.

To resolve this error, change the web.config file of the Microsoft Dynamics NAV Web client to increase the limit on concurrent report sessions.

To change the maximum concurrent report sessions in the web.config file

  1. In a text editor, such as Notepad, open the web.config file for the Microsoft Dynamics NAV Web client.

    The web.config file is located on the computer that is running the Microsoft Dynamics NAV Web Server components. The default folder is C:\Program Files\Microsoft Dynamics NAV\90\Web Client.

  2. In the <appsettings> element, add the following element.

    Copy Code
    <add key="MaxNumberOfConcurrentReportProcessing" value="nn"

    Replace nn with an integer that specifies the maximum number of concurrent reporting sessions allowed.

    Important
    The number of report sessions that are running at the same time can affect the performance and reliability of the Microsoft Dynamics NAV Web client. We recommend that you increase the value slightly, for example from 50 to 75, and then evaluate the performance and increase or decrease as necessary.

  3. Save the web.config file.

See Also

Tasks

How to: Install the Web Server Components

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Troubleshooting the Microsoft Dynamics NAV Web Client Installation


Troubleshooting: Server Error in '/' Application. Access Denied

When you try to access the Microsoft Dynamics NAV Web client, you get an error that is similar to the following:

Server Error in '/' Application.

Access is denied.

Description: An error occurred while accessing the resources required to serve this request. The server may not be configured for access to the requested URL.

Error message 401.2.: Unauthorized: Logon failed due to server configuration.

Resolution

This error can occur when the authentication method that is configured in the web.config file for the Microsoft Dynamics NAV Web client is not enabled in Internet Information Services (IIS). The Microsoft Dynamics NAV Web client can be configured to use either Windows authentication or forms authentication. By default, the Microsoft Dynamics NAV Web client uses Windows authentication.

  • When you use Windows authentication, the Windows authentication feature must be turned on in IIS and enabled on the website for the Microsoft Dynamics NAV Web client.

  • When you use forms authentication, both forms authentication and anonymous authentication must be enabled on the website for Microsoft Dynamics NAV Web client.

Note
For more information about authentication with the Microsoft Dynamics NAV Web client, see How to: Configure User Authentication for the Microsoft Dynamics NAV Web Client.

To turn on the Windows Authentication feature in IIS

  • Use Internet Information Services (IIS) Manager to turn on Windows authentication on IIS. For more information, see How to: Install and Configure Internet Information Services for Microsoft Dynamics NAV Web Client

To enable an authentication method on the Microsoft Dynamics NAV Web client website

  1. On the computer that is running Microsoft Dynamics NAV Web Server components, to open Internet Information Services (IIS) Manager and do one of the following:

    1. In Windows 7, on the Start menu, in the Search Programs and Files box, type inetmgr, and then press Enter.

    2. In Windows Server 2008 R2, on the Start menu, choose All Programs, choose Administrative Tools, and then choose Internet Information Service (IIS) Manager.

  2. In the Connections pane, under Sites, choose Microsoft Dynamics NAV 2016 Web Client.

  3. Under IIS, double-click Authentication.

  4. To enable an authentication method, in the Authentication pane, choose the authentication, and then choose Enable in the Actions pane.

  5. Restart the web server.

To restart IIS

  • In the Connections pane of Internet Information Services (IIS) Manager, choose the root node for your computer, and then in the Actions pane, choose Restart.

See Also

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components


Troubleshooting: Internet Explorer cannot display the webpage

When you try to access Microsoft Dynamics NAV Web Client you get the following message:

Internet Explorer cannot display the webpage

This error can be caused by several conditions. The most common causes are that the URL is incorrect or the web site for Microsoft Dynamics NAV Web client is not started.

Resolution

To resolve this issue, try the following:

  1. Verify that the URL is correct. For more information about URLs, see Opening a Page in the Microsoft Dynamics NAV Web Client by Using a URL.

  2. Use the Internet Information Services (IIS) Manager to start or restart the Microsoft Dynamics NAV Web client website.

  3. If the computer that is running the Microsoft Dynamics NAV Web client website has Windows Firewall turned on, then verify that there is an inbound rule that allows connections on the TCP/IP port that is used by the website.

    For more information, see How to: Create an Inbound Rule in Windows Firewall for the Port of Microsoft Dynamics NAV Web Client

See Also

Tasks

How to: Install the Web Server Components

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Troubleshooting the Microsoft Dynamics NAV Web Client Installation


Troubleshooting: A server error occurred and the content cannot be displayed

When you try to open the Microsoft Dynamics NAV Web client, you get the following error:

A server error occurred, and the content cannot be displayed. Refresh the page or open a new browser window.

In the Event Viewer of the computer that is running Microsoft Dynamics NAV Web Server components, the Windows application log includes the following event:

Message: A server was not found at “net.tcp://navserver:7046/DynamicsNAV90/Service”. Either the URL is incorrect or the server is currently not available.

navserver is the name of the computer that is running Microsoft Dynamics NAV Server.

Resolution

This error occurs when the Microsoft Dynamics NAV Web client cannot connect to Microsoft Dynamics NAV Server. There are several conditions that can cause this error. Typical causes are Microsoft Dynamics NAV Server has stopped, or the Microsoft Dynamics NAV Server instance that is configured for the client is incorrect. To resolve this error, verify that the following conditions are met:

  • The Microsoft Dynamics NAV Web client is configured to connect to the correct Microsoft Dynamics NAV Server. Verify that the Microsoft Dynamics NAV Server is running and uses the correct logon account.

    Use the Microsoft Dynamics NAV Server Administration tool to verify the status and configuration. Try to start or restart Microsoft Dynamics NAV Server.

    For more information, see Microsoft Dynamics NAV Server Administration Tool.

  • The logon account of Microsoft Dynamics NAV Server has permission to log on as a service on the computer that is running Microsoft Dynamics NAV Server.

    For more information, see Provisioning the Microsoft Dynamics NAV Server Account.

  • If you are using Mozilla Firefox as your browser, then you must enable cookies in the browser. Additionally, configure the address of the Microsoft Dynamics NAV Web client as a trusted URI in Firefox. For more information, see How to: Configure Mozilla Firefox for Microsoft Dynamics NAV Clients.

  • If IIS and the Microsoft Dynamics NAV Server are on separate computers, verify the following conditions:

    • If the Microsoft Dynamics NAV Web client is using Windows authentication, then the Negotiate provider must be included at the top of the providers list in the Windows authentication setup in IIS. For more information, see Configuring the Credential Type on the Microsoft Dynamics NAV Web Client Website.

    • Delegation is configured from the computer that is running IIS to the computer that is running Microsoft Dynamics NAV Server.

      • The following Service Principal Names are registered for the logon account of Microsoft Dynamics NAV Server:

        DynamicsNAV/navserver:port

        DynamicsNAV/navserver.domain:port

        navserver is the name of the computer that is running Microsoft Dynamics NAV Server. port is the port that is used by Microsoft Dynamics NAV Server. domain is the domain that the computer belongs to.

      • Kernel mode authentication is either disabled or configured to use the service account of Microsoft Dynamics NAV Server (Microsoft Dynamics NAV Web client only).

      Note
      If you still get this error after verifying the setup, then disable the Use Kerberos Only option in the delegation setup and try again. The Use Kerberos Only option does not work on some network configurations with Microsoft Dynamics NAV.

      For more information about delegation, see How to: Configure Delegation for Microsoft Dynamics NAV Web Client.

See Also

Tasks

How to: Install the Web Server Components
Walkthrough: Installing the Microsoft Dynamics NAV Web Server Components on Three Computers

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Troubleshooting the Microsoft Dynamics NAV Web Client Installation


Troubleshooting: A fatal error occurred. The connection to SQL server cannot be established

When you try to open Microsoft Dynamics NAV Web client, you get the following error:

A fatal error occurred. The connection to SQL server cannot be established or is no longer usable.

There can be various causes of this error. The most common causes are that Microsoft Dynamics NAV Server has stopped or the connection to SQL Server is not configured correctly.

Resolution

This error occurs when Microsoft Dynamics NAV Server cannot connect to SQL Server or to the Microsoft Dynamics NAV database. To resolve this error, verify that the following conditions are met.

  • Microsoft Dynamics NAV Server connects to the correct database by using the correct login account.

    You can do this by using the Microsoft Dynamics NAV Server Administration tool. For more information, see Microsoft Dynamics NAV Server Administration Tool.

  • Login account has the following permissions:

    • Permission to log on as a service on the computer that is running SQL Server. For more information, see Provisioning the Microsoft Dynamics NAV Server Account.

    • Set up as a user in the Microsoft Dynamics NAV database on SQL Server with the following role memberships: db_datareader, db_datawriter, and db_ddladmin. For more information, see Setting Database Owner and Security Administration Permissions

  • SQL Server has the following configurations:

    • TCP/IP protocol is enabled.

    • SQL Server executable file is allowed through the Windows Firewall.

    • SQL Server Browser Service is running. This is required only when Microsoft Dynamics NAV used a named database instance, such as NAVDEMO, and Microsoft Dynamics NAV Server is on a different computer than SQL Server. For more information, see How to: Start SQL Browser Service.

    For more information, see Troubleshooting: SQL Server Connection Problems.

See Also

Tasks

How to: Install the Web Server Components
Walkthrough: Installing the Microsoft Dynamics NAV Web Server Components on Three Computers

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Troubleshooting the Microsoft Dynamics NAV Web Client Installation


Troubleshooting: Reports that are saved as Excel or Word files are blank

While you are viewing a report in Print Preview in the Microsoft Dynamics NAV Web client, you save the report as a Microsoft Excel or Microsoft Word file. When you open the saved file, it is empty.

Resolution

On the computer that is running Microsoft Dynamics NAV Web Server components, you must give users read, write, and modify permission to the Temp folder of the user account that is used by the web site of the Microsoft Dynamics NAV Web client. The default user account is ApplicationPoolIdentity and the folder is C:\Users\Web Client Application Pool\AppData\Local\Temp\.

See Also

Tasks

How to: Configure Microsoft Report Viewer for the Microsoft Dynamics NAV Web Client

Concepts

Troubleshooting the Microsoft Dynamics NAV Web Client Installation


Troubleshooting: Decreased Performance When Running Reports in the Microsoft Dynamics NAV Web Client

When many users regularly run reports from the Microsoft Dynamics NAV Web client, the memory consumption by the Internet Information Server will grow slightly over time. If the Microsoft Dynamics NAV Web Server components and SQL Server are on the same computer, the report performance may degrade because the SQL Server computer becomes deprived of memory.

Resolution

To resolve this issue, you can do the following:

  1. In SQL Server, increase the minimum server memory option for the server instance that is used by Microsoft Dynamics NAV. You can do this by using SQL Server Management Studio. By default, the minimum server memory is 0 MB. For example, start by increasing the minimum server memory to 512 MB. For more information, see Server Memory Server Configuration Options.

  2. In IIS, change the recycle period of the application pool that is used by the Microsoft Dynamics NAV Web clients. You can do this by using IIS Manager. Recycling the application pool restarts worker processes in an application pool, which can help recover valuable system memory resources. By default, the application pool is set to recycle every 1740 minutes (29 hours). For example, decrease the application pool to recycle once a day (every 24 hours) at a time that is outside of peak operating hours. For more information, see Application Pools.

See Also

Concepts

Configuring the Microsoft Dynamics NAV Web Server and Client


Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure

Microsoft Dynamics NAV 2016 includes the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure that enable you to deploy a Microsoft Dynamics NAV environment on Microsoft Azure virtual machines. You can also use the provisioning tools to deploy Microsoft Dynamics NAV on other cloud services and on-premise installations.

About Cloud Services

Cloud service refers to a service that is provided over a network, such as the Internet. The service hosts the relevant software applications and databases, in this case Microsoft Dynamics NAV, to which users are given access. The cloud provider manages the infrastructure that runs the software applications.

About the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure

The provisioning tools automate the deployment of Microsoft Dynamics NAV on virtual machines. They are designed to fully automate the deployment on Azure. However, with slight modifications, you can use the provisioning tools for deploying on any virtual machine that is on premise or on the cloud. The provisioning tools include a set of Windows PowerShell cmdlets and scripts that install and configure Microsoft Dynamics NAV components, including Microsoft Dynamics NAV Web Server components, Microsoft Dynamics NAV Server, and SQL database components.

The provisioning tools include two end-to-end example scripts, Example-1VM.ps1 and Example-2VM.ps1, which deploy a fully functional Microsoft Dynamics NAV environment on different network topologies. Example-1VM deploys the Microsoft Dynamics NAV components on a single virtual machine. Example-2VM deploys Microsoft Dynamics NAV on two virtual machines, where Microsoft Dynamics NAV Web Server components and Microsoft Dynamics NAV Server are installed on one machine and SQL Server is on the other machine. The scripts illustrate the operations that are required for full deployment of Microsoft Dynamics NAV and can be modified to match the specific requirements for your installation.

Microsoft Dynamics NAV Clients

After the deployment using the provisioning tools is completed, users can access Microsoft Dynamics NAV from the Microsoft Dynamics NAV Windows client or the Microsoft Dynamics NAV Web client from a computer that has a network connection.

See Also

Concepts

Planning and Preparing
Deploying Microsoft Dynamics NAV Using the Example Scripts


Planning and Preparing

This section contains information and instructions to address before you start to use the provisioning tools to deploy Microsoft Dynamics NAV on Microsoft Azure or other cloud services and virtual machines.

Determine the Network Topology and Configuration

You can deploy Microsoft Dynamics NAV in different network topologies. You can deploy to a single virtual machine, where all Microsoft Dynamics NAV components are installed. Or, you can deploy on two virtual machines, where Microsoft Dynamics NAV Web Server components and Microsoft Dynamics NAV Server are on one machine and SQL Server and the Microsoft Dynamics NAV database components are on the other.

For more information, see Network Topologies for Microsoft Dynamics NAV on Azure.

Prepare the provisioning environment

To prepare for deployment, you must prepare the Azure subscription and the computer that you will use to provision Microsoft Dynamics NAV on Azure.

For more information, see Preparing for Deploying Microsoft Dynamics NAV on Microsoft Azure.

See Also

Concepts

Deploying Microsoft Dynamics NAV Using the Example Scripts


Working with PowerShell

Microsoft Dynamics NAV Documentation
Working with PowerShell
See Also

Windows PowerShell is a Windows command-line shell that is designed especially for system administrators.

To start a Microsoft Dynamics NAV PowerShell session, on the Start menu, choose All Programs, and then choose Microsoft Dynamics NAV 2016 Administration Shell. This opens a PowerShell prompt where the Microsoft Dynamics NAV cmdlets are available.

If this is your first time working with Windows PowerShell, there are various online resources for learning, which include the following:

  • Getting Started with Windows PowerShell

  • Scripting with Windows PowerShell (with videos)

  • The Windows PowerShell blog

All Windows PowerShell cmdlets support the parameters in the following table.

Parameter | Definition
-confirm | Use this parameter with a cmdlet to make sure that you do not unintentionally overwrite files that you have already uploaded.
-verbose | Use this parameter to display messages that indicate how the action is processing.

In addition, you can use the Get-Help cmdlet in combination with any Microsoft Dynamics NAV cmdlets to view a cmdlets definition, information about parameters, and examples.

Copy Code
Get-Help <cmdlet name>

You can also obtain help for the Get-Help cmdlet itself to learn about different ways to use it.

Copy Code
Get-Help Get-Help

Windows PowerShell Scripts

Because the Microsoft Dynamics NAV PowerShell cmdlets for Microsoft Azure require many parameters, it is easier and more efficient to use scripts instead of entering cmdlets directly at the prompt. By using scripts, you can easily debug your cmdlets, and save them for reuse.

Windows PowerShell scripts have a .ps1 file name extension. Before you can run a script, you must change the script execution policy to allow for scripts to run that originate on the local computer. To do this, run the following command at the PowerShell prompt.

Copy Code
Set-ExecutionPolicy "RemoteSigned" -Scope Process

For more information about PowerShell execution policy, see About Execution Policies.

See Also

Concepts

Preparing for Deploying Microsoft Dynamics NAV on Microsoft Azure
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure
Deploying Microsoft Dynamics NAV Using the Example Scripts


Network Topologies for Microsoft Dynamics NAV on Azure

The Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure support the automated deployment of Microsoft Dynamics NAV on Microsoft Azure virtual machines. This topic describes the deployment topologies that are supported. Before you start to deploy Microsoft Dynamics NAV, you should determine the deployment topology that you want for your environment.

Deploying Microsoft Dynamics NAV on One Virtual Machine

When you deploy Microsoft Dynamics NAV on a single virtual machine, the Microsoft Dynamics NAV Web Server components, Microsoft Dynamics NAV Server, SQL Server, and Microsoft Dynamics NAV database components are installed on the same virtual machine.

NAV topology on one Azure virtual machine

This virtual machine represents a single cloud service on Azure. Users can access Microsoft Dynamics NAV data by using the Microsoft Dynamics NAV Windows client from a ClickOnce deployment, the Microsoft Dynamics NAV Web client, and OData and SOAP web services.

You can specify the size of the virtual machine, such as Small, Medium, Large, or ExtraLarge. You can also scale the deployment to serve more than one customer by adding multiple Microsoft Dynamics NAV Server and Microsoft Dynamics NAV web server instances on the virtual machine.

To deploy this scenario, you can use the Example-1VM.ps1 script that is available with the provisioning tools. For more information, see Deploying Microsoft Dynamics NAV on One Virtual Machine Using Example-1VM Script.

Deploying Microsoft Dynamics NAV on Two Virtual Machines

When you deploy Microsoft Dynamics NAV on a two virtual machines, the Microsoft Dynamics NAV Web Server components and Microsoft Dynamics NAV Server are installed on one virtual machine, and the SQL Server and Microsoft Dynamics NAV database components are installed on another virtual machine.

NAV topology on two Azure virtual machines

Each virtual machine represents a cloud service on Azure. The virtual machines are joined inside the same virtual network.

Similar to the one virtual machine topology, users can access Microsoft Dynamics NAV data by using the Microsoft Dynamics NAV Windows client from a ClickOnce site, the Microsoft Dynamics NAV Web client, and OData and SOAP web services.

You can specify the size of the virtual machine, such as Small, Medium, Large, or ExtraLarge. To scale the deployment, you can add multiple Microsoft Dynamics NAV Server instances on the existing virtual machine that is running Microsoft Dynamics NAV Server or you can add new virtual machines for the Microsoft Dynamics NAV Server. You configure the virtual machines to connect to the SQL Server virtual machine.

To deploy this scenario, you can use the Example-2VM.ps1 script that is available with the provisioning tools. For more information, see Deploying Microsoft Dynamics NAV on Two Virtual Machines Using Example-2VM Script.

See Also

Concepts

Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure
Planning and Preparing
Scaling the Microsoft Dynamics NAV Network Topology


Preparing for Deploying Microsoft Dynamics NAV on Microsoft Azure

You must perform the following prerequisites before you deploy Microsoft Dynamics NAV on Microsoft Azure virtual machines:

  • Setting Up the Azure Subscription

  • Preparing the Provisioning Computer

  • Creating a Backup of the Application Database

  • Installing Control Add-ins and Server-Side Files

Before you begin, determine the network topology that you want for the Microsoft Dynamics NAV installation. For more information, see Network Topologies for Microsoft Dynamics NAV on Azure.

Setting Up the Azure Subscription

Perform the following tasks to create an Azure subscription and prepare the subscription for deploying Microsoft Dynamics NAV. You only have to perform these tasks one time.

Task Description

Sign up for a Microsoft account.

You use a Microsoft account to sign in to the Azure management portal.

For more information, see How to: Sign Up for a Microsoft Account.

Sign up for an Azure subscription.

The Azure subscription gives you access to the Azure management portal.

For more information, see How to: Sign Up for a Microsoft Azure Subscription.

Create an Azure storage account in the data center where you want to add your virtual machines.

An Azure storage account provides access to the Azure Blob, Table, and Queue services in a geographic region. To create a storage account, you use the Azure management portal. For more information, see How to Create a Storage Account.

Tip
Make a note of the name that you use for the storage account because you will use it when you deploy Microsoft Dynamics NAV.

Prepare an Azure image for Microsoft Dynamics NAV.

You will create Azure virtual machines for Microsoft Dynamics NAV deployment based on an Azure image.

You can use an image from the Azure Image Gallery, or create your own image. If you use an image from the Azure Image, then no action is needed for this prerequisite.

For more information, see Preparing a Microsoft Azure Virtual Machine Image for Microsoft Dynamics NAV.

Preparing the Provisioning Computer

Perform the following tasks on the computer that you will use to create the Azure virtual machines and deploy Microsoft Dynamics NAV. You will use this computer to run the Azure provisioning scripts for Microsoft Dynamics NAV. You only have to perform these tasks one time.

Task Description

Install Windows PowerShell 3.0.

By default, Windows 8 and Windows Server 2012 include Windows PowerShell 3.0 and its prerequisites. If Windows PowerShell 3.0 is not installed, then you can download from Installing Windows PowerShell.

Install the Windows PowerShell Integrated Scripting Environment (ISE).

This is an optional requirement. Windows PowerShell Integrated Scripting Environment (ISE) enables you to run commands, and write and debug scripts in a single graphical user interface. You can use Windows PowerShell ISE to run the sample scripts that are available with Microsoft Dynamics NAV.

For more information, see Windows PowerShell 3.0 Integrated Scripting Environment (ISE).

Note
This is an optional requirement. However, many of the procedures in this guide use Windows PowerShell ISE because of its ease of use.

Install the Azure PowerShell module.

For more information, see How to: Install the Microsoft Azure Cmdlets Module.

Download and import publish settings and subscription information.

To configure the connectivity between the provisioning computer and Azure, you download and import the PublishSettings file. For more information, see How to: Download and Import Publish Settings and Subscription Information.

Copy the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure to the computer.

The Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure are included on the Microsoft Dynamics NAV installation media in the WindowsPowerShellScripts\Cloud folder. Copy the Cloud folder and its contents to a location on the provisioning computer, such as C:\Cloud.

For more information, see How to: Install the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure.

Obtain a security certificate PFX file and password for client services.

This security certificate will be stored at the hosted service level on Azure. The security certificate is used to establish a trusted connection between clients and Microsoft Dynamics NAV services, such as SOAP and OData. You can use the sample certificate that is provided with Microsoft Dynamics NAV, or you can obtain your own certificate. If you decide to use the sample certificate, then no action is required for this task.

  • The sample certificate is called MyAzure.pfx and is located in the Cloud\HowTo folder.

  • For information about how to obtain your own certificate, see Using Certificates to Secure a Remote RoleTailored Client Connection.

Obtain a security certificate PFX file and password for configuring SSL for the Microsoft Dynamics NAV Web client.

The example scripts of the provisioning tools configure HTTPS on the Microsoft Dynamics NAV Web Server to help secure Microsoft Dynamics NAV Web client connections. If you do not have a certificate, the provisioning tools will automatically generate and implement a certificate. In this case, no action is required for this task

Obtain a security certificate PFX file and password for ClickOnce installation of the Microsoft Dynamics NAV Windows client.

This requirement is optional. The certificate is used to sign the ClickOnce installation of the Microsoft Dynamics NAV Windows client to indicate to end users that the publisher is verified. You can use the sample certificate that is provided with Microsoft Dynamics NAV, or you can obtain your own certificate.

  • The sample certificate is called ClickOnceSignature.pfx and is located in the Cloud\HowTo folder.

  • For more information about certificates, see Using Certificates to Secure a Remote RoleTailored Client Connection.

Install the Microsoft Windows HTTP Services Certificate Configuration Tool.

This tool enables administrators to install and configure client certificates. For more information, see Windows HTTP Services Certificate Configuration Tool.

Install the makecert.exe tool (Certificate Creation Tool) for creating an SSL certificate for the Microsoft Dynamics NAV Web client deployment.

The makecert.exe generates certificates for testing. It is available with Microsoft Visual Studio and Microsoft Windows SDK. For more information, see Certificate Creation Tool (Makecert.exe) in the MSDN Library.

Note
The makecert.exe tool is only required if you do not already have an SSL certificate.

Download and install the Manifest Generation and Editing Tool (mage.exe) version 4.0 or later versions.

The Manifest Generation and Editing Tool is included with .NET Framework 4 and .NET Framework 4.5, which are part of the Windows SDK for Windows 7, Windows 8, Windows 8.1, and Windows Server 2012.

  • By default, Windows 8 and Windows Server 2012 include the Windows SDK, so no action is required.

  • For information about how to download and install Windows SDK for Windows 8.1, see the http://go.microsoft.com/fwlink/?LinkID=397438

  • For information about how to download and install Windows SDK for Windows 7, see Microsoft Windows SDK for Windows 7 and .NET Framework 4.

Note
The installation of Windows SDK can fail on some computers and Windows versions. If this occurs, as a workaround, install the Windows SDK on another computer, and then copy the mage.exe file to the provisioning computer.

Microsoft Dynamics NAV license.

You must have a valid license. A demonstration license (Cronus.flf) is available on the Microsoft Dynamics NAV installation media (DVD).

Creating a Backup of the Application Database

If you will deploy your own application database instead of the CRONUS International Ltd. demonstration database, then you must create a backup of the database, and store it in a location that can be accessed from the provisioning computer. You must perform this task for each Microsoft Dynamics NAV application database that you want to deploy on Azure.

For more information, see How to: Export Your Solution to a Database Backup File.

Installing Control Add-ins and Server-Side Files

If the Microsoft Dynamics NAV application that you are deploying on Azure includes control add-ins or additional files that will run on the Microsoft Dynamics NAV Server, copy these files to a location that can be accessed from the provisioning computer, and then modify the deployment scripts to install the files.

For more information, see How to: Install Control Add-Ins and Support Files for Your Solution

See Also

Concepts

Planning and Preparing
Deploying Microsoft Dynamics NAV Using the Example Scripts
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure


How to: Sign Up for a Microsoft Account

You use a Microsoft account to sign in to the Microsoft Azure Management Portal when you configure Microsoft Dynamics NAV for use of Azure Active Directory (Azure AD) as authentication mechanism, or if you deploy Microsoft Dynamics NAV on Azure.

To obtain a Microsoft account

  • Visit the sign-up page.

    For more information about Microsoft accounts, see the What is a Microsoft account?.

See Also

Concepts

Authenticating Users with Microsoft Azure Access Control Service
Authenticating Users with Azure Active Directory
Users and Credential Types
Integrating Microsoft Dynamics NAV in SharePoint Sites
Preparing for Deploying Microsoft Dynamics NAV on Microsoft Azure
Deploying Microsoft Dynamics NAV Using the Example Scripts
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure


How to: Sign Up for a Microsoft Azure Subscription

To gain access to the Microsoft Azure management portal, you must have an Azure subscription and a Microsoft account associated with that subscription. You use the Azure management portal when you configure Microsoft Dynamics NAV for use of Azure Active Directory (Azure AD) as authentication mechanism, or if you deploy Microsoft Dynamics NAV on Azure.

You will create one or more subscriptions for the Azure account. A subscription is a grouping of Azure services and applications, including the virtual machines. The subscription provides a way to control the access to and the use of the Azure subscribed service. In a situation where you will have multiple Microsoft Dynamics NAV deployments, you may decide to use a separate subscription for each deployment in order to track expenses related to each deployment. All of the Microsoft Dynamics NAV components for a single deployment must be deployed to the same subscription however. You can set up different administrators for each subscription as required. For more information, see Overview of Subscription Management.

To sign up for an Azure subscription

  1. On the Microsoft Azure page, log in with a Microsoft account.

    For more information about Microsoft accounts, see the What is a Microsoft account? page.

  2. Choose Free Trial and follow the instructions to create a new account. Alternatively, choose Purchase Options and then choose the agreement that suits your purpose.

When your account is set up successfully, the Subscriptions page of the Account Center appears.

To create a subscription

  1. If you are not already signed on to the Subscriptions page of the Account Center, then visit the Azure Account Management Portal page and choose Account Center.

  2. Choose add a subscription.

  3. On the Add a Subscription page, choose a subscription offer from the available list to create the subscription.

You can now use the Azure management portal to manage Azure accounts, subscriptions, hosted services, virtual machines, storage accounts, databases, and more.

See Also

Tasks

How to: Sign Up for a Microsoft Account

Concepts

Authenticating Users with Microsoft Azure Access Control Service
Authenticating Users with Azure Active Directory
Users and Credential Types
Integrating Microsoft Dynamics NAV in SharePoint Sites
Preparing for Deploying Microsoft Dynamics NAV on Microsoft Azure
Deploying Microsoft Dynamics NAV Using the Example Scripts
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure


How to: Install the Microsoft Azure Cmdlets Module

This topic describes how to install the Microsoft Azure PowerShell module on the computer that you are using to deploy Microsoft Dynamics NAV on Microsoft Azure.

To install the Azure PowerShell module

  1. Go to the Microsoft Azure Downloads page.

  2. Under Command Line Tools, under Windows PowerShell, choose Install.

  3. When prompted to run or save the .exe file, choose the Run button.

  4. Follow the online instructions to complete the installation.

For more information about the installing the Azure PowerShell module procedure, see How to install and configure Azure PowerShell.

See Also

Tasks

How to: Download and Import Publish Settings and Subscription Information

Concepts

Preparing for Deploying Microsoft Dynamics NAV on Microsoft Azure
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure
Deploying Microsoft Dynamics NAV Using the Example Scripts
Network Topologies for Microsoft Dynamics NAV on Azure


How to: Download and Import Publish Settings and Subscription Information

Before you start using the Microsoft Azure cmdlets to automate deployments, you must configure connectivity between the provisioning computer and Azure. This procedure describes how to do this by using the Azure PowerShell console. For information about how to configure the connectivity, see How to install and configure Azure PowerShell.

To download and import publish settings and subscription information

  1. Sign in to the Azure Management Portal.

  2. Open the Azure PowerShell console as an administrator as follows:

    1. Choose Start, in the Search box, type Azure PowerShell.

    2. Right-click the Azure PowerShell link, and then choose Run as administrator.

  3. At the command prompt, type the following command, and then press Enter.

    Copy Code
    Get-AzurePublishSettingsFile

    A web browser opens at http://go.microsoft.com/fwlink/?LinkID=294709.

  4. When prompted, download and save the publishing settings file as a .publishsettings type file to your computer.

    The default file name format is [SubscriptionName]-[DownloadDate]-credentials.publishsettings.

    Important
    Note of the path and file name because you will use it in the next step and later on when you deploy Microsoft Dynamics NAV.

  5. At the command prompt, type the following command to import the publish settings file.

    Copy Code
    Import-AzurePublishSettingsFile [mypublishsettingsfile]

    Substitute [mypublishsettings] with the full path and file name of the publish settings file that you downloaded in the previous step. For example, if the file is in the C:\Users\Administrator folder and has the name MyAzure-2-21-2013.publishsettings, then you use the following command:

    Copy Code
    Import-AzurePublishSettingsFile C:\Users\Administrator\MyAzure-2-21-2013.publishsettings

See Also

Tasks

How to: Install the Microsoft Azure Cmdlets Module

Concepts

Preparing for Deploying Microsoft Dynamics NAV on Microsoft Azure


How to: Install the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure

The Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure are available in the WindowsPowerShellScripts folder on the Microsoft Dynamics NAV installation media (DVD). The folder includes various Windows PowerShell scripts that you can use to deploy Microsoft Dynamics NAV. The following table provides an overview of the contents of the Windows PowerShell Scripts folder and the tools.

Folder | Description
DVD\WindowsPowerShellScripts\Cloud\HowTo | Contains the example scripts, Example-1VM.ps1 and Example-2VM.ps1, which deploy a fully functional end-to-end Microsoft Dynamics NAV solution.
DVD\WindowsPowerShellScripts\Cloud\NAVAdministration DVD\WindowsPowerShellScripts\Cloud\NAVRemoteAdministration DVD\WindowsPowerShellScripts\Cloud\NAVRemoteAdministrationSamples | Contains the Windows PowerShell modules that are used by scripts Example-1VM.ps1 and Example-2VM.ps1.

To install the Microsoft Dynamics NAV Provisioning Tools

  1. Open the Microsoft Dynamics NAV installation media (DVD).

  2. Copy the Cloud folder and its content to a folder on the computer that you will use to provision Microsoft Dynamics NAV on Microsoft Azure or other virtual machines.

See Also

Concepts

Preparing for Deploying Microsoft Dynamics NAV on Microsoft Azure
Deploying Microsoft Dynamics NAV Using the Example Scripts
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure


How to: Export Your Solution to a Database Backup File

If you are deploying your own Microsoft Dynamics NAV application on Microsoft Azure instead of CRONUS International Ltd., then you must create a backup of your application database before you start to deploy Microsoft Dynamics NAV.

To create a backup of the Microsoft Dynamics NAV database

  1. Create a backup of the SQL database for the Microsoft Dynamics NAV application.

    For more information, see Create a Full Database Backup (SQL Server).

  2. Copy the backup file to the computer that you will use to provision Microsoft Dynamics NAV on Azure.

See Also

Concepts

Preparing for Deploying Microsoft Dynamics NAV on Microsoft Azure
Deploying Microsoft Dynamics NAV Using the Example Scripts
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure


How to: Install Control Add-Ins and Support Files for Your Solution

If the Microsoft Dynamics NAV application that you are deploying on Microsoft Azure includes control add-ins or additional files that will run on the Microsoft Dynamics NAV Server, then you must first install these files to the Azure virtual machine. To accomplish this, you customize the HowTo-UploadFilesToVM.ps1 script that is available with the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure. If you are using the example end-to-end scripts Example-1VM and Example-2VM to deploy Microsoft Dynamics NAV, perform the following procedure before you run the scripts.

To install control add-ins to the Azure virtual machine

  1. Place the control add-in assembly (.dll) or support files on your provisioning computer.

  2. Open the HowTo-UploadFilesToVM.ps1 script for editing.

    The script is located in the Cloud\NAVRemoteAdministration folder of the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure.

  3. Locate the following command:

    Copy Code
    # Copy-FileToRemoteMachine -SourceFile 'C:\MyAddin.dll' -DestinationFile 'C:\Program Files\Microsoft Dynamics NAV\90\Service\Add-ins\MyAddin\MyAddin.dll' -Session $psSession

  4. Do the following:

    1. Remove the comment character #.

    2. Change the value of C:\MyAddin.dll to the path and name of the control add-in or support file that you want to deploy on the Azure virtual machine.

    3. Change the value of MyAddin\MyAddin.dll to the folder and name of the control add-in on the Azure virtual machine.

      Note
      The C:\Program Files\Microsoft Dynamics NAV\90\Service\Add-ins\ folder is the default folder for control add-ins on the virtual machine that is running Microsoft Dynamics NAV Server.

    4. Add the command for each additional file that you want to upload.

  5. Save the HowTo-UploadFilesToVM.ps1 script.

See Also

Concepts

Preparing for Deploying Microsoft Dynamics NAV on Microsoft Azure
Deploying Microsoft Dynamics NAV Using the Example Scripts
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure
Extending Microsoft Dynamics NAV Using Control Add-ins


Preparing a Microsoft Azure Virtual Machine Image for Microsoft Dynamics NAV

Before you deploy Microsoft Dynamics NAV on Microsoft Azure, you must prepare images that will be used to create the virtual machines for the deployment. An image is a virtual hard drive (VHD) file that you use as a template to create new virtual machines on Azure.

The end-to-end scripts Example-1VM.ps1 and Example-2VM.ps1, which are part of the Microsoft Dynamics NAV provisioning tools, automatically create the virtual machines for Microsoft Dynamics NAV based on an image that you specify when you run the scripts.

Using Microsoft Azure Marketplace Images or Custom Images

You can use images that are available in the Azure Marketplace or you can create your own custom images. Depending on the image that you use, it must meet the requirements that are described in the next section.

We recommend that you use an image Azure Marketplace, because no preparation is needed. By default, the Set-PartnerSetting.ps1 file that is used by the Example-1VM.ps1 and Example-2VM.ps1 scripts is configured to use valid Azure Marketplace images.

For information about how to create your own image, see How to: Create a Microsoft Azure Virtual Machine Operating System Image for Microsoft Dynamics NAV.

Images Requirements

Depending on the network topology that you deploy on Azure, you will need one or two images. Example-1VM.ps1 deploys Microsoft Dynamics NAV on one virtual machine and requires a single image. Example-2VM.ps1 deploys Microsoft Dynamics NAV on two virtual machines, where one virtual machine is for the Microsoft Dynamics NAV Web Server components and Microsoft Dynamics NAV Server, and the other virtual machine is for SQL Server and the Microsoft Dynamics NAV database. The Example-2VM.ps1 script requires that you specify an image for each virtual machine. Depending on the script that you use, the images must meet the requirements that are described in the following table.

Deployment topology Image requirements

One virtual machine (Example-1VM.ps1)

  • A supported operating system, such as Windows Server 2012.

  • A supported version of Microsoft SQL Server, such a Microsoft SQL Server 2012.

  • Windows PowerShell Remoting feature enabled and allowed through Windows Firewall.

    Note
    By default, Windows PowerShell Remoting is enabled on Azure Marketplace images.

Two virtual machines (Example-2VM.ps1)

The image for the virtual machine on which Microsoft Dynamics NAV Server and Microsoft Dynamics NAV Web Server components will be installed must include the following:

  • Windows Server 2012 operating system.

  • Windows PowerShell Remoting feature enabled and allowed through Windows Firewall.

The image for the virtual machine on which Microsoft Dynamics NAV database components will be installed must include the following:

  • Windows Server 2012 operating system.

  • A supported version of Microsoft SQL Server, such a Microsoft SQL Server 2012.

  • Windows PowerShell Remoting feature enabled and allowed through Windows Firewall.

Note
You can use the same image for both virtual machines as long as the image includes Microsoft SQL Server 2012.

For a complete list of supported operating systems and Microsoft SQL Server versions, see System Requirements for Microsoft Dynamics NAV 2016.

See Also

Concepts

Preparing for Deploying Microsoft Dynamics NAV on Microsoft Azure
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure
Deploying Microsoft Dynamics NAV Using the Example Scripts


How to: Create a Microsoft Azure Virtual Machine Operating System Image for Microsoft Dynamics NAV

This topic describes how to create custom images in Microsoft Azure Gallery that you can use to create virtual machines for deploying Microsoft Dynamics NAV. Following this procedure ensures that Microsoft Dynamics NAV remains fully automated when using the scripts that are provided with the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure.

To create a custom image and add it to the Azure Gallery, you must complete the following tasks.

  • Create a New Azure Virtual Machine for Generating the Operating System Image

  • Install Microsoft .NET Framework 3.5

  • Install Microsoft SQL Server by Using SysPrep (NAV Database Image Only)

    You only perform this task if the image will include SQL Server for hosting the Microsoft Dynamics NAV database.

  • Capture the Image and Add it to the Azure Image Gallery

Create a New Azure Virtual Machine for Generating the Operating System Image

The first task in preparing an operating system image is to create a new Azure virtual machine that is running Windows Server 2012. To do this, you use the Azure management portal to create the virtual machine based on an image from the Azure Image Gallery.

To create a new Azure virtual machine

  1. Sign in to Azure at http://azure.microsoft.com.

  2. Complete the instructions for creating a new virtual machine at http://azure.microsoft.com/en-us/documentation/articles/virtual-machines-windows-tutorial.

  3. When the virtual machine has been created, establish a Remote Desktop connection to the virtual machine, and then run Windows Update and apply all recommended updates.

    To connect from the Azure management portal, under Virtual Machines, select the virtual machine, and then choose Connect. For more information, see How to Log on to a Virtual Machine Running Windows Server.

Install Microsoft .NET Framework 3.5

If Microsoft .NET Framework is not installed on the image, the Microsoft Dynamics NAV Setup will install it automatically during deployment. However, by installing Microsoft .NET Framework 3.5 manually, you can decrease the installation time and eliminate potential installation problems.

To install Microsoft .NET Framework 3.5 on Windows Server 2012

  1. Establish a Remote Desktop Connection to the Azure virtual machine.

    From the Azure management portal, under Virtual Machines, choose the virtual machine from the list, and then choose Connect. For more information, see How to Log on to a Virtual Machine Running Windows Server.

  2. Run Windows PowerShell as an Administrator.

  3. At the command prompt, type the following command and press Enter.

    Copy Code
    Add-WindowsFeature NET-Framework-Core

Install Microsoft SQL Server by Using SysPrep (NAV Database Image Only)

If you are creating an image that will be used to host the Microsoft Dynamics NAV database, then the next task is to install Microsoft SQL Server on the virtual machine. If the image will be used to create virtual machines that will only host the Microsoft Dynamics NAV Server and Microsoft Dynamics NAV Web client, not the Microsoft Dynamics NAV database, then you can skip this task.

You cannot complete the installation of SQL Server on the virtual machine before you capture it as an image in Azure. This is because when you use the captured image to create a new virtual machine, the virtual machine is configured to use a new administrator account that has a different security identifier (SID) than the administrator account on the image. Therefore, you will use SysPrep to run the first part of the SQL Server installation before you capture the operating system image, and then run the second part of the installation after the new virtual machine is created from the image and started for the first time.

Note
The following procedure illustrates how to use SysPrep to install a trial version of SQL Server.

For more information about SQL Server 2012 installation using SysPrep and configuration file generation, see Install SQL Server 2012 Using SysPrep.

To install SQL Server

  1. Establish Remote Desktop Connection to the new virtual machine.

    Note
    From the Azure management portal, under Virtual Machines, choose the virtual machine from the list, and then choose Connect.

  2. Download SQL Server 2012 from http://www.microsoft.com/sqlserver/en/us/get-sql-server/try-it.aspx.

    Note
    By default, Windows Server 2012 is enabled with the Internet Explorer Enhanced Security Configuration feature. This might prevent you from downloading SQL Server 2012. If you encounter problems, disable the feature temporarily, and then enable it again after the download is finished. To enable or disable the feature, open Server Manager, and then set the Internet Explorer Enhanced Security Configuration option.

    SQL server is downloaded as an ISO image.

  3. Mount the SQL Server ISO image as virtual drive on the virtual machine.

    To mount the ISO file, open File Explorer, right-click the file, and then choose Mount. A new drive, such as DVD Drive (F:), appears in the File Explorer.

  4. Copy SQL Server 2012 installation files from the mounted drive to the system drive (for example C:) of the virtual machine.

  5. Create a SQL SysPrep configuration file for running the SQL Server setup.exe file.

    You can use the example file that is described in SQL Server Sysprep Installation Configuration File Example or follow the instructions at Install SQL Server 2012 Using a Configuration File to create your own file.

    Name the file ConfigurationFile.ini and save it in the same location as the setup.exe file.

  6. Open a command prompt on the virtual machine, and then change to the folder that contains the setup.exe file.

  7. To run the SQL Server installer, type the following command and press Enter.

    Copy Code
    Setup.exe /ConfigurationFile=ConfigurationFile.ini /IAcceptSQLServerLicenseTerms=true

    The ConfigurationFile parameter specifies the SQL Server 2012 installation configuration file that executes the first part of the SysPrep-based SQL Server installation. The IAcceptSQLServerLicenseTerms parameter suppresses and acknowledges the SQL Server license agreement.

  8. To schedule the second part of the SQL Server Installation, follow these steps to create a SetupComplete2.cmd file.

    1. Open a text editor, such as Notepad.

    2. Include the following command:

      Copy Code
      "C:\Program Files\Microsoft SQL Server\110\Setup Bootstrap\SQLServer2012\setup.exe" /QS /ACTION=CompleteImage /INSTANCEID=MSSQLSERVER /INSTANCENAME=MSSQLSERVER /IACCEPTSQLSERVERLICENSETERMS=1 /SQLSYSADMINACCOUNTS=%COMPUTERNAME%\VMAdmin /BROWSERSVCSTARTUPTYPE=AUTOMATIC /INDICATEPROGRESS /TCPENABLED=1

      VMAdmin species the user name of the administrator account that is created on the virtual machine. If you want to specify a different user name, substitute VMAdmin with the name that you want to use. You cannot use Administrator as the user name.

      Important
      When you deploy Microsoft Dynamics NAV on Azure by using the example scripts (Example-1VM-ps1 and Example-2VM.ps1), you must specify this user name for the administrator account on the virtual machine that will host the Microsoft Dynamics NAV database. You specify the user name in the Setting-PartnerSettings.ps1 file or Set-PartnerCustom.ps1 file that is used by the example script. If you are using the Example-1VM-ps1 script, then you specify the user name in the $NAV_VMAdminUserName parameter. If you are using the Example-2VM-ps1 script, then you specify the user name in the $NAV_SqlServerMachineAdminUserName parameter. For more information about how to run the example scripts, see How to: Deploy Microsoft Dynamics NAV on Microsoft Azure by Using the Example Scripts

    3. Save the file as SetupComplete2.cmd in the C:\Windows\OEM\ folder.

      For an example of the SetupComplete2.cmd, see SetupComplete2.cmd File Example.

Capture the Image and Add it to the Azure Image Gallery

The last task for creating a custom operating system image is to capture the image and add it to the Azure Image Gallery. This operation is performed by using SysPrep.

To capture the image and add it to the Azure Image Gallery

  • For instructions about how to capture the image and add it to the Azure Image Gallery, see How to Capture an Image of a Virtual Machine Running Windows Server.

Security

We recommend that the image adheres to the guidance that is provided on Microsoft Solution Accelerators.


SQL Server Sysprep Installation Configuration File Example

The following code is an example of a configuration file that you can use for installing SQL Server 2012 with SysPrep. You can use this code when you create a custom image for installing Microsoft Dynamics NAV on Microsoft Azure.

To use the code, copy the code into a text editor, such as Notepad, and then save the file that has the name ConfigurationFile.ini. For more information about how to use the ConfigurationFile.ini file, see How to: Create a Microsoft Azure Virtual Machine Operating System Image for Microsoft Dynamics NAV.

Copy Code
;SQL Server 2012 Configuration File
[OPTIONS]
; Specifies a Setup workflow, like INSTALL, UNINSTALL, or UPGRADE. This is a required parameter.
ACTION="PrepareImage"
; Detailed help for command line argument ENU has not been defined yet.
ENU="True"
; Parameter that controls the user interface behavior. Valid values are Normal for the full UI, AutoAdvance for a simplified UI, and EnableUIOnServerCore for bypassing Server Core setup GUI block.
;UIMODE="Normal"
; Specifies setup not display any user interface.
;QUIET="False"
; Specifies setup to display progress only, without any user interaction.
QUIETSIMPLE="True"
; Specifies whether SQL Server Setup should discover and include product updates. The valid values are True and False or 1 and 0. By default SQL Server Setup will include updates that are found.
UpdateEnabled="True"
; Specifies features to install, uninstall, or upgrade. The list of top-level features include SQL, AS, RS, IS, MDS, and Tools. The SQL feature will install the Database Engine, Replication, Full-Text, and Data Quality Services (DQS) server. The Tools feature will install Management Tools, Books online components, SQL Server Data Tools, and other shared components.
FEATURES=SQLENGINE
; Specifies the location where SQL Server Setup will obtain product updates. The valid values are "MU" to search Microsoft Update, a valid folder path, a relative path such as .\MyUpdates or a UNC share. By default SQL Server Setup will search Microsoft Update or a Windows Update service through the Window Server Update Services.
UpdateSource="MU"
; Displays the command line parameters usage
HELP="False"
; Specifies that the detailed Setup log should be piped to the console.
INDICATEPROGRESS="False"
; Specifies that Setup should install into WOW64. This command line argument is not supported on an IA64 or a 32-bit system.
X86="False"
; Specifies the root installation directory for shared components.  This directory remains unchanged after shared components are already installed.
INSTALLSHAREDDIR="C:\Program Files\Microsoft SQL Server"
; Specifies the root installation directory for the WOW64 shared components.  This directory remains unchanged after WOW64 shared components are already installed.
INSTALLSHAREDWOWDIR="C:\Program Files (x86)\Microsoft SQL Server"
; Specifies the Instance ID for the SQL Server features you have specified. SQL Server directory structure, registry structure, and service names will incorporate the instance ID of the SQL Server instance.
INSTANCEID="MSSQLSERVER"
; Specifies the installation directory.
INSTANCEDIR="C:\Program Files\Microsoft SQL Server"

See Also

Concepts

Preparing for Deploying Microsoft Dynamics NAV on Microsoft Azure
Deploying Microsoft Dynamics NAV Using the Example Scripts
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure


SetupComplete2.cmd File Example

The following code is an example of the SetComplete2.cmd file on a Microsoft Azure virtual machine. When you create an Azure virtual machine that you want to use as an Azure Marketplace image for Microsoft Dynamics NAV deployment, you use the SetComplete2.cmd file to Schedule the second part of SysPrep-based SQL Server installation on the Azure virtual machine that is created from the image.

Copy the following code into the SetComplete2.cmd file.

Copy Code
@ECHO OFF && SETLOCAL && SETLOCAL ENABLEDELAYEDEXPANSION && SETLOCAL ENABLEEXTENSIONS
REM All commands will be executed during first Virtual Machine boot
"C:\Program Files\Microsoft SQL Server\110\Setup Bootstrap\SQLServer2012\setup.exe" /QS /ACTION=CompleteImage /INSTANCEID=MSSQLSERVER /INSTANCENAME=MSSQLSERVER /IACCEPTSQLSERVERLICENSETERMS=1 /SQLSYSADMINACCOUNTS=%COMPUTERNAME%\Administrator /BROWSERSVCSTARTUPTYPE=AUTOMATIC /INDICATEPROGRESS /TCPENABLED=1

For more information about how to use the SetComplete2.cmd file, see How to: Create a Microsoft Azure Virtual Machine Operating System Image for Microsoft Dynamics NAV.

See Also

Tasks

How to: Create a Microsoft Azure Virtual Machine Operating System Image for Microsoft Dynamics NAV

Concepts

SQL Server Sysprep Installation Configuration File Example
Preparing for Deploying Microsoft Dynamics NAV on Microsoft Azure
Preparing a Microsoft Azure Virtual Machine Image for Microsoft Dynamics NAV


How to: Get the Microsoft Azure Image Name

This topic describes how to get the name of the Microsoft Azure Marketplace image. When you use the provisioning tools to deploy Microsoft Dynamics NAV on Azure, you must provide the image name in the Set-PartnerSetting file or Set-PartnerSettings-Custom file.

Note
The name that appears for an image in the Azure Marketplace is a user-friendly label and not necessarily the same as the image name that is required in the Set-PartnerSetting file or Set-PartnerSettings-Custom file.

To get the Azure image name

  1. Sign in to the Azure Management Portal.

  2. Choose VIRTUAL MACHINES, choose NEW, and then choose FROM GALLERY.

  3. On the Select the virtual machine operating system page, locate the image that you want to use.

  4. Note the name of the image.

    This is the label that is assigned to the image.

  5. Start Azure PowerShell.

  6. At the command prompt, type the following command:

    Copy Code
    ( Get-AzureVMImage | where-object { $_.Label -like "<ImageLabel>*" } )

    Replace <ImageLabel> with the image label that you identified in step 3.

    For example, if the image label is Windows Server 2012, then type the following code:

    Copy Code
    ( Get-AzureVMImage | where-object { $_.Label -like "Windows Server 2012*" } )

  7. Press Enter to run the command.

    The command returns a list of images that match the image label that you provided. An image can have several versions. You will typically use the latest version.

  8. Locate the image that you want to use from the list, and then note the text string that is next to ImageName: parameter.

    This specifies the image name that you must provide in the Set-PartnerSetting file or Set-PartnerSettings-Custom file.

See Also

Reference

Modifying the Parameter Settings

Concepts

Deploying Microsoft Dynamics NAV Using the Example Scripts
Preparing a Microsoft Azure Virtual Machine Image for Microsoft Dynamics NAV


Deploying Microsoft Dynamics NAV Using the Example Scripts

Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure include two Windows PowerShell scripts, Example-1VM.ps1 and Example-2VM.ps1, which you can run to automatically deploy Microsoft Dynamics NAV on Microsoft Azure virtual machines. The scripts deploy Microsoft Dynamics NAV in two different network configurations as described in following sections. The scripts create the required Azure virtual machines, based on a specified image, and then install and configure the Microsoft Dynamics NAV components, including the Microsoft Dynamics NAV Web Server components, Microsoft Dynamics NAV Server, and Microsoft Dynamics NAV database components for SQL Server, including the application database. After the scripts are run, you will have a fully functional end-to-end Microsoft Dynamics NAV environment that enables users to access Microsoft Dynamics NAV data from the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client.

Note
The Example-1VM.ps1 and Example-2VM.ps1 scripts are located in the \WindowsPowerShellScripts\Cloud\HowTo folder on the Microsoft Dynamics NAV installation media (DVD).

For more information, see the following topics:

  • Deploying Microsoft Dynamics NAV on One Virtual Machine Using Example-1VM Script

  • Deploying Microsoft Dynamics NAV on Two Virtual Machines Using Example-2VM Script

See Also

Concepts

Planning and Preparing
Network Topologies for Microsoft Dynamics NAV on Azure


Deploying Microsoft Dynamics NAV on One Virtual Machine Using Example-1VM Script

This topic describes the Example-1VM.ps1 script of the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure. The script is located in the \WindowsPowerShellScripts\Cloud\HowTo folder on the Microsoft Dynamics NAV installation media (DVD). The Example-1VM.ps1 script deploys Microsoft Dynamics NAV on a single Microsoft Azure virtual machine. After the script is run, you will have a fully functional environment that enables you to access Microsoft Dynamics NAV data from the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client.

For information about how to use the script, see How to: Deploy Microsoft Dynamics NAV on Microsoft Azure by Using the Example Scripts or Walkthrough: Deploying Microsoft Dynamics NAV on a Microsoft Azure Virtual Machine for a step-by-step example.

Deployment Overview

The Example-1VM.ps1 script creates a virtual machine on Azure, which is based on an image that you specify, and then installs and configures Microsoft Dynamics NAV Web Server components, Microsoft Dynamics NAV Server, and Microsoft Dynamics NAV database components for SQL Server.

Network topology for Example-1VM script

The script restores a Microsoft Dynamics NAV application database of your choice, along with a Microsoft Dynamics NAV license. You can choose to install the CRONUS International Ltd. demonstration database and license. The script also configures endpoints in Azure for Microsoft Dynamics NAV client services and management services and opens the communication ports in Windows Firewall.

When the script is finished, you will have functional Microsoft Dynamics NAV environment that has the following characteristics:

  • A website on Internet Information Services (IIS) with a web server instance for the Microsoft Dynamics NAV Web client. The website runs on TCP port 443 and uses https protocol. Users can access Microsoft Dynamics NAV data by using the Microsoft Dynamics NAV Web client from a web browser.

  • A Microsoft Dynamics NAV Server instance that connects to the Microsoft Dynamics NAV database.

  • OData and SOAP Web services are enabled and configured to use https protocol.

  • A Microsoft Dynamics NAV application database that is configured to have a Microsoft Dynamics NAV license file, company, and a single Microsoft Dynamics NAV user that has SUPER permissions.

  • Uses NavUserPassword credential type as the user authentication method.

  • Microsoft Dynamics NAV Windows client available by using ClickOnce website.

Deployment Process

The Example-1VM.ps1 is a combination of several of the provisioning tools scripts that are called at various points in the deployment process. Before running each script, a secure Windows PowerShell remote session using HTTPS is established between the provisioning computer and the Azure virtual machine.

NAV powershell remoting with Azure

Deployment Phases

The following flow chart illustrates the process that is executed by the Example-1VM.ps1 script to deploy Microsoft Dynamics NAV. The dashed boxes illustrate the manual alternatives in the flow.

Process flow for Example-1VM script

The following table provides a description of each phase in the process and the Windows PowerShell script that is executed.

Note
The scripts are located in the Cloud\NAVRemoteAdministrationSamples folder of the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure. For more information, see How to: Install the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure.

Phase Script Description

Import cmdlets and scripts

Set-PowerShellEnvironment.ps1

Imports NavAzureRemoteAdminToolsSamples.psm1 with all the HowTo-prefixed scripts. Other PowerShell modules are automatically imported as needed.

Import the publishsettings file

Set-PowerShellEnvironment.ps1

Imports the PublishSettingsFile that was downloaded when Azure PowerShell was installed.

Selects the Azure storage account and imports the Azure subscription ID and certificates.

For more information about these items, see Preparing for Deploying Microsoft Dynamics NAV on Microsoft Azure.

Create new VM

HowTo-CreateAzureVM

PowerShell session established.

Creates a new virtual machine based on a selected image from the Microsoft Azure Marketplace.

NavAdministration module is transferred to new virtual machine.

Upload files to VM

HowTo-UploadFilesToVM

Creates a .VHD file and uploads the Microsoft Dynamics NAV installation files to Azure storage.

Alternatively, the Microsoft Dynamics NAV installation files can be copied directly from the provisioning computer to the virtual machine through an active PowerShell session. To specify whether to use a VHD, change the $NAV_UseAzureStorageForDvdTransfer variable in the script.

Install NAV on VM

HowTo-InstallNAVonVM

NAVAdministration module cmdlets are executed through a PowerShell session.

Installs Microsoft Dynamics NAV on the virtual machine. The Microsoft Dynamics NAV Server instance and Microsoft Dynamics NAV Web client instance are not installed in this phase.

Add server instance

HowTo-AddNAVInstance

Establishes a PowerShell session, and then does the following:

  • Installs a Microsoft Dynamics NAV Server instance.

  • Installs a Microsoft Dynamics NAV web server instance on IIS for Microsoft Dynamics NAV Web client.

  • Creates a ClickOnce website for Microsoft Dynamics NAV Windows client deployment.

  • Restores the Microsoft Dynamics NAV database from the .bak file.

  • Adds Microsoft Dynamics NAV user.

  • Imports the Microsoft Dynamics NAV license.

  • Adds Azure endpoints.

  • Configures Windows Firewall.

See Also

Tasks

How to: Deploy Microsoft Dynamics NAV on Microsoft Azure by Using the Example Scripts
Walkthrough: Deploying Microsoft Dynamics NAV on a Microsoft Azure Virtual Machine

Concepts

Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure
Planning and Preparing
Network Topologies for Microsoft Dynamics NAV on Azure
Deploying Microsoft Dynamics NAV on Two Virtual Machines Using Example-2VM Script


Walkthrough: Deploying Microsoft Dynamics NAV on a Microsoft Azure Virtual Machine

The following walkthrough demonstrates how to use the Example-1VM.ps1 script of the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure to deploy Microsoft Dynamics NAV on Microsoft Azure from a local computer. The walkthrough deploys the Microsoft Dynamics NAV components, including the CRONUS International Ltd. demonstration database, on a single virtual machine as illustrated in the following figure.

Network topology for Example-1VM script

When completed, you will have a new virtual machine on Azure with a fully functional Microsoft Dynamics NAV environment that gives users access to Microsoft Dynamics NAV data from the Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client.

About This Walkthrough

This walkthrough illustrates the following tasks:

  1. Start Windows PowerShell ISE

  2. Modifying the Set-PartnerSettings File

  3. Running the Example-1VM Script

  4. Opening the Microsoft Dynamics NAV Clients

This walkthrough sets up a Microsoft Dynamics NAV environment on Azure that has the following characteristics.

Item Value

Azure virtual machine name

MyNavVM

Domain name

.cloudapp.net

This value is combined with the Azure virtual machine name so that the fully qualified domain name of the virtual machine becomes MyNAVVM.cloudapp.net.

Administrator account on Azure virtual name

User name: NavVmAdmin

Password: This walkthrough uses an automatically generated password.

Important
If you are using a custom image to create the virtual machine, then the user name must match the administrator account user name that was specified when the custom image was created. For more information, see How to: Create a Microsoft Azure Virtual Machine Operating System Image for Microsoft Dynamics NAV.

Azure region

North Europe

Virtual machine size

Small

User authentication credential type

NavUserPassword

Service account for Microsoft Dynamics NAV Server

User name: NSTService

Password: This walkthrough uses an automatically generated password.

Microsoft Dynamics NAV user with SUPER permissions

User name: navuser

Password: This walkthrough uses an automatically generated password.

Client services port

9001

SOAP services port

9002

OData services port

9003

ClickOnce website port

9004

Microsoft Dynamics NAV company name

MyCompany

This walkthrough restores data for the CRONUS International Ltd. company from a Microsoft Dynamics NAV database backup file, and then renames the company to MyCompany.

Language setting on the Microsoft Dynamics NAV Web Server

en-US

Region format setting on the Microsoft Dynamics NAV Web Server

en-US

Prerequisites

To complete this walkthrough, you will need to install the prerequisites that are described in Preparing for Deploying Microsoft Dynamics NAV on Microsoft Azure.

The following table includes information about the prerequisites that are used to complete this walkthrough.

Item | Information
PublishSettings file | C:\Users\Administrator\MyAzure-2-21-2013.publishsettings
Azure subscription name | MyAzureSubscription
Azure storage account | MyAzureStorage
Image for virtual machine | This walkthrough will use the latest version of a supported image from the Azure Image Gallery. You do not have to do anything to meet this prerequisite.
Microsoft Dynamics NAV installation media (DVD) location | D:\NAVDVD
Microsoft Dynamics NAV database backup file location | D:\NAVDVD\SQLDemoDatabase\CommonAppData\Microsoft\Microsoft Dynamics NAV\72\Database\Demo Database NAV (7-2).bak
Microsoft Dynamics NAV license | D:\NAVDVD\SQLDemoDatabase\CommonAppData\Microsoft\Microsoft Dynamics NAV\72\Database\Cronus.flf
Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure location. | C:\Cloud The Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure are included in the WindowsPowerShellScripts\Cloud folder on Microsoft Dynamics NAV installation media. For this walkthrough, you copy the Cloud folder and its content to the C: drive. The Example-1VM.ps1 script and Set-PartnerSettings file that are used in the walkthrough are in the Cloud\HowTo folder.
Security certificate PFX file location and password for Microsoft Dynamics NAV client services | File: C:\Cloud\HowTo\MyAzureVM.pfx Password: pfxpassword
Security certificate PFX file and password for the Microsoft Dynamics NAV Web client. | This walkthrough uses the security certificate that is automatically generated by the provisioning tools. No action is required for this prerequisite.
Security certificate PFX file location and password for ClickOnce | File: C:\Cloud\HowTo\ClickOnceSignature.pfx Password: clickoncesignaturepassword
Azure Libraries location | C:\ProgramFiles(x86)\Microsoft SDKs\Microsoft Azure\PowerShell\Azure\Azure.psd1
Microsoft Windows HTTP Services Certificate Configuration Tool | C:\ProgramFiles(x86)\Windows Resource Kits\Tools\winhttpcertcfg.exe
Manifest Generation and Editing Tool (mage.exe) | C:\ProgramFiles(x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\mage.exe
makecert.exe | C:\ProgramFiles(x86)\Windows Kits\8.0\bin\x86\makecert.exe

Start Windows PowerShell ISE

To deploy Microsoft Dynamics NAV, you will run Windows PowerShell scripts. The procedures in this section use Windows PowerShell Integrated Scripting Environment (ISE) because it enables you to run commands, and write and debug scripts in a single graphical user interface.

Important
You must run Windows PowerShell ISE as an Administrator; otherwise the scripts will not run without errors.

To start Windows PowerShell ISE

  1. On the provisioning computer, choose Start, and then search for Windows PowerShell ISE.

  2. Right-click the Windows PowerShell ISE item, and then choose Run as Administrator.

  3. At the command prompt, change to the \Windows PowerShell Scripts\Cloud\HowTo folder of the provisioning tools.

    For example, enter the following code, and then press Enter:

    Copy Code
    cd C:\Cloud\HowTo

Modifying the Set-PartnerSettings File

The Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure include the Set-PartnerSettings.ps1 script. The Set-PartnerSettings.ps1 script contains parameters that are used by the Example-1VM.ps1 file to configure the Microsoft Dynamics NAV deployment. In this procedure, you will create a copy of the Set-PartnerSettings.ps1 file, and then modify the copy to include the settings for your installation. You could modify Set-PartnerSetting.ps1 directly, but using a copy enables you to test different parameter values without having to change Set-PartnerSettings.ps1 every time.

To make a copy of the Set-PartnerSettings.ps1 file

  1. In Windows PowerShell ISE, on the File menu, choose Open, and then find and open the Set-PartnerSettings.ps1 file.

    The file is located in the Cloud\Howto folder.

  2. On the File menu, choose Save As.

  3. Save the file in the same folder as Set-PartnerSettings.ps1 and give it the name Set-PartnerSettings-CUSTOM.ps1.

    Because you save this file in the same folder as Set-PartnerSettings.ps1, the Set-PartnerSettings-CUSTOM.ps1 file is automatically loaded by the Example_1VM.ps1 script.

    Note
    By default, the example scripts search the Cloud\HowTo folder for files that contain the text "custom" in the file name, so it is important that only one custom settings file is included in the folder when you run the scripts.

To modify the Set-PartnerSettings-Custom.ps1 file

  1. In the Set-PartnerSettings-Custom.ps1 file, locate the Azure subscription settings section.

    The parameters in this section configure Microsoft Azure subscription settings.

  2. By default, all parameters are commented lines that are preceded by # TODO. To set a parameter, delete the # TODO, and then provide a value for the parameter.

    Go to the following line of code that specifies the PublishSettings file for the Microsoft Azure subscription:

    Copy Code
    # TODO: $NAV_PublishSettingsFile = 'C:\users\administrator\MySubscription.PublishSettings'

    To set the parameter for this walkthrough, change the code to the following:

    Copy Code
    $NAV_PublishSettingsFile = 'C:\users\administrator\MyAzure-2-21-2013.publishsettings'

    You change all parameters in this manner.

    Tip
    For a detailed description about a parameter, see the help text that comes before the parameter in the script.

  3. Change the remaining parameters in this section as follows:

    Copy Code
    $NAV_AzureSubscriptionName = 'MyAzureSubscription'
$NAV_AzureStorageAccount = 'MyAzureStorage'

  4. Go to the Azure virtual machine settings section to specify parameters for the virtual machine that will be created on Microsoft Azure. Set the parameters as follows:

    Copy Code
    $NAV_AzureServiceName = 'MyNavVm'
$NAV_DomainName = 'cloudapp.net'
$NAV_VMAdminUserName = 'NavVmAdmin'
$NAV_VMAdminPassword = ''
$NAV_AzureLocation = 'North Europe'
$NAV_VMSize = 'Small'
$NAV_OSImageWithSqlServer = ''

    Because you do not provide a value for the $NAV_VMAdminPassword setting, the script will generate a password automatically. You will see the password in the message that appears when the script has completed.

    Because you do not provide a value for the $NAV_OSImageWithSqlServer setting, the script will use the latest version of a supported image from the Azure Gallery.

  5. Go to the Microsoft Dynamics NAV installation settings section to specify parameters that install Microsoft Dynamics NAV on the virtual machine. Set the parameters as follows:

    Copy Code
    $NAV_DvdLocation = 'D:\NAVDVD'
$NAV_UseAzureStorageForDvdTransfer = $true
$NAV_DvdVhdName = "$NAV_AzureServiceName-DynamicsNAVDvd.vhd"
$NAV_BakFile = 'D:\NAVDVD\SQLDemoDatabase\CommonAppData\Microsoft\Microsoft Dynamics NAV\72\Database\Demo Database NAV (7-2).bak'
$NAV_DatabaseDiskSizeInGB = 10
$NAV_RemoteDatabaseBackupFile = 'C:\REMOTE\navdvd\SQLDemoDatabase\CommonAppData\Microsoft\Microsoft Dynamics NAV\72\Database\Demo Database NAV (7-2).bak'

  6. Go to the Microsoft Dynamics NAV Instance settings section to specify parameters that configure Microsoft Dynamics NAV Server. Set the parameters as follows:

    Copy Code
    $NAV_InstanceName = 'DynamicsNAV72_Instance1'
$NAV_InstanceNameInternal = 'Inst1'
$NAV_ManagementServicesPort = 9000
$NAV_ClientServicesPort = 9001$
$NAV_SOAPServicesPort = 9002
$NAV_ODataServicesPort = 9003
$NAV_ClickOnceWebSitePort = 9004
$NAV_WindowsServiceAccount = 'NSTService'
$NAV_WindowsServiceAccountPassword = ''
$NAV_NAVAdminUserName = 'navadmin'
$NAV_NAVAdminPassword = ''
$NAV_LicenseFile = 'D:\NAVDVD\SQLDemoDatabase\CommonAppData\Microsoft\Microsoft Dynamics NAV\72\Database\Cronus.flf'
$NAV_ExistingCompanyFromBackup = 'CRONUS International Ltd.'
$NAV_NewCompanyName = 'MyCompany'
$NAV_WebServerLanguage = 'en-US'
$NAV_WebServerRegionFormat = 'en-US'

    Because you do not provide a values for the $NAV_WindowsServiceAccountPassword and $NAV_NAVAdminPassword settings, the script will generate passwords automatically. You will see the passwords in the message that appears when the script has completed.

  7. Go to the Security Certificates for NAV Client Services settings section to specify parameters that configure security certificates for the clients and ClickOnce installation of the Microsoft Dynamics NAV Windows client. Set the parameters as follows:

    Copy Code
    $NAV_ClientServicesPfxFile = 'C:\Cloud\HowTo\MyAzureVM.pfx'
$NAV_ClientServicesPfxPassword = "pfxpassword"
$NAV_HttpsWebClientPfxFile = ""
$NAV_HttpsWebClientPfxPassword = ""
$NAV_ClickOnceCodeSigningPfxFile = 'C:\Cloud\HowTo\ClickOnceSignature.pfx'
$NAV_ClickOnceCodeSigningPfxPassword = 'clickoncesignaturepassword'

  8. Go to the Tool dependencies section to specify parameters for the tools for the deployment.

    Copy Code
    $Global:AzurePowershellModuleFile = Join-Path ${env:ProgramFiles(x86)} 'Microsoft SDKs\Microsoft Azure\PowerShell\Azure\Azure.psd1'
$Global:MageExeFile = Join-Path ${env:ProgramFiles(x86)} 'Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\mage.exe'
$Global:WinHttpCertCfgExeFile = Join-Path ${env:ProgramFiles(x86)} 'Windows Resource Kits\Tools\winhttpcertcfg.exe'
$Global:MakeCertExeFile = Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\8.0\bin\x86\makecert.exe'

  9. Save the file.

    You are ready to run the script.

Running the Example-1VM Script

After you have set the parameters in the Set-PartnerSettings-Custom.ps1 file, you can run the script to create the virtual machine on Azure and deploy Microsoft Dynamics NAV.

To run the example script

  1. In the Windows PowerShell ISE, open Example-1VM.ps1

    The script is located in the Cloud\HowTo directory.

  2. Press F5 to run the script.

    It will take approximately 30-45 minutes for the script to finish. If the script is completed without errors, then text similar to the following appears in the console.

    Copy Code
    The NAV Server virtual machine is: MyNavVm.cloudapp.net
The NAV Server virtual machine administrator username: NSTService
The NAV Server virtual machine administrator password: [password]
The NAV Server Instance is: DynamicsNAV72_Ins1
The NAV Server account credentials: NSTService/[password]
The Windows Client can be downloaded via ClickOnce at: http://MyNavVm.cloudapp.net:9004
The Web Client can be accessed at: https://MyNavVm.cloudapp.net/DynamicsNAV72_Ins1
A user has been added to the database with the following credentials:
  user=navuser
  password=[password]

    A new virtual machine is added on Azure. To see the new virtual machine, sign in to the Microsoft Azure Management Portal, and then choose VIRTUAL MACHINES.

Opening the Microsoft Dynamics NAV Clients

When the script has completed without errors, you can then access the RoleTailored clients.

To open the Microsoft Dynamics NAV Windows client

  1. Open an Internet browser.

  2. In the address, type the following address:

    http://MyNavVm.cloudapp.net:9004

  3. Follow the instructions on the webpage to install the Microsoft Dynamics NAV Windows client.

To open the Microsoft Dynamics NAV Web client

  1. Open an Internet browser.

  2. In the address, type the following address:

    https://MyNavVm.cloudapp.net/DynamicsNAV72_Instance1

Next Steps

Scaling the Microsoft Dynamics NAV Network Topology

Security and Protection for Microsoft Dynamics NAV on Microsoft Azure

See Also

Tasks

Walkthrough: Deploying Microsoft Dynamics NAV on Two Microsoft Azure Virtual Machines

Concepts

Planning and Preparing
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure
Deploying Microsoft Dynamics NAV on Two Virtual Machines Using Example-2VM Script


Deploying Microsoft Dynamics NAV on Two Virtual Machines Using Example-2VM Script

This topic describes the Example-2VM.ps1 script of the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure. The script is located in the \WindowsPowerShellScripts\Cloud\HowTo folder on the Microsoft Dynamics NAV installation media (DVD). The Example-2VM.ps1 script deploys Microsoft Dynamics NAV on two Microsoft Azure virtual machines. After the script is run, you will have a fully functional environment that enables you to access Microsoft Dynamics NAV data from the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client.

For information about how to use the script, see How to: Deploy Microsoft Dynamics NAV on Microsoft Azure by Using the Example Scripts or Walkthrough: Deploying Microsoft Dynamics NAV on Two Microsoft Azure Virtual Machines for a step-by-step example.

Deployment Overview

The Example-2VM.ps1 script creates two virtual machines, which are created based on an Azure image that you specify, and then installs Microsoft Dynamics NAV Web Server components and Microsoft Dynamics NAV Server on one machine and Microsoft Dynamics NAV database components for SQL Server on the other machine.

Network topology for Example-2VM.ps1

The script restores a Microsoft Dynamics NAV application database of your choice, along with a Microsoft Dynamics NAV license. You can choose to install the CRONUS International Ltd. demonstration database and license. The script also configures endpoints in Azure for Microsoft Dynamics NAV client service and management services and opens the communication ports in Windows Firewall.

When the script is finished, you will have a functional Microsoft Dynamics NAV environment that has the following characteristics:

  • Two virtual machines on Azure in a virtual network and affinity group that you specify.

  • A website on Internet Information Services (IIS) with a web application for the Microsoft Dynamics NAV Web client. The website runs on TCP port 443 and uses https protocol. Users can access Microsoft Dynamics NAV data by using the Microsoft Dynamics NAV Web client from a web browser.

  • OData and SOAP Web services are enabled and configured to use https protocol.

  • A Microsoft Dynamics NAV application database that is configured to have a Microsoft Dynamics NAV license file, company, and a single Microsoft Dynamics NAV user that has SUPER permissions.

  • NavUserPassword credential type is configured as the user authentication method.

  • Microsoft Dynamics NAV Windows client available by using ClickOnce.

Deployment Process

The Example-2VM.ps1 script is a combination of several of the provisioning tools scripts that are called at various points in the deployment process. Before running each script, a secure Windows PowerShell remote session using HTTPS is established between the provisioning computer and the Azure virtual machine.

NAV powershell remoting with Azure

Deployment Phases

The following flow chart illustrates the process that is executed by the Example-2VM.ps1 script to deploy Microsoft Dynamics NAV. The dashed boxes illustrate the manual alternatives in the flow.

Process for the Example-2VM deployment on Azure

The following table provides a description of each phase and the Windows PowerShell script that is executed.

Note
The scripts are located in the Cloud\NAVRemoteAdministrationSamples folder of the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure. For more information, see How to: Install the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure.

Phase Script Description

Import cmdlets and scripts

Imports NavAzureRemoteAdminToolsSamples.psm1 with all the HowTo-prefixed scripts. Other PowerShell modules are automatically imported as needed.

Import the publishsettings file

Imports the PublishSettingsFile that was downloaded when Azure PowerShell was installed.

Selects the Azure storage account and imports the Azure subscription ID and certificates.

For more information about these items, see Preparing for Deploying Microsoft Dynamics NAV on Microsoft Azure.

Create SQL VM

HowTo-CreateAzureVM

PowerShell session established.

Creates a new virtual machine to host SQL Server and the Microsoft Dynamics NAV database. The virtual machine is created based on a selected image from the Microsoft Azure Marketplace that you specify.

NavAdministration module transferred to new virtual machine.

Create NAV Server VM

HowTo-CreateAzureVM

PowerShell session established.

Creates a new virtual machine to host Microsoft Dynamics NAV Server and Microsoft Dynamics NAV Web Server components. The virtual machine is created based on a selected image from the Azure Marketplace that you specify.

NavAdministration module is transferred to new virtual machine.

Open Firewall for SQL

HowTo-OpenFirewallPort

Modifies the Windows Firewall settings on the virtual machine that is running SQL Server to enable communication on TCP port 1443 from the virtual machine that is running Microsoft Dynamics NAV Server.

Upload DVD to NAV Server VM

HowTo-UploadFilesToVM

Creates .VHD in Azure storage, uploads the Microsoft Dynamics NAV installation files to the VHD, and then copies the files from the VHD to the virtual machine running Microsoft Dynamics NAV Server.

Creates a .VHD file on the provisioning computer.

Alternatively, the Microsoft Dynamics NAV installation files can be copied directly from the provisioning computer to the virtual machine through an active PowerShell session. To specify whether to use a VHD, change the $NAV_UseAzureStorageForDvdTransfer variable in the script.

Transfer of files by using either Azure Storage Account or through active PowerShell session.

Upload DVD to SQL VM

HowTo-UploadFilesToVM

Creates a .VHD in Azure storage, uploads the Microsoft Dynamics NAV database backup (.bak) file to the VHD, and then copies the .bak file from the VHD to the virtual machine running SQL Server.

Alternatively, the .bak file can be copied directly from the provisioning computer to the virtual machine through an active PowerShell session. To specify whether to use a VHD, change the $NAV_UseAzureStorageForDvdTransfer variable in the script.

Install NAV on VM

HowTo-InstallNAVonVM

NAVAdministration module cmdlets are executed through a PowerShell session.

Installs Microsoft Dynamics NAV on the virtual machine. The Microsoft Dynamics NAV Server instance and Microsoft Dynamics NAV Web client instance are not installed in this phase.

Add server instance

HowTo-AddNAVInstance

Establishes a PowerShell session, and then does the following:

  • Installs a Microsoft Dynamics NAV Server instance.

  • Installs a Microsoft Dynamics NAV web server instance on IIS for Microsoft Dynamics NAV Web client.

  • Creates a ClickOnce website for Microsoft Dynamics NAV Windows client deployment.

  • Restores the Microsoft Dynamics NAV database from the .bak file.

  • Adds Microsoft Dynamics NAV user.

  • Imports the Microsoft Dynamics NAV license.

  • Adds Azure endpoints.

  • Configures Windows Firewall.

See Also

Tasks

How to: Deploy Microsoft Dynamics NAV on Microsoft Azure by Using the Example Scripts
How to: Install the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure

Concepts

Deploying Microsoft Dynamics NAV on Two Virtual Machines Using Example-2VM Script
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure
Preparing for Deploying Microsoft Dynamics NAV on Microsoft Azure
Network Topologies for Microsoft Dynamics NAV on Azure
Deploying Microsoft Dynamics NAV on One Virtual Machine Using Example-1VM Script


Walkthrough: Deploying Microsoft Dynamics NAV on Two Microsoft Azure Virtual Machines

The following walkthrough demonstrates how to use the Example-2VM.ps1 script of the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure to deploy Microsoft Dynamics NAV on Microsoft Azure. The walkthrough deploys the Microsoft Dynamics NAV components, including the CRONUS International Ltd. demonstration database, on two virtual machines as illustrated in the following figure.

Network topology for Example-2VM.ps1

When completed, you will have a new virtual machine on Azure with a fully functional Microsoft Dynamics NAV environment that gives users access to Microsoft Dynamics NAV data from the Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client. Additionally, the virtual machine will have full development and administration capabilities including Microsoft Dynamics NAV Development Environment, Microsoft Dynamics NAV Server Administration tool, and Microsoft Dynamics NAV Windows PowerShell cmdlets.

About This Walkthrough

This walkthrough illustrates the following tasks:

  1. Start Windows PowerShell ISE

  2. Modifying the Set-PartnerSettings File

  3. Running the Example_1VM script

  4. Opening the RoleTailored Clients

This walkthrough sets up a Microsoft Dynamics NAV environment on Azure that has the following characteristics.

Item Value

Name of Azure virtual machine running Microsoft Dynamics NAV Server

MyNavServerVM

Domain name

.cloudapp.net

This value is combined with the Azure virtual machine name so that the fully qualified domain name of the virtual machine becomes MyNavServerVM.cloudapp.net.

Administrator account on Azure virtual running Microsoft Dynamics NAV Server

User name: NavVmAdmin

Password: This walkthrough uses an automatically generated password.

Name of Azure virtual machine running SQL Server

MyNavSQLVM

Administrator account on Azure virtual running SQL Server

User name: NavSqlAdmin

Password: This walkthrough uses an automatically generated password.

Important
If you are using a custom image to create the virtual machine, then the user name must match the administrator account user name that was specified when the custom image was created. For more information, see How to: Create a Microsoft Azure Virtual Machine Operating System Image for Microsoft Dynamics NAV.

Azure region

North Europe

Virtual machine size

Small

Azure virtual network

MyNavVirtualNetwork

Azure affinity group

MyNavAffinity

User authentication credential type

NavUserPassword

Microsoft Dynamics NAV Server Service account

User name: NSTService

Password: This walkthrough uses an automatically generated password.

Microsoft Dynamics NAV user with SUPER permissions

User name: navuser

Password: This walkthrough uses an automatically generated password.

Client services port

9001

SOAP services port

9002

OData services port

9003

ClickOnce website port

9004

Microsoft Dynamics NAV company name

MyCompany

This walkthrough restores data for the CRONUS International Ltd. company from a Microsoft Dynamics NAV database backup file, and then renames the company to MyCompany.

Language setting on the Microsoft Dynamics NAV Web Server

en-US

Region format setting on the Microsoft Dynamics NAV Web Server

en-US

Prerequisites

Install the prerequisites that are described in Preparing for Deploying Microsoft Dynamics NAV on Microsoft Azure.

The following table includes information about the prerequisites that are used to complete this walkthrough.

Item Information

PublishSettings file

C:\Users\Administrator\MyAzure-2-21-2013.publishsettings

Azure subscription name

MyAzureSubscription

Azure storage account

MyAzureStorage

Image for NAV Server virtual machine

This walkthrough will use the latest version of a supported image from the Azure Image Gallery. You do not have to do anything to meet this prerequisite.

Image for SQL Server virtual machine

This walkthrough will use the latest version of a supported image from the Azure Image Gallery. You do not have to do anything to meet this prerequisite.

Note
This is the default image that is set in the Set-PartnerSettings.ps1 file.

Microsoft Dynamics NAV installation media (DVD) location

D:\NAVDVD

Microsoft Dynamics NAV database backup file location

D:\NAVDVD\SQLDemoDatabase\CommonAppData\Microsoft\Microsoft Dynamics NAV\72\Database\Demo Database NAV (7-2).bak

Microsoft Dynamics NAV license

D:\NAVDVD\SQLDemoDatabase\CommonAppData\Microsoft\Microsoft Dynamics NAV\72\Database\Cronus.flf

Microsoft Dynamics NAV provisioning tools location

C:\Cloud

The Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure are included in the WindowsPowerShellScripts\Cloud folder on Microsoft Dynamics NAV installation media. For this walkthrough, you copy the Cloud folder and its content to the C: drive. The Example-2VM.ps1 script and Set-PartnerSettings file that are used in the walkthrough are in the Cloud\HowTo folder.

Security certificate PFX file location and password for Microsoft Dynamics NAV services

Folder: C:\Cloud\HowTo\MyAzureVM.pfx

Password: pfxpassword

Security certificate PFX file and password for the Microsoft Dynamics NAV Web client

This walkthrough uses the security certificate that is automatically generated by the provisioning tools. No action is required for this prerequisite.

Security certificate PFX file location and password for ClickOnce

Folder: C:\Cloud\HowTo\ClickOnceSignature.pfx

Password: clickoncesignaturepassword

Azure Libraries location

C:\ProgramFiles(x86)\Microsoft SDKs\Microsoft Azure\PowerShell\Azure\Azure.psd1

Microsoft Windows HTTP Services Certificate Configuration Tool

C:\ProgramFiles(x86)\Windows Resource Kits\Tools\winhttpcertcfg.exe

Manifest Generation and Editing Tool (mage.exe)

C:\ProgramFiles(x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\mage.exe

makecert.exe

C:\ProgramFiles(x86)\Windows Kits\8.0\bin\x86\makecert.exe'

Start Windows PowerShell ISE

To deploy Microsoft Dynamics NAV, you will run Windows PowerShell scripts. The procedures in this section use Windows PowerShell Integrated Scripting Environment (ISE) because it enables you to run commands, and write and debug scripts in a single graphical user interface.

Important
You must run Windows PowerShell ISE as an Administrator; otherwise the scripts will not run without errors.

To start Windows PowerShell ISE

  1. On the provisioning computer, choose Start, and then search for Windows PowerShell ISE.

  2. Right-click the Windows PowerShell ISE item, and then choose Run as Administrator.

  3. At the command prompt, change to the Cloud\HowTo folder of the provisioning tools.

    For example, enter the following code, and then press Enter:

    Copy Code
    cd C:\Cloud\HowTo

Modifying the Set-PartnerSettings File

The Microsoft Dynamics NAV provisioning tools include the Set-PartnerSettings.ps1 script. The Set-PartnerSettings.ps1 script contains parameters that are used by the Example-2VM.ps1 file to configure the Microsoft Dynamics NAV deployment. In this procedure, you will create a copy of the Set-PartnerSettings.ps1 file, and then modify the copy to include the settings for your installation. You can modify Set-PartnerSetting.ps1 directly, but using a copy enables you to test different parameter values without having to change the Set-PartnerSettings.ps1 every time.

To make a copy of the Set-PartnerSettings.ps1 file

  1. In Windows PowerShell ISE, on the File menu, choose Open, and then find and open the Set-PartnerSettings.ps1 file.

    The file is located in the Cloud\Howto folder.

  2. From the File menu, choose Save As.

  3. Save the file in the same folder as the Set-PartnerSettings.ps1 and give it the name Set-PartnerSettings-CUSTOM.ps1.

    Because you save it in the same folder as Set-PartnerSettings.ps1, the Set-PartnerSettings-CUSTOM.ps1 is automatically loaded by the Example-2VM.ps1 script.

    Note
    By default, the example scripts search the Cloud\HowTo folder for files that contain the text "custom", so it is important that only one custom settings file is included in the folder when you run the scripts.

To modify the Set-PartnerSettings-Custom.ps1 file

  1. In the Set-PartnerSettings-Custom.ps1 file, and locate the Azure subscription settings section.

    The parameters in this section configure Azure subscription settings.

  2. By default, all parameters are commented lines that are preceded by # TODO. To set a parameter, delete the # TODO, and then provide a value for the parameter.

    Start with the following line that specifies the PublishSettings file for the Azure subscription:

    Copy Code
    # TODO: $NAV_PublishSettingsFile = 'C:\users\administrator\MySubscription.PublishSettings'

    To set the parameter for this walkthrough, change the code to the following:

    Copy Code
    $NAV_PublishSettingsFile = 'C:\users\administrator\MyAzure-2-21-2013.publishsettings'

    You change all parameters in this manner

    Tip
    For a detailed description about a parameter, see the help text that comes before the parameter in the script.

  3. Change the remaining parameters in this section as follows:

    Copy Code
    $NAV_AzureSubscriptionName = 'MyAzureSubscription'
$NAV_AzureStorageAccount = 'MyAzureStorage'

  4. Go to the Azure virtual machine settings section to specify parameters for the virtual that will be created on Azure. Set the parameters as follows:

    Copy Code
    $NAV_AzureServiceName = 'MyNavServerVm'
$NAV_DomainName = 'cloudapp.net'
$NAV_VMAdminUserName = 'NavVmAdmin'
$NAV_VMAdminPassword = ''
$NAV_AzureLocation = 'North Europe'
$NAV_VMSize = 'Small'
$NAV_OSImageWithSqlServer = ''
$NAV_OSImageWithoutSqlServer = ''

    Because you do not provide a value for the $NAV_VMAdminPassword setting, the script will generate a password automatically. You will see the password in the message that appears when the script has completed.

    Because you do not provide a value for the $NAV_OSImageWithSqlServer and $NAV_OSImageWithoutSqlServer settings, the script will use the latest version of a supported image from the Azure Gallery.

  5. Go to the 2-Box NAV Deployment settings section to specify parameters that configure the virtual machine that will run SQL Server and the Microsoft Dynamics NAV database. Set the parameters as follows:

    Copy Code
    $NAV_SqlServerMachine = 'MyNavSQLVM'
$NAV_SqlServerMachineAdminUserName = 'NavSqlAdmin'
$NAV_SqlServerMachineAdminPassword = ''
$NAV_AzureVirtualNetwork = 'MyNavVirtualNetwork'
$NAV_AzureAffinityGroup = ' MyNavAffinity'

    Because you do not provide a value for the $NAV_SqlServerMachineAdminPassword setting, the script will generate a password automatically. You will see the password in the message that appears when the script has completed.

  6. Go to the Microsoft Dynamics NAV installation settings section to specify parameters that install Microsoft Dynamics NAV on the virtual machine. Set the parameters as follows:

    Copy Code
    $NAV_DvdLocation = 'D:\NAVDVD'
$NAV_UseAzureStorageForDvdTransfer = $true
$NAV_DvdVhdName = "$NAV_AzureServiceName-DynamicsNAVDvd.vhd"
$NAV_BakFile = 'D:\NAVDVD\SQLDemoDatabase\CommonAppData\Microsoft\Microsoft Dynamics NAV\72\Database\Demo Database NAV (7-2).bak'
$NAV_DatabaseDiskSizeInGB = 10
$NAV_RemoteDatabaseBackupFile = 'C:\REMOTE\navdvd\SQLDemoDatabase\CommonAppData\Microsoft\Microsoft Dynamics NAV\72\Database\Demo Database NAV (7-2).bak'

  7. Go to the Microsoft Dynamics NAV Instance settings section to specify parameters for that configure Microsoft Dynamics NAV Server. Set the parameters as follows:

    Copy Code
    $NAV_InstanceName = 'DynamicsNAV72_Instance1'
$NAV_InstanceNameInternal = 'Inst1'
$NAV_ManagementServicesPort = 9000
$NAV_ClientServicesPort = 9001
$NAV_SOAPServicesPort = 9002
$NAV_ODataServicesPort = 9003
$NAV_ClickOnceWebSitePort = 9004
$NAV_WindowsServiceAccount = 'NSTService'
$NAV_WindowsServiceAccountPassword = ''
$NAV_NAVAdminUserName = 'navadmin'
$NAV_NAVAdminPassword = ''
$NAV_LicenseFile = 'D:\NAVDVD\SQLDemoDatabase\CommonAppData\Microsoft\Microsoft Dynamics NAV\72\Database\Cronus.flf'
$NAV_ExistingCompanyFromBackup = 'CRONUS International Ltd.'
$NAV_NewCompanyName = 'MyCompany
$NAV_WebServerLanguage = 'en-US'
$NAV_WebServerRegionFormat = 'en-US'

    Because you do not provide a values for the $NAV_WindowsServiceAccountPassword and $NAV_NAVAdminPassword settings, the script will generate passwords automatically. You will see the passwords in the message that appears when the script has completed.

  8. Go to the Security Certificates for NAV Client Services settings section to specify parameters that configure security certificates for the clients and ClickOnce installation of the Microsoft Dynamics NAV Windows client. Set the parameters as follows:

    Copy Code
    $NAV_ClientServicesPfxFile = 'C:\Cloud\HowTo\MyAzureVM.pfx'
$NAV_HttpsWebClientPfxFile = ""
$NAV_HttpsWebClientPfxPassword = ""
$NAV_ClientServicesPfxPassword = "pfxpassword"
$NAV_ClickOnceCodeSigningPfxFile = 'C:\Cloud\HowTo\ClickOnceSignature.pfx'
$NAV_ClickOnceCodeSigningPfxPassword = 'clickoncesignaturepassword'

  9. Go to the Tool dependencies section to specify parameters that are required for the deployment.

    Copy Code
    $Global:AzurePowershellModuleFile = Join-Path ${env:ProgramFiles(x86)} 'Microsoft SDKs\Microsoft Azure\PowerShell\Azure\Azure.psd1'
$Global:MageExeFile = Join-Path ${env:ProgramFiles(x86)} 'Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\mage.exe'
$Global:WinHttpCertCfgExeFile = Join-Path ${env:ProgramFiles(x86)} 'Windows Resource Kits\Tools\winhttpcertcfg.exe'
$Global:MakeCertExeFile = Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\8.0\bin\x86\makecert.exe'

  10. Save the file.

    You are ready to run the script.

Running the Example_2VM script

After you have set the parameters in the Set-PartnerSettings-Custom.ps1 file, you can run the script to create the virtual machine on Azure and deploy Microsoft Dynamics NAV.

To run the example script

  1. In the Windows PowerShell ISE, open the Example-2VM.ps1

    The script is located in the Cloud\HowTo directory.

  2. Press F5 to run the script.

    It will take approximately 30-45 minutes for the script to complete. If the script completes without errors, then text similar to the following appears in the console:

    Copy Code
    The NAV Server virtual machine is: MyNavVm.cloudapp.net
The NAV Server virtual machine administrator username: NSTService
The NAV Server virtual machine administrator password: [password]
The NAV Server Instance is: DynamicsNAV72_Ins1
The NAV Server account credentials: NSTService/[password]
The SQL Server machine is: NavSqlAdmin.cloudapp.net
The SQL Server machine administrator password: [password]
The Windows Client can be downloaded via ClickOnce at: http://MyNavVm.cloudapp.net:9004
The Web Client can be accessed at: https://MyNavVm.cloudapp.net/DynamicsNAV72_Ins1
A user has been added to the database with the following credentials:
  user=navuser
  password=[password]

    Two new virtual machines are added on Azure. To see the new virtual machine, sign in to the Microsoft Azure Management Portal, and then choose VIRTUAL MACHINES.

Opening the RoleTailored Clients

When the script has completed with no errors, you can then access the RoleTailored clients.

To open the Microsoft Dynamics NAV Windows client

  1. Open an internet browser.

  2. In the address, type the following address:

    http://MyNavVm.cloudapp.net:9004

  3. Follow the instructions on the webpage to install the Microsoft Dynamics NAV Windows client.

To open the Microsoft Dynamics NAV Web client

  1. Open an internet browser.

  2. In the address, type the following address:

    http://MyNavVm.cloudapp.net/DynamicsNAV72_Instance1

Next Steps

Scaling the Microsoft Dynamics NAV Network Topology

Security and Protection for Microsoft Dynamics NAV on Microsoft Azure

See Also

Tasks

Walkthrough: Deploying Microsoft Dynamics NAV on a Microsoft Azure Virtual Machine

Concepts

Planning and Preparing
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure
Deploying Microsoft Dynamics NAV on Two Virtual Machines Using Example-2VM Script


Deploying Microsoft Dynamics NAV on Cloud Services Other Than Microsoft Azure

The Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure have been designed to provide an end-to-end scenario for deploying Microsoft Dynamics NAV on the Microsoft Azure. However, because the provisioning tools are implemented in Windows PowerShell scripts, you can adapt them to other cloud services or on-premise installations.

This topic provides an overview of the work that is required to modify the provisioning tools for deploying Microsoft Dynamics NAV on cloud services and virtual machines that are not on Azure.

Preparing the Virtual Machines

The virtual machines on the cloud service must meet the following requirements:

  • Minimum system requirements for Microsoft Dynamics NAV. For more information, see System Requirements for Microsoft Dynamics NAV 2016.

  • The Remote Desktop Protocol (RDP) and remote administration using PowerShell 3.0 must be enabled.

Modifying the Provisioning Tool Scripts

The provisioning tools are located in the WindowsPowerShellScripts\Cloud folder on the Microsoft Dynamics NAV installation media (DVD). The Cloud folder includes several subfolders where the different Windows PowerShell scripts are organized according to their function. Most of the scripts do not have any dependencies on Azure so that they can be reused in other environments without modification. You perform most of the modifications on the scripts in the Cloud\NAVRemoteAdministrationSamples folder and Cloud\NAVRemoteAdministration\Azure folder of the provisioning tools.

The Cloud\NAVRemoteAdministrationSamples folder contains the following files that you must modify:

  • Install-NAVBox.ps1

  • HowTo-CreateAzureVM.ps1

  • HowTo-InstallNAVOnVM.ps1

  • HowTo-AddNAVInstance.ps1

  • HowTo-OpenFirewallPort.ps1

  • HowTo-SetAzureVMSize.ps1

  • HowTo-UploadFilesToVM.ps1

The "HowTo” scripts import and call additional scripts from the Cloud\NAVRemoteAdministration folder and its subfolders. Most of the scripts in this folder are generic and should not be modified. However, some of the scripts have dependencies Azure for doing tasks like creating the network, the virtual machines, and the physical storage where the virtual machines are installed. The Azure-specific scripts are all located in the Cloud\NAVRemoteAdministration\Azure folder and include the following:

  • New-NAVAzureBaseVM.ps1

  • New-NAVAzureDataDisk.ps1

  • Copy-VhdFileToAzureStorage.ps1

  • Mount-VhdFileToAzureVM.ps1

  • Dismount-VhdFileFromAzureVM.ps1

  • Wait-VMReadyState.ps1

  • Remove-NAVAzureVM.ps1

  • New-AzureVhdDisk.ps1

  • New-AzureVirtualNetwork.ps1

  • Test-AzureAffinityGroup.ps1

  • Test-AzureVirtualNetwork.ps1

Replace these scripts with scripts that perform similar tasks on your environment.

Note
The scripts in the Cloud\NAVRemoteAdministration\Azure folder are very specific to Azure. The API for your cloud service provider may require a different structure of the scripts. However, the high-level concepts will be similar.

See Also

Tasks

How to: Deploy Microsoft Dynamics NAV on Microsoft Azure by Using the Example Scripts

Concepts

Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure
Deploying Microsoft Dynamics NAV on Two Virtual Machines Using Example-2VM Script
Deploying Microsoft Dynamics NAV on One Virtual Machine Using Example-1VM Script


How to: Deploy Microsoft Dynamics NAV on Microsoft Azure by Using the Example Scripts

This topic describes how to deploy Microsoft Dynamics NAV by using the Example-1VM.ps1 and Example-2VM.ps1 scripts that are available with the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure. The scripts deploy Microsoft Dynamics NAV in different network topologies. For more information, see Deploying Microsoft Dynamics NAV Using the Example Scripts.

To deploy Microsoft Dynamics NAV by using the scripts, you must follow the steps as described in this topic:

Modifying the Parameter Settings

Running the Example Scripts

Modifying the Parameter Settings

The provisioning tools include the Set-PartnerSettings.ps1 script, which by default is located in the WindowsPowerShellScripts\Cloud\HowTo folder on the Microsoft Dynamics NAV installation media (DVD). The Set-PartnerSettings.ps1 script contains parameters that are used by the -1VM.ps1 and Example-2VM.ps1 scripts to configure the Microsoft Dynamics NAV deployment. For example, the Set-PartnerSettings.ps1 file contains parameters that specify the Microsoft Azure subscription, Microsoft Dynamics NAV DVD location, security certificates, and more. Before you run the Example-1VM.ps1 or Example-2VM.ps1 script, you must modify Set-PartnerSettings.ps1 to provide values for all the parameters.

There are two ways to modify the parameters. You can modify the Set-PartnerSettings.ps1 file directly, or you can create a copy of the Set-PartnerSettings.ps1 file, and then modify the copy. Creating a copy of the Set-PartnerSettings.ps1 file is the preferred method, especially in a testing environment, because it enables testers to specify and save different parameter values without having to change the Set-PartnerSettings.ps1 every time.

Note
The procedures in this section use Windows PowerShell Integrated Scripting Environment (ISE) because if its script running, writing, and debugging capabilities. You can use Windows PowerShell if you prefer.

To configure the parameters in the Set-PartnerSettings File

  1. If you have not already done this, prepare for the deployment.

    For more information, see Preparing for Deploying Microsoft Dynamics NAV on Microsoft Azure.

  2. On the computer that you will use to provision Microsoft Dynamics NAV on Azure, run the Windows PowerShell environment as Administrator.

    Important
    You must run Windows PowerShell ISE or Windows PowerShell as an Administrator; otherwise the scripts will not execute correctly.

  3. At the command prompt, change to the Cloud\HowTo folder of the provisioning tools. For example, enter the code:

    Copy Code
    cd <rootdrive>:\Cloud\HowTo

    Substitute <rootdrive> with the drive letter on your computer.

  4. On the File menu, open the Set-PartnerSettings.ps1 file.

    The script is located in the HowTo directory.

  5. To create a copy of the Set-PartnerSettings.ps1 file for editing, do the following:

    1. On the File menu, choose Save As.

    2. Save the file in the same folder as the Set-PartnerSettings.ps1 and give it the name Set-PartnerSettings-CUSTOM.ps1.

      Because you save it in the same folder as Set-PartnerSettings.ps1, the Set-PartnerSettings-CUSTOM.ps1 is automatically loaded by the example scripts.

      Note
      By default, the example scripts search the Cloud\HowTo folder for files that contain the text "custom" in the file name, so it is important that only one custom settings file is included in the folder when you run the scripts.

  6. Open Set-PartnerSettings-CUSTOM.ps1, and then set the parameters as follows.

    By default, parameters are commented lines that are preceded by # TODO.

    To set a parameter, delete the # TODO, and then provide a value for the parameter. For example, the following line of code contains the parameter that specifies the Azure service name, which in turn becomes the virtual machine name:

    Copy Code
    # TODO: $NAV_AzureServiceName = 'MyService'

    To set this parameter to MyCompanyVM, you would change the code to the following:

    Copy Code
    $NAV_AzureServiceName = 'MyCompanyVM'
    Note
    To understand the parameters, use the help content that is provided above each parameter in the script.

  7. When you have set all the parameters, save the file, and then proceed to the next task.

Running the Example Scripts

After you have modified the partner settings, you can run the example scripts to deploy Microsoft Dynamics NAV.

To run the example script

  1. In the Windows PowerShell ISE, open the Example-1VM.ps1 or Example-2VM.ps1 file.

    The scripts are located in the Cloud\HowTo folder of the provisioning tools.

  2. Press F5 to run the script.

    It will take approximately 30-45 minutes for the script to be completed. If the script is completed without errors, then text similar to the following appears in the console:

    Copy Code
    The NAV Server machine is: MyNavVm.cloudapp.net
The NAV Server machine administrator password: 123NavVm!a
The NAV Server Instance is: DynamicsNAV90_Ins1
The NAV Server account credentials: NSTService/P@ssword312
The Windows client can be downloaded via ClickOnce at: http://MyNavVm.cloudapp.net:9004
The Web Client can be accessed at: https://MyNavVm.cloudapp.net/DynamicsNAV90_Ins1
A user has been added to the database with the following credentials:
  user=navuser
  password=N@Vpw312

    New virtual machines appear in the Azure management portal under Virtual Machines, and you can access Microsoft Dynamics NAV from the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client. For more information, see How to: Open Microsoft Dynamics NAV Clients that Connect to Microsoft Dynamics NAV on Microsoft Azure.

See Also

Tasks

How to: Install the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure
How to: Get the Microsoft Azure Image Name

Concepts

Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure
Deploying Microsoft Dynamics NAV on Two Virtual Machines Using Example-2VM Script
Deploying Microsoft Dynamics NAV on One Virtual Machine Using Example-1VM Script
Scaling the Microsoft Dynamics NAV Network Topology


How to: Open Microsoft Dynamics NAV Clients that Connect to Microsoft Dynamics NAV on Microsoft Azure

This topic describes how to open the Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client for a Microsoft Dynamics NAV deployment on Microsoft Azure. When you complete the Microsoft Dynamics NAV deployment by using one of the example scripts that are available with the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure, you receive a message in Windows PowerShell ISE that resembles the following:

Copy Code
The NAV Server machine is: MyNavVm.cloudapp.net
The NAV Server machine administrator password: 123NavVm!a
The NAV Server Instance is: DynamicsNAV90_Ins1
The NAV Server account credentials: NSTService/P@ssword312
The Windows Client can be downloaded via ClickOnce at: http://MyNavVm.cloudapp.net:9004
The Web Client can be accessed at: https://MyNavVm.cloudapp.net/DynamicsNAV90_Ins1
A user has been added to the database with the following credentials:
  user=navuser
  password=N@Vpw312

The Microsoft Dynamics NAV Windows client is available from a ClickOnce web site, which lets you install the client from a web page. The Microsoft Dynamics NAV Web client is available from any supported browser.

To open the Microsoft Dynamics NAV Windows client

  1. Open an Internet browser.

  2. In the address, type the following address:

    http://virtualmachine.cloudapp.net: port

    Substitute virtualmachine with the name of the virtual machine that in running the Microsoft Dynamics NAV Server.

    Substitute port with the TCP port on which ClickOnce website is running. In the Set-PartnerSettings.ps1 file, this is defined by the $NAV_ClickOnceWebSitePort parameter. The default port is 9004

  3. Follow the instructions on the webpage to install the Microsoft Dynamics NAV Windows client.

To open the Microsoft Dynamics NAV Web client

  1. Open an Internet browser.

  2. In the address, type the following address:

    https://virtualmachine.cloudapp.net/DynamicsNAV90_Instance1

    Substitute virtualmachine with the name of the virtual machine that in running the Microsoft Dynamics NAV Server.

See Also

Concepts

Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure
Deploying Microsoft Dynamics NAV on Two Virtual Machines Using Example-2VM Script
Deploying Microsoft Dynamics NAV on One Virtual Machine Using Example-1VM Script
Scaling the Microsoft Dynamics NAV Network Topology


Scaling the Microsoft Dynamics NAV Network Topology

When you deploy for the first time, you will have a Microsoft Dynamics NAV environment that is configured for a single Microsoft Dynamics NAV company. The environment typically consists of a Microsoft Dynamics NAV web server instance, Microsoft Dynamics NAV Server instance, and Microsoft Dynamics NAV database. Depending on the network topology that you chose for deployment, the components will be deployed on one, two, or three computers or virtual machines.

After the initial deployment, you can begin to scale the topology by adding companies, Microsoft Dynamics NAV web server instances, Microsoft Dynamics NAV Server instances, and Microsoft Dynamics NAV databases.

Scaling Configurations

There are four basic configurations for scaling up the Microsoft Dynamics NAV environment: single-server instance, multiple companies - single database, multiple server instances - multiple databases, and multiple-tenant.

Single Server Instance

With the single server instance configuration, each company has its own computer or virtual machine that hosts the Microsoft Dynamics NAV web server instance, Microsoft Dynamics NAV Server instance, and Microsoft Dynamics NAV database. Companies or instances do not share resources.

Scaling NAV on Azure Single instance

Multiple Companies - Single Database

With this configuration, companies share the same Microsoft Dynamics NAV web server instance and Microsoft Dynamics NAV Server instance, and Microsoft Dynamics NAV database on the same computer or virtual machine.

Azure Scaling Multi-Company

Multiple Server Instances - Multiple Databases

With this configuration, companies have their own Microsoft Dynamics NAV web server instance, Microsoft Dynamics NAV Server instance, and Microsoft Dynamics NAV database. Unlike the single-instance configuration, the Microsoft Dynamics NAV components for the companies are installed on the same computer or virtual machine.

NAV on Azure Multi-Instance Scaling

Multiple Tenants

With this configuration, companies share a Microsoft Dynamics NAV Server instance and application database, but have their own business database. The application database contains tables and information that describe the Microsoft Dynamics NAV application and is not specific to companies. The business database, which is referred to as a tenant, stores business data that is specific to the company.

Scaling NAV using multitenancy
Note
A tenant database can contain data for one or more companies.

To support this scenario, you must configure the Microsoft Dynamics NAV environment for multitenancy. For more information, see Migrating to Multitenancy.

How to Scale the Network Topology

To scale the network topology, depending on the task, you use can use Microsoft Dynamics NAV 2016 Administration Shell, Microsoft Dynamics NAV Server Administration tool, Microsoft Dynamics NAV Development Environment, Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client. The following table lists the tasks and the methods that you can use to perform the tasks.

Task | Administration Shell | Administration Tool | Development Environment | Windows/Web client | For more information, see
Add Microsoft Dynamics NAV Server instance | X | X |  |  | How to: Add a Microsoft Dynamics NAV Server Instance (Administration Shell) How to: Create a Microsoft Dynamics NAV Server Instance (Administration Tool)
Add Microsoft Dynamics NAV web server instance | X |  |  |  | How to: Add a Microsoft Dynamics NAV Web Server Instance
Mount a tenant on a Microsoft Dynamics NAV Server instance | X | X |  |  | How to: Mount a Tenant (Administration Shell) How to: Mount or Dismount a Tenant on a Microsoft Dynamics Server Instance (Administration Tool)
Add Microsoft Dynamics NAV database | X |  | X |  | How to: Add a Microsoft Dynamics NAV Database (Administration Shell) How to: Create Databases (Development Environment)
Add Microsoft Dynamics NAV company | X |  |  | X | How to: Add a Microsoft Dynamics NAV Company (Administration Shell) How to: Create a New Company (Windows or Web client)
Note
For Microsoft Dynamics NAV deployment on Microsoft Azure, we recommend that you establish a remote desktop connection to the virtual machines.

See Also

Concepts

Multitenant Deployment Architecture
Network Topologies for Microsoft Dynamics NAV on Azure
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure


How to: Add a Microsoft Dynamics NAV Web Server Instance

This topic describes how to use the Microsoft Dynamics NAV Administration Shell to add a Microsoft Dynamics NAV web server instance on a computer or virtual machine. The Microsoft Dynamics NAV 2016 Administration Shell includes the New-NAVWebServerInstance cmdlet that creates an application on IIS for the Microsoft Dynamics NAV Web client.

To add a Microsoft Dynamics NAV web server instance

  1. On the computer or virtual machine that is running Microsoft Dynamics NAV Server, run Microsoft Dynamics NAV Administration Shell as an Administrator.

    1. Choose Start, in the Search box, type Microsoft Dynamics NAV Administration Shell.

    2. Right-click the related link, and then choose Run as Administrator.

  2. At the command prompt, type the following command:

    Copy Code
    New-NAVWebServerInstance -WebServerInstance <MyWebApp> -Server <NAVServer> -ServerInstance <NAVServerInstance> -ClientServicesCredentialType <NAVCredentialType>

    Change the following parameter values.

    Parameter Description

    <MyWebApp>

    Specifies the name that you want to give the Microsoft Dynamics NAV Web client application instance. This name will become part of the URL for the Microsoft Dynamics NAV Web client application, for example, http://MyWebServer:8080/MyWebApp/WebClient.

    <NAVServer>

    Specifies the name of the computer that is running the Microsoft Dynamics NAV Server to connect the Microsoft Dynamics NAV web server to.

    <NAVServerInstance>

    Specifies the name of the Microsoft Dynamics NAV Server instance to connect the web server instance to.

    <NAVCredentialType>

    Specifies the credential type that is configured for the Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Server. Valid options are NavUserPassword, Windows, UserName, and AccessControlService. The default value is NavUserPassword.

    Important
    The credential type must match the credential type that is used by the Microsoft Dynamics NAV web server to authenticate Microsoft Dynamics NAV Web client users. For more information, see Configuring the Credential Type on the Microsoft Dynamics NAV Web Client.

    Note
    The command that is shown includes only the required parameters of the NAVWebServerInstance cmdlet. The cmdlet has several other parameters that can be used to configure the web server instance. For more information about the syntax and parameters, see New-NAVWebServerInstance cmdlet topic in the Administration Cmdlets for Microsoft Dynamics NAV section of the Technical Reference.

  3. Press Enter to run the cmdlet.

    A new Microsoft Dynamics NAV web server instance with the specified name is added to the Microsoft Dynamics NAV Web client site on IIS.

    Note
    If you want to change the configuration of the new Microsoft Dynamics NAV web server instance after it has been added, modify the web.config file. For more information, see Configuring Microsoft Dynamics NAV Web Client by Modifying the Web.config File.

Example

This example creates a new Microsoft Dynamics NAV web server instance that is named MyNavApp. The Microsoft Dynamics NAV web server instance connects to the DynamicsNAV90 server instance on the MyNavServer computer.

Copy Code
New-NAVWebServerInstance -WebServerInstance MyNavApp -Server MyNavServer -ServerInstance DynamicsNAV90 -Company MyNavCompany -ClientServicesCredentialType NavUserPassword

To open the Microsoft Dynamics NAV Web client for this example, open the following URL in a web browser:

http://mymachine.cloudapp.net/MyNavApp

See Also

Tasks

How to: Set Up Multiple Web Server Instances for the Microsoft Dynamics NAV Web Client
How to: Add a Microsoft Dynamics NAV Server Instance
How to: Add a Microsoft Dynamics NAV Database
How to: Add a Microsoft Dynamics NAV Company

Concepts

Scaling the Microsoft Dynamics NAV Network Topology
Deploying the Microsoft Dynamics NAV Web Server Components
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure


How to: Add a Microsoft Dynamics NAV Server Instance

This topic describes how to add a new Microsoft Dynamics NAV Server instance to an existing Microsoft Dynamics NAV Server installation. To add a Microsoft Dynamics NAV Server instance, you use the New-NAVServerInstance cmdlet of the Microsoft Dynamics NAV 2016 Administration Shell.

You specify the name for the instance, the Microsoft Dynamics NAV database to connect to, and the TCP ports for the following services:

  • Management services port

    This specifies the TCP port for the Microsoft Dynamics NAV Server Administration tool.

  • Client services port

    This specifies TCP port for the Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client.

  • SOAP web services port.

  • OData web services port.

Tip
You can also add Microsoft Dynamics NAV Server instances by using the Microsoft Dynamics NAV Server Administration tool. For more information, see How to: Create a Microsoft Dynamics NAV Server Instance.

To add a Microsoft Dynamics NAV Server instance

  1. On the computer or virtual machine that is running Microsoft Dynamics NAV Server, run Microsoft Dynamics NAV Administration Shell as an Administrator.

    1. Choose Start, in the Search box, type Microsoft Dynamics NAV Administration Shell.

    2. Right-click the related link, and then choose Run as Administrator.

  2. At the command prompt, type the following command:

    Copy Code
    New-NAVServerInstance <MyInstance> -ServiceAccount <ServiceAccount> -ManagementServicesPort <PortNumber> -ClientServicesPort <PortNumber> -SOAPServicesPort <PortNumber> -ODataServicesPort <PortNumber> -DatabaseInstance <DatabaseInstance> -DatabaseName <DatabaseName> -DatabaseServer <DatabaseServer>

    Change the following parameter values.

    Parameter Description

    <MyInstance>

    Specifies the name that you want to give the Microsoft Dynamics NAV Server instance.

    <ServiceAccount>

    Specifies the Windows account to use to log on to the Microsoft Dynamics NAV Server.

    <PortNumber>

    Specifies the TCP port number to use for the associated service.

    <DatabaseInstance>

    Specifies the name of the SQL Server database instance to connect to.

    If you are connecting to the same database instance as the existing Microsoft Dynamics NAV Server instance, then you can omit this parameter and value.

    <DatabaseName>

    Specifies the name of the Microsoft Dynamics NAV database.

    <DatabaseServer>

    Specifies the name of the Microsoft Dynamics NAV database in SQL Server. The name has the domain\computername format.

    If you are connecting to the same database as the existing Microsoft Dynamics NAV Server instance, then you can omit this parameter and value.

    Note
    The command that is shown includes only a subset of the parameters of New-NAVServerInstance cmdlet. For more information about the syntax and parameters, see New-NAVServerInstance topic in the Administration Cmdlets for Microsoft Dynamics NAV section of the Technical Reference.

  3. Press Enter to run the cmdlet.

    A new Microsoft Dynamics NAV Server instance with the specified name is added on the virtual machine in the C:\Program Files\Microsoft Dynamics NAV\90\Service\Instances folder.

    Note
    If you want to change the configuration of the new Microsoft Dynamics NAV Server instance after it has been added, see Configuring Microsoft Dynamics NAV Server.

Example

The following example creates a new Microsoft Dynamics NAV Server instance. It will enable communication on the service ports through the Windows Firewall.

Copy Code
New-NAVServerInstance MyNavInstance -ServiceAccount NetworkService -ManagementServicesPort 8099 -ClientServicesPort 8100 -SOAPServicesPort 8101 -ODataServicesPort 8102 -verbose

See Also

Tasks

How to: Add a Microsoft Dynamics NAV Web Server Instance
How to: Add a Microsoft Dynamics NAV Database
How to: Add a Microsoft Dynamics NAV Company

Concepts

Scaling the Microsoft Dynamics NAV Network Topology
Microsoft Dynamics NAV Server
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure


How to: Add a Microsoft Dynamics NAV Database

This topic describes how add a new Microsoft Dynamics NAV database instance to SQL Server from a database backup file (.bak). To add a Microsoft Dynamics NAV database, you use the New-NAVDatabase cmdlet of the Microsoft Dynamics NAV 2016 Administration Shell.

Tip
You can also create a database from the Microsoft Dynamics NAV Development Environment. For more information, see How to: Create Databases.

To add a Microsoft Dynamics NAV database

  1. On the computer that is running Microsoft Dynamics NAV Server, run Microsoft Dynamics NAV Administration Shell as an Administrator.

    1. Choose Start, in the Search box, type Microsoft Dynamics NAV Administration Shell.

    2. Right-click the related link, and then choose Run as Administrator.

  2. At the command prompt, type the following command:

    Copy Code
    New-NAVDatabase -FilePath <DatabaseBAKfile> -DatabaseName <MyNavDatabase> -DatabaseInstance <DatabaseInstance> -DatabaseServer <DatabaseServer> -ServiceAccount <ServiceAccount>

    Change the following parameter values.

    Parameter Description

    <DatabaseBAKfile>

    Specifies the path and file name of the Microsoft Dynamics NAV database backup file that you want to restore.

    <MyNavDatabase>

    Specifies the name to give the new database in SQL Server.

    <DatabaseInstance>

    Specifies the name of the SQL Server database instance to connect to.

    If you there is only one database instance on the SQL server, then you can omit this parameter. The default instance is DynamicsNAV70_Instance1.

    <DatabaseServer>

    Specifies the name of the computer that is running SQL Server. The name has the domain\computername format.

    If this is the computer that you are working from, then you can omit this parameter.

    <ServiceAccount

    Specifies the logon account that runs the Microsoft Dynamics NAV Server instance.

    This account is given the appropriate permissions to the database when you run the cmdlet. For more information, see Provisioning the Microsoft Dynamics NAV Server Account. If you do not specify an account, then Network Service is used.

    Note
    The command that is shown includes only a subset of all the parameters of the New-NavDatabase cmdlet. For more information about the syntax and parameters, see New-NAVDatabase topic in the Administration Cmdlets for Microsoft Dynamics NAV section of the Technical Reference.

  3. Press Enter to run the cmdlet.

    A new Microsoft Dynamics NAV database that has the specified name is added on SQL Server.

Example

The following example restores a database and preserves the original file names, locations, and logon accounts.

Copy Code
New-NavDatabase -FilePath C:\Backups\NavDemoDatabase.bak -DatabaseName MyNewDatabase -verbose

See Also

Tasks

How to: Add a Microsoft Dynamics NAV Server Instance
How to: Add a Microsoft Dynamics NAV Web Server Instance
How to: Add a Microsoft Dynamics NAV Company

Concepts

Scaling the Microsoft Dynamics NAV Network Topology
SQL Server Database Components
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure


How to: Add a Microsoft Dynamics NAV Company

This topic describes how to add a new company to a Microsoft Dynamics NAV database on a computer or virtual machine. To add a Microsoft Dynamics NAV company, you use the New-NAVCompany cmdlet of the Microsoft Dynamics NAV 2016 Administration Shell.

Tip
You can also create a company from the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client. For more information, see How to: Create Companies.

To add a Microsoft Dynamics NAV company

  1. On the computer that is running the Microsoft Dynamics NAV Server, run Microsoft Dynamics NAV Administration Shell as an Administrator.

    1. Choose Start, in the Search box, type Microsoft Dynamics NAV Administration Shell.

    2. Right-click the related link, and then choose Run as Administrator.

  2. At the command prompt, type the following command:

    Copy Code
    New-NAVCompany -ServerInstance <NAVServerInstance> -CompanyName <MyCompanyName>

    Or if you have a multitenant Microsoft Dynamics NAV deployment, then type the following command:

    Copy Code
    New-NAVCompany -ServerInstance <NAVServerInstance> -CompanyName <MyCompanyName> -Tenant <TenantId>

    Change the following parameter values.

    Parameter Description

    <NAVServerInstance>

    Specifies the Microsoft Dynamics NAV Server instance that the company uses, such as DynamicsNAV90.

    <MyCompanyName>

    Specifies the name of the company that you want to create. If a company with that name already exists in the Microsoft Dynamics NAV database, the cmdlet fails.

    <TenantId>

    Specifies the ID of the tenant that the company must be created in, such as Tenant1. This parameter is required unless the specified service instance is not configured to run multiple tenants.

    Note
    The command that is shown includes only a subset of all the parameters of the New-NavCompany cmdlet. For more information about the syntax and parameters, see New-NAVCompany topic in the Administration Cmdlets for Microsoft Dynamics NAV section of the Technical Reference.

  3. Press Enter to run the cmdlet.

    A new Microsoft Dynamics NAV company that has the specified name is created.

See Also

Tasks

How to: Add a Microsoft Dynamics NAV Web Server Instance
How to: Add a Microsoft Dynamics NAV Database
How to: Add a Microsoft Dynamics NAV Server Instance

Concepts

Scaling the Microsoft Dynamics NAV Network Topology
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure


How to: Mount a Tenant

This topic describes how to mount a tenant database on a Microsoft Dynamics NAV Server instance in a multitenant Microsoft Dynamics NAV deployment. To mount a tenant database, you use the Mount-NAVTenant cmdlet of the Microsoft Dynamics NAV 2016 Administration Shell.

Tip
You can also mount a tenant by using the Microsoft Dynamics NAV Server Administration tool. For more information, see How to: Mount or Dismount a Tenant on a Microsoft Dynamics Server Instance.

To mount a tenant database on a Microsoft Dynamics NAV Server instances

  1. On the computer that is running the Microsoft Dynamics NAV Server, run Microsoft Dynamics NAV Administration Shell as an Administrator.

    1. Choose Start, in the Search box, type Microsoft Dynamics NAV Administration Shell.

    2. Right-click the related link, and then choose Run as Administrator.

  2. At the command prompt, type the following command:

    Copy Code
    Mount-NAVTenant [-ServerInstance] <NAVServerInstance> -DatabaseName <NAVDatabase> -DatabaseServer <MyDatabaseServer

    Change the following parameter values.

    Parameter Description

    <NAVServerInstance>

    Specifies the Microsoft Dynamics NAV Server instance that you want to mount the tenant against, such as DynamicsNAV90.

    <NAVDatabase>

    Specifies the name of the Microsoft Dynamics NAV database that you want to mount against the Microsoft Dynamics NAV Server instance, such as 'Demo Database NAV (7-1)'.

    <MyDatabaseServer>

    Specifies the name of the database server that hosts the Microsoft Dynamics NAV database that you want to mount against the Microsoft Dynamics NAV Server instance.

    Note
    The command that is shown includes only a subset of all the parameters of the Mount-NavTenant cmdlet. For more information about the syntax and parameters, see Mount-NAVTenant topic in the Administration Cmdlets for Microsoft Dynamics NAV section of the Technical Reference.

  3. Press Enter to run the cmdlet.

    The tenant database is mounted on the Microsoft Dynamics NAV Server instance.

See Also

Tasks

How to: Add a Microsoft Dynamics NAV Web Server Instance
How to: Add a Microsoft Dynamics NAV Database
How to: Add a Microsoft Dynamics NAV Server Instance

Concepts

Scaling the Microsoft Dynamics NAV Network Topology
Multitenant Deployment Architecture
Migrating to Multitenancy
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure


Administration of Microsoft Dynamics NAV on Microsoft Azure

This topic discusses the following administration concepts and tasks for Microsoft Dynamics NAV deployments on Microsoft Azure.

  • User Authentication

  • SQL Server on Azure Virtual Machines

  • Fault Tolerance

  • Changing the Azure Virtual Machine Size

  • Managing Microsoft Dynamics NAV Hotfixes

User Authentication

Microsoft Dynamics NAV supports four different credential types for authenticating users:

  • NavUserPassword

  • Windows

  • UserName

  • AccesControlService

These credential types are also supported for Microsoft Dynamics NAV deployments on Azure. By default, the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure configure NavUserPassword credential type for Microsoft Dynamics NAV deployments on Azure. However, you can configure the deployment for any of the available credential types.

You can change the credential type programmatically by modifying the provisioning tools scripts or manually by establishing a Remote Desktop connection to the virtual machine that is running Microsoft Dynamics NAV Web Server components and Microsoft Dynamics NAV Server, and then modifying the configuration of these components. You must also configure the credential type in Microsoft Dynamics NAV user accounts.

For more information, see Users and Credential Types.

Note
The provisioning tools automatically configure a default Microsoft Dynamics NAV user who is assigned the SUPER permission set. For more information, see Security and Protection for Microsoft Dynamics NAV on Microsoft Azure.

NavUserPassword Credential Type

With the NavUserPassword credential type, authentication is managed by Microsoft Dynamics NAV Server but is not based on Windows users or Azure Active Directory (Azure AD). The user is prompted for user name and password credentials when they start the client. The credentials are then validated by an external mechanism. Security certificates are required to protect the passing of credentials. This mode is intended for hosted environments, for example, where Microsoft Dynamics NAV is implemented in Azure.

Windows or UserName Credential Type

The Windows and UserName credential types authenticate users against a Windows account in Active Directory. To use the Windows or UserName credential type, you must have an Active Directory domain controller in the same virtual network as the virtual machines that are running Microsoft Dynamics NAV components. The virtual machines must be joined to the domain and Microsoft Dynamics NAV users must have a Windows account in Active Directory. For more information, see Windows Server Active Directory on Azure VMs.

With the Windows credential type, users are authenticated using their Windows credentials. Users are not prompted for credentials when they start the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client.

You should use the UserName credential type instead of the Windows credential type if users will access Microsoft Dynamics NAV from devices that are not part of the domain. The UserName credential type uses Form authentication for the Microsoft Dynamics NAV Web client. When users access the Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client, they are prompted to enter their Windows credentials.

AccessControlService Credential Type

Azure Access Control service (ACS) is a cloud service that provides user authentication and authorization for web applications and services. To configure ACS to authenticate users, you must set up the ACS provider, and then configure the Microsoft Dynamics NAV components and users for the ACS credential type.

For more information, see Authenticating Users with Microsoft Azure Access Control Service.

SQL Server on Azure Virtual Machines

When you deploy Microsoft Dynamics NAV on Azure virtual machines, you can create an SQL server for hosting the Microsoft Dynamics NAV database. Depending on whether you built a new Microsoft Dynamics NAV database on Azure or migrated an existing Microsoft Dynamics NAV database, Azure virtual machines provide robust infrastructure for SQL Server. You can control and manage the Microsoft Dynamics NAV database by using the same development and administration tools that are available with on-premise installations.

For more information, see SQL Server in Azure Virtual Machines.

Backing Up and Restoring the Microsoft Dynamics NAV Database

Backing up the Microsoft Dynamics NAV database on SQL Server on Azure virtual machines provides a safeguard for protecting critical data. The guidelines for backing up and restoring the Microsoft Dynamics NAV database on Azure are like on-premise installations of Microsoft Dynamics NAV.

For more information, see Backup and Restore for SQL Server in Azure Virtual Machines.

Optimizing SQL Server Performance with Microsoft Dynamics NAV

There are several procedures that you can perform to optimize the performance in Microsoft Dynamics NAV when you access data from the SQL Server database. For more information, see Optimizing SQL Server Performance with Microsoft Dynamics NAV.

Fault Tolerance

Azure offers geo redundant storage (GRS) that replicates data to guarantee fault tolerance and avoid a single point of failure. Additionally, most high availability and disaster recovery (HADR) database system solutions that are available in SQL Server are supported in Azure virtual machines.

For more information, see the following topics:

  • What is a Storage Account?

  • Introducing Geo-replication for Azure Storage

  • High Availability and Disaster Recovery for SQL Server in Azure Virtual Machines

Changing the Azure Virtual Machine Size

When you deploy Microsoft Dynamics NAV on Azure by using the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure, you specify the size of the virtual machines that are created on Azure. The virtual machine size determines the number of CPU cores, the memory capacity, and the local file system size that is allocated to a running virtual machine. In the Example-1VM and Example-2VM scripts of the provisioning tools, the virtual machine size is set by the $NAV_VMSize parameter in the Set-PartnerSettings file. The provisioning tools support the following sizes: Small, Medium, Large, ExtraLarge, A6, and A7. After the initial deployment, you can change the virtual machine size to suit your requirements.

For more information, see Configure Virtual Machine Sizes.

Managing Microsoft Dynamics NAV Hotfixes

A hotfix is typically a package of one or more files that fix problems in Microsoft Dynamics NAV. Microsoft Dynamics NAV hotfixes are released for the application and platform.

Installing a Hotfix on an Existing Microsoft Dynamics NAV Deployment on Azure

You install a hotfix on a Microsoft Dynamics NAV deployment on Azure just like you install a hotfix on an on-premise deployment of Microsoft Dynamics NAV. To install a hotfix, you establish a Remote Desktop Connection to the Azure virtual machine that is running the Microsoft Dynamics NAV components, and then install the hotfix files to the Microsoft Dynamics NAV installation folder on the virtual machine.

For more information about how to install Microsoft Dynamics NAV application and platform hotfixes, see How to install a Microsoft Dynamics NAV 2013 update rollup (requires a PartnerSource account).

Installing a Hotfix on the Microsoft Dynamics NAV Installation Media

Before you deploy Microsoft Dynamics NAV on Azure, you can install a hotfix on the Microsoft Dynamics NAV installation media that you will use for the deployment. This makes sure that future Microsoft Dynamics NAV deployments on Azure include the hotfix changes. To install a hotfix, copy the hotfix files to the location of the Microsoft Dynamics NAV installation media.

See Also

Concepts

Planning and Preparing
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure
Deploying Microsoft Dynamics NAV Using the Example Scripts
Security and Protection for Microsoft Dynamics NAV on Microsoft Azure


Security and Protection for Microsoft Dynamics NAV on Microsoft Azure

This topic contains the following information and recommendations about the security and protection of Microsoft Dynamics NAV on Microsoft Azure.

  • User Accounts Created by the Microsoft Dynamics NAV Provisioning Tools

  • Clients and Services

  • Remote Desktop (RDP)

  • Windows PowerShell Remoting

  • Custom Images for Azure Virtual Machines

  • Antivirus Software

User Accounts Created by the Microsoft Dynamics NAV Provisioning Tools

When you deploy Microsoft Dynamics NAV, the example scripts of the Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure automatically create the following user accounts on the virtual machines:

  • Azure virtual machine administrator account.

  • Service account for Microsoft Dynamics NAV Server.

  • Microsoft Dynamics NAV user account.

User Name and Passwords for the User Accounts

When you deploy Microsoft Dynamics NAV by using the example scripts, you specify the user name and passwords in the Set-PartnerSettings.ps1 file. The Set-PartnerSettings.ps1 file includes a user name parameter and password parameter for every user account. If you do not provide a value for a password parameter, then the provisioning tools will automatically generate and assign a password to the account.

Like any computer, an Azure virtual machine is a potential object for a security attack. When you set the password, make sure that the password meets the Windows Server password complexity requirements. For more information, see Passwords must meet complexity requirements.

Azure Virtual Machine Administrator Accounts

The provisioning tools create new virtual machines on which Microsoft Dynamics NAV components are installed. On each virtual machine, the provisioning tools create a local Windows user account in the Administrator group. In the Set-PartnerSettings.ps1 file of the example scripts, you specify the user name and password for the virtual machine accounts by setting the following parameters:

  • $NAV_VMAdminUserName

  • $NAV_VMAdminPassword

  • $NAV_SqlServerMachineAdminUserName

  • $NAV_SqlServerMachineAdminPassword

Important
Any account that is a member of the Windows Administrator group of a virtual machine has rights to execute administrative operations on Microsoft Dynamics NAV Server instances through the Microsoft Dynamics NAV Administration Tool.

Microsoft Dynamic NAV Server Service Account

Microsoft Dynamics NAV Server is a Windows service that is configured to run under a specific Windows user account. The provisioning tools automatically create and configure a service account for the Microsoft Dynamics NAV Server. In the Set-PartnerSettings.ps1 file of the example scripts, you specify the Microsoft Dynamics NAV Server service account by setting the $NAV_WindowsServiceAccount parameter and $NAV_WindowsServiceAccountPassword parameter.

If there is more than one Microsoft Dynamics NAV Server instance on the virtual machine, then you should create a separate service account for every instance.

You should control the resources, such as files and directories, on the virtual machines that the service accounts can access by configuring Access Control Lists (ACLs) for the resources. For more information, see Access Control Lists.

Note
The service account does not have to be a member of the Administrator group.

For more information about the service account, see Provisioning the Microsoft Dynamics NAV Server Account.

Default Microsoft Dynamics NAV User

The provisioning tools create a default Microsoft Dynamics NAV user who is assigned the SUPER permission set. The user is given access to all companies in the Microsoft Dynamics NAV database. In the Set-PartnerSettings.ps1 file of the example scripts, you specify the Microsoft Dynamics NAV user by setting the $NAV_NAVAdminUserName parameter and the $NAV_NAVAdminPassword parameter.

Note
For the Microsoft Dynamics NAV user account, if you specify a user name that is already being used by a user account in the Microsoft Dynamics NAV database, then a new user is not created. Only the password of the existing user account is changed. The existing user account will not be assigned the SUPER permission set unless it is already assigned.

The first time that you try to sign in to Microsoft Dynamics NAV by using the default Microsoft Dynamics NAV user account, you will be asked to change the password.

Clients and Services

The Microsoft Dynamics NAV Provisioning Tools for Microsoft Azure configures several communication endpoints on Azure virtual machines that support clients, services, and remote administration of Microsoft Dynamics NAV.

Microsoft Dynamics NAV Web Client

The provisioning tools install a website on IIS on the virtual machine. The website acts as a container for one or more web server instances for the Microsoft Dynamics NAV Web client. To help secure the Microsoft Dynamics NAV data transmission, the provisioning tools scripts configure Secure Sockets Layer (SSL) on the connection to Microsoft Dynamics NAV Web client according to the following:

  • Create a binding that uses HTTPS communication protocol on port 443.

  • Apply an SSL certificate to the binding. You specify the SSL certificate in the Set-PartnerSettings file of the provisioning tools.

  • Open port 443 through Windows Firewall of the virtual machine and add the port to the Azure service endpoints.

For more information about SSL for the Microsoft Dynamics NAV Web client, see How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client.

Microsoft Dynamics NAV Windows Client

The provisioning tools configure a ClickOnce website from which users can install the Microsoft Dynamics NAV Windows client. To secure the ClickOnce installation, the provisioning tools implement a security certificate on the website. When you deploy Microsoft Dynamics NAV with the provisioning tools, you can specify the certificate in the Set-PartnerSetting file that is used by the example scripts. There are no specific security considerations for using the Microsoft Dynamics NAV Windows client that is deployed by the provisioning tools. The provisioning tools automatically configure the connection to Microsoft Dynamics NAV Server instance that is used by the Microsoft Dynamics NAV Windows client. The communication port that is used by a Microsoft Dynamics NAV Server instance is opened through Windows Firewall and added as an endpoint in Azure.

Remote Desktop (RDP)

The provisioning tools enable Remote Desktop connections to virtual machines on Azure. We recommend that you limit scope of the IP addresses that have permission to establish a Remote Desktop connection to the virtual machine. To do this, modify the inbound rule that enables Remote Desktop connections (RDP traffic) in Windows Firewall of the virtual machine.

For more information, see Remote Desktop Services and Windows Firewall.

Windows PowerShell Remoting

To deploy Microsoft Dynamics NAV by using the provisioning tools, Window PowerShell Remoting must be enabled on the Azure virtual machines. If you use an Azure Gallery image when you deploy Microsoft Dynamics NAV, then Windows PowerShell Remoting is enabled by default. If you are using a custom image, then make sure that Windows PowerShell Remoting is enabled on the image. For more information, see How to: Create a Microsoft Azure Virtual Machine Operating System Image for Microsoft Dynamics NAV.

When provisioning tools scripts are executed at provisioning, a Windows PowerShell remote session is established from the provisioning computer to the Azure virtual machine. To help secure the communication, the provisioning tools implement a Windows Remote Management (WinRM) session that uses an HTTPS listener with a SSL certificate.

After you deploy Microsoft Dynamics NAV, you can establish a Windows PowerShell remote session to the Azure virtual machines and run additional Windows PowerShell cmdlets and scripts to configure the deployment. We recommend that you set up HTTPS on the Windows PowerShell remote session.

Microsoft Dynamics NAV Development Environment

When you use the Microsoft Dynamics NAV Development Environment to develop Microsoft Dynamics NAV applications on Azure virtual machines, we recommended that you establish a Remote Desktop connection to the virtual machine, and then run the development environment on the virtual machine. If you open ports in Windows Firewall on the SQL Server computer to enable access the Microsoft Dynamics NAV database from a remote computer, then you introduce a potential security risk.

Custom Images for Azure Virtual Machines

The provisioning tools example scripts create virtual machines based on a VHD image that you specify in the Set-PartnerSettings.ps1 file when you run the scripts. Instead of using an image from the Azure Marketplace, you can create a custom image. If you are using a custom image, then you should make sure that the image aligns with Microsoft solution accelerators. For more information, see Microsoft Solution Accelerators.

For more information about how to create an image, see How to: Create a Microsoft Azure Virtual Machine Operating System Image for Microsoft Dynamics NAV.

Antivirus Software

Virtual machines that are created by the provisioning tools are standard Windows machines and should be protected by using common protection mechanisms. Azure provides virtual machines as an Infrastructure as a Service (IaaS), which means that you are responsible for the day-to-day protection of the virtual machine. We recommended that you use antivirus software and keep the software updated.

See Also

Tasks

How to: Deploy Microsoft Dynamics NAV on Microsoft Azure by Using the Example Scripts

Concepts

Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure


Troubleshooting: Import-NAVEncryptionKey Cmdlet: Windows Comminication Foundation The path to Windows Communication Foundation was not found on the service tier

If the Microsoft Dynamics NAV Server instance is on an Azure virtual machine that is running Windows Server 2012 R2, you get the following error when you run the Import-NAVEncryptionkey cmdlet:

Import-NAVEncryptionKey : The path to Windows Communication Foundation was not found on the service tier. It was expected to be in folder'C:\Windows\Microsoft.NET\Framework64\v3.0\Windows Communication Foundation'.Have you installed the .NET Framework 3.0?

Resolution

You must install the HTTP Activation feature on the Azure virtual machine. Perform one of the following procedures:

  • Run the Microsoft Dynamics NAV Administration Shell as Administrator, and then run the following cmdlet:

    Copy Code
    install-windowsfeature -Name NET-HTTP-Activation
  • Open Server Manager, and then use the Add Roles and Features Wizard to install HTTP Activation, which is available under the .NET Framework 3.5 feature.

    For more information, see Install or Uninstall Roles, Role Services, or Features.

See Also

Concepts

Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure


Deploying Microsoft Dynamics NAV Using ClickOnce

This document contains instructions for deploying the Microsoft Dynamics NAV Windows client using the ClickOnce deployment technology. ClickOnce allows you to deploy web applications by choosing a link on a web page. ClickOnce is a component of the Microsoft .NET Framework.

ClickOnce Installation

This section covers the end user experience of installing Microsoft Dynamics NAV deployed with ClickOnce. The end user will choose the link to the application to install Microsoft Dynamics NAV. The link may point to a file share or a website. The ClickOnce runtime opens with a confirmation dialog box, which asks whether you want to install the application and includes an Install and Don't Install button.

If you choose the Install button, ClickOnce downloads all the necessary files to a local folder on your computer.

When the download is complete, ClickOnce starts the Microsoft Dynamics NAV Windows client, and also installs a program shortcut on the Start menu of the computer.

The next time that you want to run the Microsoft Dynamics NAV Windows client, you can either select the link again, or you select the shortcut on the Start menu. In either case, ClickOnce will check if there is a newer version available, which you will have the option to install.

No configuration of the ClientUserSettings.config file is needed during install or after install as this is set up as part of the ClickOnce deployment.

Benefits of a ClickOnce Deployment of the Microsoft Dynamics NAV Windows Client

ClickOnce includes the following benefits:

  • Allows for a centralized configuration. The ClientUserSettings.config configuration file that is installed with the Microsoft Dynamics NAV Windows client contains several settings that must be adjusted for the specific installation, such as the server address and the authentication type to use. By using ClickOnce, you can control the ClientUserSettings.config centrally and push it out to the client computers. Configuration is not required on the individual client computer. If you make a mistake, or if the settings have to change, such as if you want to move the Microsoft Dynamics NAV Server instance to a different computer, then you can create an updated configuration file by using the upgrade capability.

  • Allows for bundled add-ins. By using ClickOnce, you can easily deploy your own assemblies and third-party add-in assemblies. You do not have to copy add-in files after the installation.

  • You can have side-by-side installations. You cannot have two MSI-based Microsoft Dynamics NAV Windows clients on the same computer. A ClickOnce-deployed Microsoft Dynamics NAV Windows client does not interfere with other ClickOnce-deployed Microsoft Dynamics NAV Windows clients. This makes it easy to run against different servers from the same computer. For example, you could have two Microsoft Dynamics NAV Windows client installations, one for a production server and one for a test server. This also means that you can run different versions of the Microsoft Dynamics NAV Windows client side-by-side, which is not possible with MSI.

  • Multiple languages can be included in the same installer. By using ClickOnce, you can decide which files, such as language resource files and Help files, that you want to include in the deployment. End users will not be aware of the difference between installing an EN-US-only version and a version with several additional languages.

  • Administrator permissions are not required. By using ClickOnce, a typical Windows user can install the Microsoft Dynamics NAV Windows client. The prerequisites for installation require administrator permissions. These prerequisites have to be installed one time on the computer, after which any user can install and upgrade the Microsoft Dynamics NAV Windows client.

  • ClickOnce supports a seamless upgrade. End users will hardly notice when the Microsoft Dynamics NAV Windows client is upgraded.

The result should be that end users can install the Microsoft Dynamics NAV Windows client without relying on partners or super users to do it for them.

There are some limitations of a ClickOnce-installed Microsoft Dynamics NAV Windows client. For more information, see Limitations of ClickOnce Installed on the Microsoft Dynamics NAV Windows Client.

Technical Overview of ClickOnce

ClickOnce is a standard .NET technology that has existed since .NET Framework 2.0. The instructions in this document are meant to help you start working with ClickOnce deployment, however ClickOnce has additional features that are not described in this document.

The file structure of a ClickOnce deployment is as follows:

  • Assuming that you have a folder that contains your application files, such as the EXE, DLLs, configuration files, and other files that your application needs. The files should be organized in subfolders as appropriate for your application to work correctly.

  • You create an XML file, usually called the application manifest. This file should be suffixed with .manifest, and added in the root of your application folder. The application manifest file contains metadata about your application including a list of all the files, which file is the main executable file, and so on.

  • You create another XML file, usually called the deployment manifest. This file should be suffixed with .application, and added to the directory outside the root of your application folder. The deployment manifest has a link to the application manifest. It also has information about the application, such as a product name, version number, and so on. This information will be shown in locations such as the Start menu and in Add or Remove Programs.

When a user installs the application, he runs the deployment manifest, and then ClickOnce will automatically install the application.

Installing Prerequisites

The Microsoft Dynamics NAV Windows client has three prerequisites: Microsoft Report Viewer 2015, Microsoft System CLR Types for SQL Server 2014, and .NET Framework 4.5. These are linked from the sample web page.

  • The install experience can be improved for the end user by providing a solution that packages the Microsoft Report Viewer with the ClickOnce installation. Microsoft Report Viewer requires Microsoft System CLR Types for SQL Server 2014. Microsoft Certified Partners may download and redistribute the Microsoft Report Viewer 2015 Redistributable Package and Microsoft System CLR Types for SQL Server 2014 from the Microsoft Download Center. You can download Microsoft Report Viewer at Microsoft Report Viewer 2015 RUNTIME. Microsoft System CLR Types for SQL Server 2014 is available as part of the Microsoft SQL Server 2014 Feature Pack, which you can download at Microsoft SQL Server 2014 Feature Pack.

    Note
    The Microsoft Report Viewer is an optional component. If it is not installed, the end user will get an error message when trying to print or preview reports in the Microsoft Dynamics NAV Windows client. All other functionality in the client will not be affected.

  • The .NET Framework 4.5 is pre-installed on Windows 8 and Windows Server 2012 computers and no action has to be taken. For more information about how to install .NET 4.5 Framework on earlier versions of Windows, see Installing .NET 4.5 Framework.

Installing these prerequisites requires administrative rights on the computer. If the end users are not already administrators on their computers, then an administrator or a super user must first install the prerequisite on the computer. After that is complete, any user on the computer can install, uninstall, and upgrade the Microsoft Dynamics NAV Windows client. Administrative rights are not needed for the Microsoft Dynamics NAV Windows client.

Microsoft Windows operating systems are subject to compliance with the Supplemental Redist License located at Microsoft Download Center.

Deploying Using ClickOnce Hosted on a File Share

It is easier to host a ClickOnce deployment on a file share than it is to host on a web server. Hosting on a web server is basically the same, except that you may need to make some adjustments to IIS. Hosting on a web server is covered later in this document.

Follow these steps to host on a file share:

  1. Install the Microsoft Windows SDK for Windows 7 and the .NET Framework 4. The SDK contains a utility named mage.exe, which is required in several of the following steps. It also contains utilities for creating test certificates.

    1. Download and install "Microsoft Windows SDK for Windows 7 and the .NET Framework 4" from Microsoft Download Center.

      Important
      It is important that you have "Microsoft Windows SDK for Windows 7 and the .NET Framework 4". Ensure you have the correct version of mage.exe. Locate the mage.exe in file explorer, right-click and select Properties. In the Properties window, choose the Details tab and make sure that the file version is 4.0.40391.1.

    2. The mage.exe utility should be located in the equivalent of the following location:

      C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1\Bin\NETFX 4.0 Tools\mage.exe

  2. Optionally, obtain a code signing certificate. This is a certificate that is issued by a certification authority, and will enable you to sign the application in such a way that end users can see that the application is published by the expected provider and, for example, not by a phisher.

    1. If you do not already have a code signing certificate, you will have to obtain one from one of the certification authorities. For a list of certification authorities, see Microsoft Technet.

    2. You can also create a test certificate and use it for testing. For more information, see How to: Create Your Own Test Certificate.

    3. For information about when it is acceptable to skip this step, see Security Considerations.

  3. Install the ClickOnce Installer Tools. Run setup.exe and install the ClickOnce Installer Tools. The files will be installed in C:\Program Files (x86)\Microsoft Dynamics NAV\90\ClickOnce Installer Tools.

  4. Perform a typical installation of the Microsoft Dynamics NAV Windows client by doing the following:

    1. Run setup.exe to install the Microsoft Dynamics NAV Windows client. Do not install unnecessary client components, such as the Microsoft Dynamics NAV Development Environment and the Excel add-in. These add to the download size, and contain special file types that can create problems for a ClickOnce deployment. For example, the Web.config file installed with the development environment can create problems when it is hosted on a web server.

    2. Install relevant language packs.

    3. Add additional add-ins, if you have any.

    4. Run the client, and make sure that everything works as expected.

    Now you have the files that you know will work, and which you want to deploy on end user computers.

  5. Copy the files to a file share, such as \\fileshare\clickonce.

    1. Create a folder, such as \\fileshare\clickonce\Deployment\ApplicationFiles.

    2. Copy all the files from C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client to this new folder.

    3. Move ClientUserSettings.config to that folder.

      This file typically installs to the equivalent of C:\Program Data\Microsoft\Microsoft Dynamics NAV\90\, or C:\Users\user name\AppData\Roaming\Microsoft\Microsoft Dynamics NAV\90\. The exact location depends on your operating system.

  6. Copy the template files. The ClickOnce Installer Tools installation contains template files that will be useful starting points.

    1. Copy the files in C:\Program Files (x86)\Microsoft Dynamics NAV\90\ClickOnce Installer Tools\TemplateFiles to \\fileshare\clickonce.

  7. The Microsoft Dynamics NAV 2016 Windows client requires Microsoft Report Viewer 2015 for viewing and printing a report, along with and Microsoft System CLR Types for SQL Server 2014. Therefore, these are a prerequisite installation in the ClickOnce scenario.

    Both are available on the Microsoft Download Center. You can download Microsoft Report Viewer at Microsoft Report Viewer 2015 RUNTIME. Microsoft System CLR Types for SQL Server 2014 is available as part of the Microsoft SQL Server 2014 Feature Pack, which you can download at Microsoft SQL Server 2014 Feature Pack.

    Microsoft Report Viewer 2015 is available on download at http://go.microsoft.com/fwlink/?LinkID=536665.

  8. Update the application manifest. The application manifest lists the files that are part of the installation.

    1. Open a command prompt using the Run as administrator option, and change the directory to C:\fileshare\clickonce\Deployment\ApplicationFiles.

    2. Use mage.exe to update the manifest file to have the correct files as shown in the following code example.

      mage.exe -Update Microsoft.Dynamics.Nav.Client.exe.manifest -FromDirectory .

      Important
      You must specify the fully qualified path to mage.exe, such as C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1\Bin\NETFX 4.0 Tools\mage.exe.

      The FromDirectory parameter will include all files in all subdirectories found within the specified directory. If no directory is specified, such as in the example, mage.exe uses the current directory and subdirectories. For more information, see Mage.exe in the MSDN Library.

    ClickOnce does not support having the same assembly duplicated in different folders. If you receive an error, then you will have to remove one of the copies, either in the manifest file or on disk, and then run the mage.exe again. The copy of OpenXML.dll in Add-Ins folder will not be needed in a ClickOnce deployment, therefore you can delete it.

  9. Update the application manifest. Open Microsoft.Dynamics.Nav.Client.exe.manifest in Notepad. You do not have to change anything in this file, but you should be aware of what it looks like. The application manifest has an identity (assembly.assemblyIdentity), which is referred to by the deployment manifest. This can be any string, and it will not be shown to end users. Note the version number, which will be used in upgrade scenarios.

  10. Optionally, sign the application manifest. If you do not sign the manifest, the user will get a security warning when he installs, because the publisher, who is you, cannot be verified. This means that the end user cannot distinguish between your application and malware. If you sign the manifest, the user will see that the application is coming from your company, and he will trust it. If you have the code signing certificate PartnerCodeSigningCertificate.cer and the private key PartnerPrivateKey.pvk, run the following commands.

    cert2spc PartnerCodeSigningCertificate.cer PartnerSoftwarePublisherCertificate.spc

    pvk2pfx -spc PartnerSoftwarePublisherCertificate.spc -pvk C:\PrivateFolder\PartnerPrivateKey.pvk -pfx PartnerPersonalInformationExchange.pfx

    mage.exe -sign Microsoft.Dynamics.Nav.Client.exe.manifest -certfile PartnerPersonalInformationExchange.pfx

    Now the application manifest is signed. If you modify it, you will have to sign it again. For information about when it is acceptable to skip this step, see Security Considerations.

  11. Update the deployment manifest.

    1. Change the directory to C:\fileshare\clickonce\Deployment.

    2. Change the link to the application manifest and update its hash value.

      mage.exe -update Microsoft.Dynamics.Nav.Client.application -appmanifest ApplicationFiles\Microsoft.Dynamics.Nav.Client.exe.manifest -appcodebase \\fileshare\clickonce\Deployment\ApplicationFiles\Microsoft.Dynamics.Nav.Client.exe.manifest

    3. Open Microsoft.Dynamics.Nav.Client.application in Notepad, and do the following:

      1. Adjust the assembly.assemblyIdentity.name so that it is unique. For example, you could add the customer’s name to the name, and if you deploy a test and a production server for the customer, then you could add production or test to the name. You should never change this value after end users have used it to install the Microsoft Dynamics NAV client. The value will not be shown to end users.

      2. Adjust the description contents as appropriate. For example, you could change the publisher to be "Microsoft Corporation and <your company name>", and change the product to be "Microsoft Dynamics NAV 2016 for <customer name>". These are the names that the end user will see.

      3. Change the link in deploymentProvider to \\fileshare\clickonce\Deployment\Microsoft.Dynamics.Nav.Client.application. As you can see, it is now pointing to itself so that it is possible to check for updates.

  12. Optionally, sign the deployment manifest. This is similar to the application manifest.

    mage.exe -sign Microsoft.Dynamics.Nav.Client.application -certfile PartnerPersonalInformationExchange.pfx.

    After the deployment manifest is signed, if you modify it, you will have to sign it again. For information about when it is acceptable to skip this step, see Security Considerations.

  13. Now you should be done with your ClickOnce deployment, so you can test the ClickOnce deployment. Run the deployment manifest by choosing \\fileshare\clickonce\Deployment\Microsoft.Dynamics.Nav.Client.application.

    Note
    Do not run the deployment from C:\fileshare\clickonce\Deployment\Microsoft.Dynamics.Nav.Client.application. This will give you an error that the deployment and application are in different security zones.

  14. Verify that everything works as expected. The ClickOnce files are typically installed under C:\Users\user name\AppData\Local\Apps. In the next step, you will have to know where these files are installed, so locate the files by searching for Microsoft.Dynamics.Nav.Client.exe under that folder or by typing: dir /s Microsoft.Dynamics.Nav.Client.exe.

  15. As a final verification, we recommend that you compare the files that were installed by ClickOnce, in the folder you searched for, to the files that were installed by the MSI installer in C:\Program Files\.... There will be some differences. For example, there will be multiple manifest files in the ClickOnce folder. You should review these differences and make sure they are as expected. For example, if you see a .DLL file in one folder, but not the other, this could cause an error.

In addition to creating the installer itself, you should require end users to read and accept Microsoft’s software license terms (SLT) as part of the installation experience.

Deploying Using ClickOnce Hosting on a Web Server

Hosting on a web server is similar to hosting on a file share. Using the steps outlined in the previous section, you should note that the two links in the deployment manifest should point to the http:// address, instead of a \\fileshare address. This is the only change that you need to make to the files.

All the logic needed for requesting user permissions to install or check for upgrades happens on the client computer. The web server works like a file repository.

The only problem with web server hosting is that web servers use different file types differently. For example, by default a file that has the .config extension will not be downloadable from a web server. The web server will restrict access to it. To work around this, you can create a web.config file in the folder that contains the application files, with contents similar to the following.

Copy Code
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <directoryBrowse enabled="true" />
    <staticContent>
      <mimeMap fileExtension=".config" mimeType="application/x-msdownload" />
      <mimeMap fileExtension=".tlb" mimeType="application/x-msdownload"/>
      <mimeMap fileExtension=".olb" mimeType="application/x-msdownload"/>
      <mimeMap fileExtension=".pdb" mimeType="application/x-msdownload"/>
      <mimeMap fileExtension=".hh" mimeType="application/x-msdownload"/>
      <mimeMap fileExtension=".xss" mimeType="application/x-msdownload"/>
      <mimeMap fileExtension=".xsc" mimeType="application/x-msdownload"/>
      <mimeMap fileExtension=".stx" mimeType="application/x-msdownload"/>
      <mimeMap fileExtension=".msc" mimeType="application/x-msdownload"/>
      <mimeMap fileExtension=".flf" mimeType="application/x-msdownload"/>
      <mimeMap fileExtension=".rdlc" mimeType="application/x-msdownload"/>
      <mimeMap fileExtension=".sln" mimeType="application/x-msdownload"/>
</staticContent>
    <security>
      <requestFiltering>
        <fileExtensions>
          <remove fileExtension=".config" />
        </fileExtensions>
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>

You should start with an empty .config file, and then use trial-and-error to add the necessary rules, until ClickOnce can download all the files. If ClickOnce cannot download the files, a report will show which file and which extension is the problem.

Requiring End Users to Read and Accept Software License Terms

End users who install the Microsoft Dynamics NAV Windows client are required to accept the Microsoft software license terms. By using the traditional Microsoft Dynamics NAV Windows client installer, this occurs as part of the installation process. However, by using ClickOnce deployment, this cannot occur as part of the installation process, and it must therefore occur before the ClickOnce process is started.

If you decide to deploy the Microsoft Dynamics NAV Windows client using ClickOnce, then it is your responsibility that end users accept the Microsoft software license terms before the installation. We recommend that you also require end user acceptance of your software license terms and any third-party software license terms that are part of the ClickOnce deployment.

To help you with this process, you can use the NAVClientInstallation.html template web page that was installed as part of the ClickOnce Installer Tools. When you try to open that file, you must select the Accept check boxes before you can install the Microsoft Dynamics NAV Windows client. You can design your own web page, as long as the process for the end user is the same. The end user cannot install the Microsoft Dynamics NAV Windows client until he has accepted the software license terms.

Upgrading to a New Version of the Microsoft Dynamics NAV Client

If you want to push a new version of the Microsoft Dynamics NAV Windows client out to end users, you must do the following:

  • Produce a new ApplicationFiles folder. Follow the process that you used to create the first version, but assign a larger version number to the application manifest. You can replace the old application files in \\fileshare\clickonce\Deployment\ApplicationFiles, or you can put the new files in a new directory, such as \\fileshare\clickonce\Deployment\ApplicationFiles2. Make sure to run mage.exe -update to update the application manifest's file list and hash values. Run mage.exe -sign to sign the application manifest.

  • Run mage.exe -update to update the deployment manifest's reference to the application manifest as well as its hash value. Update the deployment manifest's version number. Run mage.exe -sign to sign the deployment manifest.

The upgrade check is based on the deployment manifest’s version. This is the version of the Microsoft Dynamics NAV Windows client that will be installed if a user installs Microsoft Dynamics NAV for the first time. The deployment manifest also contains a minimumRequiredVersion. If a previously installed Microsoft Dynamics NAV Windows client has a version that is less than minimumRequiredVersion, then the user is forced to upgrade the Microsoft Dynamics NAV Windows client. This will appear similar to the following.

Copy Code
<assemblyIdentity name="Microsoft Dynamics NAV" version="7.0.0.0" … />
  <deployment install="true" minimumRequiredVersion="7.0.0.0">
    <subscription>
      <update>
        <beforeApplicationStartup />
      </update>
    </subscription>

The <update> tag determines when the upgrade check is performed. In the example earlier in this section, beforeApplicationStartupwas specified, which means the upgrade check will be performed before the Microsoft Dynamics NAV Windows client starts and the user will experience a short delay every time that the Microsoft Dynamics NAV Windows client is started. If you want the upgrade check to be performed in the background every time that the Microsoft Dynamics NAV Windows client is started, then use the following setting.

Copy Code
<update>
        <expiration maximumAge="0" unit="days" />
      </update>

With this setting, the user will be able to run the Microsoft Dynamics NAV Windows client without any delay. In the background, ClickOnce will check if the current version is too low. ClickOnce will enforce the upgrade the next time that the Microsoft Dynamics NAV Windows client starts. If you want to check for updates, such as every 14 days, then add maximumAge=”14”.

The application manifest version number can be changed independently of the deployment manifest version number. If you change the version number in the deployment manifest, but keep referring to the same version of the application manifest, then the user will experience that the Microsoft Dynamics NAV Windows client is upgraded, but nothing will occur because the new version of the deployment manifest will still point to the same application version. For example, this can be useful if you want to change the frequency of the upgrade checks or change the text in the Start menu.

Security Considerations

Installing any application on the local computer requires that you consider whether it is safe to do this. For a ClickOnce deployment of the Microsoft Dynamics NAV Windows client, here are some recommended security measures that you should consider:

  • Internal deployment - If you host the ClickOnce deployment on an internal file share or website, we recommend that you sign the ClickOnce deployment so that end users will not see an Unknown publisher message during installation. However, it is also acceptable not to sign the ClickOnce deployment.

  • Public deployment - If you host the ClickOnce deployment in a public location, we recommend that you sign the ClickOnce deployment and host it on a secure website (https://). Taking these precautions will reduce the risk of end users installing applications from bad sources and locations.

Limitations of ClickOnce Installed on the Microsoft Dynamics NAV Windows Client

The following are limitations of ClickOnce installed on the Microsoft Dynamics NAV Windows client.

Command-line arguments - ClickOnce installed on the Microsoft Dynamics NAV client cannot be run with custom command-line arguments. For example, this affects the following scenarios:

  • An end user cannot specify the Home page.

  • An end user cannot specify a profile. He can only use his default profile.

  • An end user cannot disable personalization. An administrator can disable personalization on a profile.

  • An administrator cannot configure profiles. He should use the MSI-installed client for this task.

  • An end user cannot run in full-screen mode.

  • An end user cannot disable the navigation pane.

Hyperlinks - The protocol handler dynamicsnav:// is not registered during ClickOnce installation, which means that the Microsoft Dynamics NAV client cannot be activated by choosing a hyperlink. This could impact the following scenarios:

  • End users cannot send each other links to specific pages.

  • An end user cannot use the link on a OneNote page.

  • An end user cannot use the link on a report.

  • The debugger cannot be started.

External components calling the Microsoft Dynamics NAV Windows client - A ClickOnce-installed Microsoft Dynamics NAV Windows client will be installed in a randomly generated folder, and when it is upgraded to a new version, it will be installed a new randomly generated folder. This means that external components will not be able to detect where the Microsoft Dynamics NAV Windows client executable is located. This could impact the following scenarios:

  • An end user can send a list page to Excel, but cannot refresh data from the Excel application.

  • Third-party applications cannot start the Microsoft Dynamics NAV Windows client.

See Also

Concepts

Deployment
Configuring Microsoft Dynamics NAV

Other Resources

Installation Options


Configuring Microsoft Dynamics NAV

This section identifies components that you can preconfigure in Microsoft Dynamics NAV 2016 Setup. It also provides information about settings for individual components, and, for some components, identifies another document where you can find such information.

Components That You Can Configure In Setup

You can configure some Microsoft components in Microsoft Dynamics NAV Setup. You can then either proceed to install software with Setup, or save all configuration information to a Setup configuration file for future use. For more information, see How to: Preconfigure Components.

When you install a component that you have pre-configured in Setup, the configuration information is transferred to the appropriate component configuration file. For example, if you pre-configure Microsoft Dynamics NAV Server in Setup, the relevant configuration information is transferred, upon installation, to the CustomSettings.config file. This file is stored on the Microsoft Dynamics NAV Server computer in the equivalent of C:\Program Files\Microsoft Dynamics NAV\90\Service.

The following topics provide additional information on the configuration options for specific components in Microsoft Dynamics NAV 2016 Setup:

  • Configuring the Windows Client

  • Configuring Microsoft Dynamics NAV Server

  • Configuring Database Components

  • Configuring Microsoft SQL Server

  • Configuring the Microsoft Dynamics NAV Web Server and Client

  • Configuring Microsoft Dynamics NAV Help Server

  • Configuring NAS Services

See Also

Customize the User Interface
Walkthrough: Setting Up and Using a Purchase Approval Workflow

Tasks

Walkthrough: Setting Up Outlook Synchronization
How to: Create Microsoft Dynamics NAV Users

Concepts

Configuring Automated Data Capture System
Configuring Microsoft SQL Server
Removing Elements from the User Interface According to Permissions


Configuring the Windows Client

When you install the Microsoft Dynamics NAV Windows client, the Specify Parameters page in Microsoft Dynamics NAV Setup prompts you for configuration information to enable the Microsoft Dynamics NAV Windows client to connect to Microsoft Dynamics NAV Server. This information is then saved in the default ClientUserSettings.config file.

A separate instance of the ClientUserSettings.config file is maintained for each user of the computer. The default location for this file is C:\Users\<username>\AppData\Roaming\Microsoft\Microsoft Dynamics NAV\90, where <username> is the name of the user. This folder and file are hidden by default. Change your folder options in Windows Explorer to view hidden files before you attempt to modify the ClientUserSettings.config file.

Configuring the Microsoft Dynamics NAV Windows Client in Setup

If you install the Demo Option, you are not prompted for configuration information, because all Microsoft Dynamics NAV components are automatically installed on the local computer. If you install using any other installation option, you must provide some initial configuration information to enable the Microsoft Dynamics NAV Windows client to establish a connection with an instance of Microsoft Dynamics NAV Server.

In Setup, select one of the following Installation Options to install the Microsoft Dynamics NAV Windows client:

  • Client Option

  • Developer Option

You can also customize your installation and customize the list of components to install. For more information, see How to: Choose Components to Install.

After you specify an installation option or customize your component list, the Specify parameters pane is displayed in Setup. The list of parameters that you see in the Specify parameters pane depends on which components that you have selected for configuration. Setup provides a short description for each parameter. For a description of the most important parameters for the Microsoft Dynamics NAV Windows client, see Client Option.

Choose Apply when you have finished entering values on the Specify parameters page in Setup. If you want to change the configuration after installation, you can modify the ClientUserSettings.config file for each client.

Configuring the Microsoft Dynamics NAV Windows Client After Installation

Microsoft Dynamics NAV 2016 Setup installs ClientUserSettings.config, the default configuration file, with the values that you provided as you ran Setup. This file is stored in C:\ProgramData\Microsoft\Microsoft Dynamics NAV\90. The first time a user runs the Microsoft Dynamics NAV Windows client, a copy of ClientUserSettings.config is copied to C:\Users\<username>\AppData\Roaming\Microsoft\Microsoft Dynamics NAV\90, where <username> is the name of the user. This folder and file are hidden by default.

If you want to change default Microsoft Dynamics NAV Windows client settings for all future users on this computer, edit the default ClientUserSettings.config file in C:\ProgramData\Microsoft\Microsoft Dynamics NAV\90. You must run your text editor with Administrator permissions when you do this.

If you want to change Microsoft Dynamics NAV Windows client settings for an existing user, edit the ClientUserSettings.config file in that user’s C:\Users\<username>\AppData\Roaming\Microsoft\Microsoft Dynamics NAV\90 folder. After you modify a user’s ClientUserSettings.config file, you must restart the Microsoft Dynamics NAV Windows client for changes to take effect.

In addition to the settings that you can configure in Setup, the ClientUserSettings.config file contains other settings for the Microsoft Dynamics NAV Windows client.

Settings in the ClientUserSettings.config File

The ClientUserSettings.config file is an .xml file that you can edit with any text editor. Quotation marks are required for all values.

The following settings are available.

Setting Description

Server

Specifies the name of the computer that is running Microsoft Dynamics NAV Server for this client.

Default value: Empty string if you installed by using the Client installation option, or localhost if you installed by using the Developer Environment installation option or a custom installation.

ClientServicesPort

Specifies the listening TCP port for the Microsoft Dynamics NAV Server instance that the client connects to.

Default value: 7046

ServerInstance

Specifies the name of the Microsoft Dynamics NAV Server instance that the client connects to.

Default value: DynamicsNAV90

For more information, see Managing Microsoft Dynamics NAV Server Instances.

TenantID

Specifies the tenant that the client connects to in a multitenant deployment. For more information, see Multitenant Deployment Architecture.

Default value: ""

ClientServicesProtectionLevel

Specifies the security services for protecting the client/server data stream. This value must match the value that is specified in the Microsoft Dynamics NAV Server configuration file. For more information, see Configuring Microsoft Dynamics NAV Server.

Default: EncryptAndSign

Values: EncryptAndSign, Sign, None

UrlHistory

Specifies a comma-delimited list of Microsoft Dynamics NAV Server connections that is displayed in the Select Server window when you choose the drop-down arrow in the Server name field.

This parameter is not available after you install the Microsoft Dynamics NAV Windows client, but it is created and populated after the user enters a server name in the field.

You can create and populate this field after you install the Microsoft Dynamics NAV Windows client. This gives the user a list of servers from which to choose.

Example:

Copy Code
<add key="UrlHistory" value="localhost, dev:7046/DynamicsNAV90, sales:7046/DynamicsNAV90"/>

Each value must contain a computer name and can optionally also include a port number and a Microsoft Dynamics NAV Server instance. Defaults are assumed if either value is missing.

ClientServicesCompressionThreshold

Specifies the threshold in memory consumption at which the Microsoft Dynamics NAV Windows client starts compressing datasets, in kilobytes.

Default: 64

ClientServicesChunkSize

Specifies the default size for a chunk, in kilobytes.

Default: 28.

The range of values is from 4 to 80.

ClientServicesKeepAliveInterval

Specifies the time (in seconds) between reliable session messages that are automatically sent to Microsoft Dynamics NAV Server to keep the session alive during periods of inactivity.

If Microsoft Dynamics NAV Server is located behind a load balancer, then we recommend that you set this value to approximately half of the load balancer's idle timeout.

Default: 120

MaxNoOfXMLRecordsToSend

Specifies the maximum number of data rows that can be sent as XML during export to Word or Excel.

Default: 5000

MaxImageSize

Specifies the maximum image size (in bytes) allowed by validation.

Default: 26214400

ClientServicesCredentialType

Specifies how Microsoft Dynamics NAV Windows client users are authenticated when they connect to Microsoft Dynamics NAV Server.

For more information, see Users and Credential Types.

This parameter value must be the same as the Credential Type setting for the Microsoft Dynamics NAV Server instance that the client is configured to connect to. For more information, see Configuring Microsoft Dynamics NAV Server.

Default value: Windows

ACSUri

Specifies the web location where the Microsoft Dynamics NAV Windows client goes to authenticate the client user.

This parameter is only relevant if the ClientServicesCredentialType is set to ACS.

Default value: ""

AllowNtlm

Specifies whether NTLM fallback is permitted for authentication.

To require Kerberos authentication, set this value to false.

Default value: true

ServicePrincipalNameRequired

If this parameter is set to true, then the client can only connect to a Microsoft Dynamics NAV Server instance that has been associated with a service principal name (SPN).

If this parameter is set to false, then the client attempts to connect to the configured Microsoft Dynamics NAV Server instance, regardless of whether that instance is associated with an SPN.

Default: false

ClientServicesCertificateValidationEnabled

Specifies whether to enforce validation of the certificate.

In a production environment, setting this parameter to true is strongly recommended.

When validation is enabled, the certificate must be trusted, not revoked, and the CN name should match the URL of your service.

When validation is disabled, you can use a self-signed certificate without a revocation list and no constraint on the CN name.

Default: true

DnsIdentity

Specifies the subject name of the service certificate for Microsoft Dynamics NAV Server. The Microsoft Dynamics NAV Windows client makes sure that the certificate that is provided during the SSL handshake contains a Domain Name System (DNS) or CommonName (CN) attribute that is equal to the DNS identity of the client. This check is performed in addition to determining the validity of the server certificate.

Default: ""

For more information, see Connecting the Microsoft Dynamics NAV Clients over a Wide Area Network.

HelpServer

Specifies the name of the computer than hosts the Microsoft Dynamics NAV Help Server.

HelpServerPort

Specifies the TCP listening port for the Microsoft Dynamics NAV Help Server.

Default: 49000

UnknownSpnHint

Specifies whether to use server principal name when establishing the connection between the Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Server. This setting is used to authenticate the Microsoft Dynamics NAV Server. You set the values that are based on the value of the ServicePrincipalNameRequired key.

Value: The value has the following format.

(net.tcp://NavServer:Port/ServerInstance/Service)=NoSpn|SPN

  • NavServer is the name of the computer that is running the Microsoft Dynamics NAV Server.

  • Port is the port number on which the Microsoft Dynamics NAV Server is running.

  • ServerInstance is the name of the Microsoft Dynamics NAV Server instance.

  • NoSpn|SPN specifies whether to use an SPN. If the ServicePrincipalNameRequired key is set to false, then set this value to NoSpn. If the ServicePrincipalNameRequired key is set to true, then set this value to Spn.

Default value: (net.tcp://localhost:7046/DynamicsNAV90/Service)=NoSpn

This setting is updated automatically.

See Also

Concepts

Configuring Microsoft Dynamics NAV Server
Configuring Microsoft Dynamics NAV Help Server
Configuring Microsoft Dynamics NAV


Configuring Microsoft Dynamics NAV Server

When you run Microsoft Dynamics NAV 2016 Setup and install Microsoft Dynamics NAV Server, you can provide configuration information that is then used as the configuration for the default Microsoft Dynamics NAV Server instance.

After you install Microsoft Dynamics NAV Server, you can change any of the settings that you provided during Setup, or any of the Microsoft Dynamics NAV Server settings, using either the Microsoft Dynamics NAV Server Administration tool or the Microsoft Dynamics NAV Windows PowerShell cmdlets for Microsoft Dynamics NAV 2016.

Note
Each Microsoft Dynamics NAV Server instance has its own settings.

Configuring Microsoft Dynamics NAV Server in Setup

You can configure the default instance of Microsoft Dynamics NAV Server when running Microsoft Dynamics NAV 2016 Setup. You must first select Microsoft Dynamics NAV Server as a component to install. To do this, select one of the following Installation Options that includes Microsoft Dynamics NAV Server:

  • Server Option

  • Developer Option

You can also customize your installation and the list of components to install. For more information, see How to: Choose Components to Install.

After you specify an installation option or customize your component list, the Specify parameters pane is displayed in Setup. The list of parameters that you see in the Specify parameters pane depends on which components you have selected for configuration. Setup provides a short description for each parameter. For a description of the most important parameters for Microsoft Dynamics NAV Server, see Server Option.

When you have finished entering values, choose the Apply button. This returns you to the Specify parameters page in Setup.

After you finish running Setup, you can modify Microsoft Dynamics NAV Server using any of the methods described in the following section.

Configuring Microsoft Dynamics NAV Server After Installation

After you install Microsoft Dynamics NAV Server, you can change any of the settings that you provided during Setup, or any of the Microsoft Dynamics NAV Server settings, in any of the following ways:

  • Using the Microsoft Dynamics NAV Server Administration tool. For more information, see Settings in the Microsoft Dynamics NAV Administration Console and Microsoft Dynamics NAV Server Administration Tool.

  • Using the Microsoft Dynamics NAV PowerShell cmdlets that are available in the Microsoft Dynamics NAV 2016 Administration Shell. For more information, see Using Microsoft Dynamics NAV Administration Shell Cmdlets to Modify Settings.

  • By directly editing CustomSettings.config, the Microsoft Dynamics NAV Server configuration file. By default, this file is located in C:\Program Files\Microsoft Dynamics NAV\90\Service\Instances\<instancename>. We recommend that you do not directly edit the configuration file, because if you make any errors in typing, then you may not be able to start the instance.

Important
After you modify a Microsoft Dynamics NAV Server setting, you must restart the associated Microsoft Dynamics NAV Server instance before any changes can take effect.

Settings in the Microsoft Dynamics NAV Administration Console

In the tables in the following sections, Microsoft Dynamics NAV Server Administration tool setting names are used. Settings names in the CustomSettings.config file are slightly different. Quotation marks are required for all values.

  • General Tab Settings

  • Database Tab Settings

  • Client Services Tab Settings

  • SOAP Services Tab Settings

  • OData Services Tab Settings

  • NAS Services Tab Settings

  • Management Services Tab Settings

Note
You must choose Edit in the Microsoft Dynamics NAV Server Administration tool before you can modify any values.

General Tab Settings

The following table describes fields on the General tab in the Microsoft Dynamics NAV Server Administration tool.

Setting Description

Azure Active Directory App ID URI

Specifies the App ID URI that is registered for Microsoft Dynamics NAV in the Microsoft Azure Active Directory (Azure AD). You use this setting to configure Microsoft Dynamics NAV web services for OAuth authentication, specifically when the Credential Type setting is AccessControlService.

The App ID URI is a logical identifier and does not have to represent a valid location, although it is common practice to use the physical URL of the Microsoft Dynamics NAV web service.

The App ID URI is typically the same as the value of wtrealm parameter of the ACSUri setting that is included in web.config file for the Microsoft Dynamics NAV Web client and the ClientUserSettings.config file for the Microsoft Dynamics NAV Windows client.

An example of an App ID URI is https://localhost:7047/.

For more information about how to use the Azure Active Directory App ID URI with OAuth authentication, see Using OAuth to Authenticate Microsoft Dynamics NAV Web Services (Odata and SOAP).

Build Restriction

Specifies what happens when a Microsoft Dynamics NAV client tries to connect to the Microsoft Dynamics NAV Server instance when the client is running a different build version of Microsoft Dynamics NAV 2016 than the server instance.

Values:

  • AlwaysConnect

    The client connects to the server instance without giving a warning to the user.

  • WarnClient

    Before connecting the client to the server instance, a message appears that informs the user that the build versions for the client and server instance are different. The user can choose to continue or cancel the connection.

  • DoNotAllow

    A message appears that informs the user that the client and server instance build versions are different, and the client does not connect to the server instance.

Default: WarnClient

Note
With the Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Tablet client, this setting compares the build version of the Microsoft Dynamics NAV Web Server components on IIS with the Microsoft Dynamics NAV Server instance. It controls the connection between Microsoft Dynamics NAV Web Server components and the server instance.

Certificate Thumbprint

If you use security certificates to protect communications between Microsoft Dynamics NAV Server and client services or web services over an open or wide-area network, you must provide the certificate thumbprint to Microsoft Dynamics NAV Server by updating this setting. For more information, see Walkthrough: Implementing Security Certificates in a Test Environment and How to: Implement Security Certificates in a Production Environment.

Compile and Load Business Application

Specifies whether the Microsoft Dynamics NAV Server instance compiles all the business application assemblies and loads them to cache memory when the server instance is started. The assemblies are then retrieved from memory when requested by a Microsoft Dynamics NAV client.

Enabling this setting will reduce the time it takes for the server instance to load application objects the first time they are requested by a Microsoft Dynamics NAV client after the server instance started. However, it will also slightly increase the memory usage by the server instance.

  • If you enable this setting, when the server instance starts for the first time, the business application assemblies will be compiled and loaded to the cache memory of the computer that is running the server instance. The assemblies, along with metadata such object timestamp information, are also stored to a temporary folder on the computer's file system. Whenever the server instance is restarted, it will compare the assemblies that are stored in memory with corresponding objects in the connected database to determine whether the assemblies in memory can be reused. An assembly will be reused if the following conditions are met:

    1. The connected database is the same as before, based on the databasemagic field in the dbproperty table.

    2. The object time stamp that is recorded on the compiled assembly matches the object timestamp in metadata of the connected database.

    If the conditions are not met for an assembly or an assembly for an object in the database is not found in the memory, then a new assembly is built and stored for reuse to cache memory and the file system of the server instance compute for reuse.

  • If you disable this setting, individual assemblies will be compiled on-demand as application objects are requested by the Microsoft Dynamics NAV client. The compiled assemblies will not be reused on subsequent server instance restarts.

Note
  • This setting does not apply to query objects.

  • Assembly compilation happens asynchronously.

  • On average, all application objects will be loaded within the first few minutes that the server instance operates.

Credential Type

Specifies the authentication mechanism for Microsoft Dynamics NAV users of this Microsoft Dynamics NAV Server instance.

The options are Windows, Username, NavUserPassword, AccessControlService, and None. For more information, see Users and Credential Types.

If you choose AccessControlService, you must specify a token signing key for use with Azure Access Control service (ACS), or a federation metadata location for use with Azure AD. If you choose NavUserPassword, and you specify a token signing key, you can use both NavUserPassword and AccessControlService for cthis server instance.

Note
None is only for internal use on system sessions and typically should not be used. If you choose None, then the Microsoft Dynamics NAV Server instance cannot start.

Default: Windows

Data Cache Size

The contextual size of the data cache.

Default: 9

Debugging Allowed

Specifies whether C/AL debugging is allowed for this Microsoft Dynamics NAV Server instance.

Default: Enabled

Default Client

Specifies the client type that is used to generate URLs when the client type is set to Default.

The options are Current, Windows, Web, SOAP, and OData.

Default: Current

Enable Certificate Validation

Specifies whether validation should be performed on the security certificate.

Default: Enabled

Enable Debugging

Specifies whether the Microsoft Dynamics NAV Server instance starts with debugging enabled.

If this option is enabled, the following occurs:

  • When the client first connects, all C# files for the application are generated.

  • C# files persist between Microsoft Dynamics NAV Server restarts.

  • Application objects are compiled with debug information.

    Default: Not enabled

Enable Event Logging to Windows Application Log

Specifies whether to record admin and operational type events (errors, warnings, and information messages) that occur on Microsoft Dynamics NAV Server instances in the Windows Application log on the computer that is running Microsoft Dynamics NAV Server.

Because Microsoft Dynamics NAV Server instance events are always logged to the Application and Services Logs, you can disable logging Microsoft Dynamics NAV Server instance events in the Windows Application log and not lose any data. For more information, see Monitoring Microsoft Dynamics NAV Server Events in the Windows Event Log and How to: Disable Logging Events to the Windows Application Log.

Important
If you are using System Center Operations Manager to monitor Microsoft Dynamics NAV Server instances, do not disable logging to the Windows Application log. If you do, monitoring will not work.

Enable File Access by C/AL Functions

Specifies whether C/AL functions of the file data type can access files on the Microsoft Dynamics NAV Server computer.

Default: Enabled

Enable Full C/AL Function Tracing

Specifies whether full C/AL function tracing is enabled on Event Tracing for Windows (ETW) sessions.

When this setting is enabled, all C/AL function calls and statements are traced.

When this setting is disabled, only root C/AL function calls are traced. Statements and functions that are called from a function are not traced.

For more information, see Monitoring Microsoft Dynamics NAV Server Events.

Default: Not enabled

Max Concurrent Calls

The maximum number of concurrent client calls that can be active on this Microsoft Dynamics NAV Server instance.

Default: 40

Range: 1 - 2,147,483,647

You can also use MaxValue as a value to indicate no limit.

Metadata Provider Cache Size

Specifies the number of objects that can be cached. Set this value to 0 to disable caching.

Default: 150

Multitenant

Specifies if the Microsoft Dynamics NAV Server instance can be used in a multitenant environment.

Tenant databases can only be mounted on the Microsoft Dynamics NAV Server instance if this setting is selected. For more information, see Multitenant Deployment Architecture.

Network Protocol

Specifies the network protocol for accessing the database.

Valid values: Default, Named, Sockets, MultiProtocol

Default: Default

Report PDF Font Embedding

Specifies whether fonts are embedded in PDF files that are generated for reports when the report uses an RDLC report layout at runtime. This setting applies when reports are run and saved as PDF files on the Microsoft Dynamics NAV client (from the report request page or print preview window) or on Microsoft Dynamics NAV Server (by the SAVEAS Function or SAVEASPDF Function (Report) in C/AL code).

Note
This setting does not apply when a report uses a Word report layout at runtime.

Embedding fonts in a PDF of a report makes sure that the PDF will use the same fonts as the original file, regardless of where the PDF is opened and which fonts are installed on the computer. However, embedding fonts can significantly increase the size of the PDF files. By disabling font embedding, you can decrease the size of the report PDF files.

Note
This is a global setting for font embedding in report PDF files. You can override this setting on a report basis by the specifying the PDFFontEmbedding Property.

Default: Not enabled

Send Feedback

When this setting is enabled, the Microsoft Dynamics NAV Server instance collects basic information about your hardware configuration and about how you use Microsoft Dynamics NAV Server, and sends it to Microsoft. Microsoft uses this information to identify trends and usage patterns and to improve its software.

Default: Not enabled

This is the EnableSoftwareQualityMetrics setting in the CustomSettings.conig file.

For more information, see Customer Experience Improvement Program and Microsoft Dynamics NAV Server.

Services Default Company

Specifies the Microsoft Dynamics NAV company that the client services, OData web services, and NAS services use as the default company.

If your Microsoft Dynamics NAV database contains only one company, leave the setting blank.

Services Default Time Zone

Specifies the time zone in which web service and NAS services calls are run.

Values:

  • UTC

    All business logic for web services and NAS services on the server instance runs in Coordinated Universal Time (UTC). This is how all web services business logic was handled in Microsoft Dynamics NAV 2009 and Microsoft Dynamics NAV 2009 SP1.

  • Server Time Zone

    Services use the time zone of the computer that is running Microsoft Dynamics NAV Server.

  • <ID of any time zone recognized by the current version of Windows>

    Specifies any Windows time zone as defined in the system registry under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones. For example, Romance Standard Time.

Default: UTC

Services Language

Specifies the global language version to use for text strings with SOAP and OData web services.

The value must be valid culture name for a language that is available for the Microsoft Dynamics NAV solution, such as en-US and da-DK.

Default: en-US

Services Option Format

Specifies the source of the text strings to use for the option values of an option data type field.

Values:

  • OptionString

    Uses the text strings that are specified by the OptionString Property of a field.

  • OptionCaption

    Uses the text strings that are specified by the OptionCaption Property of a field.

Default: OptionCaption

Session Event Table Retain Period

An integer value that specifies how many months events in the Session Events table are retained.

Default: 3

UI Elements Removal

Specifies if UI elements are removed when the related object is not accessible according to the license or according to user permissions or both. For more information, see How to: Specify When UI Elements Are Removed.

Use NTLM Authentication

Specifies whether NTLM authentication is enabled for web services. To require Kerberos authentication, disable this option.

Default: Not enabled

Database Tab Settings

The following table describes fields on the Database tab in the Microsoft Dynamics NAV Server Administration tool.

Note
If the Microsoft Dynamics NAV Server instance is configured as a multitenant server instance, then except for the Database Name, Database Instance, and Database Server settings, the settings apply to both the application database and the tenant database.

Setting Description

Close Inactive SQL Connections

Specifies when to close inactive SQL Server connections. The value specifies the age at which to close connections. While a connection is inactive, starting from zero, the age is increased by one every 30 seconds. When the age of the inactive connection reaches the specified value, the connection is closed. A value of 0 means that inactive SQL connections will not be closed.

Default: 10

Database Instance

The name of the SQL Server database instance to connect to. If the value is a null string (""), Microsoft Dynamics NAV Server instance connects to the default database instance of SQL Server.

If the Microsoft Dynamics NAV Server instance is configured as a multitenant server instance, then this setting specifies the SQL Server database instance that hosts the application database.

Default: NAVDEMO

Database Name

The name of the Microsoft Dynamics NAV database in SQL Server.

If the Microsoft Dynamics NAV Server instance is configured as multitenant server instance, then this setting specifies the application database.

Default: "Demo Database NAV (9-0)"

Database Server

A valid network name for the computer that is running SQL Server.

If the Microsoft Dynamics NAV Server instance is configured as multitenant server instance, then this setting specifies the computer that hosts the application database.

Default: The computer that you selected in Microsoft Dynamics NAV Setup.

Disable Smart SQL

Specifies whether the SmartSql performance optimization feature is disabled.

SmartSql converts FIND calls and FlowField calculations into a single SQL statement. This can improve performance when running pages that contain FlowFields. However, it can be helpful to disable SmartSQL when troubleshooting database queries because statements are separated into more discrete statements.

Default: Disabled (check box is selected)

Enable Buffered Insert

Specifies whether to buffer rows that are being inserted into a SQL Server database table.

When this parameter is enabled, up to 5 rows will be buffered in the table queue before they are inserted into the table.

To optimize performance in a production environment, you should enable this parameter. In a test environment, you can disable this parameter to help debug failures that occur when you insert rows in an SQL database table. For more information, see Bulk Inserts.

Default: Enabled

Enable Encryption on SQL Server Connections

Specifies whether the SQL connect string should request encryption when connecting to SQL Server services.

Enable Trust of SQL Server Certificate

Specifies whether Microsoft Dynamics NAV Server should trust the SQL Server certificate.

SQL Command Timeout

The contextual time-out for a SQL command.

Default: 0:30:00

Enable SQL Parameters by Ordinal

Specifies whether parameters in SQL statements are referenced by their ordinal number.

Enabling this setting improves performance when using buffered inserts.

Default: Enabled

Client Services Tab Settings

The following table describes fields on the Client Services tab in the Microsoft Dynamics NAV Server Administration tool.

Setting Description

Chunk Size

The default size for a chunk of data that is transferred between Microsoft Dynamics NAV Server and the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client, in kilobytes.

Default: 28

The range of values is from 4 to 80.

Compression Threshold

The threshold in memory consumption at which Microsoft Dynamics NAV Server starts compressing datasets, in kilobytes.

Default: 64

Enable Client Services

Specifies whether client services are enabled for this Microsoft Dynamics NAV Server instance.

Default: Enabled

Federation Metadata Location

Specifies the location of the federation metadata that is used to establish a trust relationship with between Microsoft Dynamics NAV and an application that you have added to Azure AD, such as https://login.windows.net/<tenant>/FederationMetadata/2007-06/FederationMetadata.xml. For more information, see Authenticating Users with Azure Active Directory.

This parameter is relevant only when Credential Type, on the General tab, is set to AccessControlService.

Idle Client Timeout

The interval of time that a Microsoft Dynamics NAV Server client session can remain inactive before the session is dropped.

Time interval format: [dd.]hh:mm:ss[.ff]

Where:

  • dd: days

  • hh: hours

  • mm: minutes

  • ss: seconds

  • ff: hundredths of a second

You can also use MaxValue as a value to indicate no time-out. This is the default value.

Max Concurrent Connections

Specifies the maximum number of concurrent client connections that the current Microsoft Dynamics NAV Server instance accepts.

Default: 150

You can also use MaxValue as a value to indicate no limit.

Max Items in Object Graph

The maximum number of objects to serialize or deserialize.

Default: 512

Max Number of Orphaned Connections

Specifies the maximum number of orphaned connections to be kept alive at the same time for the time that is specified by ReconnectPeriod.

A connection is orphaned when the client is involuntarily disconnected from Microsoft Dynamics NAV Server.

Default: 20

You can also use MaxValue as a value to indicate no limit.

Max Upload Size

The maximum size of files that can be uploaded to or downloaded from Microsoft Dynamics NAV Server, in megabytes. Use this setting to avoid out-of-memory errors.

Default: 5

Operation Timeout

The maximum time that Microsoft Dynamics NAV Server can take to return a call from the client.

Time span format: [dd.]hh:mm:ss[.ff]

Where:

  • dd: days

  • hh: hours

  • mm: minutes

  • ss: seconds

  • ff: hundredths of a second

You can also use MaxValue as a value to indicate no time-out. This is the default value.

Port

The listening HTTP port for client services.

Default: 704

Valid range: 1 - 65535

Prohibited File Types

Specifies a series of file name extensions, delimited by semi-colons. Microsoft Dynamics NAV Server will not store files of any of the specified types when requested by clients.

Example values:

* (asterisk) | All file types are prohibited.
Empty string ("") | All file types are allowed.
List of file types separated by semi-colons. For example, "txt;xml;pdf". | Microsoft Dynamics NAV Server will not store files of any of the specified types when requested by clients.

Protection Level

Specifies the security services for protecting the data stream between clients and Microsoft Dynamics NAV Server.

All Microsoft Dynamics NAV Windows client clients connecting to the Microsoft Dynamics NAV Server instance must have the same ProtectionLevel value in their ClientUserSettings.config files. For more information, see Configuring the Windows Client.

For background information about transport security, see Understanding Protection Level (links to MSDN Library).

Default: EncryptAndSign

Values: EncryptAndSign, Sign, None

Reconnect Period

The time during which a client can reconnect to a running instance of Microsoft Dynamics NAV Server.

Time span format: [dd.]hh:mm:ss[.ff]

Where:

  • dd: days

  • hh: hours

  • mm: minutes

  • ss: seconds

  • ff: hundredths of a second

Default: 00:10:00

You can also use MaxValue as a value to indicate no time limit.

Token Signing Key

Specifies the signing information that you obtain from the Azure management portal. The parameter value is a 256-bit symmetric token signing key for use with Azure Access Control service (ACS). This parameter is relevant only when Credential Type, on the General tab, is set to AccessControlService.

Web Client Base URL

Specifies the root of the URLs that are used to open hyperlinks to pages and reports in the Microsoft Dynamics NAV Web client. For example, you can change the value if you want to change the externally facing endpoint.

The base URL must have the following syntax:

http[s]://hostname:port/instance/WebClient/

This field maps to the PublicWebBaseUrl setting in the CustomSettings.config file for the Microsoft Dynamics NAV Server instance.

For more information, see How to: Copy the URL to Open a Page or Report.

Windows Client Base URL

Specifies the root of the URLs that are used to open hyperlinks to pages and reports in the Microsoft Dynamics NAV Windows client. For example, you can change the value if you want to change the externally facing endpoint.

The base URL must have the following syntax:

DynamicsNAV://hostname:port/instance/

This field maps to the PublicWinBaseUrl setting in the CustomSettings.config file for the Microsoft Dynamics NAV Server instance.

For more information, see How to: Copy the URL to Open a Page or Report.

SOAP Services Tab Settings

The following table describes fields on the SOAP Services tab in the Microsoft Dynamics NAV Server Administration tool.

Setting Description

Enable SOAP Services

Specifies whether SOAP web services are enabled for this Microsoft Dynamics NAV Server instance.

Default: Enabled

Enable SSL

Specifies whether SSL (https) is enabled for the SOAP web service port. For more information, see Walkthrough: Configuring Web Services to Use SSL (SOAP and OData).

Default: Not enabled

Max Message Size

The maximum permitted size of a SOAP web services request, in kilobytes.

Important
This setting also pertains to OData web services.

Default: 1024

Port

The listening HTTP port for Microsoft Dynamics NAV SOAP web services.

Default: 7047

Valid range: 1 - 65535

SOAP Base URL

Specifies the root of the URLs that are used to access SOAP web services. For example, you can change the value if you want to change the externally facing endpoint.

The base URL must have the following syntax:

http[s]://hostname:port/instance/WS/

This field maps to the PublicSOAPBaseUrl setting in the CustomSettings.config file for the Microsoft Dynamics NAV Server instance.

For more information, see How to: Copy the URL to Open a Page or Report.

OData Services Tab Settings

The following table describes fields on the OData Services tab in the Microsoft Dynamics NAV Server Administration tool.

Setting Description

Enable OData Services

Specifies whether OData web services are enabled for this Microsoft Dynamics NAV Server instance.

Default: Enabled

Enable SSL

Specifies whether SSL (https) is enabled for the OData web service port. For more information, see Walkthrough: Configuring Web Services to Use SSL (SOAP and OData).

Default: Not enabled

Max Page Size

Specifies the maximum number of entities returned per page of OData results. For more information, see Server-Driven Paging in OData Web Services.

Default: 1000

OData Base URL

Specifies the root of the URLs that are used to access OData web services. For example, you can change the value if you want to change the externally facing endpoint.

The base URL must have the following syntax:

http[s]://hostname:port/instance/OData/

This field maps to the PublicODataBaseUrl setting in the CustomSettings.config file for the Microsoft Dynamics NAV Server instance.

For more information, see How to: Copy the URL to Open a Page or Report.

Port

The listening HTTP port for Microsoft Dynamics NAV OData web services.

Default: 7048

Valid range: 1 - 65535

Important
The maximum permitted size of an OData web services request is specified by the Max Message Size option on the SOAP Services tab.

NAS Services Tab Settings

The following table describes fields on the NAS Services tab in the Microsoft Dynamics NAV Server Administration tool.

Setting Description

Enable Debugging

Specifies if the Microsoft Dynamics NAV Debugger must attach to the NAS Services session. When this is enabled, the NAS Services session waits 60 seconds before the first C/AL statement is run.

Retry Attempts per Day

Specifies the maximum number of times that a Microsoft Dynamics NAV NAS Service session can restart after a failure. After the next failure, the NAS Service session stops.

Run NAS Services with Admin Rights

Specifies whether NAS services run operations with administrator rights instead of the rights granted to the Microsoft Dynamics NAV Server service account.

  • If you select this setting, NAS services will have full permissions in Microsoft Dynamics NAV, similar to the permissions that are granted by the SUPER permission set. The Microsoft Dynamics NAV Server service account is not required to be set up as a user in Microsoft Dynamics NAV.

  • If you clear this setting, the Microsoft Dynamics NAV Server service account must be added as a user in Microsoft Dynamics NAV and assigned the permissions that are required to perform the operations.

Startup Argument

Specifies a string argument that will be used when NAS services start. The argument typically specifies an application type, sometimes with additional configuration information.

Example values:

  • "OSYNCH"

  • "JOBQUEUE"

Startup Codeunit

Specifies the codeunit that contains the method that will be called by the NASStartupMethod setting.

Example values:

  • 0

    When NASStartupCodeunit is set to 0, NAS Services do not start. This is the default value.

  • 1

    When NAS services start, they run the trigger specified by the NAS Startup Method in codeunit 1.

  • 450

    When NAS services start, they run codeunit 450 (Job Queue - NAS Start Up), and call the method specified by NASStartupMethod.

    Note
    When the codeunit specified by NASStartupCodeunit is a single instance codeunit, the NAS service session will remain alive even after you run all code in the specified NASStartupMethod. For information about single instance codeunits, see Using Codeunits.

Startup Method

Specifies the method that will be called in the NASStartupCodeunit.

Example values:

  • ""

    If no start method is specified (null string), the OnRun trigger is called.

  • StartNAS

    NAS services runs the StartNAS method in the NAS Startup Codeunit.

Management Services Tab Settings

The following table describes fields on the Management Services tab in the Microsoft Dynamics NAV Server Administration tool.

Setting | Description
Enable Management Services | Specifies whether Microsoft Dynamics NAV Server Administration tool is enabled for this Microsoft Dynamics NAV Server instance. Default: Enabled
Port | The listening TCP port for the Microsoft Dynamics NAV Server Administration tool. Default: 7045 Valid range: 1 - 65535

Using Microsoft Dynamics NAV Administration Shell Cmdlets to Modify Settings

The Microsoft Dynamics NAV 2016 Administration Shell includes several cmdlets that enable you to create and modify Microsoft Dynamics NAV Server instances. Use the Set- cmdlets to modify a setting on a Microsoft Dynamics NAV Server instance. For example, you can change the value for DatabaseServer to DatabaseServer.Domain.Com for the server instance named MyInstance by executing this cmdlet:

Copy Code
Set-NAVServerConfiguration MyInstance -KeyName DatabaseServer -KeyValue DatabaseServer.Domain.Com

To display all the Set- cmdlets on the Windows PowerShell console, use the following command:

Copy Code
Get-Help Set-NAVServer*

For more information, see Microsoft Dynamics NAV Windows PowerShell Cmdlets

See Also

Tasks

How to: Specify When UI Elements Are Removed

Concepts

Microsoft Dynamics NAV Server Administration Tool
Enhancing Microsoft Dynamics NAV Server Security
Microsoft Dynamics NAV Windows PowerShell Cmdlets
Configuring Microsoft Dynamics NAV Help Server
Configuring Microsoft SQL Server
Configuring the Windows Client
Configuring Microsoft Dynamics NAV


Configuring Database Components

Use Microsoft Dynamics NAV 2016 Setup to install SQL Server Database Components. This is software you install on the computer running the SQL Server database to manage interaction between Microsoft Dynamics NAV and the SQL Server database.

You can install database components on the same computer as Microsoft Dynamics NAV Server (as described in Walkthrough: Installing the Three Tiers On Two Computers) or on a separate computer (as described in Walkthrough: Installing the Three Tiers on Three Computers). SQL Server Database Components are a default component for the Developer Option in Microsoft Dynamics NAV 2016 Setup, but for a production environment you can select SQL Server Database Components either by customizing the Server Option or by performing a complete custom installation (that is, by choosing Custom on the Choose an installation option pane in Setup). For more information, see How to: Choose Components to Install.

When you select SQL Server Database Components in Setup you must also decide whether to install the second-level component, which is the Microsoft Dynamics NAV Demo database.

Configuring Database Components in Setup

If you select SQL Server Database Components in Setup you have the option of configuring related settings on the Specify parameters pane. These settings are in a section entitled SQL Server Database Components.

Settings

The following parameters pertain to database components.

Parameter | Description
SQL Server instance | Specifies the instance of SQL Server to which Microsoft Dynamics NAV Server attempts to connect. The default value is NAVDEMO, which Microsoft Dynamics NAV creates. This differs from earlier versions of Microsoft Dynamics NAV, which installed the Demo database to the default SQL Server instance.
SQL Database | Specifies the name of the database that Microsoft Dynamics NAV interacts with. The default value specifies the Demo database: Demo Database NAV (9-0). This option is only present in Setup when you include the Demo database.
Replace Existing Database | Specifies what Setup should do if the Demo database is already present in the specified SQL Server instance. With the default value (No), Setup completes with an error. With this parameter set to Yes, Setup completes with no error. This option is only present in Setup when you include the Demo database.

See Also

Concepts

Configuring Microsoft Dynamics NAV
Configuring Microsoft SQL Server


Configuring Microsoft SQL Server

The topics in this section describe actions that you can take after installing Microsoft Dynamics NAV and SQL Server to integrate the two products:

  • Setting Database Owner and Security Administration Permissions

  • How to: Start SQL Browser Service

  • Troubleshooting: SQL Server Connection Problems

See Also

Concepts

Installation Considerations for Microsoft SQL Server

Other Resources

Installation and Configuration Walkthroughs


Setting Database Owner and Security Administration Permissions

Permissions are required in SQL Server to create and manage Microsoft Dynamics NAV databases. Use SQL Server Management Studio to grant these permissions to Microsoft Dynamics NAV administrators.

If you have installed SQL Server with the guidelines in Installation Considerations for Microsoft SQL Server, then SQL Server Management Studio is already installed on your computer. Otherwise, update your SQL Server installation to include the Management Tools - Complete option for SQL Server.

Permissions for Using and Creating Databases

The administrator who installs Microsoft Dynamics NAV 2016 automatically has access to the Microsoft Dynamics NAV database in the development environment. To grant another user permission to create new databases in development environment, grant that user the sysadmin Server Role for the Microsoft Dynamics NAV SQL Server instance in SQL Server Management Studio.

Note
The administrator must also have a Microsoft Dynamics NAV developer’s license to use the development environment, and be assigned the SUPER permission set.

In the Object Explorer pane in SQL Server Management Studio, follow these steps after connecting to the Microsoft Dynamics NAV SQL Server instance:

  1. Expand the Security node, right-click Logins, and choose New Login.

    If the administrator already has a Login, right-click the user and choose Properties. Then go to step 4.

  2. In the Login - New dialog box, select Search.

  3. In the Select User or Group dialog box, select a valid Active Directory user.

  4. In the Login - New dialog box, under Select a Page, choose Server Roles. Select the sysadmin check box.

  5. Choose the OK button to close the Login - New dialog box.

When administrators create Microsoft Dynamics NAV databases in the Microsoft Dynamics NAV development environment, the account running Microsoft Dynamics NAV Server is automatically granted the db_owner database role for these databases.

Permissions for Managing Companies, Objects, and Licenses

Administrators who create Microsoft Dynamics NAV databases automatically have permission to manage companies, objects, and licenses in that database.

To grant permission to manage companies, objects, and licenses in Microsoft Dynamics NAV Development Environment to additional administrators, assign those administrators the db_owner database role for all relevant Microsoft Dynamics NAV databases.

To grant the db_owner role on a Microsoft Dynamics NAV database in SQL Server Management Studio, follow these steps:

  1. If the administrator is not already a SQL Server login, add the administrator as a login by following the first three steps in the procedure above.

  2. Select the Microsoft Dynamics NAV database, then Security, then right-click Users and choose New User.

    Choose the button at the right of the Login Name field to open the Select Login dialog box.

  3. Choose the Browse button, select the check box for the relevant Login, and then choose the OK button.

  4. Choose the OK button to exit the Select Login dialog box.

  5. Enter a User name for the user.

    This can be the same as the login name.

  6. In the Database User - New dialog box, under Select a Page, choose In the Database role membership.

  7. Select the db_owner check box.

  8. Choose the OK button to exit the Database User - New dialog box.

See Also

Concepts

Installation Considerations for Microsoft SQL Server


How to: Start SQL Browser Service

When using a named database instance for Microsoft Dynamics NAV, and the SQL Server is not on the same computer as Microsoft Dynamics NAV Server, then the SQL Server Browser Service must be running on the SQL Server. If it is not, Microsoft Dynamics NAV Server cannot connect to the Microsoft Dynamics NAV database and an error occurs when you try to open a RoleTailored client. A database instanced named NAVDEMO is used when you install the CRONUS International Ltd. demonstration database by using Microsoft Dynamics NAV 2016 Setup.

You enable and start the SQL Server Browser Service by using the SQL Server Configuration Manager that is installed with Microsoft SQL Server 2008.

To start SQL Server Browser Service

  1. On the computer running SQL Server, run the SQL Server Configuration Manager.

    On the Start menu, in the Search Programs and Files box, type SQL, and then choose SQL Server Configuration Manager.

  2. In SQL Server Configuration Manager, in the navigation pane on the left, choose SQL Server Services.

  3. Right-click SQL Server Browser, and then choose Properties.

  4. On the Service tab of the SQL Server Browser dialog box, set the Start mode to Automatic.

  5. Choose OK to return to the SQL Server Configuration Manager main page.

  6. Right-click SQL Server Browser again, and then choose Start.

See Also

Concepts

Installation Considerations for Microsoft SQL Server
Configuring Microsoft Dynamics NAV Server
Troubleshooting: SQL Server Connection Problems


Troubleshooting: SQL Server Connection Problems

After installing and configuring Microsoft Dynamics NAV software, you may not be able to connect the RoleTailored client to Microsoft Dynamics NAV Server. In this case you see an error message like the following when you attempt to start the RoleTailored client.

The program could not create a connection to the server. Do you want to try again?

This topic describes configuration changes that you can try to resolve SQL Server connection problems.

Enable Protocols in SQL Server Configuration Manager

SQL Server Configuration Manager is a tool for managing SQL Server services and network connectivity. You can use SQL Server Configuration Manager to enable and disable network protocols. For Microsoft Dynamics NAV to work correctly, the Named Pipes and TCP/IP protocols must be enabled for SQL Server.

Follow these steps to verify that these protocols are enabled or to enable them if they are currently disabled.

To enable Named Pipes and TCP/IP in SQL Server

  1. Start SQL Server Configuration Manager.

  2. Expand the SQL Server Network Configuration node in the tree view, and then choose Protocols for MSSQLSERVER.

  3. Under Protocol Name in the right pane, verify that Named Pipes and TCP/IP have the status Enabled.

  4. If either protocol is not enabled, right-click the protocol, and then choose Enable.

After exiting SQL Server Configuration Manager, start the RoleTailored client again to see if the connection problem has been resolved.

Allowing SQL Server with Windows Firewall

If Windows Firewall is running on the computer running SQL Server, then you must explicitly specify the SQL Server executable file as an allowed exception before you can connect to the Microsoft Dynamics NAV database.

To allow SQL Server with Windows Firewall

  1. In Control Panel, open Windows Firewall, choose Change settings, and then click the Exceptions tab.

  2. Choose Add program.

  3. Choose Browse, and then browse to the location of the SQL Server executable file (sqlservr.exe). The default location on a computer running Windows Server 2008 R2 is:

    Copy Code
    C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Binn\sqlservr.exe

  4. Double-click the executable file to select it and to exit the Browse window, and then choose OK to close the Add a Program window.

  5. Choose OK to close Windows Firewall.

After exiting SQL Server Configuration Manager, start the RoleTailored client again to see if the connection problem has been resolved.

Starting SQL Browser Service

When using a named database instance for Microsoft Dynamics NAV, and Microsoft Dynamics NAV Server and the SQL server are on separate computers, then SQL Browser Service must be running on the SQL Server. For more information, see How to: Start SQL Browser Service.

See Also

Tasks

Walkthrough: Installing the Three Tiers on Three Computers

Concepts

Configuring Microsoft SQL Server
Installation Considerations for Microsoft SQL Server


Configuring the Microsoft Dynamics NAV Web Server and Client

When you run Microsoft Dynamics NAV 2016 Setup and install Microsoft Dynamics NAV Web Server components, you can provide configuration information that is then used as the configuration for the default Microsoft Dynamics NAV Web Server instance.After you install Microsoft Dynamics NAV Web Server components, you can change any of the settings that you provided during Setup, or any of the Microsoft Dynamics NAV Web Server components settings, using either the Microsoft Dynamics NAV Server Administration tool or the Windows PowerShell cmdlets for Microsoft Dynamics NAV 2016.

Configuring the Microsoft Dynamics NAV Web Server components in Setup

When Microsoft Dynamics NAV 2016 Setup, you configure the Microsoft Dynamics NAV Server instance and that the Microsoft Dynamics NAV Web Server connects to. For more information, see How to: Install the Web Server Components.

Configuring the Microsoft Dynamics NAV Web Server components After Installation

After you install the Microsoft Dynamics NAV Web Server components, you can change any of the settings that you provided during Setup, or other settings. For more information, see the following topics.

Configuring Microsoft Dynamics NAV Web Client by Modifying the Web.config File

Configuring the Web Browser for the Microsoft Dynamics NAV Web Client

How to: Configure Delegation for Microsoft Dynamics NAV Web Client

How to: Configure User Authentication for the Microsoft Dynamics NAV Web Client

How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client

How to: Configure Microsoft Report Viewer for the Microsoft Dynamics NAV Web Client

How to: Set Up Multiple Web Server Instances for the Microsoft Dynamics NAV Web Client

See Also

Tasks

How to: Install the Web Server Components

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Troubleshooting the Microsoft Dynamics NAV Web Client Installation


Configuring Microsoft Dynamics NAV Web Client by Modifying the Web.config File

To install the Microsoft Dynamics NAV Web client, you run Microsoft Dynamics NAV 2016 Setup. Setup installs a website with a web server instance for the Microsoft Dynamics NAV Web client on an Internet Information Services (IIS) server and configures the connection from the Microsoft Dynamics NAV Web client to Microsoft Dynamics NAV Server. After the installation, you can use Microsoft Dynamics NAV 2016 Administration Shell to add additional web server instances for the Microsoft Dynamics NAV Web client. The connection information is saved in the web.config file of the web server instance. After installation, you can change the configuration by modifying the web.config file.

About the Web.config File

The web.config file is an .xml file that you can edit with a text editor, such as Notepad.

Locating the web.config file

You can have multiple Microsoft Dynamics NAV web server instances on IIS. Each instance has its own web.config file that is stored in the physical path of the application's virtual directory. The path is %systemroot%\inetpub\wwwroot\[VirtualDirectoryName]. For example, the folder for the default Microsoft Dynamics NAV Web client instance is %systemroot%\inetpub\wwwroot\DynamicsNAV90 folder.

Note
After you modify the web.config file, if you have Microsoft Dynamics NAV Web client open in the Internet browser, the changes will not take effect until you close the browser session, and then reopen Microsoft Dynamics NAV Web client.

Microsoft Dynamics NAV Settings in the Web.config File

The Microsoft Dynamics NAV Web client settings are included in the <DynamicsNAVSettings> element in the web.config file. The following table describes the settings that are available in the <DynamicsNAVSettings> element.

Important
All values must be enclosed in quotation marks.

Setting Description

AllowNtlm

Specifies whether NT LAN Manager (NTLM) fallback is permitted for authentication.

To require Kerberos authentication, set this value to false.

Values: true, false

Default value: true

ClientServicesChunkSize

Sets the maximum size, in kilobytes, of a data chunk that is transmitted between Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Server. Data that is transmitted between Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Server is broken down into smaller units called chunks, and then reassembled when it reaches its destination.

Values: From 4 to 80.

Default value: 28

Company

Sets the company in Microsoft Dynamics NAV to connect to. If you do not define a company, then the company that was last opened by the user is used.

Values: A company defined in the Microsoft Dynamics NAV solution.

For more information about companies, see How to: Create Companies.

Default value: none

ClientServicesCompressionThreshold

Sets the threshold in memory consumption at which Microsoft Dynamics NAV Web client starts compressing data sets. This limits amount of consumed memory. The value is in kilobytes.

Default value: 64

ClientServicesProtectionLevel

Specifies the security services used to protect the data stream between the Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Server. This value must match the value that is specified in the Microsoft Dynamics NAV Server configuration file. For more information, see Configuring Microsoft Dynamics NAV Server.

Values: EncryptAndSign, Sign, None

Default value: EncryptAndSign

Server

Specifies the name of the computer that is running the Microsoft Dynamics NAV Server.

Default value: localhost

ServerInstance

Specifies the name of the Microsoft Dynamics NAV Server instance that the Microsoft Dynamics NAV Web client connects to.

For more information, see Managing Microsoft Dynamics NAV Server Instances.

Default value: DynamicsNAV90

ClientServicesCredentialType

Specifies the authorization mechanism that is used to authenticate users who try to connect to the Microsoft Dynamics NAV Web client. For more information, see How to: Configure User Authentication for the Microsoft Dynamics NAV Web Client and Users and Credential Types.

The credential type must match the credential type configured for the Microsoft Dynamics NAV Server instance that the Microsoft Dynamics NAV Web client connects to. For information about how to set up the credential type on Microsoft Dynamics NAV Server, see Configuring Microsoft Dynamics NAV Server.

Values: Windows, UserName, NavUserPassword, AccessControlService

Default value: Windows

ClientServicesPort

Specifies the TCP port for the Microsoft Dynamics NAV Server. This is part of the Microsoft Dynamics NAV Server’s URL.

Values: 1-65535

Default value: 7046

ServicePrincipalNameRequired

If this parameter is set to true, then the Microsoft Dynamics NAV Web client can only connect to a Microsoft Dynamics NAV Server instance that has been associated with a service principal name (SPN).

If this parameter is set to false, then the Microsoft Dynamics NAV Web client attempts to connect to the configured Microsoft Dynamics NAV Server service, regardless of whether that service is associated with an SPN.

For more information about SPNs, see How to: Configure Delegation for Microsoft Dynamics NAV Web Client.

Default: false

SessionTimeout

Specifies the maximum time that a connection between the Microsoft Dynamics NAV Web client and the Microsoft Dynamics NAV Server can remain idle before the session is stopped.

In the Microsoft Dynamics NAV Web client, this setting determines how long an open Microsoft Dynamics NAV page or report can remain inactive before it closes. For example, when the SessionTimeout is set to 20 minutes, if a user does not take any action on a page within 20 minutes, then the page closes and it is replaced with the following message: The page has expired and the content cannot be displayed.

The time span has the format [dd.]hh:mm:ss[.ff]:

  • dd is the number of days

  • hh is the number of hours

  • mm is the number of minutes

  • ss is the number of seconds

  • ff is fractions of a second

Default value: 00:20:00

ShowPageSearch

Specifies whether to show the Search for Page or Report icon in the ribbon pane of the Role Center. The Search for Page or Report lets users find Microsoft Dynamics NAV objects, such as pages, reports, and codeunits.

Note
The Search for Page or Report option only finds objects that are available from the Departments page in the Microsoft Dynamics NAV Windows client.

If you do not want to the Search for Page or Report icon available in the Microsoft Dynamics NAV Web client, then set the parameter to false.

Default value: true

UnknownSpnHint

Specifies whether to use a server principal name when establishing the connection between the Microsoft Dynamics NAV Web client server and Microsoft Dynamics NAV Server. This setting is used to authenticate the Microsoft Dynamics NAV Server, and it prevents the Microsoft Dynamics NAV Web client server from restarting when it connects to Microsoft Dynamics NAV Server for the first time. You set values that are based on the value of the ServicePrincipalNameRequired key.

Value: The value has the following format.

(net.tcp://NavServer:Port/ServerInstance/Service)=NoSpn|SPN

  • NavServer is the name of the computer that is running the Microsoft Dynamics NAV Server.

  • Port is the port number on which the Microsoft Dynamics NAV Server is running.

  • ServerInstance is the name of the Microsoft Dynamics NAV Server instance.

  • NoSpn|SPN specifies whether to use an SPN. If the ServicePrincipalNameRequired key is set to false, then set this value to NoSpn. If the ServicePrincipalNameRequired key is set to true, then set this value to Spn.

Default value: (net.tcp://localhost:7046/DynamicsNAV90/Service)=NoSpn

If you set this key to the incorrect value, then during startup, the Microsoft Dynamics NAV Web client will automatically determine a correct value. This will cause the Microsoft Dynamics NAV Web client to restart.

Note
For most installations, you do not have to change this value. Unlike the Microsoft Dynamics NAV Windows client, this setting is not updated automatically. If you want to change the default value, then you must change it manually.

DnsIdentity

Specifies the subject name or common name of the service certificate for Microsoft Dynamics NAV Server.

This parameter is only relevant when the ClientServicesCredentialType is set to UserName, NavUserPassword, or AccessControlService, which requires that security certificates are used on the Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Server to protect communication.

Note
You can find the subject name by opening the certificate in the Certificates snap-in for Microsoft Management Console (MMC) on the computer that is running Microsoft Dynamics NAV Web client or Microsoft Dynamics NAV Server.

For more information, see How to: Configure User Authentication for the Microsoft Dynamics NAV Web Client.

Value: The subject name of the certificate.

Default value: none

ACSUri

This parameter is only relevant if the ClientServicesCredentialType parameter is set to AccessControlService.

With the AccessControlService setting, users are authenticated by using either Microsoft Azure Access Control service (ACS) or Microsoft Azure Active Directory (Azure AD). The value of this setting depends on whether ACS or Azure AD is used to authenticate users.

When using ACS authentication, the ACSUri parameter specifies the URI of the ACS login page for relying party applications. An example of a URI is https://CRONUSInternationalLtd.accesscontrol.windows.net/v2/wsfederation?wa=wsignin1.0%26wtrealm=https%3a%2f%2flocalhost%2f. For more information, see How to: Configure the Microsoft Dynamics NAV Web Client for ACS.

When using Azure AD authentication, the ACSUri specifies the URI of the authentication page for the Azure AD tenant where users sign in. An example of a URI is https://login.windows.net/[Tenant_ID]/wsfed?wa=wsignin1.0%26wtrealm=https%3a%2f%2flocalhost%2f. [Tenant_ID] specifies the Azure AD tenant. When the Microsoft Dynamics NAV application has external access and multiple Azure AD tenants are required, you can replace [Tenant_ID] with common. For more information, see Authenticating Users with Azure Active Directory.

Optionally, you can specify a wreply query parameter. The wreply query parameter tells the Azure AD authentication service where to send the authentication token, and the parameter must point to the SignIn.aspx page of the Microsoft Dynamics NAV Web client. If you do not specify the wreply parameter, it will be deducted from the URL in the browser. The value of the wreply parameter must correspond to a Reply-To address in the Azure AD application pointed out by the wtrealm query parameter value.

Important
The query string parameter must be URI-encoded. This means, for example, use "%26" instead of "&".

Default value: none

ForgotPasswordLink

Specifies the URL to open if the user selects Forgotten your password? on the sign in dialog.

Default value: none

HelpServer

Specifies the name of the Microsoft Dynamics NAV Help Server that the Microsoft Dynamics NAV Web client must connect to, such as MyServer.

Default value: none

HelpServerPort

Specifies the TCP port on the specified Microsoft Dynamics NAV Help Server that the Microsoft Dynamics NAV Web client can access Help through, such as 49000.

Default value: none

See Also

Tasks

How to: Set Up Multiple Web Server Instances for the Microsoft Dynamics NAV Web Client
How to: Install the Web Server Components

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Configuring Microsoft Dynamics NAV Server


Configuring the Web Browser for the Microsoft Dynamics NAV Web Client

There are several different web browsers that you can use to open the Microsoft Dynamics NAV Web client. No matter which browser you use, it must be enabled with cookies and JavaScript. Cookies are small files that are stored on your computer and contain information about the Microsoft Dynamics NAV Web client. JavaScript is a programming language for making web pages interactive.

For information about how to enable cookies and JavaScript on your browser, see the following table.

Browser | See
Internet Explorer | How to: Configure Internet Explorer for Microsoft Dynamics NAV Clients
Mozilla Firefox | How to: Configure Mozilla Firefox for Microsoft Dynamics NAV Clients
Google Chrome | Managing cookies Adjust JavaScript
Safari | Manage cookies Enabling JavaScript

For a complete list of supported web browsers and versions, see System Requirements for Microsoft Dynamics NAV 2016.


How to: Configure Internet Explorer for Microsoft Dynamics NAV Clients

To open the Microsoft Dynamics NAV Web client, Internet Explorer must be configured to allow JavaScript and cookies. JavaScript is a programming language for making web pages interactive. Cookies are small files that are stored on your computer. Cookies contain small amounts of data that is specific to a website, or in this case, the Microsoft Dynamics NAV Web client.

This topic describes how to enable JavaScript and cookies in Internet Explorer. For other browsers, refer to the instructions provided by the manufacturer.

Note
For a complete list of supported versions of Internet Explorer and other browsers, see System Requirements for Microsoft Dynamics NAV 2016.

To enable JavaScript in Internet Explorer

  1. Open Internet Explorer.

  2. On the Tools menu, choose Internet Options.

  3. Choose the Security tab.

  4. In the Select a zone to view or change security settings box, choose Internet or Local intranet.

    • Choose Internet if you are accessing Microsoft Dynamics NAV over the public Internet.

    • Choose Local intranet if you are accessing Microsoft Dynamics NAV over a private network such as a business or corporate network.

  5. Choose the Custom Level button.

  6. Scroll down until you see the Scripting section.

  7. Under Active Scripting, choose Enable.

  8. Choose the OK button.

  9. If you see a confirmation window that asks whether you want to change the settings for this zone, choose the Yes button.

  10. Choose the OK button.

  11. Refresh the browser.

To enable cookies in Internet Explorer

  1. Open Internet Explorer.

  2. On the Tools menu, choose Internet Options.

  3. Choose the Privacy tab.

  4. Choose the Advanced button.

  5. On the Advanced Privacy Settings window, select Override automatic cookie handling.

  6. Under First-party Cookies, choose Accept.

    This saves cookies from Microsoft Dynamics NAV Web client on your computer.

  7. Under Third-party Cookies, choose one of the options. The Microsoft Dynamics NAV Web client will operate correctly even if you choose Block. You should select the option that meets your security requirements.

    Note
    Third-party cookies are cookies from websites other than Microsoft Dynamics NAV Web client sites.

  8. Choose the OK button.

  9. Refresh the browser.

See Also

Tasks

How to: Configure Mozilla Firefox for Microsoft Dynamics NAV Clients

Concepts

System Requirements for Microsoft Dynamics NAV 2016
Microsoft Dynamics NAV Web Client


How to: Configure Mozilla Firefox for Microsoft Dynamics NAV Clients

This topic describes how to configure Mozilla Firefox web browser to work with the Microsoft Dynamics NAV Web client. To open the client, Firefox must be configured to allow cookies and JavaScript. In addition, the address of the Microsoft Dynamics NAV Web client must be configured as a trusted unified resource identifier (URI) in Firefox.

  • Enabling Cookies in Firefox

  • Enabling JavaScript in Firefox

  • Configuring the Microsoft Dynamics NAV Web Client Address as a Trusted URI in Firefox

Enabling Cookies in Firefox

Cookies are small files that are stored on your computer. Cookies contain small amounts of data that is specific to a website, or in this case, the Microsoft Dynamics NAV Web client.

To enable cookies in Firefox

  1. Open Firefox.

  2. At the top of the browser window, choose the Firefox button, choose Options, and then choose Options again.

  3. Choose the Privacy tab.

  4. Under History, set the Firefox will box to Use custom settings for history.

  5. Do one of the following.

    If you want to Then

    Allow cookies from all websites

    1. Select Accept cookies from sites.

    2. Choose the OK button.

    Allow cookies only from the Microsoft Dynamics NAV Web client site

    1. Select Exceptions.

    2. In the Address of the website box, type the address of the Microsoft Dynamics NAV Web client, for example: http://myNAVServer:8080//DynamicsNAV90/WebClient.

    3. Choose Allow.

      The Microsoft Dynamics NAV Web client address appears in the Site list.

    4. Choose Close, and then choose the OK button.

Enabling JavaScript in Firefox

JavaScript is a programming language for making web pages interactive.

To enable JavaScript in Firefox

  1. Open Firefox.

  2. At the top of the browser window, choose the Firefox button, choose Options, and then choose Options again.

  3. Choose the Content tab.

  4. Select the Enable JavaScript check box, and then choose the OK button.

Configuring the Microsoft Dynamics NAV Web Client Address as a Trusted URI in Firefox

If the Microsoft Dynamics NAV Web client is configured to use Windows authentication, then to open the Microsoft Dynamics NAV Web client from a computer other than the computer that is running the Microsoft Dynamics NAV Web Server components, you must add the Microsoft Dynamics NAV Web client address to the trusted URI list in Firefox. Otherwise, you will receive one of the following errors when you try to open the Microsoft Dynamics NAV Web client.

A server error occurred, and the content cannot be displayed. Refresh the page or open a new browser window.

401 - Unauthorized: Access is denied due to invalid credentials.

There are two different trusted URI lists that you can add the Microsoft Dynamics NAV Web client address to: network.negotiate-auth.trusted-uris and network.automatic-ntlm-auth.trusted-uris. The list that you use will depend on the authentication provider that is used by the website that is running the Microsoft Dynamics NAV Web client. Use the following guidelines to determine which list to use:

  • If the website uses the negotiate authentication provider, then add the Microsoft Dynamics NAV Web client address to the network.negotiate-auth.trusted-uris list.

    The negotiate authentication uses Kerberos authentication if it is configured on clients. If the Microsoft Dynamics NAV Web Server components and Microsoft Dynamics NAV Server are running on separate computers, then add the address to this list.

  • If the website uses the NTLM authentication provider, then add the Microsoft Dynamics NAV Web client address to the network.automatic-ntlm-auth.trusted-uris list.

  • If you do not know which authentication provider is used, then add the Microsoft Dynamics NAV Web client address to both lists.

To configure the Microsoft Dynamics NAV Web client address in Firefox

  1. Open Firefox.

  2. In the address box, type about:config.

  3. To add the address to the network.automatic-ntlm-auth.trusted-uris list, do the following:

    1. In the Search box, enter network.automatic, and then double-click the line network.automatic-ntlm-auth.trusted-uris.

    2. In the Enter string value dialog box, type the address that you use to open the Microsoft Dynamics NAV Web client, for example, http://myNAVServer:8080/DynamicsNAV90/WebClient.

    3. Choose the OK button.

    Note
    If there is already an address in the box, separate the existing address and the Microsoft Dynamics NAV Web client address by using a comma.

  4. To add the address to the network.negotiate-auth.trusted-uris list, do the following:

    1. In the Search box, enter network.negotiate, and then double-click the line network.negotiate-auth.trusted-uris.

    2. In the Enter string value dialog box, type the address that you use to open the Microsoft Dynamics NAV Web client, for example, http://myNAVServer:8080/DynamicsNAV90/WebClient.

    3. Choose the OK button.

  5. Close and restart Firefox.

See Also

Tasks

How to: Configure User Authentication for the Microsoft Dynamics NAV Web Client
How to: Configure Internet Explorer for Microsoft Dynamics NAV Clients

Concepts

Microsoft Dynamics NAV Web Client
System Requirements for Microsoft Dynamics NAV 2016


How to: Set Up Multiple Web Server Instances for the Microsoft Dynamics NAV Web Client

When you install the Microsoft Dynamics NAV Web Server components, a website with a web server instance for the Microsoft Dynamics NAV Web client is added on Internet Information Services (IIS). There may be scenarios when you want to set up multiple Microsoft Dynamics NAV Web client instances on the Microsoft Dynamics NAV Web client website. For example, you could set up a separate Microsoft Dynamics NAV Web client instance for the different companies.

To add a new Microsoft Dynamics NAV Web client application, you use the Microsoft Dynamics NAV Administration Shell and run the New-NAVWebServerInstance cmdlet to add a new web server instance. The resultant Microsoft Dynamics NAV web server has the following characteristics:

  • A virtual directory instance with an underlying web application is added to the Microsoft Dynamics NAV Web client website. The Microsoft Dynamics NAV Web client application has its own web.config file that you can modify to change the configuration of the Microsoft Dynamics NAV Web client.

  • You can configure IIS settings, such as application pool. You can also configure Microsoft Dynamics NAV settings, such as the Microsoft Dynamics NAV Server instance or company. These setting must be configured separately for each web server instance.

  • The new web server instance has the same URL as other instances under the parent website, except that it includes the instance name that you specify with the New-NavWebServerInstance cmdlet.

    For example, the URL for the default Microsoft Dynamics NAV Web client is http://MyNavWebServer:8080/DynamicsNAV90/WebClient. The URL for the new Microsoft Dynamics NAV Web client instance, which you name MyCompany, would be http://MyNavWebServer:8080/MyCompany/WebClient.

You can run the cmdlet multiple times to create additional Microsoft Dynamics NAV web server instances on the server.

Note
You cannot nest applications. Only one level of applications under a website is allowed.

For more information about Microsoft Dynamics NAV web server instances on IIS, see Deploying the Microsoft Dynamics NAV Web Server Components.

To add a web server instance

  1. (Optional) Modify the instanceweb.config file.

    For more information, see Modifying the Microsoft Dynamics NAV Settings in the Instanceweb.config File

    Note
    You would typically follow this step if you were adding multiple Microsoft Dynamics NAV Web client instances to save time configuring each instance.

  2. On the computer that is running IIS, run Microsoft Dynamics NAV Administration Shell as an Administrator.

    On the Start menu, right-click Microsoft Dynamics NAV Administration Shell, and then choose Run as Administrator.

  3. At the command prompt, type the following command.

    Copy Code
    New-NAVWebServerInstance -WebServerInstance MyWebApp -Server NAVServer -ServerInstance NAVServerInstance

    • Change MyWebApp to the name that you want to give the virtual directory for the web server instance. This name will become part of the URL for the Microsoft Dynamics NAV Web client application, for example, http://MyWebServer:8080/MyWebApp/WebClient.

    • Change NAVServer to the name of the computer that is running the Microsoft Dynamics NAV Server to which you want to connect.

    • Change NAVServerInstance to the name of the instance on the Microsoft Dynamics NAV Server.

    Note
    This command only sets the required parameters of the NAVWebServerInstance cmdlet. The cmdlet has several other parameters that can use to configure the web server instance. For more information about the syntax and parameters, see New-NAVWebServerInstance.

  4. Press Enter to run the cmdlet.

    A new web server instance is added.

    Note
    If you want to change the configuration of the new Microsoft Dynamics NAV web server instance, modify the web.config file. For more information, see Configuring Microsoft Dynamics NAV Web Client by Modifying the Web.config File.

Modifying the Microsoft Dynamics NAV Settings in the Instanceweb.config File

The Microsoft Dynamics NAV web server instances that you add with the New-NavWebServerInstance cmdlet use the instanceweb.config file as a template file to create the actual web.config file for the instance. Modifying the instanceweb.config file enables you to configure the Microsoft Dynamics NAV settings in advance, and then pass the settings to new web server instances when they are created.

By default, the instanceweb.config file is located in the C:\Program Files\Microsoft Dynamics NAV\90\Web Client folder of the computer on which Microsoft Dynamics NAV Web Server components are installed.

To modify the Microsoft Dynamics NAV settings in the instanceweb.config file

  1. On the computer that you installed the Microsoft Dynamics NAV Web Server components, open the instanceweb.config file in a text editor, such as Notepad.

  2. Locate the <DynamicsNAVSettings> element.

  3. Change the parameter values as needed.

    For more information, see Configuring Microsoft Dynamics NAV Web Client by Modifying the Web.config File.

  4. Save the web.config file.

See Also

Tasks

How to: Install the Web Server Components

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Configuring Microsoft Dynamics NAV Web Client by Modifying the Web.config File


How to: Configure Delegation for Microsoft Dynamics NAV Web Client

When the client device, Microsoft Dynamics NAV Web client, and Microsoft Dynamics NAV Server are on separate computers, the client device interacts with Microsoft Dynamics NAV Server through the computer that is running Microsoft Dynamics NAV Web client. Microsoft Dynamics NAV Web client is performing actions on the client device's behalf. This process is known as impersonation. Impersonation cannot be used across multiple computers, so you must set up delegation from Microsoft Dynamics NAV Web client to Microsoft Dynamics NAV Server. Delegation occurs when Microsoft Dynamics NAV Web client forwards a request from a device request to the Microsoft Dynamics NAV Server service so that the Microsoft Dynamics NAV Server service can impersonate the device.

  • Delegating Access from the Web Server to <token xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">nav_server</token>

  • Registering Service Principal Names for Microsoft Dynamics NAV Server

    This task is only required if the service account for Microsoft Dynamics NAV Server is not configured to register SPNs automatically.

  • Configuring Kernel Mode Authentication on the Microsoft Dynamics NAV Web Client Website

Delegating Access from the Web Server to Microsoft Dynamics NAV Server

Configuring delegation means explicitly configuring the computer that is running Microsoft Dynamics NAV Web Server components to delegate its access to the Microsoft Dynamics NAV Server on behalf of the device that is trying to connect to Microsoft Dynamics NAV. To make the access more secure, you specify delegation to a specific service on a specific server. This is known as constrained delegation.

Note
You must run the following procedure on a domain controller computer or on a computer that is installed with Active Directory Domain Services tools.

To delegate access to Microsoft Dynamics NAV Server

  1. On the domain controller computer for your network, or on a computer that is installed with Active Directory Domain Services tools, choose Start, and then choose Run.

  2. In the Open field, type dsa.msc.

    This opens the Active Directory Users and Computers utility.

  3. Expand the node for the domain where you have installed the Microsoft Dynamics NAV Development Environment. For this example, the domain is Corp.

  4. Select the Computers node. Right-click the computer that is running the Microsoft Dynamics NAV Web Server components, and then choose Properties.

  5. On the Delegation tab, choose Trust this user for delegation to specified services only, and then choose Use Kerberos only.

    Note
    The Use Kerberos Only option does not work for some network configurations with Microsoft Dynamics NAV. If you get a server error when you try open the Microsoft Dynamics NAV Web client, then disable the Use Kerberos Only option and see whether this fixes the error. For more information about this error, see Troubleshooting: A server error occurred and the content cannot be displayed.

  6. You must add the following service entries for the computer that is running Microsoft Dynamics NAV Server, where NAVSERVER indicates the name of the computer that is running Microsoft Dynamics NAV Server.

    Service type User or computer Port

    DynamicsNAV

    NAVSERVER

    7046

    DynamicsNAV

    NAVSERVER.corp

    7046

    HOST

    NAVSERVER

    HOST

    NAVSERVER.corp

  7. To add the HOST service, select Expanded, and then choose Add.

  8. In the Add Services window, choose Users or Computers.

  9. In the Enter the object names to select box, type the name of the computer that is running Microsoft Dynamics NAV Server, in this case NAVSERVER, and then choose the OK button.

  10. In the list of available services, select HOST, and then choose the OK button.

  11. To add the DynamicsNAV service, select Expanded, and then choose Add.

  12. In the Enter the object names to select box, type the name of the user that is running the Microsoft Dynamics NAV Server, and then choose the OK button.

  13. Choose the OK button to close the dialog box.

Registering Service Principal Names for Microsoft Dynamics NAV Server

When Microsoft Dynamics NAV Server is using a dedicated domain user account as its logon account, then you must register service principal names (SPN) for the Microsoft Dynamics NAV Server on the domain user account to make delegation work. An SPN is the name by which a client uniquely identifies an instance of a service, using the account under which the service runs. To register SPNs, you used the setspn command-line tool that is available in Windows Server 2008 and Windows 7.

Note
You do not have to perform this task if the domain user account has permissions to register SPNs. In this case, SPNs for Microsoft Dynamics NAV Server will be automatically registered when Microsoft Dynamics NAV Server instance starts and then unregistered when the Microsoft Dynamics NAV Server instance stops. For information about how to configure the service account to register SPNs, see Provisioning the Microsoft Dynamics NAV Server Account.

To create a service principal name

  1. Using any computer in the network, open a command prompt as an administrator. To do this, choose Start, and then in the search window, type Command Prompt. Right-click Command Prompt, and then choose Run as administrator.

  2. To view the registered SPNs for Microsoft Dynamics NAV Server on the domain account, type the following command.

    Copy Code
    setspn -l domain\username

    To view the registered SPNs for a specific computer, type the following command.

    Copy Code
    setspn -l domain\computername$

  3. At the command prompt, create an SPN for the Microsoft Dynamics NAV Server service using the following syntax.

    Copy Code
    setspn -A InstanceName/FullyQualifiedDomainNameOfServer:Port Domain\User

    Replace InstanceName, FullyQualifiedDomainNameOfServer, Port, and Domain\ServiceAccountUserName with the appropriate values.

    For example, if NAVSERVER is the name of the computer that is running Microsoft Dynamics NAV Server and DynamicsNAV is the instance name for Microsoft Dynamics NAV Server, the actual command has the following format.

    Copy Code
    setspn -A DynamicsNAV/NAVSERV.corp:7046 corp\navdomainuser

Configuring Kernel Mode Authentication on the Microsoft Dynamics NAV Web Client Website

By default, Windows authentication on the Microsoft Dynamics NAV Web client site on IIS is set to use kernel mode authentication. Kernel-mode authentication improves authentication performance. However, when you are using delegation with Kerberos, you must either disable kernel mode or configure it to use the credentials of the application pool of Microsoft Dynamics NAV Web client; otherwise, authentication will fail and Microsoft Dynamics NAV Web client will not be able to connect to Microsoft Dynamics NAV Server. This is because kernel mode authentication runs under the machine account of the computer that is running IIS and the Microsoft Dynamics NAV Web Server components, while the Microsoft Dynamics NAV Web client runs under the user account of the user trying to access Microsoft Dynamics NAV.

As a best practice, you should configure kernel mode authentication to use the application pool credentials, as described in the following procedure.

To configure Kernel Mode Authentication to use the Application Pool Credentials

  1. On the computer that you installed Microsoft Dynamics NAV Web Server components, open the applicationHost.config file for Internet Information Services in a text editor, such as Notepad. By default, the file is located in c:\Windows\System32\inetsrv\config.

  2. Locate the <location path="Microsoft Dynamics NAV 2016 Web Client"> element.

  3. Change the <windowsAuthentication enabled="true"> element to the following.

    Copy Code
    <windowsAuthentication enabled="true" useAppPoolCredentials="true" />

  4. Save the file.

  5. Restart IIS. To restart IIS in a command prompt, do the following:

    1. On the Start menu, choose Run.

    2. In the Open box, type cmd, and then choose the OK button.

    3. At the command prompt, type iisreset, and then press Enter.

    Tip
    You can also restart IIS using Internet Information Services Manager, if you have it installed.

To disable configure Kernel Mode Authentication

  1. Open Internet Information Services Manager.

    On the Start menu, in the Search Programs and Files box, type inetmgr, and then press Enter.

  2. In the Connections pane, expand Sites, and then select Microsoft Dynamics NAV 2016 Web client.

  3. In the IIS section, double-click Authentication.

  4. In the Authentication pane, choose Windows Authentication, and then choose Advanced Settings.

  5. Clear the Enable Kernel-mode authentication box, and then choose the OK button.

See Also

Concepts

Microsoft Dynamics NAV Web Client
Deploying the Microsoft Dynamics NAV Web Server Components
Deploying the Microsoft Dynamics NAV Web Server Components in a Two Computer Environment
Deploying the Microsoft Dynamics NAV Web Server Components in a Three Computer Environment


How to: Configure User Authentication for the Microsoft Dynamics NAV Web Client

You can configure the Microsoft Dynamics NAV Web client to authenticate users on one of the following credential types.

Credential type | Description | Prompted to sign in
Windows | Users are authenticated using a Windows account (Active Directory). Users are automatically authenticated using the Windows account that is currently logged on to the device that they are using to access the Microsoft Dynamics NAV Web client. | No
UserName | Users are authenticated using their Windows account. | Yes
NavUserPassword | Users are authenticated using their Microsoft Dynamics NAV user name and password, instead of their Windows credentials. | Yes
AccessControlService | Users are authenticated using either Microsoft Azure Access Control Service (ACS) or Microsoft Azure Active Directory (AAD). | Yes

For more information about the credential types and their use, see Users and Credential Types.

To set up user authentication, complete the following tasks:

  • Implementing Security Certificates

    Implement security certificates on the computer that is running Microsoft Dynamics NAV Server and the computer that is running Microsoft Dynamics NAV Web Server components.

    Note
    This step is not required when you use the Windows credential type.

  • Configuring the Credential Type for Microsoft Dynamics NAV Server

  • Configuring the Credential Type on the Microsoft Dynamics NAV Web Client

Implementing Security Certificates

When using the UserName, NavUserPassword, or AccessControlService credential type, you must implement security certificates on the computer that is running Microsoft Dynamics NAV Server and the web server computer that is running Microsoft Dynamics NAV Web Server components. Security certificates protect the passing of credentials between the Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Server. A certificate is a file that the web server uses to prove its identity and establish a trusted connection with Microsoft Dynamics NAV Server.

Note
You do not have to perform this task for Windows authentication.

To implement security certificates

  • To create your own certificates and implement them in a test environment for the Microsoft Dynamics NAV Web client, see Walkthrough: Implementing Security Certificates in a Test Environment.

    In this scenario, you create your own self-signed certificates, and then install them on the computers that are running Microsoft Dynamics NAV Server and the Microsoft Dynamics NAV Web Server components.

  • To implement certificates in a production environment for Microsoft Dynamics NAV Web client, see How to: Implement Security Certificates in a Production Environment.

    In this scenario, you obtain certificates from a certification authority. Some large organizations may have their own certification authorities, and other organizations can request a certificate from a third-party organization. After you obtain the certificates, you install them on the computers that are running Microsoft Dynamics NAV Server and the Microsoft Dynamics NAV Web Server components.

Configuring the Credential Type for Microsoft Dynamics NAV Server

The credential type of the Microsoft Dynamics NAV Web client must match the credential type in the Microsoft Dynamics NAV Server instance that is used by the Microsoft Dynamics NAV Web client.

To configure the credential type for the Microsoft Dynamics NAV Server instance

  1. Start either the Microsoft Dynamics NAV Server Administration tool or the Microsoft Dynamics NAV 2016 Administration Shell.

    For more information, see Microsoft Dynamics NAV Server Administration Tool or Microsoft Dynamics NAV Windows PowerShell Cmdlets.

  2. Find the ClientServicesCredentialType parameter in the configuration for the Microsoft Dynamics NAV Server instance.

    In the Microsoft Dynamics NAV Server Administration tool, the parameter is named Credential Type and is on the General tab.

    For more information, see Configuring Microsoft Dynamics NAV Server.

  3. Change the value to either Windows, UserName, NavUserPassword, or AccessControlService.

    Important
    On the Client Services tab, you must set the Certificate Thumbprint parameter to the thumbprint of the security certificate that is used by Microsoft Dynamics NAV Server.

  4. Restart the Microsoft Dynamics NAV Server instance.

Configuring the Credential Type on the Microsoft Dynamics NAV Web Client

To configure the credential type for the Microsoft Dynamics NAV Web client, perform the following procedures, as described in this section:

  1. Configure the credential type in the web.config files for the web server instance of the Microsoft Dynamics NAV Web client.

  2. Enable the authentication methods on the Internet Information Services (IIS) website for Microsoft Dynamics NAV Web client.

To configure the credential type in the web.config files of the Microsoft Dynamics NAV Web client

  1. On the computer that is running the Microsoft Dynamics NAV Web Server components, open the web.config file that is located in the physical path of the virtual directory for the Microsoft Dynamics NAV Web client application. This web.config file contains the Microsoft Dynamics NAV settings.

  2. The folder path is %systemroot%\inetpub\wwwroot\[VirtualDirectoryName]. For example, the folder for the default Microsoft Dynamics NAV Web client application is %systemroot%\inetpub\wwwroot\DynamicsNAV90 folder.

  3. In the <DynamicsNavSettings> element, which is located toward the end of the file, find the <add key="ClientServicesCredentialType" value=""/> element, and then change it to one of the following.

    Copy Code
    <add key="ClientServicesCredentialType" value="Windows"/>
    Copy Code
    <add key="ClientServicesCredentialType" value="UserName"/>
    Copy Code
    <add key="ClientServicesCredentialType" value="NavUserPassword"/>
    Copy Code
    <add key="ClientServicesCredentialType" value="AccessControlService/>

  4. If you are configuring the Windows credential type, then you are finished. Save the web.config file. For other credential types, continue to the next step.

  5. Find the <add key="DnsIdentity" value=""/> element, and change it as follows.

    Copy Code
    <add key="DnsIdentity" value="SubjectName"/>

    Replace subjectName with the subject name or common name (CN) of the certificate that is used on the computer that is running Microsoft Dynamics NAV Server.

    Note
    You can find the subject name by opening the certificate in the Certificates snap-in for Microsoft Management Console (MMC) on the computer that is running Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Server. For more information, see Walkthrough: Implementing Security Certificates in a Test Environment or How to: Implement Security Certificates in a Production Environment.

  6. If you are configuring AccessControlService authentication, then find the <add key="ACSUri" value=""/> element, and set the value to the URI of the ACS or AAD authentication page.

    Copy Code
    <add key="ACSUri" value=""/>

    For more information, see Authenticating Users with Microsoft Azure Access Control Service and Authenticating Users with Azure Active Directory.

  7. Save the web.config file.

To enable an authentication method on the website for the Microsoft Dynamics NAV Web client

  1. On the computer that is running Microsoft Dynamics NAV Web Server components, open Internet Information Services (IIS) Manager.

    On the Start menu, in the Search programs and files box, type inetmgr, and then press Enter.

  2. In the Connections pane, under Sites, choose Microsoft Dynamics NAV 2016 Web Client.

  3. Under IIS, double-click Authentication.

  4. In the Authentication pane, enable the appropriate authentication based on the credential type.

    • For the Windows credential type, enable Windows authentication.

    • For the UserName and NavUserPassword credential types, enable both Forms authentication and Anonymous authentication.

    To enable an authentication method, choose the authentication method from the list, and then choose Enable in the Actions pane.

  5. For Windows authentication, you must set up an authentication provider. By default, Windows authentication is configured to use the Negotiate and NTML providers, which is sufficient for most installations and no action is required. If the computer that is running Microsoft Dynamics NAV Web Server components and Microsoft Dynamics NAV Server are on different computers, and delegation with Kerberos is configured between the two computers, then the Negotiate provider must be first in the list of providers.

    To set up the providers, do the following:

    1. Choose Window Authentication, and then under Actions, choose Providers.

    2. To add a provider, select the provider from the Available Providers list, and then choose Add.

    3. To move a provider in the Enables Providers list, select the provider, and then choose the Move Up or Move Up button.

    4. Choose the OK button.

  6. Restart the web server.

    In the Connections pane of IIS Manager, choose the root node for your computer, and then in the Actions pane, choose Restart.

See Also

Tasks

How to: Install the Web Server Components
How to: Specify When UI Elements Are Removed

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Configuring Microsoft Dynamics NAV Web Client by Modifying the Web.config File


How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client

We recommend that you secure Microsoft Dynamics NAV data that is transmitted over the Internet by enabling Secure Sockets Layer (SSL) on the connection to Microsoft Dynamics NAV Web client.

SSL is a web protocol that encrypts data that is transmitted over a network to make the data and the network more secure and reliable. A website that is enabled with SSL uses Hypertext Transfer Protocol Secure (HTTPS) instead of Hypertext Transfer Protocol (HTTP) as a communication protocol. Enabling SSL on a website requires that an SSL certificate is installed on the web server. An SSL certificate is a small file that the web server uses to prove its identity and establish a trusted connection with the browser that is trying to access Microsoft Dynamics NAV Web client. When a browser connects to the Microsoft Dynamics NAV Web client, the web server replies by sending its certificate to the browser. This certificate contains the web server's public encryption key and the name of the authority that granted the certificate. The browser verifies the certificate using the authority's public key.

To configure SSL, you must follow these steps.

  • Obtaining an SSL Certificate

  • Adding an HTTPS Binding That Uses the Certificate on the Microsoft Dynamics NAV Web Client Site

  • Redirecting HTTP to HTTPS (Optional)

Note
You can configure SSL for the Microsoft Dynamics NAV Web client when you install the Microsoft Dynamics NAV Web Server components. For more information, see How to: Install the Web Server Components.

Obtaining an SSL Certificate

In a production environment, you should obtain an SSL certificate from a certification authority. Some large organizations may have their own certification authorities, and other organizations can request a certificate from a third-party organization. In a test environment or development environment, you can create your own self-signed certificate.

To create a self-signed SSL certificate

  1. To open Internet Information Services (IIS) Manager, use one of the following methods:

    • In Windows 7, on the Start menu, in the Search programs and files box, type inetmgr, and then press Enter.

    • In Windows Server 2008 R2, on the Start menu, choose Administrative Tools, and then choose Internet Information Service (IIS) Manager.

  2. In the Connections pane, choose the top-level node for the server.

  3. On the Home page, under IIS, choose Server Certificates, and then in the Actions pane, choose Open Feature.

  4. On the Server Certificates page, choose Create Self-Signed Certificate.

  5. In the Specify Friendly Name dialog box, type a brief name for the certificate, and then choose the OK button.

    The new certificate appears on the Server Certificate page.

Adding an HTTPS Binding That Uses the Certificate on the Microsoft Dynamics NAV Web Client Site

After you get the certificate, you add a binding to the https protocol on the website. When you add the binding, you associate it with the certificate.

To add an https binding with the certificate to the website

  1. Open Internet Information Services (IIS) Manager.

  2. In the Connections pane, expand the Sites node, and then choose the Microsoft Dynamics NAV Web client site to which you want to add the binding.

    By default, the site has the name Microsoft Dynamics NAV 2016 Web Client.

  3. In the Actions pane, choose Bindings.

  4. In the Site Bindings dialog box, choose Add.

  5. In the Add Site Binding dialog box, set the Type field to https.

    You can use the default port 443 or change it to another port. If you change it to another port, you will have to provide the port number in the URL when you try to open the client.

  6. Set the SSL certificate field to the certificate that you obtained or created for the site.

  7. Choose the OK button, and then choose the Close button.

Redirecting HTTP to HTTPS (Optional)

To ensure that users always access the site that is secured with SSL, you can automatically redirect HTTP requests to HTTPS. This means that users do not have to explicitly include https in the URL in the browser. For example, the nonsecure URL of the Microsoft Dynamics NAV Web client could be http://MyWebclient:8080/DynamicsNAV90/WebClient and the secure URL could be https://MyWebclient:443/DynamicsNAV90/WebClient. If a user types http://MyWebclient:8080/DynamicsNAV90/WebClient, the browser automatically redirects to https://MyWebclient:443/DynamicsNAV90/WebClient.

There are different ways to redirect HTTP requests to HTTPS. The following procedure describes how to redirect HTTP requests to HTTPS by installing the Microsoft Application Request Routing for IIS 7 and modifying the web.config file for the Microsoft Dynamics NAV Web client.

To redirect HTTP to HTTPS

  1. Download and install Microsoft Application Request Routing for IIS. You can use one of the following links:

    • Microsoft Application Request Routing Version 2 for IIS 7 (x64)

    • Microsoft Application Request Routing Version 2 for IIS 7 (x86)

  2. On the computer that is running Microsoft Dynamics NAV Web Server components, open the web.config file for the web server instance for Microsoft Dynamics NAV Web client. Use a text editor, such as Notepad.

    The web.config file is located in the physical path of the web application on IIS. By default, the path is %systemroot%\inetpub\wwwroot\[VirtualDirectoryName]\WebClient. For example, the folder for the default Microsoft Dynamics NAV Web client application is %systemroot%\inetpub\wwwroot\DynamicsNAV90\WebClient.

  3. In the <system.webServer> element, add the following elements.

    Copy Code
    <rewrite>
  <rules>
    <rule name="Redirect to HTTPS">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
      </conditions>
      <action type="Redirect" url="https://{SERVER_NAME}/{R:1}" redirectType="SeeOther" />
    </rule>
  </rules>
</rewrite>

  4. Save the web.config file.

See Also

Tasks

How to: Install the Web Server Components

Concepts

Microsoft Dynamics NAV Web Client
Deploying the Microsoft Dynamics NAV Web Server Components


How to: Configure Microsoft Report Viewer for the Microsoft Dynamics NAV Web Client

The Microsoft Dynamics NAV Web client uses Microsoft Report Viewer to display Microsoft Dynamics NAV reports. Before you can do this, Microsoft Report Viewer must be configured on a web site of the Microsoft Dynamics NAV Web client. To configure Microsoft Report Viewer, you add the ASP.NET web handler file for Microsoft Report Viewer to the web.config file of the Microsoft Dynamics NAV Web client site.

Note
By default, Microsoft Report Viewer is configured. The following procedure is only required if you have removed the Microsoft Report Viewer configuration from the web.config file for the Microsoft Dynamics NAV Web client.

Report Viewer also includes an option that lets users save a report as a Microsoft Excel, Microsoft Word, or PDF file. This functionality is not enabled by default. If you want to be able to save reports, you must configure the Report Viewer to save reports. For more information, see Configuring Report Viewer to Save Reports as Excel XLSX, Word DOCX, or PDF Files.

To configure Microsoft Report Viewer

  1. On the computer that is running Microsoft Dynamics NAV Web Server components, open the web.config file for the web server instance for the Microsoft Dynamics NAV Web client. Use a text editor, such as Notepad.

    The web.config file is located in the physical path of the web application on Internet Information Services (IIS). By default, the path is %systemroot%\inetpub\wwwroot\[VirtualDirectoryName]\WebClient. For example, the folder for the default Microsoft Dynamics NAV Web client application is %systemroot%\inetpub\wwwroot\DynamicsNAV90\WebClient.

  2. In the <handlers></handlers> element of the web.config file, add the following code for the Microsoft Report Viewer handler.

    Copy Code
    <add name="ReportViewerWebControl" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" resourceType="Unspecified" />

  3. Save the web.config file.

Configuring Report Viewer to Save Reports as Excel XLSX, Word DOCX, or PDF Files

You can set up the Print Preview for reports to include an option that enables users to save a report as an Excel XLSX, Word DOCX, or PDF file. Microsoft Report Viewer uses the Temp folder of the user account that is used as the application pool identity of the Microsoft Dynamics NAV Web client. To set up the save as Excel and Word options, the user account must have read, write, and modify permission to the folder. If the user account does not have the correct permissions, then the saved file will be empty.

Note
If your company uses Microsoft Office 365, the temporary files are stored in the location that is specified for the Office 365 document library. For more information, see Integrating with Office 365 and SharePoint Online.

To configure Report Viewer to save reports as Excel XLSX, Word DOCX, or PDF files

  1. Open the web.config file for the Microsoft Dynamics NAV Web client application that contains the Microsoft Dynamics NAV settings. Use a text editor, such as Notepad.

    The web.config file is located in the physical path of the virtual directory for the Microsoft Dynamics NAV Web client application on IIS. By default, the path is %systemroot%\inetpub\wwwroot\[VirtualDirectoryName]. For example, the folder for the default Microsoft Dynamics NAV Web client application is %systemroot%\inetpub\wwwroot\DynamicsNAV90.

  2. On the computer that is running Microsoft Dynamics NAV Web Server components, grant users read, write, and modify permission to the user account’s Temp folder that is used as the identity of the application pool for Microsoft Dynamics NAV Web client.

    Note
    This step is not required if you only want to enable saving reports as PDF files.

    For the Microsoft Dynamics NAV Web client, the default user account is ApplicationPoolIdentity and the folder is C:\Users\Web Client Application Pool\AppData\Local\Temp\.

    Tip
    To determine the application pool identity, open Internet Information Services Manager, and then choose Application Pools in the Connections pane.

See Also

Concepts

Configuring Microsoft Dynamics NAV Web Client by Modifying the Web.config File
Deploying the Microsoft Dynamics NAV Web Server Components


How to: Change the Microsoft Dynamics NAV Server for the Microsoft NAV Web Client

The Microsoft Dynamics NAV Server that the Microsoft Dynamics NAV Web client connects to is configured in the web.config file for the website that is running the Microsoft Dynamics NAV Web Server components. By default, Microsoft Dynamics NAV Setup configures the Microsoft Dynamics NAV Web client to connect to the following Microsoft Dynamics NAV Server instance:

  • Server name: localhost

  • Service instance: DynamicsNAV90

  • Client service port: 7046

To change the Microsoft Dynamics NAV Server instance after you install the Microsoft Dynamics NAV Web Server components, you modify the web.config file.

To change the Microsoft Dynamics NAV Server instance

  1. On the computer that is running Microsoft Dynamics NAV Web Server components, open the web.config file for the web server instance of Microsoft Dynamics NAV Web client. Use a text editor, such as Notepad.

    The web.config file is located in the physical path of the virtual directory for the web server instance on Internet Information Services (IIS). By default, the path is %systemroot%\inetpub\wwwroot\[VirtualDirectoryName]. For example, the folder for the default Microsoft Dynamics NAV Web client instance is %systemroot%\inetpub\wwwroot\DynamicsNAV90.

    Important
    You must open the web.config file as an administrator or have permission to modify the file.

  2. Locate the <DynamicsNAVSettings> element.

  3. Change the values for the following <add /> elements.

    Value Description

    ClientServicesPort

    Specifies the TCP port for the Microsoft Dynamics NAV Server.

    Values: 1-65535

    Default value: 7046

    Server

    Specifies the name of the computer that is running Microsoft Dynamics NAV Server.

    Default value: localhost

    ServerInstance

    Specifies the name of the Microsoft Dynamics NAV Server instance that the Microsoft Dynamics NAV Web client connects to.

    For more information, see Managing Microsoft Dynamics NAV Server Instances.

    Default value: DynamicsNAV90

  4. Save the web.config file.

See Also

Tasks

How to: Install the Web Server Components

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components


How to: Configure the Microsoft Dynamics NAV Web client to Accept Host Names for Tenants

If you deploy the Microsoft Dynamics NAV Web client in a multitenant deployment architecture, URLs that must access a specific tenant must specify the tenant ID. However, the Microsoft Dynamics NAV Web client can be accessed from URLs that specify a host name. If your deployment must support host names for tenants, then you must enable the corresponding URL rewrite rule in the web.config file for the Microsoft Dynamics NAV Web Server components.

To enable the URL rewrite rule to configure the Microsoft Dynamics NAV Web client to accept host names for tenants

  1. On the computer that is running the Microsoft Dynamics NAV Web Server components, open the web.config file that is located in the physical path of the web application for the Microsoft Dynamics NAV Web client.

    The path is %systemroot%\inetpub\wwwroot\[VirtualDirectoryName]\WebClient. For example, the folder for the default Microsoft Dynamics NAV Web client application is %systemroot%\inetpub\wwwroot\DynamicsNAV90\WebClient.

    Note
    You must open the web.config file as an administrator or have permission to modify the file.

  2. In the <system.webServer> element, find the <rule name="Hostname (without port) to tenant" enabled="false" stopProcessing="true"> element, and then change the value of the enabled attribute to true.

  3. Save and close the web.config file.

This enables support for host names for the Microsoft Dynamics NAV Web Server components. If a tenant has been mounted with a host name as an alternative ID, the Microsoft Dynamics NAV Web client will accept a URL that contains this host name to identify the tenant.

If you create a non-tenant specific app for SharePoint that accesses the Microsoft Dynamics NAV Web client by using Microsoft Azure Active Directory, the resulting URL includes a parameter that specified a SharePoint host URL. This represents the URL for opening the Microsoft Dynamics NAV Web client that you have specified in the app manifest. You must enable a URL rewrite rule in order to accept the URL.

See Also

Tasks

How to: Mount or Dismount a Tenant on a Microsoft Dynamics Server Instance

Concepts

Multitenant Deployment Architecture
Configuring the Microsoft Dynamics NAV Web Server and Client
Integrating Microsoft Dynamics NAV in SharePoint Sites


Configuring Microsoft Dynamics NAV Help Server

Microsoft Dynamics NAV Help deploys to a Microsoft Dynamics NAV Help Server, which is a website that installs on the specified server. The website includes Search and other navigation, and it provides context-sensitive Help for Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Windows client. You can configure each client to access Help on any Microsoft Dynamics NAV Help Server. Depending on your deployment architecture, you can choose to set up a dedicated Help Server that all clients connect to, or you can choose to deploy customer-specific Help Servers. You can deploy a Help Server under either http or https protocols.

Deploying the Help Server

The Microsoft Dynamics NAV Help Server is an installation component that you can choose from the Custom option of Microsoft Dynamics NAV Setup. When you choose to install the Help Server, a website is created on the specified server. If Internet Information Services (IIS) are not present on the server, Setup installs this and other prerequisites. When the Setup program is finished, the website is set up with a folder for each language in your version of Microsoft Dynamics NAV. However, the Help content consists of many files, and therefore, the content is not fully available until after several minutes. Exactly how much time it takes to make the content available depends on the number of Help files that must be added to the website.

You can add solution-specific and customer-specific Help, and you can add as many languages to the Help Server as your deployment requires. When accessed from Microsoft Dynamics NAV, Help displays in the language that the current client uses. If that language is not available, the Help Server defaults to English.

Configuration Settings

When you install the Microsoft Dynamics NAV Help Server, you must specify the following information.

Field | Description
Install location | Specifies where the Microsoft Dynamics NAV Help Server is installed, such as C:\inetpub\wwwroot.
Port | Specifies the TCP listening port for the Microsoft Dynamics NAV Help Server, such as 49000. The valid range is 1-65535.

Then, when you install Microsoft Dynamics NAV Server, the Microsoft Dynamics NAV Windows client, or the Microsoft Dynamics NAV Web Server components, you must specify where the Help Server is located as described in the following table.

Field Description

Server

Specifies the location of the computer that hosts the Microsoft Dynamics NAV Help Server, such as MyWebServer.

If the value of the HelpServer setting starts with "http," then the HelpServer port setting is ignored and the entire value is used to create the base of the help url. This enable you to set up a server that uses https or that includes a subpath, as in the following examples:

https://myserver.com

-or-

http://myserver.com:45672/navhelp/financeapp

If the Help Server setting does not begin with "http," then Microsoft Dynamics NAV will format the url as follows: http://<HelpServer value>:<HelpServerPort value>.

Port

Specifies the TCP listening port for the Microsoft Dynamics NAV Help Server, such as 49000.

For Microsoft Dynamics NAV Windows client users, this configuration is stored in the ClientUserSetting.config file. For more information, see Configuring the Windows Client.

Configuring the Website

The Microsoft Dynamics NAV Help Server deploys as a website that you can configure like any other website. For example, you must make the website available to your users by granting them permission to access the website. By default, users that you set up in Microsoft Dynamics NAV can access the website, because Microsoft Dynamics NAV Setup enables Windows authentication and anonymous authentication. For example, if your Microsoft Dynamics NAV deployment uses Windows authentication, you can add the relevant domain group to the IIS users group. If you want to use other types of authentication, you can set up NET authorization rules, for example.

The website for the Help Server contains several folders as described in the following table.

Folder Description

App_GlobalResources

Contains the localized strings for the website itself.

bin

Contains the Microsoft.Dynamics.Nav.WebHelp.dll assembly that provides core functionality for the Microsoft Dynamics NAV Help Server.

css

Contains the stylesheets for the website.

help

Contains the Help content with a subfolder for each language module in your deployment, an en folder, and a local folder.

The locale-specific Help content is in locale-specific folders. For example, in the Danish version of Microsoft Dynamics NAV, the Help Server website includes a da-DK folder with the Help content in Danish.

The en folder contains Help content in the non-locale-specific version. This is the version of the Help that Microsoft Dynamics NAV defaults to if the client locale cannot be found.

The local folder contains pictures and other supporting files for the Help content.

images

Contains icons for the website.

js

Contains support files for the website.

Help is installed as CAB files, which self-extract when the installation is completed, such as htmlhelp.en.cab.

If you want to add your own Help content to the Help Server website, you can add the relevant HTML files to the relevant locale-specific folder.

Each locale-specific Help folder contains a ToC.xml file that defines the navigation pane on the website, the table of contents. If you want to add your Help content to the table of contents file, you can edit the ToC.xml file in the XML editor of your choice, such as Notepad or Visual Studio.

In a multitenant deployment, the Help links that open a specific page in Microsoft Dynamics NAV do not work by default. To convert all of the hyperlinks in your existing Help, you can use a search-and-replace tool to find the links that look like this example:

Copy Code
<a href="DynamicsNAV:////runpage?Page=536" alt=

and replace them with:

Copy Code
<a href="DynamicsNAV://///runpage?Page=536" alt=

See Also

Concepts

Microsoft Dynamics NAV Help Server
Help Table of Contents
Upgrading Your Existing Help Content
Configuring Microsoft Dynamics NAV
Configuring Microsoft Dynamics NAV Server
Configuring the Windows Client
Configuring the Microsoft Dynamics NAV Web Server and Client
Demo Option


Help Table of Contents

The Microsoft Dynamics NAV 2016 Help Server includes a navigation pane with links to key topics on the Help Server. The table of contents in the navigation pane is determined by a ToC.xml file. When you add new Help for customized functionality to Microsoft Dynamics NAV, you should make this Help discoverable by adding entries in the ToC.xml file. Likewise, if your users do not have access to certain areas of the application, you can remove these entries from the navigation pane.

The ToC.xml file can be found in the folders that contain the Help content in each language, such as C:\inetpub\wwwroot\DynamicsNAV90Help\help\en.

Important
Make sure to work on a local copy of the ToC.xml file and upload when you are done editing.

Linking to Help Topics

The ToC.xml file contains a <node> element for each link from the navigation pane to a Help topic. The following table describes the attributes of a <node> element.

Attribute | Description | Example
Name | Specifies a unique name for the entry in the ToC.xml file. This name is not visible on the website, but the Help Server uses the name to generate the navigation pane. | GettingStarted
DisplayName | Specifies the text that displays in the navigation pane. It is a best practice that the display name is the same as or very similar to the title of the target topic. | Getting Started with Microsoft Dynamics NAV 2016
Page | Specifies the target topic that opens when the user chooses the link. | conGettingStarted.htm

You can create subentries for an entry in the navigation pane by embedding <node> elements within another <node> element. However, you should keep the navigation pane limited to key topics only since most users access Help through context-sensitive Help calls and through Search.

See Also

Concepts

Configuring Microsoft Dynamics NAV Help Server
Upgrading Your Existing Help Content


Upgrading Your Existing Help Content

It is possible to reuse Help that you created using the Microsoft Dynamics NAV 2013 Help Toolkit for an earlier version of Microsoft Dynamics NAV. The difference is that you must now use the HTML files instead of the CHM files, and that you have to update the links in the HTML files to reflect this change.

On the Help Server, all Help is in HTML files, and all HTML files for a specific language are located in the same folder on the web server. As a result, there is a significant difference in the formatting of the hyperlinks between the topics. In earlier versions, the hyperlinks must include information about the CHM file that the target topic was in. On the Help Server, all Help topics are in the same folder, so the navigation element is no longer needed.

Updates to Existing Help Content

In earlier versions of Microsoft Dynamics NAV, if your Help was contained in addin_a.chm, and you wanted to link to the topic How to: Enter Company Information in gl_m.chm, the hyperlink was formatted as shown in the following example:

Copy Code
<a href=”ms-its:gl_m.chm::/html/tskEnterCompanyInformation.htm>How to: Enter Company Information</a>

In the example, the following content describes the location of the target topic: ms-its:gl_m.chm::/html/. However, since all topics are now in the same location, this content is no longer needed. The following example illustrates the same link in a topic on the Microsoft Dynamics NAV 2016 Help Server:

Copy Code
<a HREF="tskEnterCompanyInformation.htm>How to: Enter Company Information</a>

To convert all of the hyperlinks in your existing Help, you can use a search-and-replace tool to find and replace the navigation content, create a script with a regular expression that handles the conversion, or rebuild your Help project with the Microsoft Dynamics NAV 2013 Help Toolkit.

If you choose to rebuild your Help project with the Microsoft Dynamics NAV 2013 Help Toolkit, you must modify the configuration file for the Microsoft Dynamics NAV 2013 Help Builder tool to remove the navigation content from the links that are injected by the tool. These links are specified in the <hyperlinks> element in the config.default.xml file. You can modify those boilerplate links to exclude the navigation content, and you can also update the build number to the following value:

Copy Code
<buildNumber>8.0.Customized</buildNumber>

You can verify that your Help topics work with the classic.css stylesheet by adding the topics to a local Help Server on your own computer. Then, you can add the relevant topics to the navigation pane by modifying the ToC.xml file. For more information, see Help Table of Contents.

See Also

Concepts

Configuring Microsoft Dynamics NAV Help Server


Configuring NAS Services

NAS services are a middle-tier server component that executes business logic without a user interface or user interaction. NAS services in Microsoft Dynamics NAV Server support applications such as Microsoft Office Outlook Integration and the NAV Job Queue.

NAS stands for NAV Application Server, which was a component in earlier versions of Microsoft Dynamics NAV. NAS services replace the NAS component, and this requires you to modify any use of server-side COM. For more information, see Extending Microsoft Dynamics NAV Using Microsoft .NET Framework Interoperability.

Run NAS Services Applications in Dedicated Server Instances

It is recommended that you create a separate Microsoft Dynamics NAV Server instance for each NAS services application. See How to: Create a Microsoft Dynamics NAV Server Instance.

There are multiple reasons for running NAS services sessions in dedicated Microsoft Dynamics NAV Server instances:

  • Efficiency and convenience

    When you change any Microsoft Dynamics NAV Server setting, you must restart the instance for the change to take effect, which interrupts all services using that instance. So if you are running different types of services in the same instance—for example, RoleTailored client services and NAS services—making a change to the settings for either service type will require a server instance restart that interrupts all other service types running through that instance.

    Even for different types of NAS services applications it’s wise to run each application in a separate server instance. For example, if you will be using NAS services for a Microsoft Office Outlook Integration application and also for a Microsoft Dynamics NAV job queue application, create a separate Microsoft Dynamics NAV Server instance for each NAS services application. This way, if you need to modify settings for the Microsoft Office Outlook Integration application you will not affect the Microsoft Dynamics NAV job queue application, and vice-versa.

  • Performance

    Configuring NAS services applications to use separate server instances makes better use of the server computer’s resources, allowing you to run more applications with less degradation.

  • Efficient error tracking

    If a NAS services session terminates in an error, and there are no other services running on the Microsoft Dynamics NAV Server instance, the service instance terminates and can be handled like any other Windows service. For example, you could configure the Recovery tab on the Service configuration tool in Control Panel to restart or otherwise manage the service.

Configuring NAS Services Settings

You can configure NAS services by using the settings in Microsoft Dynamics NAV Server Administration tool. In a multitenent Microsoft Dynamics NAV Server instance deployment, some NAS services settings, such as enabling NAS services and running NAS services with admin rights, are specified when you mount the tenant on the Microsoft Dynamics NAV Server instance.

To configure NAS Services

  1. Start the Microsoft Dynamics NAV Server Administration tool, and open the Microsoft Dynamics NAV Server instance configuration.

    For more information, see Microsoft Dynamics NAV Server Administration Tool

  2. On the NAS Services tab, fill in the settings.

    For more information about the settings, see NAS Services Tab Settings.

    Important
    On the General tab, the Services Default Company specifies the default company that is used by NAS Services and also other types of client connections.

    NAS services sessions execute in the time zone specified by the ServicesDefaultTimeZone parameter for Microsoft Dynamics NAV Server. See.

    For more information about these settings, see General Tab Settings.

  3. If the Microsoft Dynamics NAV Server is a configured as a multitenant server, mount the tenant to configure the NAS services settings for the tenant.

    For more information, see How to: Mount or Dismount a Tenant on a Microsoft Dynamics Server Instance.

  4. Save the changes and restart the Microsoft Dynamics NAV Server instance.

  5. If you chose not to run NAS services with admin rights, add the service account for the Microsoft Dynamics NAV Server instance to be a user in Microsoft Dynamics NAV.

    For more information, How to: Create Microsoft Dynamics NAV Users.

NAS Services and Languages

In multilanguage deployments of Microsoft Dynamics NAV, the language preferences and regional settings for the user account that NAS services settings runs as determine the formatting of the data. Language preferences for a user account can be set in Windows or in Microsoft Dynamics NAV. For example, in Microsoft Dynamics NAV, in the User Personalization Card window, you can specify a language for the user. But you can also set up a default language for the Microsoft Dynamics NAV deployment by creating an empty row in the User Personalization List window. If you create an entry where you specify a language but not a user ID, then NAS services will use that language unless the session runs with a user account where you have specified another language.

The following table illustrates how combinations of language personalization and regional settings impact data that a NAS services session processes. In this example, the NAS services session runs a computer where the regional settings are set to use the Spanish format. In Microsoft Dynamics NAV, the user account that the NAS services session runs as either has a language personalization or not.

Regional settings format | User personalization language ID | Generic personalization language ID | NAS services language and format
Spanish (Spain) | 3086 |  | 8036 and Spanish (Spain)
Spanish (Spain) |  |  | 1033 and Spanish (Spain)
Spanish (Spain) |  | 8036 | 8036 and Spanish (Spain)

See Also

Concepts

Configuring Microsoft Dynamics NAV Server
Client Types
Managing Microsoft Dynamics NAV Server Instances
Administration


Configuring Automated Data Capture System

The Automated Data Capture System (ADCS) is a Microsoft Dynamics NAV tool that gives companies the ability to accurately capture data for inbound, outbound, and internal documents, primarily in connection with warehouse activities. ADCS enables company employees to use handheld devices and radio frequency technology to validate warehouse inventories.

When you run the setup of Microsoft Dynamics NAV, you can provide configuration information for ADCS.

Installing ADCS in Setup

You can install ADCS when you run Microsoft Dynamics NAV Setup. You must first select ADCS as a component to install. To do this, you have to customize the list of components to install to include ADCS, which is not included in any of the predefined Installation Options. For more information, see How to: Choose Components to Install.

Configuring ADCS After Installation

For more information about additional configuration tasks that you must perform to set up ADCS, see the following topics:

  • How to: Configure ADCS Options

  • How to: Test the ADCS Connection

  • How to: Modify ADCS Functions

  • How to: Add Users for ADCS

See Also

Use Automated Data Capture Systems (ADCS)

Tasks

How to: Enable Web Services for ADCS
How to: Create a Microsoft Dynamics NAV Server Instance

Concepts

System Requirements for Microsoft Dynamics NAV 2016


ADCS Overview

The Automated Data Capture System (ADCS) solution provides a way for Microsoft Dynamics NAV to communicate with handheld devices through web services. You can test your solution by using the VT100 plug-in.

Note
We recommend that you install Microsoft Dynamics NAV Server and the VT100 plug-in on separate computers. For more information, see How to: Create a Microsoft Dynamics NAV Server Instance.

Overview and Architecture

ADCS enables you to accurately capture data for inbound, outbound, and internal documents, primarily for warehouse activities. For example, you can have users scan the bar codes of items in your warehouse as they perform daily tasks, and that information is recorded from these handheld device activities in Microsoft Dynamics NAV.

Microsoft Dynamics NAV Server processes the data coming to in from the handheld devices via the plug-in and sends the appropriate response back to the handheld devices via the plug-in. An XML format is used to send and receive the data. The VT100 plug-in makes sure that the response from Microsoft Dynamics NAV is directed to the correct handheld device. This reduces the load on the server.

The VT100 plug-in provides the link between the server and the Access Points for the handheld devices and acts as a virtual Telnet server. All connection requests and data transmissions are handled by this service, and the incoming native protocol is transformed into standard XML that the server can interpret. After a request has been transformed, the request is forwarded by the VT100 plug-in to the server. When a reply is received, it is converted from XML into the native protocol of the handheld device. Function keys are mapped using an XSLT file that you can modify. After the data has been transformed and formatted, it is forwarded to the handheld device.

Design Overview

The following illustration provides a simple diagram of ADCS. The part of the illustration that is shaded, which does not include ADCS, represents what could be developed.

Consider the following when you deploy an ADCS solution:

  • You can configure multiple instances of Microsoft Dynamics NAV Server on a single computer, but each instance can only access one company. Therefore, if you want to access several companies from the same computer, you must configure several Microsoft Dynamics NAV Server instances for NAS Services.

  • You can only install one instance of the VT100 plug-in on a single computer. The VT100 plug-in can only serve one company but it can communicate with multiple instances of Microsoft Dynamics NAV Server. This means that all of the instances of the server that use the same VT100 plug-in can only access the same company.

  • If you want to communicate with more than one company, you must install the VT100 plug-in on more than one computer, one for each company. Each of the VT100 plug-in installations must then use a separate Microsoft Dynamics NAV Server to access one of the companies.

    Note
    You can also install the VT100 plug-in multiple times on the same computer, one for each company.

Supported Devices

An ADCS device includes devices such as bar code readers or optical character readers that are used to mechanize the entry of information into the database.

All character-based handheld devices that have a VT100 interface will work with ADCS, although you may have to implement minor adjustments with some models. When you use a handheld device, you must be able to connect either the Access Point or the RF terminal to the IP or port address of the ADCS server.

If you want to use a graphics-based handheld device, you will have to develop your own plug-in.

You can connect multiple handheld devices to the VT100 plug-in. However, if performance becomes an issue, you can always add an additional Microsoft Dynamics NAV Server and direct the VT100 plug-in to also connect with the new server to improve performance.

See Also

Tasks

How to: Configure ADCS Options


How to: Enable Web Services for ADCS

To use Automated Data Capture System, you must enable the ADCS web service.

To enable and publish the ADCS web service

  1. Start the RoleTailored client.

  2. In the Search box, enter Web Services, and then choose the related link.

  3. On the Home tab, choose New.

  4. In the Web Services window, enter the following information on a new line:

    Field Value

    Object Type

    Codeunit

    Object ID

    7714

    Service Name

    ADCS

    Important
    It is required that you name the service ADCS.

  5. Select the Published check box.

  6. Choose the OK button.

To verify that the web service has been published

  1. In a web browser window, enter a URL in the following format: http://<web services path>/Services. The following example demonstrates the results.

    Copy Code
    http://localhost:7047/DynamicsNAV90/WS/Services

    You see the following XML information if the ADCS web service is published.

    Copy Code
    <contractRef xmlns="http://schemas.xmlsoap.org/disco/scl/" ref="http://localhost:7047/DynamicsNAV90/WS/Codeunit/ADCS"/>

  2. To verify that the codeunit is performing as expected, enter a URL in the following format: http://<web services path>/Codeunit/<Service Name>.

    Copy Code
    http://localhost:7047/DynamicsNAV90/WS/Codeunit/ADCS

    Information about the ADCS web service is displayed.

See Also

Miniforms

Tasks

How to: Configure ADCS Options

Concepts

Configuring Automated Data Capture System
SOAP Web Services


How to: Set Up a Local Language for the ADCS Web Service

To have messages, including errors, display in the language of the user, you have to modify the ADCS web service codeunit to account for the language setting.

To specify the local language of ADCS messages

  1. Start the Microsoft Dynamics NAV Development Environment, and on the Tools menu, choose Object Designer.

  2. Choose CodeUnit, and from the list, select codeunit 7714. Choose the Design button. The C/AL Editor opens.

  3. In the ProcessDocument function, add a line of code as highlighted in the following code. The following example demonstrates setting the language code for German.

    Copy Code
    GLOBALLANGUAGE(1031);
InputXmlDocument := InputXmlDocument.XmlDocument;
InputXmlDocument.LoadXml(Document);
ADCSManagement.ProcessDocument(InputXmlDocument);
ADCSManagement.GetOutboundDocument(OutputXmlDocument);
Document := OutputXmlDocument.OuterXml;

See Also

Concepts

Configuring Automated Data Capture System


How to: Configure ADCS Options

Before you can work with Automated Data Capture Systems (ADCS), you have to configure Microsoft Dynamics NAV by modifying the VT100Plugin configuration file.

Important
Modification of the configuration file should only be performed by a system administrator.

To modify and update the ADCS configuration file for the terminal listener

  1. Locate and open the NavisionVT100Plugin.exe.config configuration file. It is typically located in the following location: C:\Program Files (x86)\Microsoft Dynamics NAV\90\Automated Data Capture System.

    The following example shows the XML that is contained in the configuration file by default.

    Copy Code
    <configuration>
<configSections>
<section name="VT100" type="Microsoft.Dynamics.Nav.Adcs.Configuration.VT100ConfigurationSection, Microsoft.Dynamics.Nav.VT100Plugin" />
</configSections>
<VT100>
<Warehouse>
<!-- Endpoint attributes are described in the table in step 3. -->
</Warehouse>
<Terminal />
<!-- Terminal attributes are described in the table in step 2. -->
</VT100>
</configuration>

  2. For the Terminal element, update the attributes in the configuration file using attributes as described in the following table. You specify the attribute values in quotation marks.

    Attribute Description

    listenIP

    Required. IP address that specifies where to listen for terminal connections.

    listenPort

    Required. Positive integer that specifies the port number to listen for terminal connections.

    stylesheet

    Required. Path to transformation style sheet, which transforms warehouse functions to terminal keycodes. Two style sheets are provided with the ADCS installation.

    screenLines

    Optional. Positive integer that specifies the number of screen lines. The default is 5.

    screenWidth

    Optional. Positive integer that specifies the screen width. The default is 30.

    codePage

    Optional. Positive integer that specifies the codepage. The default is the system codepage defined in HKey_Local_Machine\SYSTEM\CurrentControlSet\Control\Nls\CodePage\ACP.

    terminalTimeout

    Optional. Positive integer that specifies the terminal time-out in milliseconds. The default is 65000 and cannot be fewer than 6000.

    debugDirectory

    Optional. Output directory for debug data.

  3. For the Endpoints element, update the attributes in the configuration file and modify an endpoint to support your processes. You can also add more endpoints. The following table provides some options.

    Attribute Description

    defaultType

    Optional. defaultType is an attribute of the Endpoints element. It specifies what type of endpoint to use when no type is specified, if you want to customize it. The default is the NavEndpoint type.

    name

    Required. Endpoint name. The name must be unique.

    url

    Required. Endpoint URL address.

    Note
    This attribute does not have to be included if the clientEndpointName attribute is specified.

    type

    Optional. Fully qualified name of a non-default endpoint.

    clientEndpointName

    Optional. Windows Communications Foundation client endpoint configuration name. If specified, a WCF configuration with the specified name must exist. For more information, see Client Configuration in the MSDN Library.

The following example describes the XML for a Terminal element and the Endpoints element. It adds one endpoint for Microsoft Dynamics NAV.

Copy Code
<configuration>
<configSections>
<section name="VT100" type="Microsoft.Dynamics.Nav.Adcs.Configuration.VT100ConfigurationSection, NavisionVT100Plugin" />
</configSections>
<VT100>
<Warehouse>
<Endpoints>
<add name="NavEndpoint" url="http://[local]:7047/DynamicsNAV90/WS/CRONUS%20International%20Ltd/Codeunit/ADCS" />
</Endpoints>
</Warehouse>
<Terminal listenIP="127.0.0.1" listenPort="6666" stylesheet="VT100_W2k_and_OtherClients.xsl" />
</VT100>
</configuration>

Security

By default, the NavEndpoint uses the security settings that you have specified for web services generally. You can configure additional security by changing the configuration of Microsoft Dynamics NAV Server and matching that configuration in the VT100Plugin configuration service.

For more information, see Configuring Microsoft Dynamics NAV Server.

See Also

Tasks

How to: Create a Microsoft Dynamics NAV Server Instance
How to: Enable Web Services for ADCS

Concepts

Configuring Microsoft Dynamics NAV Server


How to: Add a Beep to an ADCS Solution

You can add beep sounds to your ADCS solution. To do this, you add the keyword _BELL_ to a string for the miniform that has the functionality you want to modify. The keyword is case sensitive. The following procedure demonstrates modifying codeunit 7705, which controls the logon screen for a handheld device.

To add a beep sound to an ADCS string

  1. Start Microsoft Dynamics NAV Development Environment, and on the Tools menu, choose Object Designer.

  2. Choose CodeUnit, and from the list, select a codeunit for ADCS miniforms, for example, codeunit 7705.

  3. Choose the Design button. The C/AL Editor opens.

  4. On the View menu, choose C/AL Globals.

  5. Choose the Text Constants tab.

  6. For each string for which you want to sound a beep, append the following code to the end of the string.

    Copy Code
    _BELL_

    The following is example code.

    Copy Code
    Invalid User ID._BELL_

    For a double-beep, append the following code.

    Copy Code
    _BELL__BELL_

    Recompile the codeunit.

See Also

Concepts

ADCS Overview


How to: Test the ADCS Connection

The following procedure demonstrates how to use Windows Services and Telnet to test your Automated Data Capture System connection. Before you can begin, you must install the ADCS component as part of a customized installation of Microsoft Dynamics NAV. For more information, see How to: Choose Components to Install.

To configure and start the Microsoft Dynamics NAV VT100 Plugin service

  1. From the Windows Start menu, in the Start Search box, enter services.msc, and then press the Enter key. The Services window opens.

  2. Right-click the Microsoft Dynamics NAV VT100Plugin service, and then choose Properties.

  3. To specify the user account that the service can use to log on, choose the Log On tab.

    To specify an account, choose This account, choose Browse, and then specify a user account in the Select User dialog box. When you are finished, choose the OK button. The format is as follows:

    <Domain>\<Windows User ID>

    Note
    To complete testing, you must also add the same user to Microsoft Dynamics NAV, with an appropriate permission set. For more information, see How to: Create Microsoft Dynamics NAV Users.

  4. Type the password for the user account in Password and in Confirm password, and then choose the OK button.

  5. On the General tab, choose Start.

To verify that the service is running

  1. Start the Windows Event Viewer. From the Windows Start menu, in the Start Search box, enter eventvwr.msc, and then press the Enter key.

  2. In the Windows Logs console tree, choose Application, and then locate event information for the Microsoft Dynamics NAV VT100 Plugin.

Testing Your Connection

In the following procedure, you will open a terminal connection and use HyperTerminal to simulate using handheld devices. HyperTerminal is a program that you can use to connect to other computers, Telnet sites, bulletin board systems (BBSs), online services, and host computers. HyperTerminal connections are made using a modem, a null modem cable (used to emulate modem communication), or an Ethernet connection.

Note
HyperTerminal is no longer included with Windows. You can usually find a free downloadable version on the Internet. For more information, see What-happened-to-HyperTerminal. Alternatively, in Windows 7, you can turn on the Telnet Client feature. For more information, see Install Telnet Client.

To test your ADCS connection

  1. Start your HyperTerminal application.

  2. Enter a name for the connection. Choose the OK button.

  3. In the Connect Using list, select TCP/IP (Winsock).

  4. The following table describes the details of a local installation on one machine.

    Detail Description Example

    Host Address

    IP address of the machine that is running the VT100 Plug-in service.

    localhost

    Port Number

    Port number that the VT100 Plug-in is listening on.

    6666

    Choose the OK button. The HyperTerminal window opens.

  5. Enter a user ID and password. Choose the OK button.

  6. Select a warehouse activity option. For example, enter 1 in the Choose field if you want to simulate working with pick documents.

    You can review the data about warehouse picks in Microsoft Dynamics NAV. For example, you can use the data in the CRONUS International Ltd. demonstration database to send information from and to Microsoft Dynamics NAV.

    Note
    To see the interaction between Microsoft Dynamics NAV and ADCS, in CRONUS International Ltd., you can use warehouse activities that are located in the White warehouse. It is preconfigured to use ADCS. For more information, see Use ADCS.

See Also

Concepts

Configuring Automated Data Capture System


How to: Add Users for ADCS

You can add any user as a user of an Automated Data Capture System (ADCS). When you do this, the user must also provide a password. Optionally, you can also provide a connection that identifies the ADCS user as a warehouse employee. The ADCS user password can be different from the Windows logon password of the user.

To add an ADCS user

  1. In the Search box, enter ADCS Users, and then choose the related link.

  2. On the Home tab, choose New to add a new user.

  3. In the Name field, enter a name for the user. The name cannot contain more than 20 characters, including spaces.

  4. In the Password field, enter a password. The password is masked.

To indicate that a warehouse employee is an ADCS user

  1. In the Search box, enter Warehouse Employees, and then choose the related link.

  2. If needed, add a new warehouse employee. For more information, see How to: Set Up Warehouse Employees.

  3. On the Home tab, in the Manage group, choose Edit List.

  4. Select a warehouse employee from the list. In the ADCS User field, choose the drop-down arrow, and then select the name of an ADCS user from the list.

    Note
    The default warehouse for the employee should be one that uses ADCS. For more information, see How to: Set Up a Warehouse to Use ADCS.

See Also

ADCS Users
ADCS User

Tasks

How to: Test the ADCS Connection
How to: Create Microsoft Dynamics NAV Users


How to: Modify ADCS Functions

To implement or change the functionality of a miniform function, you must create a new codeunit or modify an existing one. You can learn more about ADCS functionality by examining codeunits such as 7705. That codeunit shows how a Card-type miniform works.

Any change to an ADCS miniform, other than the addition of an output or text field, must be reflected in the code in the miniform-specific codeunit.

Each codeunit must contain the following functions.

Function | Description
OnRun | Required. Every miniform-specific codeunit must receive a Miniform Header record as a parameter, passed by variance. If this is the first call to the codeunit, the codeunit sends the XML document. If the user has entered some data, the function runs the ProcessInput function to process the user's data.
ProcessInput | Must appear in all Card-type miniform-specific codeunits. This function processes the user's input. For example, in codeunit 7705, this function reacts to the entry of a User ID, a Password, or the ESC function. Since this is a Card-type miniform, the function also reacts when the user enters data in the last field in the form.
PrepareData | Sets the active input field and sends the form.
SendForm | Required. This function sends the prepared XML form.

You can use the following codeunits as templates when creating new miniform-specific codeunits.

Miniform Type | Sample Codeunit
Card | 7705
Selection list | 7706
Data list | 7712
Data list input | 7713

To add support for a function key

  1. The following example code is added to the .xsl file for the plug-in. This creates a function for the F6 key. The key sequence information can be obtained from the device manufacturer.

    Copy Code
    <xsl:template match="Function[.='F6']">
  <Function Key1="27" Key2="91" Key3="49" Key4="55" Key5="126" Key6="0"><xsl:value-of select="."/></Function>
</xsl:template>

  2. In the Microsoft Dynamics NAV Development Environment, open table 7702, and add a code representing the new key. This example creates a key called F6.

  3. Add C/AL code to the relevant function of the miniform-specific codeunit to handle the function key.


Troubleshooting: ADCS

This topic lists some common problems that can occur when you use Automated Data Capture Systems for Microsoft Dynamics NAV.

HyperTerminal or other Telnet application does not work

You have installed all ADCS components correctly, but when you start HyperTerminal or another Telnet application, nothing happens. You also get a warning in the Event Viewer stating that the TCP/IP address has not been identified. This problem may occur when you have not logged onto the correct domain server.

To resolve this error, make sure that you have logged onto the domain server. Also, review the information provided in the Windows Event Viewer.

Resolving a web service exception about callback functions

When using Microsoft Dynamics NAV web services, the web service call may return a fault with the following message:

Callback functions are not allowed.

The error generally occurs because the web service has accessed other application code that requires interaction with a client. For example, you may be using ADCS with warehouse functionality, such as bin capacity policy. The warehouse logic may include confirmation dialog boxes that users interact with as they register warehouse picks and put-aways. If a user encounters the error, the pick or put-away is not registered.

To resolve this error, make sure that the web service call does not call code that requires interaction with a client, or modify your Microsoft Dynamics NAV solution to allow data to be inserted or modified without such interactions.

For more information, see Handling UI Interaction When Working with Web Services.

National character sets

Your national characters do not display correctly. In order for the national characters to display correctly, the terminal software should support the code page that you are interested in using. For example, code page 1251 refers to ANSI Cyrillic, which is supported by Hyper Terminal on a Russian environment (including the special Cyrillic font).

To resolve this error, check that you have specified the correct code page in your configuration file. You may want to update the codePage attribute.

For more information, see How to: Configure ADCS Options. For a list of code pages, see Code Page Identifiers.

Performance considerations

Depending on the load on your system, you may encounter performance issues.

To resolve this problem, you can configure multiple endpoints, instead of just one, for your plug-in. It is possible for one plug-in to connect to several servers on one or more distributed computers. The plug-in and servers, a pool of endpoints, can be on the same computer or divided among any number of computers, as long as they are all available via TCP. This can improve performance in busy scenarios, as calculations can be performed on different processes at the same time.

For more information, see How to: Configure ADCS Options.

See Also

Concepts

Handling UI Interaction When Working with Web Services


Configuring Authentication

In the following sections, you can read about how to configure Microsoft Dynamics NAV to authenticate users.

Users and Credential Types

Authenticating Users with Microsoft Azure Access Control Service

Authenticating Users with Azure Active Directory

See Also

Concepts

Managing Users

Other Resources

Managing Permissions and Permission Sets


Users and Credential Types

Microsoft Dynamics NAV 2016 supports four credential authorization mechanisms for Microsoft Dynamics NAV users. When you create a user, you provide different information depending on the credential type that you are using in the current Microsoft Dynamics NAV Server instance.

Important
All users of a Microsoft Dynamics NAV Server instance must be using the same credential type. You specify which credential type is used for a particular Microsoft Dynamics NAV Server instance in the Microsoft Dynamics NAV Server Administration tool.

For more information about how to create users, see How to: Create Microsoft Dynamics NAV Users. Alternatively, you can create new users using the Windows PowerShell cmdlet, New-NAVServerUser. For more information, see Microsoft Dynamics NAV Windows PowerShell Cmdlets.

Credential Types

Microsoft Dynamics NAV supports the following credential types.

Credential types Description

Windows

With this credential type, users are authenticated using their Windows credentials. You can only specify Windows as the credential type if the corresponding user exists in Windows (Active Directory, local workgroup, or the local computer’s users). Because they are authenticated through Windows, Windows users are not prompted for credentials when they access Microsoft Dynamics NAV.

UserName

With this setting, the user is prompted for username/password credentials when they access Microsoft Dynamics NAV. These credentials are then validated against Windows authentication by Microsoft Dynamics NAV Server. There must already be a corresponding user in Windows. Security certificates are required to protect the passing of credentials across a wide-area network. Typically, this setting should be used when the Microsoft Dynamics NAV Server computer is part of an authenticating Active Directory domain, but the computer where the Microsoft Dynamics NAV Windows client is installed is not part of the domain.

NavUserPassword

With this setting, authentication is managed by Microsoft Dynamics NAV Server but is not based on Windows users or Active Directory. The user is prompted for username/password credentials when they start the client. The credentials are then validated by an external mechanism. Security certificates are required to protect the passing of credentials. This mode is intended for hosted environments, for example, where Microsoft Dynamics NAV is implemented in Azure.

AccessControlService

With this setting, Microsoft Dynamics NAV relies on Microsoft Azure Access Control service (ACS) or Azure Active Directory (Azure AD) for user authentication services.

ACS is a cloud service that provides user authentication and authorization for web applications and services. ACS integrates with standards-based identity providers, including enterprise directories such as Active Directory, and web identities such as Microsoft account, Google, Yahoo!, and Facebook. For more information, see Authenticating Users with Microsoft Azure Access Control Service.

Azure AD is a cloud service that provides identity and access capabilities, such as for applications on Azure, in Microsoft Office 365, and for applications that install on-premises. If the Microsoft Dynamics NAV Server instance is configured to use AccessControlService authentication, you can specify an Azure AD account for each user in the Office 365 Authentication field so that they can access both the Microsoft Dynamics NAV Web client and their Office 365 site. Also, if you use Microsoft Dynamics NAV in an app for SharePoint, users have single sign-on between the SharePoint site and Microsoft Dynamics NAV. For more information, see Authenticating Users with Azure Active Directory.

Important
If Microsoft Dynamics NAV Server is configured to use NavUserPassword or AccessControlService authentication, then the username, password, and access key can be exposed if the SOAP or OData data traffic is intercepted and the connection string is decoded. To avoid this condition, configure SOAP and OData web services to use Secure Socket Layer (SSL). For more information, see Walkthrough: Configuring Web Services to Use SSL (SOAP and OData).

Configuring the Credential Type

RoleTailored clients and Microsoft Dynamics NAV Server must be configured to use the same credential type.

To edit the configuration for the Microsoft Dynamics NAV Server instance, you can use either the Microsoft Dynamics NAV Server Administration tool or the Microsoft Dynamics NAV 2016 Administration Shell. In the Microsoft Dynamics NAV Server Administration tool, you configure the credential type in the Credential Type field on the General tab. Alternatively, you can edit the CustomSettings.config file. For more information, see Configuring Microsoft Dynamics NAV Server.

Important
When Microsoft Dynamics NAV Server services are deployed on Azure, you must configure them on Azure. For more information, see How to: Open Microsoft Dynamics NAV Clients that Connect to Microsoft Dynamics NAV on Microsoft Azure.

For each Microsoft Dynamics NAV Windows client user, you must modify the ClientUserSettings.config file. The default location for this file is C:\Users\<username>\AppData\Roaming\Microsoft\Microsoft Dynamics NAV\90, where <username> is the name of the user. For the Microsoft Dynamics NAV Web client users, you must modify the web.config file for the Microsoft Dynamics NAV Web Server components. For information, see Configuring Microsoft Dynamics NAV Web Client by Modifying the Web.config File. In the relevant configuration file, find the ClientServicesCredentialType parameter and change the value to one of the options listed earlier.

When you change the credential type for a Microsoft Dynamics NAV Server instance and the relevant client configurations, the changes take effect when you restart the Microsoft Dynamics NAV Server instance and users connect to the instance again.

See Also

Tasks

How to: Create Microsoft Dynamics NAV Users
How to: Open Microsoft Dynamics NAV Clients that Connect to Microsoft Dynamics NAV on Microsoft Azure

Concepts

Configuring Microsoft Dynamics NAV Server
Configuring Microsoft Dynamics NAV Web Client by Modifying the Web.config File
Configuring the Windows Client
Microsoft Dynamics NAV Windows PowerShell Cmdlets


Authenticating Users with Microsoft Azure Access Control Service

Microsoft Azure Access Control service (ACS) is a cloud service that provides user authentication and authorization for web applications and services. By using ACS, you do not have to factor authentication and authorization into your application code. Instead of implementing an authentication system with user accounts that are specific to your application, you can let ACS orchestrate the authentication and much of the authorization of your users. ACS integrates with standards-based identity providers, including enterprise directories such as Active Directory, and web identities such as Microsoft account, Google, Yahoo!, and Facebook.

For Microsoft Dynamics NAV 2016, use the following sequence of tasks to configure software and users to use ACS:

  • How to: Sign Up for a Microsoft Account

  • How to: Sign Up for a Microsoft Azure Subscription

  • Create Microsoft Azure Access Control Service Users

  • How to: Configure a Deployment for ACS

  • Configure Microsoft Dynamics NAV Components for ACS

  • Prepare Users for First ACS Login


Create Microsoft Azure Access Control Service Users

Microsoft Azure Access Control service (ACS) users are one of four types of users that you can create in Microsoft Dynamics NAV clients. For more information about how to create one or more users for ACS authentication, see the "To create a new user for AccessControlService authentication" section in How to: Create Microsoft Dynamics NAV Users. Follow the instructions and make a note of the user names and authentication keys for any users that you create.

Important
If ACS authentication is not available, consider creating at least one user who will be able to connect by using a Microsoft Dynamics NAV client. For example, if users are registered by using a certain ACS namespace and that namespace changes, then the users will no longer be able to connect.

One way to prevent this kind of lockout is to create a user who will be able to access the client using NavUserPassword authentication. For more information, see Users and Credential Types. Another option is to create an ACS user but to never log that user in with ACS authentication, so that the user's ACS status remains Pending.

For either option, make sure that you assign the SUPER permission set to this user, to make sure that there is at least one user with full access to all client functionality.


How to: Configure a Deployment for ACS

To configure your Microsoft Dynamics NAV deployment to use Microsoft Azure Access Control service (ACS) authentication requires the following series of configuration procedures in the Azure management portal:

  • Create a namespace.

  • Configure the namespace.

  • Specify relying party applications.

  • Add a rule group.

  • Add a logon page for relying party applications.

To create a namespace

  1. In the Azure management portal, choose the Active Directory button.

  2. Choose the New button, point to Access Control, and then choose Quick Create.

  3. Fill in the fields as described in the following table.

    Field Description

    Namespace

    Enter a name for the namespace. The name can be any text. For example, you can enter the name of your company for the namespace name.

    A green checkmark appears if the namespace is available. The value that you specify because a prefix for the fully qualified namespace, such as mynamespace.accesscontrol.windows.net.

    Region

    Choose the Azure region that you want to host your namespace in.

    Choose the region that most closely matches your country/region. For example, if you and your customers are located in Denmark, choose North Europe, unless another region suits your needs better.

    Subscription

    Choose your Azure subscription.

  4. Choose Create.

After the status of your namespace becomes Active, you can continue with configuring the namespace.

To configure the namespace

  1. Select your namespace. In the menu at the bottom of the page, choose Manage.

    Note
    If this button is not available, you may want to obtain Portal Administrator permission for the namespace. Ask the Service Administrator for the Azure subscription to grant you this permission. Co-administrator permission is sufficient for creating a namespace, but not for managing ACS.

  2. In the left pane of the Access Control Service section of the Azure management portal, choose Identity Providers.

    An identity provider is an organization that provides authentication services that you can use as your ACS authentication mechanism. There are five possible identity providers. Windows Live ID is the default identity provider. Two of the other options require no configuration: Google and Yahoo!. The final two require additional configuration: Facebook and WS-Federation. WS-Federation lets users authenticate by logging on to their corporate account, which is managed by Active Directory. For more information about how to configure a WS-Federation identity provider, see How to configure AD FS 2.0 as an Identity Provider in the MSDN Library.

  3. Select the identity providers that you want to make available to the users. You can choose as few as one, such as just Windows Live ID, or as many as all five identity providers.

    Next, you specify relying party applications. Relying party applications are the websites, applications, and services for which you want to use ACS to implement Shared Services authentication. In this case, the relying party applications are Microsoft Dynamics NAV clients.

To specify relying party applications

  1. In the left pane of the Access Control Service section of the Azure management portal, choose Relying Party Applications, and then choose Add.

  2. In the Add Relying Party Application page, fill in the fields as described in the following table.

    Field Description

    Name

    Specify a name for the application.

    A typical value would be the name of the organization for which the deployment was created.

    Mode

    Choose Enter settings manually.

    Realm

    Enter the DNS name of the Microsoft Dynamics NAV Server instance, such as https://MyCompany.com or https://localhost.

    The DNS name must be the same that is specified in the Server parameter in the clientUserSettings.config file for Microsoft Dynamics NAV Windows client client and the web.config file for Microsoft Dynamics NAV Web client clients.

    Return URL

    Enter the fully qualified URL for the Microsoft Dynamics NAV Web Server components, such as https://MyCompany.com or https://MyServer/WebClient.

    The URL is case-sensitive.

    If you do not deploy the Microsoft Dynamics NAV Web Server components, you can specify any address since the Microsoft Dynamics NAV Windows client does not use this setting.

    Token format

    Select SWT. Other token types are not supported in this version of Microsoft Dynamics NAV.

    This adds a Token Signing Settings section to the page.

  3. In the Token Signing Settings section, in the Token signing key field, choose the Generate button.

  4. Specify an effective date and an expiration date for the key.

    Security Note
    To help secure your deployment, schedule a regeneration of this key regularly.

  5. Copy the string of characters that automatically populate the field.

    You will use this string to update the TokenSigningKey in the server configuration.

  6. Choose the Save button to save your relying party application configuration.

    Next, you add a rule group. Rule groups define how claims are passed from identity providers to your relying party applications.

To add a rule group

  1. In the left pane of the Access Control Service portal, choose Rule groups.

  2. Choose the default rule group for the relying party applications that you just created.

  3. In the Edit Rule Group page, choose Generate. In the Generate Rules page, choose the relevant identity provider, and then choose the Generate button.

  4. Choose the Save button.

    The final step in the Access Control configuration is to add a Shared Services login page to your relying party application. There is where your user can present credentials for the configured identity provider.

To add a login page for relying party applications

  1. In the left pane of the Access Control Service portal, choose Application Integration.

  2. On the Application Integration page, choose Login Pages.

  3. Choose your relying party application.

  4. Under Option 1: Link to an ACS-hosted login page, copy the URI from the first text box to Notepad.

  5. In Notepad, replace any instances of the ampersand character (&) with %26.

    You will use this URI in the server configuration for ACS.

Next Steps

  • During the configuration of your deployment for ACS, you have saved two values:

    • The string of characters from the Token signing key field in the Add Relying Party Application page.

    • The URI for your relying party application from the Application Integration section.

    You will need these values for the next stage in the ACS configuration process, which is configuring your Microsoft Dynamics NAV components for ACS.

See Also

Tasks

How to: Set up Microsoft Dynamics NAV for Single Sign-on With Office 365 using Windows PowerShell

Concepts

Configure Microsoft Dynamics NAV Components for ACS


Configure Microsoft Dynamics NAV Components for ACS

The components to configure are the Microsoft Dynamics NAV Server instance and the client. This is either the Microsoft Dynamics NAV Windows client or the Microsoft Dynamics NAV Web client.

Warning
Before you configure components, you must have created at least one user who will be able to log on using ACS authentication. For more information, see Create Microsoft Azure Access Control Service Users.

For more information about how to configure components, see the following topics:

  • How to: Configure the Microsoft Dynamics NAV Server Instance for ACS

  • How to: Configure the Microsoft Dynamics NAV Windows Client for ACS

  • How to: Configure the Microsoft Dynamics NAV Web Client for ACS

See Also

Concepts

Authenticating Users with Microsoft Azure Access Control Service


How to: Configure the Microsoft Dynamics NAV Server Instance for ACS

You configure your Microsoft Dynamics NAV Server instance for Access Control Service (ACS) by using either the Microsoft Dynamics NAV Server Administration tool or the Microsoft Dynamics NAV PowerShell API.

Before you begin this procedure, you must perform the steps to configure your deployment for ACS. For more information, see Authenticating Users with Microsoft Azure Access Control Service.

To configure the Microsoft Dynamics NAV Server instance for ACS

  1. Start either the Microsoft Dynamics NAV Server Administration tool or the Microsoft Dynamics NAV PowerShell API.

    For more information, see Microsoft Dynamics NAV Server Administration Tool or Microsoft Dynamics NAV Windows PowerShell Cmdlets.

  2. Find the ClientServicesCredentialType parameter in the configuration for the Microsoft Dynamics NAV Server instance.

    In the Microsoft Dynamics NAV Server Administration tool, the parameter is named Credential Type and is on the General tab.

    For more information, see Configuring Microsoft Dynamics NAV Server.

  3. Change the value to AccessControlService.

    Important
    If not already done, under the Client Services tab, you must set the Certificate Thumbprint parameter to the thumbprint of the security certificate that is used by Microsoft Dynamics NAV Server.

  4. Find the ClientServicesTokenSigningKey parameter in the configuration for the Microsoft Dynamics NAV Server instance.

    In the Microsoft Dynamics NAV Server Administration tool, the parameter is named Token Signing Key and is on the Client Services tab.

    For more information, see Configuring Microsoft Dynamics NAV Server.

  5. Replace the current value with the string of characters from the Token signing key field in the Add Relying Party Application page.

  6. Restart the Microsoft Dynamics NAV Server instance.

The next steps are to configure your clients for ACS. For more information, see How to: Configure the Microsoft Dynamics NAV Windows Client for ACS and How to: Configure the Microsoft Dynamics NAV Web Client for ACS.

See Also

Concepts

Configure Microsoft Dynamics NAV Components for ACS


How to: Configure the Microsoft Dynamics NAV Windows Client for ACS

You configure the Microsoft Dynamics NAV Windows client for Access Control Service (ACS) by editing the client configuration file (ClientUserSettings.config).

Before you begin this procedure, you must perform the steps to configure your deployment for ACS. For more information, see Authenticating Users with Microsoft Azure Access Control Service.

To configure the Microsoft Dynamics NAV Windows client for ACS

  1. Edit the client configuration file (ClientUserSettings.config) for each copy of the Microsoft Dynamics NAV Windows client that will be supporting users for ACS authentication.

    A separate instance of the ClientUserSettings.config file is maintained for each client user. The default location for this file is C:\Users\<username>\AppData\Roaming\Microsoft\Microsoft Dynamics NAV\90, where <username> is the name of the user. By default, this folder and file are hidden. Change your folder options in Windows Explorer to view hidden files before you modify the ClientUserSettings.config file.

    Caution
    To ensure that your edits to ClientUserSettings.config are saved, first open Notepad as an Administrator and then, in Notepad, open the settings file. To open Notepad as an Administrator, from the Start menu, right-click Notepad, and then choose Run as Administrator.

  2. In ClientUserSettings.config, modify the following settings.

    Setting Value

    ClientServicesCredentialType

    "AccessControlService"

    ACSUri

    Use the URI for your relying party application from the Application Integration section of the Access Control configuration. For more information, see How to: Configure a Deployment for ACS.

  3. After updating the values, save ClientUserSettings.config.

See Also

Concepts

Configure Microsoft Dynamics NAV Components for ACS


How to: Configure the Microsoft Dynamics NAV Web Client for ACS

You configure the Microsoft Dynamics NAV Web client for Access Control Service (ACS) by editing the web.config file. The web.config file is an .xml file that you can edit with a text editor, such as Notepad. By default, the web.config file is located in the C:\Program Files\Microsoft Dynamics NAV\90\Web Client\ folder.

Before you begin this procedure, you must perform the steps to configure your deployment for ACS. For more information, see Authenticating Users with Microsoft Azure Access Control Service.

To configure the Microsoft Dynamics NAV Web client for ACS

  1. Edit the web server configuration file (web.config) for each instance of the Microsoft Dynamics NAV Web Server components that will be supporting users for ACS authentication.

    A separate instance of the web.config file is maintained for each server instance. The default location for this file is C:\Program Files\Microsoft Dynamics NAV\90\WebClient\.

    Caution
    To ensure that your edits to web.config are saved, first open Notepad as an Administrator and then, in Notepad, open the settings file. To open Notepad as an Administrator, from the Start menu, right-click Notepad, and then choose Run as Administrator.

  2. In the web.config file, modify the following settings.

    Setting Value

    ClientServicesCredentialType

    "AccessControlService"

    ACSUri

    Use the URI for your relying party application from the Application Integration section of the Access Control configuration. For more information, see How to: Configure a Deployment for ACS.

  3. After updating the values, save ClientUserSettings.config.

See Also

Concepts

Configure Microsoft Dynamics NAV Components for ACS


Prepare Users for First ACS Login

After you have completed all of the steps needed to use Access Control service (ACS) to authenticate users, you can set up new users to use ACS, or you can modify existing users to use ACS. You must send the User Name and Authentication Key values to the users and instruct them to submit these values when they log on to a Microsoft Dynamics NAV client, either Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client.

For more information, see How to: Create Microsoft Dynamics NAV Users.

When users first access the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client, they are asked to log on. When they sign in, they must provide the user name and authentication key that you sent them. The user name and authentication key are validated by the one of the identity providers that you specified in the Microsoft Azure management portal. If the user is already signed in, or if the user has previously chosen the Keep me signed in field in the browser, the sign-in page does not appear.

When a user has been authenticated by the ACS identity provider, the user's ACS identity is tied to the Microsoft Dynamics NAV user. The next time the user logs on, Microsoft Dynamics NAV will not request the authentication key because the user account is recognized as a Microsoft Dynamics NAV user.

When the Administrator opens the User page and edits the User card for a user who has successfully logged on using ACS authentication, the ACS Access Status value will change to Enabled.

See Also

Tasks

How to: Create Microsoft Dynamics NAV Users

Concepts

Authenticating Users with Microsoft Azure Access Control Service
Configure Microsoft Dynamics NAV Components for ACS


Authenticating Users with Azure Active Directory

Azure Active Directory (Azure AD) is a cloud service that provides identity and access capabilities, such as for applications on Microsoft Azure, Microsoft Office 365, and for applications that install on-premises. If the Microsoft Dynamics NAV Server instance is configured to use the AccessControlService credential type, you can associate the Microsoft Dynamics NAV user accounts with Azure AD accounts that users use to access the Microsoft Dynamics NAV Web client, Microsoft Dynamics NAV Windows client, Office 365, and SharePoint.

For example, your users access a website, such as a SharePoint site. From there, they have single sign-on access to Microsoft Dynamics NAV because you have configured Microsoft Dynamics NAV for Azure AD.

Azure AD and Microsoft Dynamics NAV

You can use the Azure AD service to associate your existing Microsoft account with your Microsoft Dynamics NAV user account and achieve single sign-on between the Microsoft Dynamics NAV Web client and Office 365. Also, if you use Microsoft Dynamics NAV in an app for SharePoint, you can use Azure AD to achieve single sign-on between the Microsoft Dynamics NAV Web client and SharePoint. You can still host the Microsoft Dynamics NAV Server instance and Microsoft Dynamics NAV Web Server components on-premises. You do not have to deploy Microsoft Dynamics NAV on Azure to use Azure AD for user authentication.

Creating an Azure AD Tenant

If you have an Office 365 subscription that is based on a domain such as solutions.onmicrosoft.com, you are already using Azure AD because the user accounts are based on Azure AD. Then, if you add the email addresses for those user accounts to the user accounts in Microsoft Dynamics NAV, the users experience seamless integration between your SharePoint site and the Microsoft Dynamics NAV Web client.

If you want to sign up for an Office 365 plan, you can use a plan such as Office 365 Enterprise E1 as your test site, or sign up for a trial developer plan. A trial plan includes an administrative account which you will use to access the Azure management portal. For example, if your Office 365 site is Solutions.onmicrosoft.com, your administrative account can be admin@solutions.onmicrosoft.com. For more information, see Select an Office 365 plan for business.

Alternatively, you can sign up for an Azure subscription that is not associated with an Office 365 subscription. You can sign up in the Azure management portal at http://manage.windowsazure.com. Then, you can configure an Active Directory, which creates an Azure AD tenant. For more information, see Administering your Azure AD tenant.

When you create a directory in the Azure management portal, you must specify a domain name that identifies your Azure AD tenant, such as solutions.onmicrosoft.com. You will use the domain name when you add users to your Azure AD.

When you have created the Azure AD tenant, you must add users. For more information, see User account management.

Configuring Microsoft Dynamics NAV Server for Azure AD

The Microsoft Dynamics NAV Server instances that must support Azure AD must be configured to use AccessControlService as the credential type. The AccessControlService credential type for the Microsoft Dynamics NAV Server instance includes support for Azure AD so that you can achieve single sign-on between the SharePoint site and Microsoft Dynamics NAV.

You must also specify the location of the federation metadata. The federation metadata is used to establish a trust relationship between Microsoft Dynamics NAV and Azure AD. You must specify the federation metadata document URL that you retrieved from the Azure AD overview page in the configuration settings for the Microsoft Dynamics NAV Server instances. The federation metadata location is part of the client services section of the Microsoft Dynamics NAV Server configuration. For example, in the Microsoft Dynamics NAV Server Administration tool, on the Client Services tab, the Federation Metadata Location field specifies the location, such as https://login.windows.net/Solutions.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml.

To configure SOAP and OData web services for Azure AD authentication, in the Microsoft Dynamics NAV Server configuration, you must specify the App ID URI that is registered for Microsoft Dynamics NAV in the Azure AD. The App ID URI is typically the same as the wtrealm parameter value of the ACSUri setting in the configuration files for the Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Windows client.

You can configure the Microsoft Dynamics NAV Server instances in the Microsoft Dynamics NAV Server Administration tool and by using Windows PowerShell cmdlets. For more information, see Configuring Microsoft Dynamics NAV Server.

Configuring Microsoft Dynamics NAV Web Server components for Azure AD

The Microsoft Dynamics NAV Web Server components that must support Azure AD must also be configured to use AccessControlService as the credential type.

Also, you must specify an ACSUri for Azure AD authentication. The ACSUri specifies the authentication page for your Azure AD tenant, such as the following: https://login.windows.net/Solutions.onmicrosoft.com/wsfed?wa=wsignin1.0%26wtrealm=https%3a%2f%2fSolutions.onmicrosoft.com%2fNAV, where Solutions.onmicrosoft.com is the domain of your Azure AD tenant, and wtrealm=https%3a%2f%2fSolutions.onmicrosoft.com is the App ID URI.

Configuring Microsoft Dynamics NAV Windows client for Azure AD

The Microsoft Dynamics NAV Windows client must also be configured to use AccessControlService as the credential type in order to support Azure AD. The ACSUri for Azure AD authentication should have the following format https://login.windows.net/<tenant>/wsfed?wa=wsignin1.0%26wtrealm=<realm>%26wreply=<reply>. The <reply> parameter in the URL must be equal to the <App URL>, for example, https://www.solutions.onmicrosoft.com/DynamicsNAV/WebClient. For a list of parameters, see the section Adding Microsoft Dynamics NAV to your Azure AD Tenant later in this topic.

Associating the Azure AD Accounts with the Microsoft Dynamics NAV User Accounts

Each user in your Azure AD tenant that will access Microsoft Dynamics NAV must be set up in Microsoft Dynamics NAV. For example, create the users with Windows authentication or with user name/password authentication, depending on your deployment scenario. But you must also specify an authentication email address on the Office 365 Authentication FastTab in the User Card window. The authentication email address is the email account for that user in your Azure AD tenant. When you combine this with the relevant configuration of the Microsoft Dynamics NAV Server instance, users achieve single sign-on when they access Microsoft Dynamics NAV Web client from the SharePoint site, for example. For more information, see How to: Create Microsoft Dynamics NAV Users.

Important
The single sign-on means that users are still signed in to Azure AD when they sign out from Microsoft Dynamics NAV, unless they close all browser windows. However, if a user selected the Keep me signed in field when they signed in, they are still signed in when they close the browser window. To fully sign out from Azure AD, the user must sign out from each application that uses Azure AD, including Microsoft Dynamics NAV and SharePoint.

We recommend that you provide guidance to your users for signing out of their account when they’re done, so that you can keep your Microsoft Dynamics NAV deployment more secure.

Adding Microsoft Dynamics NAV to your Azure AD Tenant

You must register your Microsoft Dynamics NAV solution as an application in Azure AD tenant. Then, you can choose to make it available to other Azure AD tenants.

When you access your Azure AD tenant in the Azure management portal at http://manage.windowsazure.com, in the Applications view, you can add an application. When you add an application to an Azure AD tenant, you must specify the following information in the Add Application wizard:

Wizard page Field Description

1

Name

The name of your application as it will display to your users, such as Financial App by Solutions.

1

Type

Choose Web application and/or web app.

2

App URL

The URI for signing in to your Microsoft Dynamics NAV Web Server components, such as https://www.solutions.com/DynamicsNAV/WebClient/.

2

App ID URI

The URI to a domain in your Azure AD tenant, such as https://solutions.onmicrosoft.com/Financials.

Important
The App ID URI must be unique within the Azure AD tenant. However, if you want to share your Microsoft Dynamics NAV solution with other Azure AD tenants, the App ID URI must be unique in Azure AD.

This URI is appended to the ACSUri in the configuration settings for Microsoft Dynamics NAV Server and Microsoft Dynamics NAV Web Server components. Additionally, in the Microsoft Dynamics NAV Server configuration, it must be specified in the Azure Active Directory App ID URI setting. For more information, see Authenticating Users with Azure Active Directory.

3

Directory Access

Choose Single Sign-On.

Your Microsoft Dynamics NAV solution is now registered in your Azure AD tenant. To enable single sign-on with Azure AD, you must copy the App ID URI and the federation metadata document URL to a document of your choice for future reference. Both values are available in the overview page for the application in Azure management portal, and you will use them to configure your Microsoft Dynamics NAV Server instances.

Next, you must configure the application to be externally available. Also, you can change the logo to reflect the functionality of the application. From the overview page for Microsoft Dynamics NAV as an application, you can change configuration settings by choosing Configure. Then, save your changes.

Making Microsoft Dynamics NAV Available to Azure AD Tenants

In the overview page for the application, the URL for Granting Access field contains a URL that you can send to users in other Azure AD tenants. Then, when they choose the link, a page displays where they must agree to trust the application. If they accept, the app is added to their SharePoint site.

See Also

Integrating with Office 365 and SharePoint Online

Tasks

How to: Create Microsoft Dynamics NAV Users
How to: Sign Up for a Microsoft Account
How to: Sign Up for a Microsoft Azure Subscription
How to: Set up Microsoft Dynamics NAV for Single Sign-on With Office 365 using Windows PowerShell

Concepts

Users and Credential Types


How to: Set up Microsoft Dynamics NAV for Single Sign-on With Office 365 using Windows PowerShell

Microsoft Dynamics NAV supports federated user authentication with Microsoft Azure Active Directory (Azure AD). This is the Identity Provider service that is used by Office 365. Every time a new Office 365 subscription is provisioned, the Azure AD tenant for this subscription is also created. Thus, when Microsoft Dynamics NAV is configured for federated authentication with an Azure AD tenant, a Single Sign-on (SSO) user experience is achieved between Microsoft Dynamics NAV and the Office 365 Web Applications or/and any other applications which use the Single Sign-on capability provided by the Azure AD tenant.

The Set-NavSingleSignOnWithOffice365 cmdlet also supports enabling Office 365 account authentication both for Microsoft Dynamics NAV Web client and for Microsoft Dynamics NAV Windows client. Office 365 authentication is described in this topic for both clients.

The Set-NavSingleSignOnWithOffice365 cmdlet can be used to perform the configuration task by automating all the steps of this process. The cmdlet performs the following operations:

  • It validates that both your Microsoft Dynamics NAV Server and Microsoft Dynamics NAV Web Server components are ready for this change.

  • It validates your Office 365 credentials.

  • Once the validation is over, the cmdlet starts the configuration:

    • It links your Microsoft Dynamics NAV user account to your Office 365 provided account by providing your Office 365 email address as the AuthenticationEmail for the provided Microsoft Dynamics NAV user account.

    • It configures the Microsoft Dynamics NAV Server by changing the values of the following configuration settings: ClientServicesFederationMetadataLocation, ClientServicesCredentialType, and ServicesCertificateThumbprint.

    • It configures the Microsoft Dynamics NAV Web Server components by changing the values for the following configuration settings: ClientServicesCredentialType, ACSUri, and DnsIdentity.

    • It configures the Azure AD tenant by creating a Service Principal that represents the Microsoft Dynamics NAV Web Server components.

If the configuration sub steps fail, the cmdlet reverts all of the changes in the sub steps made to the Microsoft Dynamics NAV Server and Microsoft Dynamics NAV Web Server components.

To follow this how-to, you will need:

  • Microsoft Dynamics NAV with a user account. For more information, see How to: Create Microsoft Dynamics NAV Users

  • Microsoft Dynamics NAV Server

  • Microsoft Dynamics NAV Web Server components

  • An Office365 subscription

    If you want to sign up for an Office 365 plan, you can use a plan such as Office 365 Enterprise E1 as your test site, or sign up for a trial developer plan. A trial plan includes an administrative account which you will use to access the Azure management portal. For example, if your Office 365 site is Solutions.onmicrosoft.com, your administrative account can be admin@solutions.onmicrosoft.com. For more information, see Select an Office 365 plan for business.

  • Azure Active Directory Tenant Management Components

    The cmdlet relies on the presence of the following components on the system:

    • Microsoft Online Services Sign-In Assistant for IT Professionals

    • Microsoft Azure Active Directory Module for Windows PowerShell

    You can download and install these components from the links provided earlier in this section. If you have to decide between 32-bit and 64-bit versions of components, download the version that matches the Windows Operating System type.

  • Security Certificate Used to Secure the Server - Web Server Communication Channel

    Setting up user authentication types other than Windows for the Microsoft Dynamics NAV Development Environment requires securing the communication between the server and the client. This can be done by using a security certificate. The Set-NavSingleSignOnWithOffice365 cmdlet assumes that you have already imported the security certificate in your certificate store. You can use a security certificate issued by a trusted certification authority. For more information, How to: Implement Security Certificates in a Production Environment. You can also use a self-signed certificate. For more information, see Walkthrough: Implementing Security Certificates in a Test Environment. We do not recommend the latter approach in a production environment; however, it is an alternative to consider when testing your environment.

To Import the NAVOffice365Administration Module

  1. Open Windows PowerShell as administrator, by right-clicking the program and selecting Run as administrator.

  2. Navigate to your Microsoft Dynamics NAV DVD, and then to the WindowsPowerShellScripts\NAVOffice365Administration folder.

  3. Run the following cmdlet in order to import the NAVOffice365Administration PowerShell module: Import-Module .\NAVOffice365Administration.psm1.

When you have imported the NAVOffice365Administration module, you can now run the Set-NavSingleSignOnWithOffice365 cmdlet on the computer that hosts the Microsoft Dynamics NAV components with the relevant parameters set.

To Automate the Single Sign-on Configuration in a One-Computer Microsoft Dynamics NAV Environment

  1. In Windows PowerShell, at the prompt, enter Set-NavSingleSignOnWithOffice365 -NavServerInstance “ServerInstanceName” -NavWebServerInstanceName “WebServerInstanceName” -NavUser “YourNavUser” -AuthenticationEmail “YourOffice365Email” -NavServerCertificateThumbprint “SecurityCertificateThumbprint”. See the table below for a description of parameters.

    Parameter Name Description

    ServerInstanceName

    Specifies the name of your Microsoft Dynamics NAV Server instance. To find the names for the Microsoft Dynamics NAV Server instances, run the Get-NAVServerInstance cmdlet

    WebServerInstanceName

    Specifies the name of your Microsoft Dynamics NAV Server instance. To find the names for the Microsoft Dynamics NAV Web client instances running in your IIS, run the Get-NAVWebServerInstance cmdlet.

    YourNavUser

    Specifies the name of your Microsoft Dynamics NAV user account. YourNavUser links the Microsoft Dynamics NAV user account to your Office 365 account by providing your Office 365 email address as the AuthenticationEmail for the provided Microsoft Dynamics NAV user account. This parameter is optional.

    YourOffice365Email

    Specifies the email address of your Office 365 user account. The syntax is username@o365tenant.onmicrosoft.com. This parameter is optional.

    Important
    This user must have administrative permissions, such as the Global Administrator role. If you create a custom administrator role for this account, the account must have permission to create service principals in Azure. For more information, see Assigning admin roles.

    SecurityCertificateThumbprint

    Specifies the thumbprint for the security certificate that was used for securing the client-server communication channel. Get the list of thumbprints for your certificates by issuing this Windows PowerShell command: Get-ChildItem -Path "Cert:\LocalMachine\My"

    Note
    You can avoid providing this parameter if you already have your Microsoft Dynamics NAV Server configured to use a security certificate. This applies to Microsoft Dynamics NAV installations in the Azure environment, and other environments where any credential type other than Windows is active and functional.

  2. When the Set-NavSingleSignOnWithOffice365 cmdlet is run, a dialog box will open, requesting your Office 365 account user name and password.

Automating the Single Sign-on Configuration in a Multi-Computer Microsoft Dynamics NAV Environment

This configuration type assumes that your Microsoft Dynamics NAV Server and Microsoft Dynamics NAV Web Server components are on different computers. This means that you have to run the Set-NavSingleSignOnWithOffice365 cmdlet on each of these computers separately with a different parameter set in order to correctly configure your Microsoft Dynamics NAV Web client for single sign-on with Office 365.

To automate single sign-on configuration in a multi-computer Microsoft Dynamics NAV environment

  1. Run the Set-NavSingleSignOnWithOffice365 cmdlet on the Microsoft Dynamics NAV Server computer.

  2. To configure your Microsoft Dynamics NAV Server for single sign-on, you have to run the cmdlet with the following parameter set:

    Copy Code
    Set-NavSingleSignOnWithOffice365 -NavServerInstance “ServerInstanceName” -NavUser “YourNavUser” -NavServerCertificateThumbprint “SecurityCertificateThumbprint” -SkipWebServerConfiguration -SkipWinClientConfiguration
    Note
    The SkipWebServerConfiguration switch specifies that the Microsoft Dynamics NAV Web client configuration should not be generated.

  3. Run the Set-NavSingleSignOnWithOffice365 cmdlet on the Microsoft Dynamics NAV Web Server components computer

  4. To configure your Microsoft Dynamics NAV Web Server components for single sign-on, you have to run the cmdlet with the following parameter set:

    Copy Code
    Set-NavSingleSignOnWithOffice365 -NavWebServerInstanceName “WebServerInstanceName” -AuthenticationEmail “YourOffice365Email” -SkipNavServerConfiguration -SkipWinClientConfiguration
    Note
    The SkipNavServerConfiguration switch specifies that the Microsoft Dynamics NAV Web client configuration should not be generated.

To Enable Office 365 Account Authentication for Microsoft Dynamics NAV Windows client

The Set-NavSingleSignOnWithOffice365 can be also used to perform most of the configuration steps necessary for enabling user authentication with Office 365 accounts for Microsoft Dynamics NAV Windows client. The example in this section only configures the Microsoft Dynamics NAV Service and the Azure AD tenant in order to enable Office 365 authentication for the Microsoft Dynamics NAV Windows client.

Copy Code
$result = Set-NavSingleSignOnWithOffice365 -AuthenticationEmail “YourOffice365Email” -SkipNavWebServerConfiguration -SkipNavServerConfiguration
Note
The SkipNavWebServerConfiguration switch specifies that the Microsoft Dynamics NAV Server should not be configured. The SkipNavServerConfiguration switch specifies that the Microsoft Dynamics NAV Web Server components should not be configured.

Because this cmdlet is usually run on the computer that is hosting the Microsoft Dynamics NAV service, the value returned by the cmdlet, which in this case is the sign-in page, must be copied and pasted in the ACSUri setting from the ClientUserSettings.config file.

Important
When setting ACSUri in the ClientUserSettings.config file, make sure that the ClientServicesCredentialType is set to AccessControlService.

Adjusting the Client User Settings

To make sure that the account authentication for the Microsoft Dynamics NAV Windows client works correctly, the ClientUserSettings.Config file needs two settings to be of a specific type. The default location for the ClientUserSettings.Config file is C:\Users\<username>\AppData\Roaming\Microsoft\Microsoft Dynamics NAV\90. For more information, see Configuring the Windows Client.

The ClientServicesCredentialType must be set to AccessControlService.

Depending on the Security Certificate that you are using, you may also need to change the DnsIdentity setting. For more information, see How to: Implement Security Certificates in a Production Environment.

AcsUri should have the following format https://login.windows.net/<tenant>/wsfed?wa=wsignin1.0%26wtrealm=<realm>%26wreply=<reply>.

Note
The difference between configuring the Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Windows client for single sign-on with Office 365 is the addition of the wreply parameter in the URL. The Microsoft Dynamics NAV Web client automatically sets the wreply parameter to the web site login page, whereas the Microsoft Dynamics NAV Windows client requires that it is preconfigured.

Tip
Use the Set-NavSingleSignOnWithOffice365 PowerShell script to get the AcsUri for Azure AD by running the following statement:

Set-NavSingleSignOnWithOffice365 -SkipNavServerConfiguration -SkipWebServerConfiguration

To change the client user settings in a ClickOnce environment, see Deploying Microsoft Dynamics NAV Using ClickOnce.

See Also

Tasks

Troubleshooting: Running the Cmdlet Fails Because the Microosft Dynamics NAV Server Fails to Start/Restart
Troubleshooting: Running the Cmdlet in a Multitenant Microsoft Dynamics NAV Environment
Troubleshooting: Avoiding the Office 365 Credentials Dialog box
Troubleshooting: Running the Cmdlet for a Microsoft Dynamics NAV Web Server Hosted in Complex Network Topology

Concepts

Authenticating Users with Azure Active Directory


Troubleshooting: Running the Cmdlet Fails Because the Microosft Dynamics NAV Server Fails to Start/Restart

You can find more information about the Microsoft Dynamics NAV Server failure reason in the event log. The error most likely occurs because of the impossibility of the Microsoft Dynamics NAV Server to correctly configure the ACL for the ports that are used by the server’s communication endpoints. In some situations, when there are URLACL entries for the same ports but reserved by other services, including other Microsoft Dynamics NAV Servers, the removal procedure fails because of insufficient permissions. The user account running the Microsoft Dynamics NAV Server has to have administrative permissions for the modification of the URLACL to succeed. To fix the issue, you can try one of the following:

  • Remove the URL ACL entries manually. For more information, see Walkthrough: Configuring Web Services to Use SSL (SOAP and OData).

  • Set the Microsoft Dynamics NAV Server to run as Administrator account on your computer.

See Also

Tasks

How to: Set up Microsoft Dynamics NAV for Single Sign-on With Office 365 using Windows PowerShell

Concepts

Authenticating Users with Azure Active Directory


Troubleshooting: Running the Cmdlet in a Multitenant Microsoft Dynamics NAV Environment

Only one tenant can be automatically configured at a time, so the Microsoft Dynamics NAV tenant name needs to be provided as the NavTenant parameter to the Set-NavSingleSignOnWithOffice365 cmdlet.

See Also

Tasks

How to: Set up Microsoft Dynamics NAV for Single Sign-on With Office 365 using Windows PowerShell

Concepts

Authenticating Users with Azure Active Directory


Troubleshooting: Avoiding the Office 365 Credentials Dialog box

You can fully automate the script, and thereby avoid the Office 365 credentials dialog box by providing the credentials as parameters.Use the AuthenticationEmail parameter to specify the Office 365 account email and the AuthenticationEmailPassword parameter to specify the Office 365 account password. Note, that the latter parameter should be a SecureString.

See Also

Tasks

How to: Set up Microsoft Dynamics NAV for Single Sign-on With Office 365 using Windows PowerShell

Concepts

Authenticating Users with Azure Active Directory


Troubleshooting: Running the Cmdlet for a Microsoft Dynamics NAV Web Server Hosted in Complex Network Topology

Setting the trust relationship between the Microsoft Dynamics NAV Web client and Microsoft Azure Active Directory requires specifying a remote endpoint for the Microsoft Dynamics NAV Web client in the Azure AD Service Principal that is created for this web application. If the Microsoft Dynamics NAV Web server runs behind a DNS or another network component that changes or rewrites the web client’s address, the Set-NavSingleSignOnWithOffice365 cmdlet is not able to compute this address, since it only runs on the local computer. To fix this issue, you can provide the cmdlet with the address as seen remotely for your Microsoft Dynamics NAV Web client. The parameter you need to pass this address to is NavWebAddress.

See Also

Tasks

How to: Set up Microsoft Dynamics NAV for Single Sign-on With Office 365 using Windows PowerShell

Concepts

Authenticating Users with Azure Active Directory


Configuring Authentication Between the Microsoft Dynamics NAV Server and Database

For a Microsoft Dynamics NAV Server instance to connect to and access a Microsoft Dynamics NAV database in SQL Server, the Microsoft Dynamics NAV Server instance must be authenticated by the database. As in SQL Server, Microsoft Dynamics NAV supports two authentication modes: Windows Authentication and SQL Server Authentication. When you set up Microsoft Dynamics NAV, you must ensure that database authentication is configured correctly on both the Microsoft Dynamics NAV Server instance and Microsoft Dynamics NAV database, otherwise the Microsoft Dynamics NAV Server instance will not be able to connect to the Microsoft Dynamics NAV database in SQL Server. By default, Windows Authentication is configured on the Microsoft Dynamics NAV Server instance and database.

For more information about SQL Server authentication, see How to: Configure SQL Server Authentication in Microsoft Dynamics NAV.

See Also

Concepts

Configuring Authentication


How to: Configure SQL Server Authentication in Microsoft Dynamics NAV

This topic describes how to configure SQL Server Authentication between the Microsoft Dynamics NAV Server instance and a Microsoft Dynamics NAV database. You perform the configuration in two places: on the databases in SQL Server and on the Microsoft Dynamics NAV Server instance. The procedure is different when the Microsoft Dynamics NAV Server instance is configured as a multitenant server instance than when it is not a multitenant server instance. To configure SQL Server authentication, complete the following procedures:

  1. Set Up an Encryption Key

  2. Configure SQL Authentication on the Database

  3. Configure SQL Server Authentication on Microsoft NAV Server Instance (Non-Multitenant) or Configure SQL Server Authentication on Microsoft NAV Server Instance in a Multitenant Deployment

Set Up an Encryption Key

When using SQL Server authentication, Microsoft Dynamics NAV requires an encryption key to encrypt the credentials (user name and password) that the Microsoft Dynamics NAV Server instance uses to connect to the Microsoft Dynamics NAV database in SQL Server. The encryption key must be installed on the computer where the Microsoft Dynamics NAV Server is installed and also in the database in SQL Server. In a multitenant deployment, the encryption key must be installed in the application database.

To set up an encryption key, you can use one of the following methods:

  • You can create and import your own encryption key by using Microsoft Dynamics NAV 2016 Administration Shell cmdlets, as described in the following procedure.

  • If you are configuring SQL Server authentication on a Microsoft Dynamics NAV Server instance for the first time, you can use the Microsoft Dynamics NAV Server Administration tool which can automatically create and install a system encryption key. If you decide to use this method, no action is required.

To create and import encryption key

  1. In the Microsoft Dynamics NAV 2016 Administration Shell, run the New-NAVEncryptionkey cmdlet.

    This creates a file that contains an encryption key. If you already have an encryption key file, you can skip this step.

  2. Run the Import-NAVEncryptionkey cmdlet to install the encryption key on the Microsoft Dynamics NAV Server instance and database.

For more information, see Managing Encryption Keys for SQL Server Authentication.

Configure SQL Authentication on the Database

This section describes how to configure a Microsoft Dynamics NAV database to use SQL Server Authentication with a Microsoft Dynamics NAV Server instance. You can complete the steps in this procedure by using SQL Server Management Studio or Transact-SQL.

Important
In a deployment where the Microsoft Dynamics NAV Server instance is configured as a multitenant server instance, you must complete the following procedure on the application database and tenant database.

To configure SQL Server Authentication on the database in SQL Server

  1. Configure the SQL Server instance (Database Engine) that hosts the Microsoft Dynamics NAV database to use SQL Server Authentication.

    To use SQL Server authentication, you configure the database instance to mixed authentication mode (SQL Server and Windows Authentication). For more information, see Change Server Authentication Mode.

  2. In the SQL Server instance, create a login that uses SQL Server authentication.

    For more information, see Create a Login.

  3. Map the login to a user in the Microsoft Dynamics NAV database, and add the user to the db_owner role of the Microsoft Dynamics NAV database.

    For more information, see Create a Database User.

Configure SQL Server Authentication on Microsoft NAV Server Instance (Non-Multitenant)

You configure the Microsoft Dynamics NAV Server instance with the login credentials (user name and password) of the user account in the Microsoft Dynamics NAV database in SQL Server that you want to use for authentication. You can do this using the Microsoft Dynamics NAV Server Administration tool or Microsoft Dynamics NAV 2016 Administration Shell.

To configure SQL Authentication on Microsoft NAV Server Instance using Microsoft Dynamics NAV Server Administration tool

  1. Open the Microsoft Dynamics NAV Server Administration tool.

    Choose Start, and in the Search programs and files box, enter Microsoft Dynamics NAV Administration, and then choose the related link.

  2. In the console tree, which is the left pane, expand the node for the computer that contains the Microsoft Dynamics NAV Server instance, and then select the Microsoft Dynamics NAV Server instance.

  3. In the Actions pane, choose Database Credentials.

  4. On the Database Credentials page, choose the Edit button.

  5. Set the Database Authentication Type to SQL Authentication.

  6. In the Database User Name field, type the login name for the database user that you want to use to access the Microsoft Dynamics NAV database in SQL Server.

  7. In the Password field, type the login password for the database user that you want to use to access the Microsoft Dynamics NAV database in SQL Server.

  8. Choose the Save button, and then on the Enable Encryption on SQL Server Connections dialog box, choose the OK button.

    Encryption keys are used to help secure the login credentials over the connection between the Microsoft Dynamics NAV Server instance and the Microsoft Dynamics NAV database in SQL Server.

  9. On the Information dialog box about encryption, choose the OK button.

    This dialog box is to inform you to enable encryption on SQL Server connections, which is disabled by default.

  10. If you want to enable encryption on SQL Server connections, in the Action pane, choose Configuration, and then choose the Edit button. In the Database tab, select Enable Encryption on SQL Connections, choose the Save button, and then the OK button.

  11. Restart the server instance. For more information, see How to: Start, Stop, Restart, or Remove a Microsoft Dynamics NAV Server Instance.

To configure SQL Authentication on Microsoft NAV Server Instance using Microsoft Dynamics NAV 2016 Administration Shell

  • If you are modifying an existing Microsoft Dynamics NAV Server instance, run the Set-NAVServerConfiguration cmdlet.

    Use the DatabaseCredentials parameter to provide the login credentials of the database user that you want to use to access the application database.

  • If you are creating a new Microsoft Dynamics NAV Server instance, run the New-NAVServerInstance cmdlet.

    Use the DatabaseCredentials parameter to provide the login credentials of the database user that you want to use to access the application database.

Configure SQL Server Authentication on Microsoft NAV Server Instance in a Multitenant Deployment

This section describes how to configure a Microsoft Dynamics NAV database to use SQL Server Authentication with a Microsoft Dynamics NAV Server instance. You can complete the steps in this procedure by using SQL Server Management Studio or Transact-SQL.

To configure a SQL Server Authentication on a Microsoft Dynamics NAV Server instance, you set up the server instance with the login credentials (user name and password) for the user accounts for the application and tenant databases in SQL Server. You can do this using the Microsoft Dynamics NAV Server Administration tool or Microsoft Dynamics NAV 2016 Administration Shell.

To configure SQL Authentication on Microsoft NAV Server Instance using Microsoft Dynamics NAV Server Administration tool

  1. Open the Microsoft Dynamics NAV Server Administration tool.

    Choose Start, and in the Search programs and files box, enter Microsoft Dynamics NAV Administration, and then choose the related link.

  2. In the console tree, which is the left pane, expand the node for the computer that contains the Microsoft Dynamics NAV Server instance, and then select the Microsoft Dynamics NAV Server instance.

  3. Configure SQL Server Authentication with the application database as follows:

    1. In the Actions pane, choose Database Credentials.

    2. On the Database Credentials page, choose the Edit button.

    3. Set the Database Authentication Mode to SQL Server Authentication.

    4. In the Database User Name field, type the login name for the database user that you want to use to access the Microsoft Dynamics NAV application database in SQL Server.

    5. In the Password field, type the login password for the database user that you want to use to access the Microsoft Dynamics NAV database in SQL Server.

    6. Choose the Save button, and then on the Enable Encryption on SQL Server Connections dialog box, choose the OK button.

      Encryption keys are used to help secure the login credentials over the connection between the Microsoft Dynamics NAV Server instance and the Microsoft Dynamics NAV database in SQL Server.

    7. On the Information dialog box about encryption, choose the OK button.

      This dialog box is to inform you to enable encryption on SQL Server connections, which is disabled by default.

    8. If you want to enable encryption on SQL Server connections, in the Action pane, choose Configuration, and then choose the Edit button. In the Database tab, select Enable Encryption on SQL Connections, choose the Save button, and then the OK button.

  4. To configure SQL Server Authentication with the tenant database, mount the tenant to the Microsoft Dynamics NAV Server instance and specify the login credentials (user name and password) for the database user that you want to use to access the Microsoft Dynamics NAV tenant database in SQL Server.

    If the tenant is already mounted to the Microsoft Dynamics NAV Server instance, you must dismount the tenant, and mount it again.

    For more information see How to: Mount or Dismount a Tenant on a Microsoft Dynamics Server Instance.

  5. Restart the server instance. For more information, see How to: Start, Stop, Restart, or Remove a Microsoft Dynamics NAV Server Instance.

To configure SQL Authentication on Microsoft NAV Server Instance using Microsoft Dynamics NAV 2016 Administration Shell

  1. Configure SQL Server Authentication with the application database as follows:

    • If you are modifying an existing Microsoft Dynamics NAV Server instance, run the Set-NAVServerConfiguration cmdlet.

      Use the DatabaseCredentials parameter to provide the login credentials of the database user that you want to use to access the application database.

    • If you are creating a new Microsoft Dynamics NAV Server instance, run the New-NAVServerInstance cmdlet.

      Use the DatabaseCredentials parameter to provide the login credentials of the database user that you want to use to access the application database.

  2. To configure SQL Authentication with the tenant database, run the Mount-NAVTenant cmdlet.

    Use the DatabaseCredentials parameter to provide the login credentials of the database user that you want to use to access the tenant database.

See Also

Concepts

Working with PowerShell
Microsoft Dynamics NAV Windows PowerShell Cmdlets
Configuring Authentication Between the Microsoft Dynamics NAV Server and Database


Managing Encryption Keys for SQL Server Authentication

When using SQL Server authentication between the Microsoft Dynamics NAV Server instance and the database in SQL Server, an encryption key is used to encrypt the credentials that the Microsoft Dynamics NAV Server instance uses to log on to the database. The encryption key is stored on the computer running Microsoft Dynamics NAV Server and also registered in the database. There is single encryption key per Microsoft Dynamics NAV Server instance and it must match the encryption key in the database.

On the computer running the Microsoft Dynamics NAV Server instance, the encryption key file has the name DynamicsNAV90.key and is stored in the %systemroot%\ProgramData\Microsoft\Microsoft Dynamics NAV\90\Server\Keys. In the database, the encryption key is registered in the dbo.$ndo$publicencryptionkey table. In a multitenant deployment, the encryption key is registered in the application database.

You can create encryption keys and then import and export the keys to and from databases by using encryption key cmdlets in the Microsoft Dynamics NAV 2016 Administration Shell. These cmdlets are useful when upgrading or transferring a solution from one set of hardware to another, where you might need a copy of the encryption key to use it on another Microsoft Dynamics NAV Server instance.

Note
When you use the Microsoft Dynamics NAV Server Administration tool to set up SQL Server Authentication on a Microsoft Dynamics NAV Server instance for the first time, instead of creating or importing your own encryption key in advance, you can decide to use a system encryption key, which is generated and installed automatically.

Managing Encryption Keys by Using Microsoft Dynamics NAV 2016 Administration Shell

The Microsoft Dynamics NAV 2016 Administration Shell includes the following cmdlets that enable you to manage the encryption key that is used on Microsoft Dynamics NAV Server instances:

Cmdlet | Description
Export-NAVEncryptionKey | Exports an encryption key from a Microsoft Dynamics NAV Server instance to a password protected file.
Import-NAVEncryptionKey | Imports an encryption key from a password protected file to a Microsoft Dynamics NAV Server instance.
New-NAVEncryptionKey | Create an encryption key in a password protected file.

For more information about how to run the cmdlets, see Microsoft Dynamics NAV Windows PowerShell Cmdlets.

Changing the Current Encryption Key

If you want to change an encryption key that is currently used by a Microsoft Dynamics NAV Server instance and database to another encryption key that is contained in an encryption key file, use the Import-NAVEncryptionkey cmdlet. Before you run the Import-NAVEncryptionkey cmdlet, you must delete the encryption key that is stored on the Microsoft Dynamics NAV Server computer.

To change the encryption key that is used by the Microsoft Dynamics NAV Server instance

  1. On the computer that is running the Microsoft Dynamics NAV Server instance, delete the encryption key file for SQL Server authentication.

    The encryption key file has the name DynamicsNAV90.key and is stored in the %systemroot%\ProgramData\Microsoft\Microsoft Dynamics NAV\90\Server\Keys folder.

  2. In the Microsoft Dynamics NAV 2016 Administration Shell, run the Import-NAVEncryptionkey cmdlet with the -Force parameter set.

    Copy Code
    Import-NAVEncryptionKey -ServerInstance [Server Instance] -KeyPath [Encryption key file path] - ApplicationDatabaseServer [Database server instance] -ApplicationDatabaseName [Database name] -Force

See Also

Tasks

How to: Configure SQL Server Authentication in Microsoft Dynamics NAV


Troubleshooting: Microsoft Office Outlook Integration and Synchronization

This topic lists some common problems that can occur when you use the Microsoft Office Outlook Add-in.

Cleaning Up Data and Configuration Information

You may have to test multiple installations and configurations of the Microsoft Dynamics NAV Synchronization Add-in.

To make sure that you are starting from a clean installation, you should delete the following files from your computer before you start a new setup. The following table describes the details.

Product version | Description | File location
Microsoft Dynamics NAV 2009 SP1 | Storage of what has been synchronized and set up in the add-in. | C:\Users\<user name>\AppData\Local\Microsoft Dynamics NAV\OutlookSynch\settings.xml
Microsoft Dynamics NAV 2016 | Storage of what has been synchronized and set up in the add-in. | C:\Users\<user name>\AppData\Roaming\Microsoft Dynamics NAV\OutlookSynch

Treating Uncompleted Tasks that Have Been Deleted

If you attempt to delete a task in Outlook before the task is completed, after you synchronize, you will receive a message noting that there is a conflict, because the Outlook version of the task has been deleted. When you address the conflict and delete it, and synchronize again, the task is added back to the Tasks folder as completed.

To work around this problem, create a task, synchronize the first time, and set the status of the task to Complete. Synchronize again, and then delete the task. Synchronize again.

Using Outlook Links Collection With Outlook 2013

When you are setting up a user and specifying APP and Task entities, you cannot use the Outlook Links collection, which is not supported by Outlook 2013. If you have configured links, when you synchronize, it will fail with the following error:

An error has occurred during the synchronization process. You can find the error details in the DynamicsNAVsync.log file.

To work around this problem, do not configure the APP and TASK entities to use the Links collection.

Verifying Information in the Change Log Setup Window

By default, the change log is activated. However, you may want to verify that the activation is valid. For example, you may have to do this when no Contacts or To-Dos are synchronized when Outlook synchronization runs.

To verify the Change Log Setup setting

  1. In the Search box, enter Change Log Setup, and then choose the related link.

  2. Verify that the Change Log Activated field is selected.

  3. To validate specific Change Log Setup settings, on the Actions tab, in the Setup group, choose Tables.

  4. The default change log setup contains information for the Salesperson/Purchaser, Contact, and To-do tables. You can make additional modifications.

Synchronizing Addresses for Contacts

When you specify a salesperson for a contact and then synchronize the contact with Outlook, information from the contact’s Country/Region Code field in Microsoft Dynamics NAV is missing from the Address field in the Outlook Contact form. When you attempt to modify information, for example, the street address, for the contact’s address in Outlook, and then synchronize that information back to Microsoft Dynamics NAV, you may encounter the following error:.

An Outlook item cannot be synchronized because the Country/Region Code field of the CONT_PERS entity cannot be processed. Try again later and if the problem persists contact your system administrator.

To fix this issue, add the country/region information to the multiline address field in the Outlook Contact form and then proceed with synchronization.

Setting Conditions

Setting conditions for the TASK and APP entities is required. Meetings and tasks need a Meeting Organizer or Task Owner, so you must create a condition.

To configure conditions

  1. In the Search box, enter Outlook Synch. User Setup, and then choose the related link.

  2. Select the line for the APP entity, and then select the Condition field.

  3. In the Outlook Synch. Filters -Condition window, in the Field Name field, select Salesperson Code.

  4. In the Value field, add the code for the salesperson.

  5. Repeat these steps for the TASK entity.

Setting conditions is not required, but you should do it to prevent mass data transfer to a local mailbox or a public folder. In large environments with hundreds of contacts, you may want to set conditions to limit the data that is to be synchronized to every salesperson who has a mailbox that is configured for Outlook synchronization.

If there are no conditions set for the contacts entities, then you may get the following message to view the debug log:

Closing Mapi session "/o=First Organization/ou=First Administrative Group/cn=Recipients/cn=XY" because it exceeded the maximum of 250 objects of type "objtMessage

This is due to a security setting on the Exchange Server. If a large set of data, which is first triggered with 250 objects, is synchronized to Exchange Server, then Exchange Server logs an error in the event log file and does not let you add the data to the mailbox.

To work around this limitation, you can adjust the registry based on the objects that can be found in event ID 9646 in the application event log file on Exchange Server. After you have completed setting conditions, you may have to register the changes in the change log but only if you have made changes to the default configuration in the Outlook Synch. Entities window. The changes are registered in the following order in the change log: CONT_SP, CONT_COMP, CONT_PERS, TASK, and APP entity.

For more information, see the following articles:

  • Knowledge Base article 830836: Event ID 9646 is logged when you try to send many messages in Exchange Server 2003

  • Knowledge Base article 830829: Your Exchange Server 2003 computer may stop responding after a MAPI client opens more than the default value of certain server objects

  • An Exchange 2007 server stops responding to a MAPI client and logs event ID 9646 in the Application log

    Note
    By default, there is no debug log. You must enable it first. For more information, see Knowledge Base article 944237: How to enable the log file mode for the Outlook Synchronization feature in Microsoft Dynamics NAV 5.0 (requires PartnerSource account).

Locating the Error Log Created By the Outlook Synchronization Process

You may receive the following message:

An Error has occurred during the synchronization process. You can find the error details in the log file

The location of this log file depends on the operating system that you are using. You can find the path of the file by looking in the Outlook.exe.config file: c:\Program Files\Microsoft Office\Office<version number>\Outlook.exe.config.

Note
You can modify the Outlook.exe.config file to change the amount of information that is logged in the log file and to show more detailed information. For more information, see Knowledge Base article 944237: How to enable the log file mode for the Outlook Synchronization feature in Microsoft Dynamics NAV 5.0 (requires PartnerSource account).

Synchronizing Large Sets of Data

Synchronizing large amounts of data can cause issues with the connection through NAS Services and web services.

If you are synchronizing with the web services connection, then the maximum size of the web service can be changed. You can configure the maximum permitted size of a web services request in the CustomSettings.config file.

Copy Code
<!--  Maximum permitted size of a web services request, in kilobytes-->
<add key="WebServicesMaxMsgSize" value="512"></add>

You should not regularly synchronize large sets of data, although it may be appropriate to do this during initial setup. Instead, we recommend that you change the web service size back to an appropriate level after you perform a full synchronization.

Setting Up Microsoft Outlook Integration in a Three-Machine Environment

When selecting a company, you may receive a message that resembles one of the following messages:

  • The connection to "" Microsoft Dynamics NAV database failed. The program returned the following error: GetCompaniesList error: The login failed when connecting to SQL Server <DatabaseTier>. connection string: NavSynchronizationUrl=http://<ServiceTier>:7047/DynamicsNAV71/WS/Codeunit/DynamicsNAVsynchOutlook;CompanyName=<CompanyName>; Please verify your synchronization settings. If the problem persists contact your system administrator.

  • The connection to "" Microsoft Dynamics NAV database failed. The program returned the following error: GetCompaniesList error: The request failed with HTTP status 401: Unauthorized. connection string: NavSynchronizationUrl=http://<ServiceTier>:7047/DynamicsNAV70/WS/Codeunit/DynamicsNAVsynchOutlook;CompanyName=<CompanyName>; Please verify your synchronization settings. If the problem persists contact your system administrator.

In the message, <DatabaseTier> is the server name of the SQL Server, <ServiceTier> is the server name of the Microsoft Dynamics NAV Server, and <CompanyName> is the company name.

These errors can occur if Microsoft Dynamics NAV web services are not set up with the correct Service Principal Names (SPN) and delegation information. They can also occur if the web service path is not set correctly in the Connection tab. For more information, see Walkthrough: Installing the Three Tiers on Three Computers. You can also see the NAV 2009 Web Services on a three machine setup blog post in the Microsoft Dynamics NAV Team Blog on MSDN.

Configuring the Outlook Profile in an Environment Other than Microsoft Exchange

When you add and configure a new user Outlook profile in an environment other than Microsoft Exchange and are working with the TASK entity, you must make sure that the name of the Active Directory user (Full name) or name of the Mailbox owner matches the Salesperson as configured on the Salesperson/Purchaser card.

Otherwise, you may receive this message:

The error occurred while setting the Owner property of the item: Task owner can be set to XXX only

Displaying the Microsoft Dynamics NAV Synchronization Toolbar

After you reinstall the Microsoft Office Outlook Add-in, the Microsoft Dynamics NAV Synchronization toolbar items may not appear in Outlook on the Add-ins tab, even though the toolbar is selected in the list of available toolbars from the View menu. This occurs because an earlier version of the add-in is running during reinstallation.

To display the Microsoft Dynamics NAV Synchronization toolbar

  1. In Outlook, on the File tab, choose Options, and then, in the Options dialog, choose Add-Ins.

  2. In the Manage box, verify that COM Add-ins is selected, and then choose Go.

  3. If the Microsoft Dynamics NAV Synchronization Add-in is selected, clear the check box, and then choose the OK button.

  4. In the Manage box, verify that COM Add-ins is selected, and then choose Go.

  5. Select the Microsoft Dynamics NAV Synchronization Add-in check box, and then choose the OK button.

Showing Synchronization

We recommend that you enable the Show Synchronization Progress option in Outlook so that a user knows when synchronization is occurring. This helps a user avoid receiving an error if Outlook is closed when synchronization is occurring.

To set rules for synchronization

  1. In Outlook, on the Microsoft Dynamics NAV Synchronization toolbar, choose Settings.

  2. On the General tab, select the Show synchronization progress and Show synchronization summary check boxes.

Finding Additional Information

For additional information about the set up and configuration of the Microsoft Dynamics Synchronization Add-in, see the Microsoft Dynamics NAV Help. You can search for the "Set Up Outlook Synchronization" topic as a starting point. In addition, see the Outlook Integration Installation & Setup Technical White Paper (requires PartnerSource account). Although this document describes installation for Microsoft Dynamics NAV 5.0, much of the information applies to Microsoft Dynamics NAV 2016. You can also find troubleshooting information on the NAV Developer's Blog on MSDN.

See Also

Walkthrough: Synchronizing Information Between Outlook and Microsoft Dynamics NAV

Tasks

Walkthrough: Setting Up Outlook Synchronization

Other Resources

Installation Options


Adding Languages to Microsoft Dynamics NAV

In Microsoft Dynamics NAV, you can display the user interface (UI) in different languages. Your version of Microsoft Dynamics NAV can include multiple languages by default, and you can add additional languages to an existing deployment.

You can add a language layer by importing a language module, or you can import a multilanguage file that contains newly translated strings.

Translated User Interface Strings

In Microsoft Dynamics NAV, the user interface includes the following types of translatable user interface strings:

  • Captions for application objects, such as pages, tables, reports, option fields, icons, menus, and so on, that are defined in the CaptionML property for an object.

    For more information, see Developing Multilanguage-Enabled Applications.

  • Text messages that are defined in the development environment, such as text constants and error messages that are defined in the C/AL Globals window or the C/AL Locals window.

  • Text messages and strings that are defined in Microsoft Dynamics NAV Server and Microsoft Dynamics NAV Windows client.

If you are a developer or an administrator, you can add languages to the captions for application objects and to the text messages that are defined in the C/AL Globals window or the C/AL Locals window. To add a language to the text messages that are defined in the resource files for Microsoft Dynamics NAV Server and Microsoft Dynamics NAV Windows client, special tools are required.

Language Modules and Translated Text Files

You can install language modules so that you can view text in the user interface in different languages. Once you have installed a language module, you change the language of the user interface in the Microsoft Dynamics NAV Windows client and for users of the Microsoft Dynamics NAV Web client. When you change a language in the UI, you change the language of all text that is displayed in the UI in captions for text boxes, on command buttons, in menus, and so on. For more information, see Language Modules.

Alternatively, you can manage translations by using text files. In the development environment, you can export all strings for the specified objects to a text file, translate the strings in a translation tool of your choice, and then import the new translations. Then, when you compile the updated objects, the new translations are available to users in the Microsoft Dynamics NAV Windows client. For more information, see How to: Add Translated Strings By Importing and Exporting Multilanguage Files.

Language modules and multilanguage text files are the default way of supporting users of your application so that they can switch between Dutch and English, for example.

Translating Multilanguage Files

Captions and other user interface text that you define for objects in the Microsoft Dynamics NAV Development Environment can be exported to a text file. You can then add new translations to the text file and import the new translations in the development environment. You can use a dedicated translation tool, or you can add translations manually using Notepad, Microsoft Excel, and so on.

The exported text files contain an entry for each translatable user interface element for the objects that you selected in the development environment. However, the text file also includes entries that cannot be translated. For example, if you export the strings for table 18, the resulting text file contains hundreds of entries, of which fewer than 170 can be translated. The translatable strings include the captions of for all fields and the error messages that you have defined. The non-translatable strings include names of variables, and so on.

In CRONUS International Ltd. demonstration database, all objects are multilanguage enabled, and they include strings with captions in the 1033 locale, English (US). The locale is specified by a multilanguage property such as P8629, but the ID of the actual property is different for different types of strings. However, the locale for the multilanguage property value always starts with the character A. For example, the English (US) captions are identified by the A1033 locale value for the relevant multilanguage property. You can identify which strings can be translated by opening the file in Microsoft Excel and then filter by the English locale.

If you export strings for objects of different types, the text file lists the strings by object type and then by object ID. For example, if you export strings for table 18, page 21, and report 111, the text file lists strings in the following order:

  1. Table 18

  2. Report 111

  3. Page 21

The format of the exported text files can be difficult to read, because for each type of object, the text file contains different types of strings. Each type of string is identified by a property that starts with the character P followed by an ID. For example, for a table object and the fields on the table, the multilanguage property has the ID 8629. For option values for fields on tables, the multilanguage property has the ID 8632. This means that you can identify the type of string when you translate the strings. However, you should filter out all strings that are not translatable, which makes the remaining strings easier to understand.

The following table illustrates the translatable strings for table 18 in the CRONUS International Ltd. demonstration database.

String | Description
T18-P8629-A1033-L999:Customer | The caption of the table object.
T18-F1-P8629-A1033-L999:No. | The caption of field 1.
T18-F7601-P8629-A1033-L999:Copy Sell-to Addr. to Qte From T18-F7601-P8632-A1033-L999:Company,Person | The caption of field 7601 and the captions of the option values for the field.
T18-Q1001-P26171-A1033-L999:Do you wish to create a contact for %1 %2? | A text constant that defines user interface text.

For more information, see How to: Add Translated Strings By Importing and Exporting Multilanguage Files.

Multilanguage across Conflicting Text Encoding Formats

In most deployments of Microsoft Dynamics NAV, you use the default multilanguage capabilities of Microsoft Dynamics NAV. However, if your users use languages with conflicting text encoding formats, such as Dutch and Chinese, for example, then you must add the translated strings to Microsoft Dynamics NAV in a different way.

To support users with translated strings across conflicting text encoding formats, you must save the translations to a text file in UTF-8 text encoding format. This converts the file to Unicode, which Microsoft Dynamics NAV Development Environment cannot import. Instead, you add the files to a dedicated Translations folder on the Microsoft Dynamics NAV Server computer. The default location of this folder is C:\Program Files\Microsoft Dynamics NAV\90\Service\Translations. When you have more than one service instance, there is a Translations folder for each service instance, such as C:\Program Files\Microsoft Dynamics NAV\90\Service\Instances\MyInstance\Translations. Microsoft Dynamics NAV Server adds any strings in text files that you place in the relevant Translations folder to the metadata for Microsoft Dynamics NAV. As a result, users can switch the language of the user interface between Dutch, English, and Chinese, for example. For more information, see How to: Add Translated Strings for Conflicting Text Encoding Formats.

Important
Microsoft Dynamics NAV Server imports strings from .txt files only. If you save your strings to a file with a different extension, they cannot be imported by Microsoft Dynamics NAV Server.

Also, we recommend that you use .txt files only for those strings that cannot be added by importing multilanguage files into the development environment.

See Also

Tasks

How to: Install Language Modules
How to: Uninstall Language Modules
How to: Add Translated Strings By Importing and Exporting Multilanguage Files
How to: Add Translated Strings for Conflicting Text Encoding Formats

Concepts

Language Modules
Multilanguage Development


How to: Install Language Modules

To install language modules in Microsoft Dynamics NAV 2016, you must first download the language module from Language Modules for Microsoft Dynamics NAV 2015 (requires PartnerSource login), and then you install the following different components separately:

  • Server Component

  • Microsoft Dynamics NAV Windows Client Component

  • Microsoft Dynamics NAV Web Client Component

  • Microsoft Office Outlook Component (optional)

  • Database Component

  • Profiles

After you install a language module, you may need to translate additional strings for customized objects in the application.

Important
For mixed language modules to work on your computer, you must install the language pack that corresponds to your regional settings.

For more information, see the following topics:

  • How to: Add Translated Strings By Using the Multilanguage Editor

  • How to: Add Translated Strings By Importing and Exporting Multilanguage Files

Server Component

To install the server component of a language module

  1. On the computer that is running Microsoft Dynamics NAV Server, navigate to the location where you downloaded the language module.

  2. Run the .exe file to unzip the language module files.

  3. In the Server folder, run Server.Local.<country/region code>.<language code>.msi.

  4. In Control Panel, choose Administrative Tools, and then choose Services to open the Services snap-in.

  5. In the list of services, right-click Microsoft Dynamics NAV Server, and then choose Restart.

Microsoft Dynamics NAV Windows Client Component

To install the Microsoft Dynamics NAV Windows client component of a language module

  1. Confirm that you have installed the server component of the language module before you install the Microsoft Dynamics NAV Windows client component.

  2. On the computer that is running the Microsoft Dynamics NAV Windows client, navigate to the location where you downloaded the language module.

  3. In the RoleTailoredClient folder, run RoleTailoredClient.Local.<country/region code>.<language code>.msi.

  4. (optional) To import a localized chart for a Role Center, do the following:

    1. In the development environment client, open Object Designer.

    2. On the File menu, choose Import.

    3. In the Import Objects window, browse to the location where you downloaded the language module, navigate to the RoleTailored Client folder, and then navigate to the Charts folder.

    4. Select the chart that you want to add to a Role Center, and then choose Open.

      Note
      By default, this will overwrite an existing chart page with the same ID.

    5. Personalize a Role Center to use the chart part.

Microsoft Dynamics NAV Web Client Component

To install the Microsoft Dynamics NAV Web client component of a language module

  1. Confirm that you have installed the server component of the language module before you install the Microsoft Dynamics NAV Web client component.

  2. On the computer that is running the Microsoft Dynamics NAV Web Server components, navigate to the location where you downloaded the language module.

  3. In the WebClient folder, run WebClient.Local.<country/region code>.<language code>.msi.

Microsoft Office Outlook Component

To install the Microsoft Office Outlook component of a language module

  1. On the computer that is running the development environment, navigate to the location where you downloaded the language module.

  2. In the OutlookAddIn folder, run OutlookAddIn.Local.<country/region code>.<language code>.msi.

Database Component

To install the database component of a language module

  1. Verify that the license that you are using allows you to compile objects.

  2. In the development environment client, open Object Designer and verify that all objects are compiled.

  3. In Object Designer, choose All.

  4. On the Edit menu, choose Select All.

  5. If you have Microsoft Office 2010 installed, then compile all objects.

    • On the Tools menu, choose Compile, and then choose the Yes button.

      Note
      If you do not compile objects before you import the language module, you will receive the “Could not load the selected type library” error when you import a language module in the Microsoft Dynamics NAV Development Environment. The error occurs because several objects have a reference to Microsoft Office 2013 components, and these are not present when you have Microsoft Office 2010 installed.

  6. On the Tools menu, point to Language Module, and then choose Import.

  7. In the Language Module Import window, browse to the location where you downloaded the language module, navigate to the Database folder, select the .flm file, and then choose Open.

  8. With all objects selected, on the Tools menu, choose Compile.

Profiles

To import profiles

  1. On the computer running the Microsoft Dynamics NAV Windows client, in the Search box, enter Profiles, and then choose the related link.

  2. Select all profiles, and then choose the Import Translated Profile Resources From Folder button.

  3. In the Browse For Folder dialog, navigate to the location where you downloaded the language module, select the Language Module folder, unzip this folder, then select the RoleTailoredClient folder, and then Profiles.

  4. Choose the OK button to import the translated profiles.

See Also

Manage Profiles

Concepts

Language Modules


How to: Uninstall Language Modules

To uninstall a language module, you must delete the language from the database and uninstall each component of the language module that you installed.

For more information about how to delete translated strings from individual objects, see How to: Delete Translated Strings.

For more information about how to install language modules, see How to: Install Language Modules.

To uninstall a language module

  1. If you have imported translated profile resources, you must first go to the computer running the Microsoft Dynamics NAV Windows client.

  2. In the Search box, enter Profiles, and then choose the related link.

  3. Select all profiles, and then choose the Remove Translated Profile Resources button.

  4. Select the language that you want to delete and for which to remove the profile translations, and then choose the OK button.

  5. Now in the development environment, on the Tools menu, choose Object Designer.

  6. In Object Designer, select all objects.

  7. On the Tools menu, choose Language Module, and then choose Export.

  8. In the Language Module Export window, in the File Name field, enter the path and file name of the file that will contain the deleted language module.

  9. In the Language field, choose the AssistEdit button.

  10. In the Windows Language List window, select the language that you want to delete, and then choose the OK button.

  11. In the Language Module Export window, select the Delete language field, and then choose the OK button.

  12. In Control Panel, choose Programs and Features.

  13. For each component of the language module that is installed, select the component, and then choose Uninstall/Change.


How to: Add Translated Strings By Importing and Exporting Multilanguage Files

To add string translations for UI elements in a standard country/region-specific version of Microsoft Dynamics NAV 2016, you install a language module so that end users can view the UI elements in a different language. If you have customized objects in the application, then you must also add translations for those objects. You can translate strings in the following ways:

  • By importing and exporting text files that contain translated strings for multiple objects in the Microsoft Dynamics NAV Development Environment.

  • By using the Multilanguage Editor and editing the CaptionML property of individual objects.

  • By running Windows PowerShell cmdlets to update CaptionML properties.

This topic describes how to import and export multilanguage files. For more information about how to use the Multilanguage Editor, see How to: Add Translated Strings By Using the Multilanguage Editor. For more information about how to run Windows PowerShell cmdlets to export and import languages, see Working with Application Objects as Text Files.

Exporting Multilanguage Files

To translate strings for multiple objects, you must first export all text strings.

To export a multilanguage file

  1. In the development environment, in Object Designer, select the objects that you want to export strings for.

  2. On the Tools menu, point to Translate, and then choose Export.

  3. In the Translate Export window, select the location where you want to export the file.

  4. In the File name field, enter an appropriate name for the file.

  5. In the Save as Type field, select the format type, and then choose the Save button.

Translating Multilanguage Files

You can add translated strings directly to the exported file, or you can use a translation tool. If you add translated strings directly to the exported file, then use the following procedure.

To translate strings in a multilanguage file

  1. Open the multilanguage file for editing. For example, open the file with a text editor or in Microsoft Office Excel.

  2. For each string that you want to translate, create a new line in the file.

  3. Copy and paste the source ID of the item to be translated into the new line.

  4. Modify the four-character language code to the language to which you are translating.

  5. Add the translated string to the new line.

    The following illustration uses #### to represent the language code of the language to which you translate the string.

    Translated Strings file in Excel

Importing Multilanguage Files

After you add translated strings to the multilanguage file, you must import the file into the application.

To import a multilanguage file

  1. In the development environment, in Object Designer, select the objects that you want to import strings for.

    If you do not know which objects are included in the multilanguage file, select all objects.

  2. On the Tools menu, point to Translate, and then choose Import.

  3. In the TranslateImport window, navigate to the file that you want to import.

  4. Select the file, and then choose Open.

See Also

Concepts

Multilanguage Development
Working with Application Objects as Text Files


How to: Add Translated Strings for Conflicting Text Encoding Formats

You can configure your Microsoft Dynamics NAV solution so that users with different regional settings and text formats can access the same Microsoft Dynamics NAV Server and see user interface strings in their local language. This functionality supplements the use of language modules and helps resolve issues with conflicting text encoding.

The following procedure assumes that your solution contains strings in English and Dutch, and that you want to add support for Chinese. English and Dutch follow the same text encoding format, so you have been able to import the translation into Dutch to your Microsoft Dynamics NAV solution. But you cannot import strings in Chinese into the development environment because the text file cannot handle Chinese as well as Dutch and English. The same situation will occur if you want to add Chinese and Japanese to your solution.

To add translated strings for a conflicting text encoding format

  1. In the development environment, export the strings for the objects that you want to translate. For more information, see How to: Add Translated Strings By Importing and Exporting Multilanguage Files.

    The resulting text file contains user interface strings in English and Dutch.

  2. Translate the strings in the resulting text file into Chinese by using your preferred translation process.

  3. When translations are complete, save the translated strings into a text file in the UTF-8 text encoding format. For example, open the text file in Notepad, choose File, and then choose Save As. In the dialog that appears, in the Encoding field, choose UTF-8, and then choose Save.

    Optionally, choose to replace the existing file, or save the file with a different file name. However, the extension of the file must be .txt.

    Depending on your translation process, this file contains strings in Chinese, English, and Dutch. You save it in Unicode format so that Microsoft Dynamics NAV Server can access the content of the file.

    Important
    We recommend that you remove the English and Dutch strings from the Unicode file before you copy it to the Microsoft Dynamics NAV Server computer. Microsoft Dynamics NAV Server queries the Translations folder for updated strings, and for performance reasons the folder should only contain strings that you cannot import into the development environment because of conflicting codepages.

  4. Copy the UTF-8 file to the equivalent of C:\Program Files\Microsoft Dynamics NAV\90\Service\Translations on the Microsoft Dynamics NAV Server computer.

    When you have more than one service instance, there is a Translations folder for each service instance, such as C:\Program Files\Microsoft Dynamics NAV\90\Service\Instances\MyInstance\Translations.

  5. Restart the Microsoft Dynamics NAV Server instance.

Microsoft Dynamics NAV Server adds the translated strings in the file to the metadata store for the Microsoft Dynamics NAV deployment. Users of this Microsoft Dynamics NAV Server session can now change the user interface language from English to Dutch, and then to Chinese.

The metadata store is updated whenever you add new strings to the Translations folder and then restart the Microsoft Dynamics NAV Server service instance. Cached strings are not deleted from the metadata store when you restart the service instance.

See Also

Tasks

How to: Add Translated Strings By Importing and Exporting Multilanguage Files

Concepts

Adding Languages to Microsoft Dynamics NAV
Multilanguage Development


How to: Change the Language in the User Interface

You can change the language that is used for captions in windows, on command buttons, and in other UI elements from both the Microsoft Dynamics NAV Development Environment and the Microsoft Dynamics NAV Windows client.

To change the language from the development environment

  1. In the development environment, on the Tools menu, choose Language.

  2. In the Application Languages window, select the language, and then choose the OK button.

To change the language from the Microsoft Dynamics NAV Windows client

  1. In the Microsoft Dynamics NAV Windows client, in the app menu choose Select Language.

  2. In the Select Language page, select the language, and then choose the OK button.

    Note
    If you personalize a component such as a FactBox and then select a different language, then the personalized element is displayed in the original language. To view the elements in the new language, restore the default settings and reapply the personalization settings.

To change the language from the Microsoft Dynamics NAV Web client

  1. In the Microsoft Dynamics NAV Web client, in the app bar upper right corner, choose the user name, and then choose My Settings.

  2. In the My Settings page, select the language, and then choose the OK button.

    Note
    This applies to the Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client also.

    Regional settings follow the selected language.

See Also

Concepts

Viewing the Application in Different Languages
Multilanguage Development


How to: Export, Edit, and Import Translated Profile Strings

To enable customized translation of profiles, the Profile List window has actions for exporting and importing resources (.resx) files. This topic explains the process of exporting .resx files for translation, and then importing the translated .resx files for one or more profiles. Any imported translation can also be removed from the Profile List window.

Note
When installing a language module, we recommend that you import the profile resource files for all of the profiles. For more information, see How to: Install Language Modules.

To export a profile resource file

  1. In the Search box, enter Profiles, and then choose the related link.

  2. Select the profile, or profiles that you want to export a resource file for, and then choose the Export Translated Profile Resources action.

  3. In the Browse for Folder dialog, select which folder to export the resource file to and then choose the OK button.

  4. A dialog will appear when the export is completed.

    The Microsoft Dynamics NAV Web client only supports exporting and importing .zip files, and if you are exporting profile resource files from the Microsoft Dynamics NAV Web client, you will be prompted for where to save the .zip file after step 4.

To edit a profile resource file

  1. Navigate to where you exported the profile resource file and open the file with your preferred editor.

  2. Find the text strings that you want to translate marked in <value></value> tags, for example, <value>Send To</value>. The <comment></comment> tag contains information about which object the string is used for.

    Important
    Do not translate the strings in the <data name="Profile ID" xml:space="preserve"> and <data name="Profile Description" xml:space="preserve"> tags. These contain the Profile ID and Profile Description and modifying these will cause an error.

  3. Once you are done, save the file.

To import a profile resource file

  1. In the Search box, enter Profiles, and then choose the related link.

  2. Select the profile, or profiles that you want to import a resource file for, and then choose either the Import Translated Profile Resources From Folder action, or the Import Translated Profile Resources From Zip File action, depending on the format of your resource files.

    When you import from a folder, select the folder that contains the individual language folders.

    When you import from a .zip file, the .zip file must contain the same structure as is generated when exporting to a .zip file. You can try this by exporting the profile resource file from the Microsoft Dynamics NAV Web client.

    Note
    In the Microsoft Dynamics NAV Web client, you only have the Import Translated Profile Resources From Zip option.

  3. In the Browse For Folder dialog, select the folder to import the translated resource file from, and then choose the OK button.

    Important
    Any existing translations will be overwritten.

  4. A dialog will appear when the import is completed.

To remove a profile resource file

  1. On the Profiles page, select the profile, or profiles that you want to remove translated profile resource for.

  2. Select the Remove Translated Profile Resources action, and in the dialog box, select the language to remove the profile translations for.

  3. Choose the OK button.

See Also

Tasks

How to: Install Language Modules
How to: Uninstall Language Modules


Migrating a Deployment to a New Microsoft Dynamics NAV Server Instance

When you have deployed Microsoft Dynamics NAV, you may want to move existing client connections to a new Microsoft Dynamics NAV Server instance. In that case, you can move the clients that are connecting to the Microsoft Dynamics NAV Server instance to a new instance.

Moving Client Connections to a New Microsoft Dynamics NAV Server Instance

You can move existing client connections to a new Microsoft Dynamics NAV Server instance without changing the client configuration. For example, you can set up a new Microsoft Dynamics NAV Server instance that is a copy of the existing configuration. By reusing the configuration on the server side, the client connections do not have to be updated because the client configuration settings are the same. The following list describes the main steps in moving client connections to a new Microsoft Dynamics NAV Server instance:

  1. Install the new Microsoft Dynamics NAV Server instance. For more information, see Server Option.

  2. Replace the CustomSettings.config file for the new server instance with the CustomSettings.config file from the original server instance.

  3. Stop the original server instance.

  4. Start the new server instance.

Your users access the Microsoft Dynamics NAV Server based on the name of the server computer, the name of the service instance, and the port. Provided that those values are the same for the original Microsoft Dynamics NAV Server instance and the new instance, the client connection settings are the same, and users will not know that you replaced the server instance. Also, if you do not expose physical server names to users, the client configurations do not change either. If the server name is different, you must update the ClientUserSettings.config file for each Microsoft Dynamics NAV Windows client user, and you must provide Microsoft Dynamics NAV Web client users with a new URL.

See Also

Concepts

Configuring Microsoft Dynamics NAV Server
Working with Microsoft Dynamics NAV Setup
Server Option
Deployment


How to: Upload the License File

After an administrator or a Microsoft Certified Partner initially installs Microsoft Dynamics NAV, the next step is to upload the license file that is supplied by Microsoft.

To save the license file, you must have the Per Database license granule (2020) in your license. You must also have the necessary roles and permissions in SQL Server. See Setting Database Owner and Security Administration Permissions.

Note
Uploading the license file is typically something you do once for each database installation, not once for each client installation. If you need to upload a license for a specific database, see Uploading a License File for a Specific Database.

Initially, Microsoft Dynamics NAV uses CRONUS.flf, which is the demonstration license file. All license files that are not demonstration license files are named FIN.flf. The demonstration license file has been given a different name so that it cannot be mistakenly overwritten.

Uploading the License File to SQL Server

The following procedure uploads the license for all Microsoft Dynamics NAV databases on the SQL Server instance.

To upload your license file for all Microsoft Dynamics NAV databases

  1. Start the Microsoft Dynamics NAV Development Environment.

    Note
    On a computer running any version of Windows with User Access Control enabled, you must start the development environment with administrator privileges. In the Start menu, right-click Microsoft Dynamics NAV Development Environment in the Start menu, and then choose Run as administrator.

  2. Verify that you are connected to your database. On the File menu, point to Database, and then choose Open.

  3. Upload the new license.

    1. On the Tools menu, choose License Information.

    2. In the License Information window, choose Upload.

    3. In the Upload License File dialog box, browse to and open the license file.

    You should see the following message:

    The Server license was successfully uploaded.

  4. Restart the development environment to activate the license.

  5. Restart all Microsoft Dynamics NAV Server instances on the computer to activate the license for other clients. For more information, see Managing Microsoft Dynamics NAV Server Instances.

Note
Always review your license file after uploading, to verify that all information is correct and that you have all necessary license granules.

Uploading a License File for a Specific Database

To upload a license file for a specific database

  1. In the development environment, on the File menu, point to Database, and then choose Alter.

  2. In the Alter Database window, choose Integration, and then select Save license in database.

  3. Restart all Microsoft Dynamics NAV Server instances on the computer to activate the license for other clients. For more information, see Managing Microsoft Dynamics NAV Server Instances.

See Also

Tasks

How to: Install C/SIDE Development Environment

Concepts

License Types

Other Resources

Microsoft Dynamics ERP Software License Terms (requires login)
Microsoft Dynamics ERP Licensing Guide (requires PartnerSource login)


Removing Elements from the User Interface According to Permissions

You can configure Microsoft Dynamics NAV to show and hide user interface (UI) elements based on the license or the user's permissions to the underlying tables. All elements, fields, actions, and page parts, can be removed from the user’s view of Microsoft Dynamics NAV.

Depending on the setting in the UI Elements Removal field in the Microsoft Dynamics NAV Server Administration tool, only UI elements on objects in the license or on objects that the user has permissions to will appear in the user interface.

UI elements that are directly related to an object through the TableRelation or the CalcFormula property can be removed automatically according to the license file and/or user permissions.

For UI elements that are not directly related to an object, you can use the AccessByPermission property to remove the element according to the user’s permission to a related object.

To make full use of the LicenseFileAndUserPermissions option in the UI Elements Removal field, it is recommended that you assign the special permission set, FOUNDATION, along with the relevant permission sets that define which application objects the user will access.

Important
The majority of the permission sets that are provided with the CRONUS demonstration database cannot be combined with the FOUNDATION permission set to fully use the UI Elements Removal feature. You must first create or edit the relevant permission sets to avoid that the user is blocked from performing the involved tasks. You must first create or edit the relevant permission sets to avoid that the user is blocked from performing the involved tasks.

If you only use the LicenseFile option in the UI Elements Removal field, then you do not have to edit any permission sets as they will not affect which UI elements are removed.

A couple of permission sets in the CRONUS demonstration database are adapted to support the FOUNDATION permission set for demonstration purposes. You can use those permission sets to try out how UI elements are removed for a user performing the task to create and edit a new customer.

The following table describes a sequence of tasks, with links to the topics that describe them. These tasks are listed in the order in which they are generally performed.

To | See
Configure Microsoft Dynamics NAV Server to automatically remove UI elements from the user’s interface if they are on objects that are not in the license or on objects that the user does not have permissions for. | How to: Specify When UI Elements Are Removed
Use the AccessByPermission property to define which user permissions to a certain object are required before the user can see and access the UI element. This method can be used to remove UI elements without a direct object relation from the user’s interface based on permissions. | How to: Remove UI Elements Using the AccessByPermission Property
To experience how UI elements are removed for a user performing the task to create and edit a new customer, create a sample user interface based on two permission sets that are provided with Microsoft Dynamics NAV. | How to: Try Out the UI Elements Removal Feature Based on Demonstration Permission Sets
Learn about FOUNDATION and other special permission sets. | Special Permission Sets
Modify the existing permission sets to fully support the FOUNDATION permission set. | How to: Create or Modify Permission Sets

See Also

Customize the User Interface

Concepts

Configuring Microsoft Dynamics NAV


How to: Specify When UI Elements Are Removed

Depending on the setting in the UI Elements Removal field in the Microsoft Dynamics NAV Server Administration tool, only user interface (UI) elements on objects in the license or on objects that the user has permissions to will appear in the user interface.

All types of UI elements will be removed if they relate to objects that are not included in the license or the user does not have the required permission to the objects:

  • Fields

  • Actions

  • Page parts

UI elements that are directly related to an object through the TableRelation or the CalcFormula property can be removed automatically according to the license file and/or user permissions.

For UI elements that are not directly related to an object, you can use the AccessByPermission property to remove the element according to the user’s permission to a related object. For more information, see How to: Remove UI Elements Using the AccessByPermission Property.

To make full use of the LicenseFileAndUserPermissions option in the UI Elements Removal field, it is recommended that you assign the special permission set, FOUNDATION, along with the relevant permission sets that define which application objects the user will access.

Important
The majority of the permission sets that are provided with the CRONUS demonstration database cannot be combined with the FOUNDATION permission set to fully use the UI Elements Removal feature. You must first create or edit the relevant permission sets to avoid that the user is blocked from performing the involved tasks. You must first create or edit the relevant permission sets to avoid that the user is blocked from performing the involved tasks. For more information, see How to: Create or Modify Permission Sets.

If you only use the LicenseFile option in the UI Elements Removal field, then you do not have to edit any permission sets as they will not affect which UI elements are removed.

To specify when UI elements are removed

  1. Open the Microsoft Dynamics NAV Server Administration tool. For more information, see Microsoft Dynamics NAV Server Administration Tool.

  2. In the UI Elements Removal field, choose the relevant option as described in the following table.

    Option Description

    None

    All UI elements are displayed, even if the license file does not include the related object and the user does not have permissions to the related object.

    LicenseFile

    A UI element is removed if the related object is not included in the license file.

    LicenseFileAndUserPermissions

    A UI element is removed if the related object is not included in the license file and the user does not have permissions to the object as defined in the AccessByPermission property for the related UI element.

    By default, this option is selected.

Tip
When you configure user interfaces in Microsoft Dynamics NAV, you should make sure that the UI Elements Removal field is set to its default, LicenseFileAndUserPermissions, so that you only see the relevant UI elements in the Customize window. For more information, see Configure the User Interface.

When you develop in Microsoft Dynamics NAV, you should make sure that the UI Elements Removal field is set to its default, None, to make sure that all UI elements are visible when you review your development in the UI.

See Also

Configure the User Interface
Administration in the Clients

Tasks

How to: Remove UI Elements Using the AccessByPermission Property
How to: Try Out the UI Elements Removal Feature Based on Demonstration Permission Sets
How to: Create or Modify Permission Sets
How to: Define Permissions for Users

Concepts

Removing Elements from the User Interface According to Permissions
Configuring Microsoft Dynamics NAV Server
Special Permission Sets


How to: Remove UI Elements Using the AccessByPermission Property

UI elements that are directly related to an object through the TableRelation or the CalcFormula property can be removed automatically according to the license file and/or user permissions. For more information, see How to: Specify When UI Elements Are Removed.

For UI elements that are not directly related to an object, you can use the AccessByPermission property to remove an element according to the user’s permission to a related object.

The AccessByPermission property sets a value for a table field or UI element that determines the permission mask for an object that a user must have to see and access the related page fields or UI element in the client. The UI element will be removed at runtime if the user does not have permissions to a certain object as specified in the Access By Permission window. For more information, see AccessByPermission Property.

To make full use of the LicenseFileAndUserPermissions option in the UI Elements Removal field, it is recommended that you assign the special permission set, FOUNDATION, along with the relevant permission sets that define which application objects the user will access.

Important
The majority of the permission sets that are provided with the CRONUS demonstration database cannot be combined with the FOUNDATION permission set to fully use the UI Elements Removal feature. You must first create or edit the relevant permission sets to avoid that the user is blocked from performing the involved tasks. You must first create or edit the relevant permission sets to avoid that the user is blocked from performing the involved tasks. For more information, see How to: Create or Modify Permission Sets.

If you only use the LicenseFile option in the UI Elements Removal field, then you do not have to edit any permission sets as they will not affect which UI elements are removed.

To remove UI elements by using the AccessByPermission property

  1. In the Microsoft Dynamics NAV Development Environment, view the properties of a table field for which you want to remove its page control(s) or view the properties of a field, action, or part on a page object. For more information, see How to: View or Modify Properties on a Table or Field.

  2. For the AccessByPermission property, choose the AssistEdit button.

  3. In the Access By Permission window, fill the fields as described in the following table.

    Field Description

    Object Type

    Specify the type of object to which permission is required for the UI element to be visible.

    Object ID

    Specify the object to which permission is required for the UI element to be visible.

    Read

    Specify if Read permission is required for the UI element to be visible.

    Insert

    Specify if Insert permission is required for the UI element to be visible.

    Modify

    Specify if Modify permission is required for the UI element to be visible.

    Delete

    Specify if Delete permission is required for the UI element to be visible.

    Execute

    Specify if Execute permission is required for the UI element to be visible.

    Note
    When multiple permissions are selected, then one or another applies. For example, if you choose Insert and Modify, then the user must have either the Insert or the Modify permission to the object for the UI element to be visible.

  4. Save and compile the changes.

The UI element in question is now invisible to users who do not have the specified permissions to the object.

Important
If you defined the property for a table field, then all instances of the field on pages are removed from the user’s view. To override the property on an individual page field, delete the permission value after the = sign in the Value field. Do not delete the whole string as that will be replicated on the property of the table field.

Tip
When you configure user interfaces in Microsoft Dynamics NAV, you should make sure that the UI Elements Removal field is set to its default, LicenseFileAndUserPermissions, so that you only see the relevant UI elements in the Customize window. For more information, see Configure the User Interface.

When you develop in Microsoft Dynamics NAV, you should make sure that the UI Elements Removal field is set to its default, None, to make sure that all UI elements are visible when you review your development in the UI.

Example: Remove the Unit Price field if the user does not have permission to the Sales Price table

  1. Open table 27, Item Card, in the Table Designer.

  2. View the properties of field 18, Unit Price.

  3. For the AccessByPermission property, choose the AssistEdit button in the Value field.

  4. In the Access By Permission window, fill the fields as described in the following table.

    Field Description

    Object Type

    TableData

    Object ID

    Sales Price

    Read

    Select

    Insert

    Select

    Modify

    Leave blank

    Delete

    Leave blank

    Execute

    Leave blank

  5. Close the Access By Permission window and save the changes on table 27.

All instances of the Unit Price field on pages are now removed if the user does have Read or Insert permission to the Sales Price table.

Important
If you defined the property for a table field, then all instances of the field on pages are removed. To override the property on an individual page field, delete the permission value after the = sign in the Value field. Do NOT delete the whole string as that will be replicated on the property of the table field.

See Also

Tasks

How to: Specify When UI Elements Are Removed
How to: Try Out the UI Elements Removal Feature Based on Demonstration Permission Sets
How to: Create or Modify Permission Sets
How to: Define Permissions for Users
How to: View or Modify Properties on a Table or Field

Reference

AccessByPermission Property
Access By Permission

Concepts

Removing Elements from the User Interface According to Permissions
Configuring Microsoft Dynamics NAV Server
Special Permission Sets
Properties


How to: Try Out the UI Elements Removal Feature Based on Demonstration Permission Sets

Depending on the setting in the UI Elements Removal field in the Microsoft Dynamics NAV Server Administration tool, only UI elements on objects in the license or on objects that the user has permissions for will appear in the user interface. For more information, see How to: Specify When UI Elements Are Removed.

Important
The majority of the permission sets that are provided with the CRONUS demonstration database cannot be combined with the FOUNDATION permission set to fully use the UI Elements Removal feature. You must first create or edit the relevant permission sets to avoid that the user is blocked from performing the involved tasks. You must first create or edit the relevant permission sets to avoid that the user is blocked from performing the involved tasks. For more information, see How to: Create or Modify Permission Sets.

To try out or demonstrate the effect of the feature to remove UI elements according to user permissions, you can quickly prepare a test UI based on two permission sets (S&R-Customer and S&R-Customer, EDIT) in CRONUS that are ready to support the FOUNDATION permission set for this purpose.

Prepare a permissions-based ORDER PROCESSOR UI that only shows UI elements for creating and editing a customer

  1. Create a test user who has the ORDER PROCESSOR profile. For more information, see How to: Create Microsoft Dynamics NAV Users and How to: Assign Users to Profiles.

  2. Assign the FOUNDATION permission set. For more information, see How to: Define Permissions for Users.

  3. Assign the following two application permission sets, which support the task to create and edit a customer in conjunction with the FOUNDATION permission set:

    • S&R-Customer

    • S&R-Customer, EDIT

  4. Upload a user license. For more information, see How to: Upload the License File.

  5. Set the UI Elements Removal field to LicenseFileAndUserPermissions. For more information, see How to: Specify When UI Elements Are Removed.

  6. Start the client for the ORDER PROCESSOR profile.

On the Sales Order Processor Role Center, you now only see the UI elements that are required to create and edit a customer. For example, only the Customers action is visible on the navigation pane, and all the tiles for sales documents are removed from the Activities part. On the involved pages, such as the Customer Card window, you now only see the fields, actions, and page parts that are required to create and edit a customer.

See Also

Tasks

How to: Specify When UI Elements Are Removed
How to: Create or Modify Permission Sets

Concepts

Special Permission Sets

Other Resources

Managing Permissions and Permission Sets


How to: Create or Modify Permission Sets

If the default permission sets that are provided with Microsoft Dynamics NAV are not sufficient or not appropriate for your organization, then you can create new permission sets. If the individual object permissions that define a permission set are not adequate, then you can modify a permission set.

Note
Depending on the setting in the UI Elements Removal field in the Microsoft Dynamics NAV Server Administration tool, only UI elements on objects in the license or on objects that the user has permissions for will appear in the user interface. For more information, see Removing Elements from the User Interface According to Permissions.

The majority of the permission sets that are provided with the CRONUS demonstration database cannot be combined with the FOUNDATION permission set to fully use the UI Elements Removal feature. You must first create or edit the relevant permission sets to avoid that the user is blocked from performing the involved tasks.

You can create a permission set manually, or you can record permissions by navigating in the application.

Creating or Modifying Permission Sets

To create or edit a permission set

  1. In the Search box, enter Permission Sets, and then choose the related link.

  2. In the Permission Sets window, choose New.

  3. In the Permission Sets window, type a name for the new permission set in the Permission Set field and a brief description in the Name field.

    The name of the new permission set is automatically formatted in all uppercase letters.

  4. On the User Permission Sets FastTab, on the toolbar, choose Permissions.

  5. In the Permissions window, type or select a value in the Object Type field on the first line in the list.

    Note
    If you would prefer to select from list that shows all database objects, on the Home tab, in the New group, choose All Permissions.

  6. In the Object ID field, enter the object that you want to define permissions for.

  7. Fill in the five fields for the different permission types as described in the following table.

    Option Description

    <Blank>

    Specifies that the permission type is not granted for the object.

    Yes

    Specifies that the permission type is granted with direct access to the object.

    Indirect

    Specifies that the permission type is granted with indirect access to the object.

    Having indirect permission to a table means that you cannot open the table and read from it, but you can view the data in the table through another object, such as a page, that you have direct permission to access.

    For more information, see the “Example - Indirect Permission” section in this topic.

  8. In the Security Filter field, enter a filter that you want to apply to the permissions that you have assigned to the object. For more information, see Record-Level Security.

  9. Repeat steps 2 through 8 to add permissions for additional objects to the permission set.

To record permissions

  1. In the Search box, enter Permission Sets, and then choose the related link.

  2. On the home tab, choose New.

  3. Specify a name for the new permission set in the Permission Set field and a brief description in the Name field.

  4. On the Home tab, in the Process group, choose Permissions.

  5. In the Permissions window, on the Actions tab, choose Start.

    This starts a recording process that is based on the code coverage functionality in Microsoft Dynamics NAV. You can now access the various windows and activities in the Microsoft Dynamics NAV Windows client or the Microsoft Dynamics NAV Web client that you want users with this permission set to access. You must carry out the tasks that you want to record permissions for.

  6. When you want to finish the recording, return to the Permissions window, and then, on the Actions tab, choose Stop.

  7. Choose Yes to add the recorded permissions to the new permission set, or choose No to cancel.

  8. If you choose Yes, the objects that you accessed are added to the window. In Microsoft Dynamics NAV 2016, only the objects are recorded, so you must specify if users must be able to insert, modify, or delete records in the recorded tables.

    For more information, see the previous procedure.

Example - Indirect Permission

You can assign an indirect permission to use an object only through another object.

For example, a user can have permission to run codeunit 80, Sales-Post. The Sales-Post codeunit performs many tasks, including modifying table 39, Purchase Line. When the user runs the Sales-Post codeunit, Microsoft Dynamics NAV checks whether the user has permission to modify the Purchase Line table.

  • If not, then the codeunit cannot complete its tasks, and the user receives an error message.

  • If so, the codeunit runs successfully.

However, the user does not need to have full access to the Purchase Line table to run the codeunit. If the user has indirect permission for the Purchase Line table, then the Sales-Post codeunit runs successfully.

When a user has indirect permission, that user can only modify the Purchase Line table by running the Sales-Post codeunit or another object that has permission to modify the Purchase Line table. The user can only modify the Purchase Line table when doing so from supported application areas. The user cannot run the feature inadvertently or maliciously by other methods.

See Also

How to: Work with the BASIC Permission Set
User Groups
Customize the User Interface

Tasks

How to: Try Out the UI Elements Removal Feature Based on Demonstration Permission Sets
How to: Specify When UI Elements Are Removed
How to: Remove UI Elements Using the AccessByPermission Property

Concepts

Special Permission Sets
About Permissions
Object-Level Security
Removing Elements from the User Interface According to Permissions


Migrating to Multitenancy

You can choose to migrate your Microsoft Dynamics NAV solution to a multitenant deployment architecture where you maintain a single application that is used by two or more companies that store their data in separate databases.

This can make maintenance of your solution easier if you support multiple customers with the same application functionality.

Tenants and Companies

When you upgrade your application and the data to Microsoft Dynamics NAV 2016, you have a database that has the same number of companies as you had before the upgrade. This database is considered a tenant. This does not mean that you have to turn your solution into a multitenant deployment. But it means that you can if you want to.

For example, your Microsoft Dynamics NAV deployment in the earlier version consisted of a database that has 20 companies. In other words, you support 20 companies that all share the same application functionality. In this example, the companies are separate companies that have nothing to do with each other except that they are supported by you in one database. In Microsoft Dynamics NAV 2016, you can choose to extract the application-wide tables into a separate database and keep the data for all 20 companies in the original database. This becomes a single-tenant business data database. Then, you can choose to split the business data database into one for each company so that you run a truly multitenant environment. The application is stored separately in the application database, and you maintain application functionality centrally. When you modify the application, you make the changes available to one tenant at a time. As a result, if something goes wrong, all other tenants are not affected.

Compare this to earlier versions of Microsoft Dynamics NAV where a database could contain several companies. These companies could be related or not, but they would all use the same application and write to the same database. Also, when you modified the application, it would affect all companies immediately. So if something went wrong, all companies would be affected.

Note
The email logging functionality in Microsoft Dynamics NAV requires the Microsoft Dynamics NAV Server service account to have access to the Exchange server. But in a multitenant deployment, this is not always possible.

In multitenant deployments of Microsoft Dynamics NAV, permission sets are stored centrally in the application database, so only the administrator of the central application can add, remove, or modify permission sets. Instead, the tenants can use user groups to manage permissions. For more information, see User Groups.

Migration Process

If you decide to move to a multitenant architecture, you must complete the following steps:

  1. If your current solution is based on an earlier version of Microsoft Dynamics NAV, upgrade the database to Microsoft Dynamics NAV 2016. For more information, see Upgrading the Data.

    After this step, you have a database that contains the application-wide tables and the same companies as before. But it has been upgraded to the Microsoft Dynamics NAV 2016 database schema.

  2. Move the tables that describe the application to a separate database. For more information, see Separating Application Data from Business Data.

    After this step, you have two databases: an application database and a business data database.

  3. Split the business data database into one for each company. For more information, see Creating Tenants from Companies.

    After this step, you have an application database and a business data database for each company in the original database. The company-specific business data databases are tenants, and your solution is multitenant.

If you want to move back to storing application tables and business data in a single database, you can use the Microsoft Dynamics NAV Windows PowerShell cmdlets to merge the databases. For more information, see Merging an Application Database with a Tenant Database.

See Also

Upgrading the Application Code

Concepts

Separating Application Data from Business Data
Creating Tenants from Companies
Upgrading the Data
Merging an Application Database with a Tenant Database

Other Resources

Upgrading to Microsoft Dynamics NAV 2016


Separating Application Data from Business Data

Microsoft Dynamics NAV 2016 separates tables that describe the application from the tables that contain business data. Depending on your deployment scenario, you can choose to store all Microsoft Dynamics NAV tables in one database, or you can export the application tables to a dedicated database. In multitenant deployments, the application must be stored in a dedicated database.

Application Database versus Business Data Databases

The application database contains tables that describe your application. This includes a description of the objects that your application consists of, and other data that is common to all tenants. The data that users enter in your application is stored in the business data database because this data is specific to their company. Optionally, you can create multiple business data databases, such as if you want to support your customers as tenants.

When you have exported the application tables to a separate database, you can no longer access the business database from the Microsoft Dynamics NAV Development Environment. This is because the metadata for the tables in the business database is stored in the application database and modified in that database.

For example, if you want to modify a report, you modify the report object in the application database. Then, when you deploy the updated application to your production environment, when a user accesses the report, they see the modified report.

Microsoft Dynamics NAV includes Windows PowerShell cmdlets that help you export application tables to a dedicated database, and other cmdlets to help you maintain a multitenant deployment. For more information, see Microsoft Dynamics NAV Windows PowerShell Cmdlets.

Distribution of the System Tables in Each Database

The application tables are system tables that define the application. Other system tables remain in the business data database. The following table describes which system tables are moved to the application database when you run the Export-NAVApplication cmdlet and which tables remain in the business data database.

Application database | Business data database
Chart | Access Control
Client Add-in | Active Session
Client Add-in Resources | Company
Debugger Breakpoint | Device
Debugger Watch | Document Service
Object | Integration Page
Object Metadata | Object Metadata Snapshot
Object Tracking | Object Translation
Permission | Page Data Personalization
Permission Set | Printer Selection
Profile | Record Link
Profile Metadata | Report List Translation
Send-To Program | Session Event
Server Instance | User
Style Sheet | User Default Style Sheet
Web Service | User Metadata
 | User Personalization
 | User Property

See Also

Tasks

How to: Export the Application Tables to a Dedicated Database

Concepts

Migrating to Multitenancy
Microsoft Dynamics NAV Windows PowerShell Cmdlets


How to: Export the Application Tables to a Dedicated Database

In Microsoft Dynamics NAV, you can export the tables that define the application to a dedicated database. To export the application tables from an existing database, Microsoft Dynamics NAV provides a Windows PowerShell cmdlet as part of the Microsoft Dynamics NAV 2016 Administration Shell.

Important
Before you can run the script, you must upgrade to Microsoft Dynamics NAV 2016. For more information, see Upgrading to Microsoft Dynamics NAV 2016.

The following procedure illustrates how you can separate the application tables in an existing database into two databases: an application database and a business data database. You can automate this process and combine it with the use of other cmdlets. For more information, see the samples in the Windows PowerShell scripts in the …\WindowsPowerShellScripts\Multitenancy\ folder on the Microsoft Dynamics NAV product media.

To export the application tables to a dedicated database

  1. Stop all Microsoft Dynamics NAV Server services that access the database that you are modifying.

  2. Open the Microsoft Dynamics NAV 2016 Administration Shell.

    Important
    You must run the program as administrator. Also, you must ensure that scripting is enabled on the computer.

    For more information, see Microsoft Dynamics NAV Windows PowerShell Cmdlets.

  3. For an overview of the cmdlet, type the following command:

    Copy Code
    get-help Export-NAVApplication

  4. To export the application tables, type the following command:

    Copy Code
    Export-NAVApplication -DatabaseServer <server name> -DatabaseInstance <instance name> -DatabaseName <name of original database> -DestinationDatabaseName <name of new application database> -ServiceAccount <the account used by Microsoft Dynamics NAV Server if not NT AUTHORITY\NETWORK SERVICE>

    For example, to run the cmdlet against the CRONUS International Ltd. demonstration database, type the following command:

    Copy Code
    Export-NAVApplication -DatabaseServer ‘MyServer’ -DatabaseInstance ‘NavDemo’ -DatabaseName ‘Demo Database NAV (9-0)’ -DestinationDatabaseName ‘NAV App’

    In the example, the database server name is MyServer , and the SQL Server instance is NavDemo. The name of the new application database can be anything. You can specify a name that reflects your application.

    The application database is created on the same SQL Server instance as the original database. In the example, if you connect to the NavDemo instance using SQL Server Management Studio you will see two databases: the original database, Demo Database NAV (9-0), and the new application database, NAV App.

    At this stage, the original database still contains the application tables, and you can still access it using the Microsoft Dynamics NAV Development Environment. Next, you must remove the application tables from the original database to make it a tenant database.

    Tip
    Optionally, you can combine the Export-NAVApplication and Remove-NAVApplication cmdlets. For an example of how you can combine the two cmdlets, see the Example section.

  5. To remove the application tables from the original database, type the following command:

    Copy Code
    Remove-NAVApplication -DatabaseServer <server name> -DatabaseInstance <instance name> -DatabaseName <name of the original database>

    For example, to run the cmdlet against the CRONUS International Ltd. demonstration database where you have exported the application tables, type the following command:

    Copy Code
    Remove-NAVApplication -DatabaseServer ‘MyServer’ -DatabaseInstance ‘NavDemo’ -DatabaseName ‘Demo Database NAV (9-0)’

    You will be asked to confirm that you want to remove the tables.

    Warning
    Running the Remove-NAVApplication cmdlet is not reversible. When you have removed the application tables from the database, you cannot import them again. Make sure that you have a full backup available.

At the end of the process, you have two databases. In the example earlier in this topic, the databases are as follows.

Database name | Database type | Description
Demo Database NAV (9-0) | Business data database | Contains the data from the original database.
NAV App | Application database | Contains the tables that define the application. For a list of tables, see Separating Application Data from Business Data.

You must take additional steps to get the final business data database operational. For an example of how you can write a script that runs the cmdlet for creating an application database, see the …\Windows PowerShell\Multitenancy\ folder on the Microsoft Dynamics NAV product media. For an example of how to write individual commands in Windows PowerShell, see the Example section.

Next, you must restart the Microsoft Dynamics NAV Server service, and you must mount the two databases by using the Mount-NAVApplication and Mount-NAVTenant cmdlets. For more information, see Microsoft Dynamics NAV Windows PowerShell Cmdlets.

Example

The following code example illustrates how you can manually write commands in the Microsoft Dynamics NAV administration shell. The commands create an application database based on an existing Microsoft Dynamics NAV database.

The sample commands are assumed to run in the Microsoft Dynamics NAV administration shell based on the CRONUS International Ltd. demonstration database on a local computer.

Copy Code
PS C:\Windows\System32> Set-NAVServerInstance -ServerInstance ‘DynamicsNAV90’ -stop
PS C:\Windows\System32> Export-NAVApplication -DatabaseServer ‘MyServer’ -DatabaseInstance ‘NAVDEMO’ -DatabaseName ‘Demo Database NAV (9-0)’ -DestinationDatabaseName ‘NAV App’| Remove-NAVApplication -DatabaseName ‘Demo Database NAV (9-0)’ -Force
PS C:\Windows\System32> Set-NAVServerConfiguration -ServerInstance ‘DynamicsNAV90’ -element appSettings -KeyName ‘DatabaseName’ -KeyValue ‘’
PS C:\Windows\System32> Set-NAVServerInstance -ServerInstance ‘DynamicsNAV90’ -Start
PS C:\Windows\System32> Mount-NAVApplication -ServerInstance ‘DynamicsNAV90’ -DatabaseServer ‘MyServer\NAVDEMO’ -DatabaseName ‘NAV App’
PS C:\Windows\System32> Mount-NAVTenant -ServerInstance ‘DynamicsNAV90’ -Id tenant1 -DatabaseServer ‘MyServer\NAVDEMO’ -DatabaseName ‘Demo Database NAV (9-0)’ -OverwriteTenantIdInDatabase

In the example, the commands stop the Microsoft Dynamics NAV Server service, creates the application database, clears the default database name in the server configuration, and then restarts the service. Then, the application database and the tenant database are mounted, and the configuration is saved in the Tenants.config file on the server. As a result, you have an application database and a single-tenant deployment. When you try to open the Microsoft Dynamics NAV Windows client, an error displays because you have not specified a tenant. So in the Select Server window, in the Server Address field, add the tenant ID to the address. In this example, the address is localhost:7046/DynamicsNAV90/tenant1.

Tip
For an example of how you can automate the process of transferring user accounts from the original database to the new application database, see the HowTo-ExportNAVApplicationDatabase.ps1 sample script. This and other sample scripts are in the …\Windows PowerShell\Upgrade\ folder on the Microsoft Dynamics NAV product media. The ExportNAVApplicationDatabase.ps1 sample script can be run in the context of the NAVUpgradeSamples.psm1 script module file. When you call a script such as this, it will export the application tables to a new application database and copy all accounts and SQL Server user roles to the application database. To only transfer the account that the Microsoft Dynamics NAV Server instance uses, use the -ServiceAccount parameter for the Export-NAVApplication cmdlet. In the examples in this topic, this parameter has not been specified. As a result, the default account, NT AUTHORITY\NETWORK SERVICE, is set up with the required user roles.

See Also

Concepts

Separating Application Data from Business Data
Migrating to Multitenancy
Microsoft Dynamics NAV Windows PowerShell Cmdlets
Creating Tenants from Companies
Merging an Application Database with a Tenant Database

Other Resources

Upgrading to Microsoft Dynamics NAV 2016


Creating Tenants from Companies

If your Microsoft Dynamics NAV solution includes multiple companies in one database, you can choose to migrate to multitenancy where the Microsoft Dynamics NAV companies become tenants of your application database.

Companies in Multitenancy Deployments

In Microsoft Dynamics NAV 2016, you can maintain multiple companies in each business database, and you can choose to export all or some of the companies to separate tenant databases. A tenant database can contain one or more companies. Therefore, you can deploy the number of tenants that suits your solution. This varies between solutions. You may prefer to have a dedicated tenant database for each legal entity in your deployment. Or you may prefer to have a tenant database for each group of legal entities where each legal entity is a Microsoft Dynamics NAV company in that tenant database. In this example, we assume that your current deployment consists of one or more databases with multiple companies in each database. If you migrate your solution as suggested by the examples in this section, you will have a deployment where your application is stored in a dedicated application database. Each company in the original database will be moved into a dedicated business database, which is mounted as tenants on a Microsoft Dynamics NAV Server instance.

Important
Before you can create tenants from Microsoft Dynamics NAV companies, you must have exported the application to a dedicated application database. For more information, see Separating Application Data from Business Data.

Running a Windows PowerShell Script to Create Tenants from Companies

Microsoft Dynamics NAV includes a sample Windows PowerShell script and a sample SQL script, HowTo-MoveCompanyToTenant.ps1 and HowTo-MoveCompanyToTenant.sql. These scripts illustrate how you can move company-specific data to new business databases and mount them as new tenants. You can modify the scripts and then run them in the Microsoft Dynamics NAV 2016 Administration Shell. For more information, see Sample Windows PowerShell Scripts for Microsoft Dynamics NAV.

The HowTo-MoveCompanyToTenant.ps1 script uses Microsoft Dynamics NAV cmdlets and SQL commands to copy data from a Microsoft Dynamics NAV company in a business database to a new tenant database. It mounts the tenant database on a Microsoft Dynamics NAV Server instance, and then deletes the data and the company from the original database. You can adapt the scripts to your solution and rename them so that they do not start with “HowTo-“. Then, you can run the MoveCompanyToTenant.ps1 script in Windows PowerShell with the relevant parameters as shown in the following example.

Copy Code
MoveCompanyToTenant -ServerInstance ‘DynamicsNAV’ -FromDatabase 'Demo Database NAV (9-0)' -CompanyName 'CRONUS International Ltd.' -OldTenantName default -NewTenantName CRONUS1 -ServiceAccount 'NT AUTHORITY\NETWORK SERVICE' -DatabaseServer MySQLServer

In the example, the script will move the CRONUS International Ltd. company from the Demo Database NAV (9-0) database to a new tenant database, CRONUS1.The script also adds an account for the Microsoft Dynamics NAV Server instance in the new database and removes the company from the original database. All information that is stored in shared tables, but which is specific to the company, is copied to the new tenant. The following table describes the parameters and the parameter values in the example.

Parameter Value Description

ServerInstance

DynamicsNAV

The name of the Microsoft Dynamics NAV Server instance.

FromDatabase

Demo Database NAV (9-0)

The name of the business database that the company must be moved from.

This database must have been upgraded to Microsoft Dynamics NAV 2016, and you must have exported the application tables to an application database. For more information, see Separating Application Data from Business Data.

CompanyName

CRONUS International Ltd.

The name of the company that you want to move to a new tenant database.

OldTenantName

default

The name of the tenant in the database that you are exporting from.

In many cases, you are working with a single-tenant business database that contains multiple companies. If you did not specify another ID for the tenant when you created the tenant database, specify default. If you have added more tenants to the solution, you must specify the tenant name.

NewTenantName

CRONUS1

The name of the new tenant database.

In the example, this is based on the name of the original company. But because this value will identify the tenant, the value must be unique.

For example, if the name of the company is Spotsmeyer’s Furnishings, the name of the new tenant database can be SPOTSMEYERS. Alternatively, you can use a naming scheme of your choice, such as TENANT1, TENANT2, and so on.

ServiceAccount

NT AUTHORITY\NETWORK SERVICE

The account that Microsoft Dynamics NAV Server uses to access SQL Server. In a default deployment, this is the NT AUTHORITY\NETWORK SERVICE account.

DatabaseServer

MySQLServer

The name of the database tier server where the current business database is located. The new tenant database for the exported company will be created on the same server.

RemoveCompanyWhenMoved

Specifies if each company must be deleted in the original tenant database when it is created in the new tenant database. The default value is true. Therefore, you must set the parameter to false if you do not want the script to delete the companies.

The script uses the sqlcmd utility to create the database, assign database permissions to the service account, and move the data. This utility is part of SQL Server. The script creates four temporary tables in the original database to handle user-specific data, company-specific data, tables that will not be moved, and user IDs. You must modify the MoveCompanyToTenant.sql script to change the default values.

See Also

Concepts

Migrating to Multitenancy
Multitenant Deployment Architecture
Sample Windows PowerShell Scripts for Microsoft Dynamics NAV


Merging an Application Database with a Tenant Database

In Microsoft Dynamics NAV 2016, you can separate the application data into a dedicated application database. However, if you want revert the separation of application data and business data, you can merge the two databases. Microsoft Dynamics NAV includes Windows PowerShell cmdlets that can help you merge the databases, and you can use the cmdlets in a script that runs in Windows PowerShell. This topic provides sample scripts that you can use.

When you merge the two databases, you migrate to single-tenancy. In a multitenant deployment, you can merge a single tenant with the application tables and leave the remaining tenants in the existing deployment. In that case, you add the application tables to the relevant tenant database and leave the original application database unchanged. If you have separated the application data into a dedicated database but you have not used it in a multitenant deployment, you can also use the cmdlet and a sample script to merge the two databases.

Migrating to Single-Tenancy

Before you can start the merge of the two databases, you must collect the relevant information. If you write a script, you must be able to provide values for the parameters that the Windows PowerShell cmdlets require. The migration includes the following main steps:

  1. Gather the prerequisite information.

  2. Merge the two databases.

    1. Migrate from multitenancy to single-tenancy.

    2. Migrate from two databases to one database.

  3. Change the client connection endpoints.

  4. Post-migration clean-up.

Each step is explained in more details in the following sections.

Step 1: Gather the Prerequisite Information

The sample scripts require the following information:

  • Identify the name of the Microsoft Dynamics NAV Server server instance that the tenant database is connected to. This value is used as the input for the serverInstance variable in the sample scripts.

  • Identify the name of the application database that the tenant database is connected to. This value is used as the input for the appDatabaseName variable in the sample scripts.

  • Identify the name of the tenant database that you want to merge with the application database. This value is used as the input for the tenantDatabaseName variable in the sample scripts.

  • If you are migrating from a multitenant deployment, identify the tenant ID of the tenant database. This value is used as the input for the tenantId variable in the sample scripts.

  • Make sure that you have the server role called securityadmin in the relevant instance of SQL Server.

  • Make sure that you have the db_owner role for both the application database and the tenant database.

  • Make sure that you are a member of the Administrators security group on the server that runs the Microsoft Dynamics NAV Server instance and where the Windows PowerShell scripts run.

Step 2: Merge the Two Databases

To merge the application database and the tenant database, you must run the Microsoft Dynamics NAV 2016 Administration Shell as an administrator. Depending on your scenario, you can copy one of the sample scripts and update the variables based on the prerequisite information that you gathered in the previous section. This section includes two sample scripts that you can base your own script on.

The first script merges an application database and a tenant database that is currently a tenant in a multitenant deployment.

Copy Code
# PURPOSE: This sample script migrates a tenant in a multitenant deployment to a single-tenant deployment.
### Modify these variables with values appropriate to your environment ###
$serverInstance = ""
$appDatabaseName = ""
$tenantDatabaseName = ""
$tenantId = ""
### You should not need to modify any variables below this line ###
# Create a new server instance for the requested tenant.
New-NAVServerInstance -ServerInstance $tenantId -ManagementServicesPort 7045
# Dismount the requested tenant from the multitenant server instance.
Dismount-NAVTenant -ServerInstance $serverInstance -Tenant $tenantId
# Remove any application tables from the tenant database if these were not already removed.
Remove-NAVApplication -DatabaseName $tenantDatabaseName
# Copy the application tables from the current application database to the tenant database.
Export-NAVApplication -DatabaseName $appDatabaseName -DestinationDatabaseName $tenantDatabaseName
# Reconfigure the CustomSettings.config file for the new server instance to use the tenant database.
Set-NAVServerConfiguration -ServerInstance $tenantId -KeyName DatabaseName -KeyValue $tenantDatabaseName -WarningAction Ignore
# Reconfigure the CustomSettings.config to use single-tenant mode.
# Set-NAVServerConfiguration -ServerInstance $serverInstance -KeyName Multitenant -KeyValue false -WarningAction Ignore
# Start the new server instance if it is not running.
Set-NAVServerInstance -ServerInstance $tenantId -Start
# Dismount all tenants on the new server instance that are not using the current tenant database.
Get-NAVTenant -ServerInstance $tenantId | where {$_.Database -ne $tenantDatabaseName} | foreach { Dismount-NAVTenant -ServerInstance $tenantId -Tenant $_.Id }
Write-Host "Operation complete." -foregroundcolor cyan

The second script merges an application database and a tenant database that has not been mounted on a Microsoft Dynamics NAV Server instance as a tenant.

Copy Code
# PURPOSE: This sample script merges an application database and a tenant database that are not part of a multitenant deployment.
### Modify these variables with values appropriate to your environment ###
$serverInstance = ""
$appDatabaseName = ""
$tenantDatabaseName = ""
### You should not need to modify any variables below this line ###
# Stop the server instance if it is running.
Set-NAVServerInstance -ServerInstance $serverInstance -Stop
# Remove any application tables from the tenant database if these have not already been removed.
Remove-NAVApplication -DatabaseName $tenantDatabaseName
# Copy the application tables from the application database to the tenant database.
Export-NAVApplication -DatabaseName $appDatabaseName -DestinationDatabaseName $tenantDatabaseName
# Reconfigure the CustomSettings.config to use the tenant database.
Set-NAVServerConfiguration -ServerInstance $serverInstance -KeyName DatabaseName -KeyValue $tenantDatabaseName -WarningAction Ignore
# Reconfigure the CustomSettings.config to use single-tenant mode
# Set-NAVServerConfiguration -ServerInstance $serverInstance -KeyName Multitenant -KeyValue false -WarningAction Ignore
# Start the server instance.
Set-NAVServerInstance -ServerInstance $serverInstance -Start
# Dismount all tenants that are not using the current tenant database.
Get-NAVTenant -ServerInstance $serverInstance | where {$_.Database -ne $tenantDatabaseName} | foreach { Dismount-NAVTenant -ServerInstance $serverInstance -Tenant $_.Id }
Write-Host "Operation complete." -foregroundcolor cyan

In both scenarios, you can create scripts that are based on these samples, provide value for the variables, run the script, and the review the output to make sure that you achieved the expected result.

Step 3: Change the Client Connection Endpoints

The first sample script creates a new Microsoft Dynamics NAV Server instance with a name that is based on the specified tenant ID. The script only enables the management services endpoint in the Microsoft Dynamics NAV Server configuration settings. You must also configure the server instance to enable client services, SOAP web services, and OData web services. You must send the configuration changes to the users who access the reconfigured tenant. Otherwise, they are not able to connect to the database. For more information, see Managing Microsoft Dynamics NAV Server Instances.

The second sample script illustrates a simpler scenario where you move the application tables to the only database that accessed the application database. As a result, all client endpoints continue as they did before, and you do not have to update any clients.

Step 4: Post-Migration Clean-Up

In the first scenario where you move a tenant from multitenancy to single-tenancy, you must update the Microsoft Dynamics NAV Server account and database permissions. Also, any tenant-specific files that have been saved to the original server location must be moved to the relevant location on the new server.

See Also

Concepts

Migrating to Multitenancy
Separating Application Data from Business Data
Microsoft Dynamics NAV Windows PowerShell Cmdlets


Installation and Configuration Walkthroughs

The walkthrough topics in this section present the various procedures that administrators or Microsoft Certified Partners would have to perform to successfully install the three tiers in the Microsoft Dynamics NAV 2016 Product Architecture.

Note
For assistance with setting up companies after installing and configuring Microsoft Dynamics NAV software, see Set Up a Company With RapidStart Services for Microsoft Dynamics NAV.

In This Section

Walkthrough: Installing the Demo Version

Walkthrough: Installing the Three Tiers On Two Computers

Walkthrough: Installing the Three Tiers on Three Computers

Walkthrough: Installing the Microsoft Dynamics NAV Web Server Components on a Single Computer

Walkthrough: Installing the Microsoft Dynamics NAV Web Server Components on Two Computers

Walkthrough: Installing the Microsoft Dynamics NAV Web Server Components on Three Computers

Walkthrough: Deploying Microsoft Dynamics NAV on a Microsoft Azure Virtual Machine

Walkthrough: Deploying Microsoft Dynamics NAV on Two Microsoft Azure Virtual Machines

Walkthrough: Setting Up Outlook Synchronization

See Also

Tasks

How to: Run Setup
How to: Choose Components to Install
How to: Preconfigure Components

Concepts

Product and Architecture Overview


Walkthrough: Installing the Demo Version

You can install the Demo version of Microsoft Dynamics NAV 2016 to evaluate or learn how to use the product. You should not use the CRONUS International Ltd. demonstration database as the basis for an actual deployed production environment.

Note
Microsoft Dynamics NAV 2016 Setup always installs all components for the demonstration database on a single computer.

Installed Components

The Demo Install includes:

  • The Microsoft Dynamics NAV Windows client

  • Microsoft Dynamics NAV Server

  • Development Environment (C/SIDE)

  • Microsoft Office Outlook Add-in for Microsoft Dynamics NAV

  • SQL Server Database Components

  • CRONUS International Ltd. demonstration database

  • Demo license

Note
If SQL Server 2008 R2, SQL Server 2008, or SQL Server 2012 is present on the computer, and there is an existing SQL Server instance named NAVDEMO, then the CRONUS International Ltd. demonstration database is installed in this instance. Otherwise, Setup automatically installs SQL Server 2012 Express, then creates a NAVDEMO instance, then installs CRONUS International Ltd. demonstration database in this instance.

Recommendations and Constraints

You should consider the following factors before you install and use the Demo Install:

  • The CRONUS International Ltd. demonstration database has not been tested to run side by side with earlier versions of Microsoft Dynamics NAV. We recommend that you do not install the CRONUS International Ltd. demonstration database on a computer that already has an earlier version of Microsoft Dynamics NAV installed.

  • If you want to use the Microsoft Outlook Add-In, then install Outlook before you install the CRONUS International Ltd. demonstration database.

  • If User Account Control is enabled on the computer where you want to install the demonstration database, then right-click Microsoft Dynamics NAV 2016, and then choose Run as administrator to run the Microsoft Dynamics NAV Windows client with administrative credentials.

Running Setup

To install the Demo version of Microsoft Dynamics NAV 2016

  1. Insert the Microsoft Dynamics NAV 2016 DVD, or navigate to the folder containing the Microsoft Dynamics NAV 2016 Setup.exe program.

  2. Run Setup.exe to start the Microsoft Dynamics NAV Setup wizard.

  3. Choose Next to move to the next page.

  4. Choose I accept to accept the license terms.

  5. Choose Install Demo.

  6. When the installation is complete, choose Close.

  7. Choose Start, choose All Programs, and then choose Microsoft Dynamics NAV 2013 to open the RoleTailored client.

Next Steps

You can now work with the CRONUS International Ltd. demonstration database to try the different features with demonstration data.

Note
When you uninstall Microsoft Dynamics NAV 2016, the demonstration database is not removed. You have to remove it manually. For more information, see "Removing the Demo Database" in Modifying, Uninstalling, or Repairing Microsoft Dynamics NAV.

See Also

Concepts

Properties of the Demo License


Walkthrough: Installing the Three Tiers On Two Computers

In this walkthrough, you install a new instance of Microsoft Dynamics NAV 2016 in a production environment with SQL Server and Microsoft Dynamics NAV Server together on one computer and the Microsoft Dynamics NAV Windows client on a second computer.

Computer Installed operating system and software Tier

NAVSERV

Microsoft Windows Server 2008 R2 with the 64-bit edition of Microsoft SQL Server 2008 R2 already installed.

You will install the Microsoft Dynamics NAV Server and Microsoft Dynamics NAV database components on this computer.

Database and Server

NAVCLIENT

Windows 7.

You will install the Microsoft Dynamics NAV Windows client on this computer.

Client

Note
For information on system requirements for Microsoft Dynamics NAV 2016 components, see System Requirements for Microsoft Dynamics NAV 2016.

The key characteristic of this configuration is that the server and database tiers—Microsoft Dynamics NAV Server and SQL Server—are on the same computer. In an actual production environment you would have multiple Microsoft Dynamics NAV Windows clients; you might also have multiple server computers. But installation and configuration issues would be the same as long as the configuration topology was the same: database and Microsoft Dynamics NAV Server installed together on a computer, Microsoft Dynamics NAV Windows clients installed on separate computers.

If you plan on installing each of the three tiers on a separate computer, see Walkthrough: Installing the Three Tiers on Three Computers.

About This Walkthrough

After completing this walkthrough, you will have a functioning three-tier installation on two computers. This installation uses the CRONUS International Ltd. demonstration database.

In this walkthrough, the Microsoft Dynamics NAV Server service runs using the credentials a dedicated domain user account. (“Dedicated” means that this account is reserved exclusively for Microsoft Dynamics NAV Server and for the Microsoft Dynamics NAV instance in SQL Server.) The default in Microsoft Dynamics NAV Setup is for Microsoft Dynamics NAV Server to run using the built-in Network Service account. But this account is considered less secure because it is a shared account: users who have rights to this account have rights to all services that run using this account’s credentials.

This walkthrough illustrates the following tasks:

  • Installing the Microsoft Dynamics NAV 2016 database components with Microsoft Dynamics NAV Server.

  • Configuring Microsoft Dynamics NAV Server to run using the credentials of a dedicated domain user account.

  • Installing the Microsoft Dynamics NAV Windows client.

Prerequisites

To complete this walkthrough, you will need two computers provisioned as described in the introduction.

Although Microsoft Dynamics NAV 2016 Setup will automatically install the 64-bit edition of SQL Server 2012 Express when you install SQL Server Database Components on a computer without any other version of SQL Server, the Express version is not recommended for production environments. For that reason, this walkthrough assumes that you have installed a non-Express version of SQL Server 2008 R2, and then created a SQL Server instance named NAVDEMO, before you begin. For information on how to install SQL Server, see Installation Considerations for Microsoft SQL Server.

Story

A consultant wants to install Microsoft Dynamics NAV 2016 in a production environment.

  1. She installs Microsoft Dynamics NAV Server, Microsoft Dynamics NAV database components, and the Demo database on a Windows Server 2008 R2 computer (NAVSERV) where she has already installed Microsoft SQL Server 2008 R2. As part of the installation she provides configuration information to allow the server to communicate with the database.

  2. She creates a domain user account in Active Directory and uses Microsoft Dynamics NAV Server Administration tool to configure a Microsoft Dynamics NAV Server instance to run using the account’s domain credentials.

  3. She installs the Microsoft Dynamics NAV Windows client on a Windows 7 computer (NAVCLIENT) and configures it to communicate with Microsoft Dynamics NAV Server.

Installing the Microsoft Dynamics NAV Database Components and Microsoft Dynamics NAV Server

When you run Microsoft Dynamics NAV 2016 Setup, you see a menu of Installation Options. You configure one of those options, the Server Option, to install the SQL Server Database components, the CRONUS International, Ltd., Demo database, and Microsoft Dynamics NAV Server, all at the same time.

To install the Microsoft Dynamics NAV Database Components and Microsoft Dynamics NAV Server

  1. Insert the Microsoft Dynamics NAV 2016 DVD into the DVD drive of NAVSERV, the server computer where SQL Server is already installed. Or if you are installing over your network, navigate to the directory containing the Microsoft Dynamics NAV 2016 Setup program and run Setup.exe, the Microsoft Dynamics NAV Setup wizard.

  2. On the introductory pane, choose Next.

  3. To accept the license terms, choose I accept.

  4. On the Microsoft Dynamics NAV Setup pane, choose Choose an installation option.

  5. On the Choose an installation option pane, choose the word Customize that is underneath the Server option

    Configure Server option

  6. On the Customize the installation pane, click within the SQL Server Database Components box and select Run all from my computer.

    Add Database Components to the Install

    This specifies that you want to install this component and all sub-components. In this case, there is a single sub-component: the Demo database.

  7. Choose Next to proceed to the Specify parameters pane.

    There are many parameters that you can configure here, but default parameters are provided for all but one of the required parameters—SQL Server. Setup needs to know which computer you have installed SQL Server on.

    Note
    An asterisk (*) before a parameter field indicates that it is a required parameter for Setup.

  8. Type localhost in the SQL Server field. Then choose Apply.

    Setup warns you that some parameters are missing.

  9. Choose OK to dismiss the dialog box.

    Setup now begins copying software.

  10. After the installation is complete, choose Close to exit Setup.

Configuring Microsoft Dynamics NAV Server to Run Using the Credentials of a Dedicated Domain User Account

The steps for creating a domain user account using the Active Directory Users and Computers utility (dsa.msc) are available as part of the online Windows Server 2008 and Windows Server 2008 R2 documentation. See Create a New User Account. Only network administrators can perform this task.

After you create the account, you must give it the necessary permissions and privileges to interact securely with Microsoft Dynamics NAV clients and SQL Server databases. To do this, complete the procedures in Provisioning the Microsoft Dynamics NAV Server Account.

After your account is created and provisioned, use the following procedure to configure a Microsoft Dynamics NAV Server instance to use a domain user account. This procedure assumes the default Microsoft Dynamics NAV Server instance since this instance is always present. It would work as well for any other instance you create. See Managing Microsoft Dynamics NAV Server Instances.

To configure a Microsoft Dynamics NAV Server instance to use a domain user account

  1. Start Microsoft Dynamics NAV Server Administration tool: Choose Start, and in the Search programs and files box, enter Microsoft Dynamics NAV Administration, and then choose the related link.

    The Microsoft Dynamics NAV Server Administration tool is one of the default components for the Microsoft Dynamics NAV Server Option. If you have followed the installation steps above, Microsoft Dynamics NAV Server Administration tool should be installed on the server computer.

  2. In Microsoft Dynamics NAV Server Administration tool, choose the triangle to the left of the local computer to display any instances on the server computer:

    Console root with two server instances

  3. Right-click the default instance (in the left pane) and select Log on Account.

  4. Choose the Edit button at the bottom of the pane.

  5. In the Service Account field, select User Account.

  6. In the remaining fields, type the account’s User name, Domain, and the Password, respectively. Retype the password in the Confirm Password field.

  7. Choose Save.

  8. You must now restart the Microsoft Dynamics NAV Server instance to activate the new log in account. In the left pane of the Microsoft Dynamics NAV Server Administration tool, select the Microsoft Dynamics NAV Server computer.

    Except when administering a remote computer, this is named Dynamics NAV (Local).

  9. In the center pane, right-click the instance and choose Restart.

Installing the Microsoft Dynamics NAV Windows client

The final task is to install the Microsoft Dynamics NAV Windows client to NAVCLIENT, a Windows 7 computer.

To install the Microsoft Dynamics NAV Windows client

  1. On NAVCLIENT, the Microsoft Dynamics NAV client computer running Windows 7, navigate to the Setup media directory containing the Microsoft Dynamics NAV 2016 Setup program and run Setup.exe, the Microsoft Dynamics NAV Setup wizard.

  2. Under Install, choose Microsoft Dynamics NAV.

  3. On the introductory pane, choose Next.

  4. On the Microsoft Software License Terms pane, review the software license, and then choose I accept.

  5. On the Microsoft Dynamics NAV Setup pane, choose Choose an installation option.

  6. On the Choose an installation option pane, choose Client.

  7. On the Specify Parameters pane, type the name of the Microsoft Dynamics NAV Server computer, which is NAVSERV, in the Server Name box.

    Note
    You can leave all other parameters set to their default values.

  8. Choose Apply.

  9. On the Specify parameters pane, choose Install to begin installing software.

  10. After the installation is complete, choose Close to exit Setup.

Next Steps

Software installation is now complete. When you start the Microsoft Dynamics NAV Windows client it should connect to the Microsoft Dynamics NAV Server and inform you that you are connected to CRONUS International, Ltd. This the fictional company associated with the demo database.

The next steps are to upload your license (see How to: Upload the License File), create users (see How to: Create Microsoft Dynamics NAV Users), and integrate them into the Microsoft Dynamics NAV security system (see Managing Users).

See Also

Tasks

Walkthrough: Setting Up Outlook Synchronization
How to: Upload the License File
How to: Create Microsoft Dynamics NAV Users

Concepts

Product and Architecture Overview
Configuring Microsoft SQL Server
Configuring Microsoft Dynamics NAV Server
Configuring the Windows Client
Installation Considerations for Microsoft SQL Server
Security and Protection


Walkthrough: Installing the Three Tiers on Three Computers

In this walkthrough, you will install Microsoft Dynamics NAV 2016 in a production environment, with each of the three Microsoft Dynamics NAV tiers (client, server, database) on a separate computer:

Computer | Installed operating system and software | Tier
NAVSQL | Microsoft Windows Server 2008 R2 with the 64-bit edition of SQL Server 2008 R2 installed. You will install Microsoft Dynamics NAV database components on this computer. | Database
NAVSERV | Microsoft Windows Server 2008 R2. You will install Microsoft Dynamics NAV Server on this computer. | Server (middle)
NAVCLIENT | Windows 7. You will install the Microsoft Dynamics NAV Windows client on this computer. | Client
Note
For information on system requirements for Microsoft Dynamics NAV 2016 components, see System Requirements for Microsoft Dynamics NAV 2016.

The key characteristic of this walkthrough is that the Microsoft Dynamics NAV Windows client, Microsoft Dynamics NAV Server, and SQL Server are installed on separate computers. In a production environment, you may have multiple computers running SQL Server, multiple computers running Microsoft Dynamics NAV Server, and multiple computers running the Microsoft Dynamics NAV Windows client. When any client user is accessing Microsoft Dynamics NAV Server on a remote computer and SQL Server on a different remote computer, the procedures and issues presented in this walkthrough apply.

For information about how to configure deployments where Microsoft Dynamics NAV Server and SQL Server are installed on a single computer, see Walkthrough: Installing the Three Tiers On Two Computers.

Domain User Account vs. Network Service

In this walkthrough, the SQL Server service and Microsoft Dynamics NAV Server share a domain user account. No other application or service uses this account.

You could run SQL Server or Microsoft Dynamics NAV Server using the credentials of the Network Service account. But this is considered less secure because the Network Service account is a shared account that can be used by other unrelated network services. Any users who have rights to this account have rights to all services that are running on this account. Running SQL Server and Microsoft Dynamics NAV Server under a dedicated domain user account is more secure but requires more work by a domain administrator, as described in this walkthrough.

About This Walkthrough

After completing this walkthrough, you will have a functioning three-tier installation on three computers. The installation uses the CRONUS International Ltd. demonstration database, which contains the CRONUS International Ltd. company.

This walkthrough illustrates the following tasks:

  • Installing the Microsoft Dynamics NAV database components.

  • Installing Microsoft Dynamics NAV Server.

  • Configuring Microsoft Dynamics NAV Server to run using the credentials of a dedicated domain user account.

  • Installing the Microsoft Dynamics NAV Windows client.

Prerequisites

To complete this walkthrough, you need three computers that are configured as described in the introduction.

If SQL Server is not present on the computer where you install the SQL Server Database Components, then Setup automatically installs the 64-bit edition of SQL Server Express 2008 R2, which you can use for prototyping, developing, and testing. We recommend that you use SQL Server 2008 R2 in production environments. For that reason, this walkthrough assumes that you have installed a non-Express version of SQL Server 2008 R2, and then created a SQL Server instance named NAVDEMO, before you begin. For more information, see Installation Considerations for Microsoft SQL Server.

Story

A consultant wants to install Microsoft Dynamics NAV 2016 in a production environment.

  • She installs Microsoft Dynamics NAV database components on a Windows Server 2008 R2 computer (NAVSQL) where she has already installed Microsoft SQL Server 2008 R2.

  • She installs Microsoft Dynamics NAV Server on a Windows Server 2008 R2 computer (NAVSERV).

  • She creates a domain user account in Active Directory and uses Microsoft Dynamics NAV Server Administration tool to configure a Microsoft Dynamics NAV Server instance to run using that account’s credentials.

  • She installs the Microsoft Dynamics NAV Windows client on a Windows 7 computer (NAVCLIENT) and configures it to communicate with Microsoft Dynamics NAV Server.

Installing the Microsoft Dynamics NAV Database Components

When you run Microsoft Dynamics NAV 2016 Setup, you see a menu of installation options. You configure the Server Option to install the SQL Server Database components and the CRONUS International Ltd. demonstration database. When Setup is finished, you start the SQL Browser Service on the SQL Server.

To install the Microsoft Dynamics NAV database components and the demo database

  1. Insert the Microsoft Dynamics NAV 2016 installation media in the drive of NAVSQL, which is the computer where SQL Server 2008 R2 is already installed.

  2. On the introductory pane, choose Next.

  3. To accept the license terms, choose I accept.

  4. On the Microsoft Dynamics NAV Setup page, choose Choose an installation option.

  5. On the Choose an installation option page, choose Customize underneath the Server option.

    Configure Server option

  6. On the Customize the installation page, choose the SQL Server Database Components box, and then select Run all from My computer.

    Add Database Components to the Install

    This specifies that you want to install this component and all subcomponents. In this case, there is a single subcomponent, which is the CRONUS International Ltd. demonstration database.

  7. Choose the Server box, and then choose Not Available. Choose the Administration Tool box, and then choose Not Available.

    This excludes server components that you will install later on a different computer.

    Your list of components should now look like this:

    Install database tier without other components

  8. Choose Next.

  9. On the Specify parameters page, do not modify any parameters, and then choose Apply.

    Setup installs the database components.

  10. After the installation is complete, choose Close.

Starting the SQL Server Browser Service on the SQL Server

When you installed the Microsoft Dynamics NAV database components, the CRONUS International Ltd. demonstration database was installed on a database instance named NAVDEMO. Because you are using a named database instance and Microsoft Dynamics NAV Server is on a separate computer, you must enable and start the SQL Server Browser Service on the SQL Server computer to ensure the Microsoft Dynamics NAV Server can connect to the database instance.

To start SQL Server Browser Service

  1. On the computer running SQL Server, run the SQL Server Configuration Manager.

    On the Start menu, in the Search Programs and Files box, type SQL, and then choose SQL Server Configuration Manager.

  2. In SQL Server Configuration Manager, in the navigation pane on the left, choose SQL Server Services.

  3. Right-click SQL Server Browser, and then choose Properties.

  4. On the Service tab in the SQL Server Browser dialog box, set the Start mode to Automatic.

  5. Choose OK to return to the SQL Server Configuration Manager main page.

  6. Right-click SQL Server Browser again, and then choose Start.

Installing Microsoft Dynamics NAV Server

The next step is to install Microsoft Dynamics NAV Server on NAVSERV. This is a different computer from the one where you installed the Microsoft Dynamics NAV database components.

To install Microsoft Dynamics NAV Server

  1. Insert the Microsoft Dynamics NAV installation media into the drive of NAVSERV.

  2. On the introductory page, choose Next.

  3. To accept the license terms, choose I accept.

  4. On the Microsoft Dynamics NAV Setup page, choose Choose an installation option.

  5. On the Choose an installation option page, choose Server.

    In this case, you do not need to customize the parameter list. By choosing Server instead of Customize, you bypass the Customize the installation page.

  6. On the Specify parameters page, type NAVSQL, which is the name of the computer running SQL Server.

    Default values are sufficient for all other parameters.

  7. Choose Apply to save your setting information. Setup installs the components.

  8. After the installation is complete, choose Close.

Configuring Microsoft Dynamics NAV Server to Run Using the Credentials of a Dedicated Domain User Account

The steps for creating a domain user account using the Active Directory Users and Computers utility (dsa.msc) are available in the Windows Server 2008 and Windows Server 2008 R2 documentation. For more information, see Create a New User Account in the TechNet Library. You must be a network administrator to perform this task.

After you create the account, you must give it the necessary permissions and privileges to interact securely with Microsoft Dynamics NAV clients and SQL Server databases. To do this, complete the procedures in Provisioning the Microsoft Dynamics NAV Server Account.

Then follow these steps to configure a Microsoft Dynamics NAV Server instance to use a domain user account. This procedure uses the default Microsoft Dynamics NAV Server instance because this instance is always present. It works for any other instance that you create. For more information, see Managing Microsoft Dynamics NAV Server Instances.

To configure a Microsoft Dynamics NAV Server instance to use a domain user account

  1. Start the Microsoft Dynamics NAV Server Administration tool on NAVSERV, which is the computer running Microsoft Dynamics NAV Server. Choose Start, and in the Search programs and files box, enter Microsoft Dynamics NAV Administration, and then choose the related link.

    Microsoft Dynamics NAV Server Administration tool is a default component for the Server Option.

  2. Choose Microsoft Dynamics NAV (Local), under Console Root, in the left pane of the Microsoft Dynamics NAV Server Administration tool, to display all Microsoft Dynamics NAV instances on the server computer in the center pane:

    Console root with two server instances

  3. In the left pane, choose the default instance, then right-click it, then choose Log on Account.

  4. Choose the Edit button at the bottom of the center pane.

  5. In the Service Account field, choose the drop-down arrow, and then choose User Account.

  6. In the remaining fields, enter the correct values in the User name, Domain, and Password fields. Enter the password again in the Confirm Password field.

  7. Choose Save.

  8. Now restart the Microsoft Dynamics NAV Server instance to enable the new login account. To do this, choose the Microsoft Dynamics NAV Server computer in the left pane.

    Except when you are administering a remote computer, this is Dynamics NAV (Local).

  9. In the center pane, right-click the instance, and then choose Restart.

Installing the RoleTailored Client

The final task is to install the Microsoft Dynamics NAV Windows client to NAVCLIENT, which is a computer running Windows 7.

To install the RoleTailored client

  1. Insert the Microsoft Dynamics NAV installation media into the drive of NAVCLIENT.

  2. On the introductory page, choose Next.

  3. To accept the license terms, choose I accept.

  4. On the Microsoft Dynamics NAV Setup page, choose Choose an installation option.

  5. On the Choose an installation option page, choose Client.

  6. On the Specify parameters page, in the Server Name field, enter NAVSERV, which is the name of the computer running Microsoft Dynamics NAV Server.

    You should fully qualify the domain name in this field in the form YourServer. YourDomain. YourCompany.com.

  7. Choose Apply to begin install the components.

  8. After installation is complete, choose Close.

Establishing a Connection

The configuration is now complete. You should be able to start the RoleTailored client and connect to the CRONUS International Ltd. demonstration database.

If you cannot connect the Microsoft Dynamics NAV Windows client to Microsoft Dynamics NAV Server after completing this procedure, then the problem may be that Microsoft Dynamics NAV Server is not able to establish a connection to SQL Server. For more information, see Troubleshooting: SQL Server Connection Problems.

Next Steps

You have now installed all Microsoft Dynamics NAV components. When you start the Microsoft Dynamics NAV Windows client, it connects to Microsoft Dynamics NAV Server and to CRONUS International Ltd., which is the demonstration company that is associated with the demonstration database.

The next steps are to upload your license, create users, and integrate them into the Microsoft Dynamics NAV security system. For more information, see How to: Upload the License File, How to: Create Microsoft Dynamics NAV Users, and Managing Users.

See Also

Tasks

How to: Upload the License File

Concepts

Product and Architecture Overview
Configuring Microsoft SQL Server
Configuring Microsoft Dynamics NAV Server
Configuring the Windows Client


Walkthrough: Setting Up Outlook Synchronization

You can synchronize data, such as to-dos, contacts, and tasks, between Microsoft Dynamics NAV and Microsoft Outlook. This allows users who rarely connect to Microsoft Dynamics NAV, such as salespeople who frequently work away from the office, to keep their data synchronized. For example, a sales manager can set a meeting for a salesperson as a to-do in Microsoft Dynamics NAV. That salesperson can then view or modify the meeting in Outlook. A salesperson can also add a new contact in Outlook. That contact is then added to the company's Microsoft Dynamics NAV database.

You define the mapping between Microsoft Dynamics NAV entities and Outlook items in Microsoft Dynamics NAV. You then specify the entities that users synchronize.

The Microsoft Outlook Add-In for Microsoft Dynamics NAV is required to set up and use synchronization. Outlook must be set up and configured for users before you install the add-in. If it is not, then the add-in may not display correctly. You must also set up a web service.

About This Walkthrough

This walkthrough illustrates the following tasks:

  • Setting up Microsoft Dynamics NAV synchronization in a multiple-user environment.

  • Configuring Microsoft Dynamics NAV for Outlook synchronization.

  • Mapping Microsoft Dynamics NAV entities to Outlook items, which lets you:

    • Assign synchronization entities to synchronization users.

    • Apply change log settings.

  • Setting conditions for entities.

  • Setting up a web services connection between Outlook and Microsoft Dynamics NAV.

  • Configuring synchronization in Outlook, which lets you:

    • Apply synchronization settings.

    • Establish the connection using web services.

    • Set up synchronization folders.

    • Set a filter to exclude Outlook contacts from synchronizing with Microsoft Dynamics NAV.

    Note
    After you have set up and configured Outlook synchronization, you can test your setup by performing the steps that are described in.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Outlook 2013 or Microsoft Outlook 2010 installed and configured for you as a user on a client machine. Outlook integration requires the 32-bit version of Outlook.

  • Microsoft Office Outlook Integration, installed on the Microsoft Dynamics NAV Server.

  • Microsoft Office Outlook Add-in, installed with the Microsoft Dynamics NAV Windows client.

For more information, see How to: Choose Components to Install and System Requirements for Microsoft Dynamics NAV 2016.

Setting Up Synchronization for a Single User on a Single Computer

This walkthrough describes how to set up and use the Outlook add-in for a single user on a single computer. You can also set up and use the Outlook add-in for multiple users on a single computer, using tools such as Terminal Services. You should follow these steps before you use the Outlook add-in in this environment.

  1. Ensure that Outlook is correctly installed and configured for all users who need the add-in.

  2. Install the Outlook add-in from the Microsoft Dynamics NAV product media and make sure that the installation is for all users.

For best results, install Microsoft Dynamics NAV 2016 and the Outlook add-in on a machine that has not previously had Microsoft Dynamics NAV installed and then uninstalled on it.

Configuring Microsoft Dynamics NAV for Outlook Synchronization

In this walkthrough, before you set up synchronization, make sure that the correct permissions are set up.

Note
In a production environment, you can specify any permission set that lets you add a salesperson and modify data in the Outlook Synch. Entities and Outlook Synch. User Setup tables.

To define synchronization users

  1. Start the Microsoft Dynamics NAV Windows client.

  2. In the Search box, enter Users, and then choose the related link.

  3. If you are not already listed in the Users window, then create a new user.

  4. On the User card, in the User Permission Sets FastTab, specify the SUPER permission set. Choose the OK button.

Next, you add yourself as a salesperson in Microsoft Dynamics NAV so that you can assign synchronization entities to yourself and then test your setup.

To add yourself as a salesperson

  1. In the Search box, enter Salespeople, and then choose the related link.

  2. On the Home tab, choose New, and then fill in the following fields in the Salesperson/Purchaser Card card.

    The following table describes the fields.

    Field Description

    Code

    Your initials.

    Name

    Your name as defined in your Outlook profile.

    E-Mail

    Your email address as defined in your Outlook profile.

Mapping Microsoft Dynamics NAV Entities to Outlook Items

You start synchronization setup by identifying the Microsoft Dynamics NAV objects to synchronize. When you open the Outlook Synch. Entity List window for the first time, you may receive a message that asks for permission to connect to a .dll file that is installed with the Outlook add-in. You should choose the option that lets you connect: Allow for this session.

For this walkthrough, you can use the synchronization entities that come with Microsoft Dynamics NAV by default. But you can also customize and add entities. For more information, see How to: Set Up Outlook Synchronization Entities and Define Synchronization with Outlook Items.

To set up default synchronization entities

  1. In the Search box, enter Outlook Synch. Entities, and then choose the related link.

  2. In the dialog box asking for permissions, choose Allow for this session, and then choose the OK button. The Outlook Synch. Entity List window opens.

    The following table lists the default Microsoft Dynamics NAV entities and the Outlook item types to which they map.

    Microsoft Dynamics NAV entity code Description Outlook items

    APP

    To-do type: Meeting

    Meetings

    CONT_COMP

    Contacts: Company

    Contacts

    CONT_PERS

    Contacts: Person

    Contacts

    CONT_SP

    Contacts: Salesperson

    Contacts

    TASK

    To-do type: Blank or Phone

    Tasks

After you have set up entities to synchronize with Outlook items, you assign a user to the entity that the user wants to synchronize. In the following procedure, you assign yourself as the user who is associated with the default entities.

When you are setting up synchronization, you can first assign a user to one or two entities and then continue with the setup to test whether your connection works.

To assign synchronization entities to users

  1. In the Search box, enter Outlook Sync. User Setup, and then choose the related link. The Outlook Synch. User Setup window opens.

  2. Choose New. In the Outlook Synch. User Setup window, choose the User ID field, and then choose your user ID.

  3. Choose the Synch. Entity Code field, and then add synchronization entities in the following order with your user ID:

    1. Add CONT_SP. Leave the No. of Elements field as 0.

    2. Add CONT_PERS. Leave the No. of Elements field as 0.

    3. Add Cont_COMP. Leave the No. of Elements field as 0.

    4. Add APP.

      1. Choose the No. of Elements field to open the Outlook Synch. Setup Details window.

      2. On the Home tab, choose New, choose the line under Outlook Collection, choose Recipients, and then choose the OK button.

      3. Choose the Close button to close the Outlook Synch. Setup Details window.

      4. Choose the Condition field, and enter information in the Filter window.

        The following table describes the information that you have to enter.

        Column Value

        Field Name

        Salesperson Code

        Type

        CONST

        Value

        <salesperson code>

      5. Choose the OK button.

    5. Add Task.

      1. Choose the No. of Elements field to open the Outlook Synch. Setup Details window.

      2. Choose New, choose the line under Outlook Collection, choose Links, and then choose the OK button. Choose the OK button again to close the window.

      3. Choose the Condition field, and enter information in the Filter window.

        The following table describes the information that you have to enter.

        Column Value

        Field Name

        Salesperson Code

        Type

        CONST

        Value

        <salesperson code>

  4. Choose the OK button. Choose the OK button again to close the window.

You must activate the change log to enable tracking of the changes that you made to the synchronization entities.

To apply change log settings

  1. In the Outlook Synch. User Setup window, on the Navigate tab, in the Setup group, choose Register in Change Log Setup. The Outlook Synch. Change Log Set. window opens.

  2. Clear the filter value for Code. This lets you enable the change log for all entities at the same time.

  3. Choose the OK button. Close and reopen the company to enable the change log settings.

    Note
    Run the Outlook Synch. Change Log Set. batch job every time that you add or change a synchronization entity to make sure that changes are collected for the required fields.

Setting Conditions for Entities

You can set conditions for the TASK and APP entities to help limit the tasks and meetings that are included on your Outlook calendar. For example, you can set a condition to retrieve only those meetings and tasks that involve you as the salesperson and that you own. Meetings and tasks must have a Meeting Organizer or Task Owner, so that you must create a condition. If you do not, then you cannot synchronize meetings with Microsoft Dynamics NAV.

To configure conditions

  1. In the Search box, enter Outlook Synch. User Setup, and then choose the related link.

  2. Select the line with the APP entity, and then choose the Condition field.

  3. In the Outlook Synch. Filters window, in the Field Name field, select Salesperson Code. In the Value field, enter the code for the salesperson.

  4. Repeat these steps for the TASK entity.

Setting conditions for other entities is not required, but we recommend doing it to prevent mass data transfer to a local mailbox or a public folder.

Setting Up Web Services Connections

You must set up a web services connection between Microsoft Dynamics NAV and Outlook.

Before starting the next procedure, make sure that you have previously opened the Outlook Synch. Entity List window. When you do this, there is preparation in the background that is needed for the web service to appear in the later steps.

To set up a web services connection

  1. On the computer that is running Microsoft Dynamics NAV Server, verify that web services are running. The web service has to run in English for locale 1033.

  2. In the Search box, enter Web Services, and then choose the related link.

  3. On the Home tab, in the Manage group, choose Edit List.

  4. Choose the DynamicsNAVsynchOutlook service, and then select the Published check box.

Configuring Synchronization in Outlook

You can now start Outlook. By default, the Microsoft Dynamics NAV Synchronization items are on the Add-ins tab.

The following table describes the items on the Synchronization toolbar.

Ribbon command | Description
Synchronize | Start synchronization manually. When you choose this command, synchronization applies to items that have been created or modified since the last synchronization.
Full Synchronization | Synchronize all items.
Settings | Configure synchronization, including automatic synchronization, conflict resolution, and connection, and set folders and filters for synchronization entities.
Troubleshooting | Resolve synchronization issues. If the Troubleshooting icon is red, then you have existing errors that must be fixed.
Connection State | Indicate the status of the connection state between Outlook and Microsoft Dynamics NAV. Choose the command to get a message that describes the status.

Applying Synchronization Settings

You start to establish synchronization settings in the Settings dialog box. You can set synchronization to run automatically and set how frequently that it should run. You can also set how conflicts should be resolved between Microsoft Dynamics NAV and Outlook when changes have been made in each application at the same time.

Because you want to test the synchronization setup manually to make sure that it is working correctly, in this walkthrough, you do not select the automatic synchronization setting. You also do not select the automatic resolution setting.

To set rules for synchronization

  1. In Outlook, on the Add-ins tab, choose Settings. The Settings dialog box opens.

  2. On the General tab, select Show synchronization progress and Show synchronization summary.

  3. Select Resolve conflicts manually. Choose the Apply button.

Establishing a Connection Between Microsoft Dynamics NAV and Outlook

On the Connection tab, you must select a type of connection. You must have a working connection before you can create the synchronization settings.

You can be either a Microsoft Dynamics NAV user or a Windows user. A NAV user requires that you supply a username and password.

You follow these steps to establish your web services connection on the NAV Service tier.

Important
When you are connecting to a Microsoft Dynamics NAV Server in Azure, you must specify settings for Internet Explorer.

  1. Open Internet Explorer.

  2. On the Tools menu, and then choose Internet Options.

  3. Choose the Connections tab and choose the LAN Settings button.

  4. Clear the Automatically detect settings check box.

To establish a web services synchronization connection

  1. In the Settings dialog box, choose the Connection tab.

    Specify a Web service path in the Web Service Path text box:

    On premises (default): http://localhost:7047/DynamicsNAV71/WS/Codeunit/DynamicsNAVsynchOutlook

    -or-

    Azure: https://<cloud NST URL>:7047/DynamicsNAV71/WS/Codeunit/DynamicsNAVsynchOutlook

  2. Select an authentication type:

    On premises: Basic or Windows

    -or-

    Azure: Basic

  3. Enter the NavUserPassword credentials for the user whose meetings, tasks, and contacts you are synchronizing from Microsoft Dynamics NAV to Outlook.

  4. In the Company Name box, select CRONUS International Ltd.

  5. Choose the Apply button.

  6. Choose the Test Connection button.

    If your connection succeeds, then you receive a confirmation message. Choose the OK button. The red X is cleared from the Connection State button in the Add-ins tab. If your connection does not succeed, then you receive an error message. To resolve the error, stop and start the web service again.

Defining Synchronization Folders

Each Microsoft Dynamics NAV entity must be mapped to folders that you create for synchronization in Outlook. The folders must map to the entity type. For contacts, the folder must be created in Outlook Contacts. For tasks, the folder must be created in Outlook Tasks. If you create a new entity, then you set the Outlook item that the entity maps to. You can verify what Outlook item that you have set by selecting the entity in the Outlook Synch. Entities window in Microsoft Dynamics NAV.

To set folders for synchronization entities

  1. Create a new folder in Outlook for each entity that you have set up for synchronization. For example, create a folder named Company Contacts, and then set the folder to contain Contact Items. The following table lists the default entities and the type of folder to create.

    Microsoft Dynamics NAV entities Outlook folder item types

    Microsoft Dynamics NAV Contacts of the Company type

    Contacts

    Microsoft Dynamics NAV Contacts of the Person type

    Contacts

    Microsoft Dynamics NAV Salespeople

    Contacts

    Microsoft Dynamics NAV Meetings

    Calendar

    Microsoft Dynamics NAV Tasks

    Tasks

  2. In Outlook, in the Settings dialog box, choose the Folders tab.

    The entities that you set for synchronization are displayed in the Synchronization Folders area. If you add a new entity in Microsoft Dynamics NAV, then it is displayed in this list.

  3. Choose the Browse button, and then map each entity to the folder that you created for it. Choose Apply.

To specify which toolbar commands are displayed

  1. In the Settings dialog box, choose the Customize tab.

  2. Choose the Full Synchronization and Synchronize options. Choose the Apply button, and then choose the OK button.

In addition to the options you have chosen, the Settings command is always available on the ribbon.

Setting Filters

You set filters to define any items that you do not want to be synchronized. For example, if you have personal contacts that you do not want to be synchronized with your Microsoft Dynamics NAV contacts, then you can filter for those. In this procedure, you filter to exclude personal contacts from synchronization by excluding contacts that contain home telephone numbers.

To set a filter

  1. In the Settings dialog box, on the Filters tab, on the Microsoft Dynamics NAV Contacts of the Person type line, choose the Edit button.

  2. In the Field Name box, select HomeTelephoneNumber.

  3. In the Condition box, select is not empty, and then choose Add to List.

  4. Choose the Apply button, and then choose the OK button.

  5. On the Microsoft Dynamics NAV Synchronization toolbar, choose the Synchronize button.

    The Synchronization Progress message is displayed. When synchronization is complete, you can view the details for the synchronization.

Next Steps

You have completed the required setup for synchronizing information between Microsoft Dynamics NAV and Outlook. To test your setup, see Walkthrough: Synchronizing Information Between Outlook and Microsoft Dynamics NAV.

See Also

Tasks

Troubleshooting: Microsoft Office Outlook Integration and Synchronization

Concepts

Configuring Microsoft Dynamics NAV
Configuring Microsoft Dynamics NAV Server


Development

Before you begin developing code for Microsoft Dynamics NAV 2016, you should consider the following:

  • How to start learning about C/AL.

  • How to build on your C/AL knowledge.

  • How to build an application by using your knowledge of C/AL.

  • What the differences are between developing applications that run on different clients.

  • What the differences are between developing in Microsoft Dynamics NAV 2016 and earlier versions of Microsoft Dynamics NAV.

  • How to upload and download files between the server and the client.

Developing in Microsoft Dynamics NAV 2016

To See

Learn what you can do with C/AL and where to add C/AL code.

Programming in C/AL

Learn what the C/AL data types are.

C/AL Data Types

Learn how to write C/AL statements and expressions.

  • Statements and Expressions

  • Elements of C/AL Expressions

  • C/AL Simple Statements

  • C/AL Control Statements

Learn about how to debug C/AL.

Debugging

Learn about how to use custom controls with C/AL.

Extending Microsoft Dynamics NAV Using COM

Learn about the Microsoft Dynamics NAV Development Environment and designing applications.

Application Design Overview

Learn about how to use multilanguage functionality.

Multilanguage Development

Learn the differences in how numeric values are sorted.

Sorting Numeric Values

Learn how to use display language-specific strings without modifying code.

CaptionClass Functionality

Learn about how to develop Microsoft Dynamics NAV Web client applications.

Developing for the Microsoft Dynamics NAV Web Client

Learn about how to develop the Microsoft Dynamics NAV Universal App.

Developing for the Microsoft Dynamics NAV Universal App

Learn about differences between developing in Microsoft Dynamics NAV 2016 and earlier versions of Microsoft Dynamics NAV.

Changes in C/AL Behavior and Support from Earlier Versions of Microsoft Dynamics NAV

Learn about how to transfer files between the client and the server.

File Handling

Learn about how to test an application.

Testing the Application


Application Design Overview

Carefully planning the details of your database application will help to ensure that your database has the best possible design. An application that has been correctly designed is easier to build and maintain. This section contains guidelines for creating applications by using the methods of analysis, design, and implementation.

Steps in Designing a Microsoft Dynamics NAV Application

Designing a Microsoft Dynamics NAV application usually includes the following steps:

  1. Understanding the problem.

  2. Designing the data model (tables, fields, relationships, and constraints).

  3. Designing the application.

Understanding the Problem

First, you must understand the business problem that you want your application to solve. You may want to know who will be using the application and what they will be trying to accomplish. For more information about gathering information and using that information to plan your design, see Developing a Database Plan (SQL Server).

Designing the Data Model

After you understand the problem that you want your application to solve, you must design the structure of the database for your application. For more information about how to design the data model, see the following topics:

  • Designing Databases (SQL Server)

  • Database Basics (SQL Server)

One consideration when you design your data model is data integrity. Enforcing data integrity guarantees the quality of the data in the database. You must consider how to define and enforce the following:

  • Unique values in identifier columns of a table.

  • Valid data types in each field of a table.

  • Consistency across tables.

  • Other constraints that are specific to your application.

For more information about data integrity, see the following topics:

  • Data Integrity (SQL Server)

  • Table Keys

  • Field Data Types

  • Triggers Overview

Designing the Application

After you have a design for your database, you can begin to design the application itself. Designing the application involves:

  • Creating table objects in Microsoft Dynamics NAV to implement the design of your database.

  • Designing pages for entering and retrieving data, and reports for viewing and presenting data.

  • Creating C/AL code to connect the application objects.

  • Designing objects or writing code to extend functionality or to integrate your application together with other systems.

For more information about how to design your application, see the following topics:

  • Designing Application Objects

  • Programming in C/AL

  • Objects

  • Web Services

  • Extending Microsoft Dynamics NAV

See Also

Concepts

Development


Designing Application Objects

All Microsoft Dynamics NAV applications are based on the following types of application objects.

Application object Description

Tables

You use tables to store data. For example, a business application may contain a customer table that stores information about each customer, such as, name, address, telephone number, and contact person.

Reports

You use reports to present data. You use filters and sorting to select the data that you want to present in a report.

XMLports

You use XMLports to import and export data in .xml, .txt, or .csv format.

Codeunits

A codeunit contains user-defined functions that are written in C/AL code. You can use the functions in a codeunit from the other objects in your application.

MenuSuites

A MenuSuite object contains the set of menus that are displayed in the navigation pane.

Pages

Pages display data from the database and allow users to enter new data into the database.

Note
Every application object is identified by an ID number. However, there are restrictions about which numbers you should use when you create your own application objects. Contact your Microsoft Certified Partner for more information.

Queries

A query specifies a set of data from the database.

You use the Microsoft Dynamics NAV Development Environment to create business applications. Object Designer is a tool in the development environment that you use to design application objects in Microsoft Dynamics NAV. Object Designer lets you do the following:

  • Design new tables, reports, XMLports, codeunits, MenuSuites, pages, and queries.

  • View existing application objects.

  • Modify existing application objects.

  • Run application objects.

Microsoft Dynamics NAV Object Designer

With the exception of MenuSuite objects, you can work on any number of application objects at the same time, each in its own designer. This means that you can run multiple instances of these designers. For example, if you work on three new pages at the same time, then each page is displayed in its own Page Designer window. However, you can only run one instance of Object Designer.

Elements of Microsoft Dynamics NAV Objects

Properties

Properties control the appearance and behavior of the application objects and data. For more information, see Properties.

Triggers

A trigger activates a function when a certain event occurs on an application object. The event and the function together make a trigger. You can add C/AL code to the trigger to modify the default behavior of the application object or extend its functionality. For more information, see Triggers.

Keys

Keys define the order in which data is stored in your tables. You can speed up searches in tables by defining several keys which sort information in different ways. For more information, see Table Keys.

Fields

A field on a table is a building block in the database that stores a piece of data. A field typically stores information such as a name or a number. For more information, see Overview of Tables.

Object Designer and MenuSuite Objects

When you choose the MenuSuite button in Object Designer, select a MenuSuite object and then choose Design, the content of the object is displayed in Navigation Pane Designer. This is where you modify the content.

When you choose the MenuSuite button and then choose New, a dialog opens asking you to specify which menu suite level (for example, Developer or Administrator) that you want to create. If you have created a MenuSuite object for each level that you have permissions for, then the New button is disabled. This is because only one MenuSuite object is allowed per level. After you have made a selection, the Navigation Pane Designer opens and you have the appropriate design permissions.

Object-Oriented vs. Object-Based

The Microsoft Dynamics NAV Development Environment is not object-oriented but object-based. This is an important distinction. In an object-oriented language or environment, a developer can create new types of objects based on the ones already in the system. In Microsoft Dynamics NAV, you can only create objects that are either tables, reports, XMLports, codeunits, MenuSuites, pages, or queries.

Standard Microsoft Dynamics NAV Version Conventions

The following illustration shows the version convention that is used in Microsoft Dynamics NAV.

NAV Versioning Convention

Product family code, country/region reference, major version, and minor version are required. Service pack and hotfix are optional.

Standard Object with Local Functionality Modifications Version Convention

A standard object with local functionality modifications contains the following version strings.

  • A standard object version string.

  • A local functionality version string.

The following example shows a standard object with local functionality modifications.

NAVW15.00.01.01, NAVFR4.00.02.02

This version string contains the following information:

  • The object is based on a standard (W1) object and has been modified to support local functionality.

  • The W1 object was created or last changed with Microsoft Dynamics NAV 5.0 with W1 Service Pack 1 and W1 hotfix 1.

  • The local functionality that is contained in the object was created or last changed in Microsoft Dynamics NAV 4.0 for France with the local Service Pack 2 and local hotfix 2.

Microsoft CertifiedPartner Object Version Convention

Microsoft Certified Partners must follow the same version convention. Instead of using the two-letter country/region code, partners should use two letters that refer to their company. For example, the Fabrikam Company would use FC as their code. The rest of the version information should be updated as appropriate.


Using the Development Environment from the Command Prompt

You can start the Microsoft Dynamics NAV Development Environment by running finsql.exe at the command prompt. You can also use the finsql.exe command to perform the following development tasks without using the development environment:

  • Create databases

  • Upgrade databases

  • Compile objects

  • Delete objects

  • Export objects

  • Import objects

  • Export language modules

  • Import language modules

  • Export text strings for translation

  • Import translated text strings

  • Build metadata for application objects.

  • Set the object cache.

  • Set the temporary file location.

  • Set the path and file name of the ZUP file for storing setup parameters.

  • Get the Microsoft Dynamics NAV build version.

By default, finsql.exe is located at C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client\.

Finsql.exe Command Syntax

The finsql.exe has the following syntax.

Copy Code
Finsql.exe [command=<command> | designobject=<object type> <object ID>,] [servername=<server>,] [database=<database>,] [collationname=<collation>,] [file=<file>,] [filter=<filter>], [importaction=<default|overwrite|skip|0|1|2>,] [langid=<ID>,] [logfile=<logfile>,] [navservername=<name>,] [navserverinstance=<instance>,] [navservermanagementport=<port>,] [ntauthentication=<yes|no|0|1>,] [objectcache=<cache>,] [password=<password>,] [temppath=<path>,] [tenant=<tenant ID>,] [username=<user name>,] [synchronizeschemachanges=<yes|no|force>, ] [useoldeditor=<yes|no>]

Syntax Key

The following table describes the notation that is used to indicate syntax.

Notation | Description
Text without brackets | Parameters that you must type as shown.
<> | A placeholder for values that you must supply. Do not include the brackets in the value.
[ ] | Optional parameters. Do not include the brackets.
| | A set of values from which to choose. Use one of the options and do not include | in the value.

Information about building commands

  • The parameters that you use will depend on the command that you are running as determined by the command and designobjects parameters.

  • You can place parameters in any order after finsql.exe.

Finsql.exe Parameters

The following table describes the parameters that you can use with finsql.exe.

Parameter Description Related command

collation

The collation to use when you create a new database. The value must be one of the following:

  • A full language culture name. For example, da-DK for Danish or hu-HU for Hungarian.

  • A SQL Server collation name without case or accent. For example, Latin1_General_100.

  • A SQL Server collation name with case and accent. For example, Danish_Greenlandic_100_CS_AI.

Use this optional parameter when you create a database with the command=createdatabase parameter.

CreateDatabase

command

The development command that you want to run. The possible values are as follows:

  • BuildVirtualMetadata

  • CreateDatabase

  • UpgradeDatabase

  • CompileObjects

  • DeleteObjects

  • ExportObjects

  • ImportObjects

  • ExportLangModule

  • ImportLangModule

  • ExportTranslate

  • ImportTranslate

  • GetBuildVersion

If you specify this parameter and run a command, then the development environment does not open.

Not applicable

database

If you use the command=CreateDatabase parameter, then the database parameter specifies the name of the new database that you want to create. In this case, the database parameter is required.

For all other commands, the database parameter specifies the database that you want to open.

If you do not specify both the servername and the database parameter, then the database server and database that are stored in the .zup file are used. If you do not specify the database parameter but you do specify the servername parameter, then the Open Database window opens so that you can specify the database name.

For more information, see Saving Setup Parameters in the Zup File.

All

designobject

The type and ID of the object that you want to design. The possible values of the object type are as follows:

  • Table

  • Page

  • Report

  • Codeunit

  • Query

  • XMLport

The possible values of the object ID are 0 and any ID of an existing object. If you specify 0 for the object ID, then you open a new object to design.

For more information, see DesignObject.

Not applicable

file

The path and file name of the file that is used exporting data to or importing data from . The file type depends on the command.

CreateDatabase

ExportObjects

ImportObjects

ExportLangModule

ImportLangModule

ExportTranslate

ImportTranslate

filter

A filter on the Object table.

Use this parameter to specify which objects the command applies to.

CompileObjects

CreateLanguage

ExportObjects

ExportTranslate

id

Specifies the path and file name of the .zup file for storing setup parameters. By default, the setup parameters are stored in and retrieved from the fin.zup file. If you specify the id parameter, then the setup parameters are stored in and retrieved from a file that is named <id>.zup.

By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\. To change the location of the .zup file, specify the path and ID in the id parameter.

For example, the following command sets the path and file name of the .zup file to C:\mynavfin.zup:

Copy Code
finsql.exe id="C:\mynavfin.zup"

For more information, see Saving Setup Parameters in the Zup File.

None. You use this as a stand-alone parameter with the finslg.exe.

importaction

Specifies how to handle conflicts with existing objects when you import from a .fob file. The possible values are:

  • default or 0 (default) - If there is a conflict, then an error is logged in the log file and no objects from the file are imported.

  • overwrite or 1 - If there is a conflict, then overwrite the existing object with the object in the import file.

  • skip or 2 - If there is a conflict, then skip the object. The existing object remains unchanged.

ImportObjects

langid

Specifies the standard Windows three-letter ID of the language.

CreateLanguage

ExportLangModule

logfile

Specifies the path and file name for the file that contains error messages that result from running finsql.exe with the command parameter. If there are no errors, then a log file is not created.

All

navservername

Specifies the name of the server that hosts the Microsoft Dynamics NAV Server instance, such as MyServer.

CompileObjects

DeleteObjects

ImportObjects

navserverinstance

Specifies the Microsoft Dynamics NAV Server instance that is being used, such as DynamicsNAV90.

CompileObjects

DeleteObjects

ImportObjects

navservermanagementport

Specifies the port on the Microsoft Dynamics NAV Server that the Microsoft Dynamics NAV Windows PowerShell cmdlets access, such as 7045.

CompileObjects

DeleteObjects

ImportObjects

ntauthentication

Specifies if you want to use NT authentication. The possible values are yes, no, 1, or 0. If you specify the username and password parameters, then you must specify ntauthentication=no or ntauthentication=0.

All

objectcache

Specifies the size of the object cache, in kilobytes. Objects such as code, descriptions, and windows that are used on the computer that is running the development environment are stored in the object cache.

The default value is 32000.

For example, the following command sets the object cache to 50000:

Copy Code
finsql.exe objectcache=50000

You can also set the object cache from the Options window in the Tools menu of the development environment. For more information, see Options,

None. You use this as a stand-alone parameter with the finsql.exe.

password

Specifies the password to use with the username parameter to authenticate to the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

All

servername

Specifies the name of the database server.

If you do not specify both the servername parameter and the database parameter, then the database server and database that are stored in the .zup file are used. If you do not specify the servername parameter but you do specify the database parameter, then the Open Database window opens so that you can specify the database server name.

For more information, see Saving Setup Parameters in the Zup File.

All

temppath

Specifies the path of the location to store temporary files that are created while Microsoft Dynamics NAV runs. These files are automatically deleted when Microsoft Dynamics NAV is closed.

By default, these files are put in the Temp folder for the user, such as <C:\Users\<user name>\AppData\Local\Temp\>.

For example, the following command sets the temporary file path to C:\Temp:

Copy Code
finsql.exe temppath="c:\temp"

You can also set the temporary file path from the Options window in the Tools menu of the development environment. For more information, see Options,

None. You use this as a stand-alone parameter with the finsql.exe.

tenant

Specifies the ID of the tenant that is accessed when you run objects from the development environment. If your solution is not set up to deploy in a multitenant deployment architecture, leave the parameter empty.

CompileObjects

DeleteObjects

ImportObjects

useoldeditor

Specifies whether to use the C/AL Editor that was available in Microsoft Dynamics NAV 2015 and earlier versions. The C/AL Editor was redesigned in Microsoft Dynamics NAV 2016.

To use the old editor, specify the parameter as useoldeditor=yes or useoldeditor.

To use the new editor, omit the parameter or specify it as useoldeditor=no.

None. This parameter is not relevant when you use command because the development environment does not open.

username

The user name to use to authenticate to the database. The user name must exist in the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

Warning
If User Access Control (UAC) is turned on and you do not specify to run the Command Prompt window as Administrator, then the Command Prompt window runs as a standard user. In this case, if you do not specify the username parameter and the current Windows user is an Administrator, then the command is run as the standard user.

If you specify the username parameter, then you must also specify the password parameter and the ntauthentication parameter must be no or 0.

For more information about database users and permissions, see Setting Database Owner and Security Administration Permissions.

All

See Also

Concepts

Development Environment Commands
Saving Setup Parameters in the Zup File
Designing Application Objects


Programming in C/AL

This section describes where to write C/AL code and how to reuse code.

For more information about how to use system-defined variables, see System-Defined Variables.

For more information about the most frequently used C/AL functions, see Essential C/AL Functions.

Where to Write C/AL Code

Almost every object in Microsoft Dynamics NAV contains triggers where you can add your C/AL code. Triggers exist for the following objects:

  • Tables

  • Table fields

  • Pages, including request pages

  • Reports

  • Data items

  • XMLports

  • Queries

You can initiate the execution of your C/AL code from the following:

  • Actions

  • Menu items

  • Any object that has an instantiation of the object that contains C/AL code. An example of an instantiation is a variable declaration.

    Note
    If the C/AL code is in a local function, then you cannot run it from another object.

Guidelines for Placing C/AL Code

We recommend the following guidelines for C/AL code:

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

  • If you must put code on an object instead of in a codeunit, then put the code as close as possible to the object on which it operates. For example, put code that modifies records in the triggers of the table fields.

Reusing Code

Reusing code makes developing applications both faster and easier. More importantly, if you organize your C/AL code as suggested, your applications will be less prone to errors. By centralizing the code, you will not unintentionally create inconsistencies by performing the same calculation in many places, for example, in several triggers that have the same table field as their source expression. If you have to change the code, you could either forget about some of these triggers or make a mistake when you modify one of them.

See Also

Concepts

System-Defined Variables
Essential C/AL Functions


Standard and User-Defined Functions

To create an application in Microsoft Dynamics NAV, you must make database objects work together. You can use C/AL code to bind all the database objects together to form a unified whole.

When you design professional applications, you often need specialized functions. C/AL lets you create functions that extend the functionality of Microsoft Dynamics NAV. You can create special functions for use anywhere in the database.

C/AL enables you to do the following:

  • Design your own functions.

  • Use standard, built-in functions.

  • Connect database objects.

  • Read, write, and modify data.

Designing Your Own Functions

Although Microsoft Dynamics NAV has many built-in functions, you may want to create your own functions. For example, you will have to develop your own functions when the application that you develop repeatedly uses the same nontrivial processing.

We recommend the following guidelines when you want to create new functions and when you want to create parameters and local variables for a function:

  • Do not move a block of code to a new function unless either the code is nontrivial and the new function is afterward called from more than one location, or the move is required to keep the code clear and manageable.

  • Create only parameters that are required for the function to operate on different data, depending on where it is called from. If a function also changes a global variable, however, then we recommend that you transfer the global variable to the function to indicate that the function will change this variable.

  • Use additional local variables just like you would use them in other development languages and environments.

  • When you create a user-defined function, we recommend that you set the Local Property to Yes unless you want to access the function from outside the object. This makes the code easier to understand because it is clear that the function is not referenced from other objects.

    Note
    When you add a function, the Local property is set to Yes by default.

Important
When you define your own functions, you can give two functions the same name. However, if one function is defined in a report or a page and the other is defined in a table that is referenced by the report or page, you cannot directly invoke the function defined in the report or page. By default, a call to the function invokes the function that is defined in the table. This behavior occurs when the function is called from a source expression or a trigger.

See Also

Concepts

Essential C/AL Functions
C/AL Functions


Statements and Expressions

A C/AL statement is a code instruction that when it is executed, causes operations to occur, which can change one or more variables or initiate read and write transactions to the database.

A C/AL statement is built from expressions.

A C/AL expression is a group of characters (data values, variables, arrays, operators, and functions) that can be evaluated, with the result having an associated data type. An expression is a fundamental C/AL concept. All expressions in C/AL are built from the following:

  • Constants

  • Variables

  • Operators

  • Functions

  • Keywords

For more information about constants, variables, operators, functions, and keywords, see Elements of C/AL Expressions.

Example 1

For this example, consider the following C/AL code.

Copy Code
Amount := 34 + Total;

This line of code is also called a statement. The following table illustrates how the statement can be broken into smaller elements.

Element | Description
34 + Total | An expression. This expression consists of an arithmetic operator (+) and two arguments (34 and Total), which could also be called sub-expressions. Every valid C/AL expression can be evaluated to a specific value.
:= | The assignment operator. When the expression on the right side has been evaluated, this operator is used to assign or store the value in the variable on the left side.
Amount | A variable. Used to reference a memory location where data is stored.

Example 2

An expression can be used as an argument for a C/AL function. Consider the following C/AL statement.

Copy Code
Date := DMY2DATE(31, 12, 2001);

This function takes three simple expressions as arguments: 31, 12, and 2001.

Typical Expressions

Depending on the elements in the expression, the evaluation gives you a value with a C/AL data type. The following table shows some typical expressions.

Expression | Evaluates to | Description
'Welcome to Hawaii' | The string 'Welcome to Hawaii' | Evaluates to itself.
'Welcome ' + 'to Hawaii' | The string 'Welcome to Hawaii' | Evaluates to a concatenation of the two strings.
43.234 | The number 43.234 | Evaluates to itself, a decimal number.
ABS(-7234) | The number 7234 | A function that evaluates to a number.
len1 < 618 | TRUE or FALSE, depending on the value of len1 | A comparison between a variable and a numeric constant, which evaluates to a Boolean value.

These examples show that when C/AL expressions are evaluated, the results have a specific data type. For more information about data types, see C/AL Data Types.


C/AL Data Types

C/AL uses variables to store data of various types. By declaring variables of the correct type, you do the following:

  • Create faster code.

  • Save space.

  • Avoid run-time errors because of overflow.

  • Avoid run-time errors that are caused by impossible type conversions.

For example, if you know that a variable will always contain a number between 0 and 700, then you should use an integer variable instead of a decimal variable. Any calculations that are performed will be faster because four bytes per integer operation are used instead of twelve bytes per decimal operation. However, you must use a data type that can hold every possible value that is needed in your calculations. For example, if you try to store the value 1233.3456 in an integer variable, then the result will be an error.

C/AL Data Types

The following table shows the C/AL data types. All C/AL data types are either fundamental or complex. Some data types can also be divided into other categories.

Data type | Fundamental or complex | Other categories
Action Data Type | Fundamental | Numeric
BigInteger Data Type | Fundamental | Numeric
Byte Data Type | Fundamental | Numeric
Char Data Type | Fundamental | Numeric
Decimal Data Type | Fundamental | Numeric
Duration Data Type | Fundamental | Numeric
EXECUTIONMODE Data Type | Fundamental | Numeric
FILTERPAGEBUILDER Data Type | Complex |
Integer Data Type | Fundamental | Numeric
Option Data Type | Fundamental | Numeric
Code Data Type | Fundamental | String
Text Data Type | Fundamental | String
Boolean Data Type | Fundamental |
Date Data Type | Fundamental |
DateTime Data Type | Fundamental |
Time Data Type | Fundamental |
Automation Data Type | Complex |
BigText Data Type | Complex |
BLOB Data Type | Complex |
Codeunit Data Type | Complex |
DateFormula Data Type | Complex |
Dialog Data Type | Complex |
DotNet Data Type | Complex |
File Data Type | Complex |
FieldRef Data Type | Complex |
GUID Data Type | Complex |
InStream and OutStream Data Types | Complex |
KeyRef Data Type | Complex |
OCX Data Type | Complex |
Page Data Type | Complex |
Query Data Type | Complex |
Record Data Type | Complex |
RecordID Data Type | Complex |
RecordRef Data Type | Complex |
Report Data Type | Complex |
System | Complex |
TableFilter Data Type | Complex |
Variant Data Type | Complex |

Fundamental Data Types

Fundamental data types are designed to store Boolean values, numbers, text, time, and dates.

Action Data Type

The Action data type specifies what action a user performs on a page. The PAGE.RUNMODAL Function and the RUNMODAL Function (Page) return an Action data type value. The possible values are the following:

  • OK

  • Cancel

  • LookupOK

  • LookupCancel

  • Yes

  • No

  • RunObject

  • RunSystem

BigInteger Data Type

The BigInteger data type stores very large whole numbers in range of 9,223,372,036,854,775,807 to 9,223,372,036,854,775,807.

Byte Data Type

The Byte data type stores a single, 8-bit character as a value in the range 0 to 255. This data type can be converted between a number and a character. This means that you can use the same mathematical operators as you can with a variable of a numeric data type.

For example, you can assign a constant string of length 1 to a Byte variable.

Copy Code
B := "A";

You can also assign a single character in a Text or Code data type variable to a Byte variable.

Copy Code
B := S[2];

You can also assign a numeric value to a Byte variable. This will cause the Byte variable to contain the character from the ASCII character set that corresponds to the numeric ASCII code.

Copy Code
C := 65;

Char Data Type

The Char data type stores a single character. This data type can be converted between a number and a character. This means that you can use the same mathematical operators as you can with a variable of a numeric data type.

Decimal Data Type

In the development environment, the Decimal data type represents decimal numbers ranging from -10+E63 to +10+E63. The exponent ranges from -63 to +63. Decimal numbers are held in memory with 18 significant digits. Although you can store decimal numbers ranging from -10+E63 to +10+E63, you cannot specify a number outside the range +/- 999,999,999,999,999.99 in the UI or in code.

In SQL Server, you can store a decimal number with up to 18 digits and 20 decimal place digits. However, if a number is more than 15 digits, then you cannot enter it in SQL Server or view it in the UI.

In the client, you can store a decimal number with up to 29 digits and precision of 18 digits.

In general, we recommend that you construct decimals that operate on numbers in the range of +/- 999,999,999,999,999.99. Although you can construct larger numbers in some cases, overflow, truncation, or loss of precision can occur.

Duration Data Type

The Duration data type represents the difference between two DateTimes, in milliseconds. For example, you can calculate the difference between two DateTimes by running the following code. This example requires that you define the following variables.

Variable | Data type
DateTime1 | DateTime
Datetime2 | DateTime
Duration | Duration

This example is run on a computer that has the Current Format in the Regional and Language Options set to English (United States).

Copy Code
DateTime1 := CREATEDATETIME(010109D, 080000T); // January 1, 2009 at 08:00:00 AM
DateTime2 := CREATEDATETIME(050509D, 133001T); // May 5, 2009 at 1:30:01 PM
Duration := DateTime2 - DateTime1;
MESSAGE(FORMAT(Duration));

The message window displays the following:

124 days 4 hours 30 minutes 1 second

ExecutionMode Data Type

The ExecutionMode data type specifies the mode in which a session is running. The CURRENTEXECUTIONMODE Function (Sessions) returns an ExecutionMode data type value.

The execution mode is one of the following:

  • Debug

  • Standard

Integer Data Type

The Integer data type stores integers between -2,147,483,647 and 2,147,483,647.

Option Data Type

The Option data type represents an option value. The Option type is a zero-based enumerator type. Therefore, you can convert option values to integers. For example, assume that Number is a numeric variable and that Type represents a field of type Option in the Purchase Header table. The following statement converts the option value to a number.

Copy Code
Number := "Purchase Header".Type;

In another example, the following code shows how to use the possible values of an option field as constants.

Copy Code
"Purchase Header".Type := "Purchase Header".Type::Invoice;

Code Data Type

The Code data type represents a special type of text string. When a given text is assigned to a variable of data type Code, the text is changed to uppercase and any leading and trailing spaces are removed. You can index any character position in a string, for example, A[65]. The resulting values will be of the Char data type. The length of a variable of data type Code always corresponds to the number of characters in the text without leading and trailing spaces. If you do not specify the length of a Code variable, then the maximum length is 2GB, which is the limit imposed by Microsoft .NET Framework. The maximum length of a table field of data type Code is 250 characters.

The following table shows some typical examples of Code string assignments. In the following examples, it is assumed that the variable c is of data type Code, and has a maximum length of 4.

Assignment | Variable c contains | Length
c := 'AbC'; | 'ABC' | 3
c := '1'; | '1' | 1
c := ''; | '' (empty string) | 0 (zero)
c := '2'; | '2' | 1
c := '1 2'; | '1 2' | 3

Text Data Type

The Text data type represents a text string. You can index any character position in a string, for example A[65] refers to the 65th character in the variable called A. The resulting values will be of data type Char. The length of a variable of data type Text corresponds to the number of characters in the text. For example, an empty text string has length 0. If you do not specify the length of a Text variable, then the maximum length is 2GB, which is the limit imposed by Microsoft .NET Framework. The maximum length of a table field of data type Text is 250 characters.

The following table shows some typical examples of text strings. In these examples, it is assumed that the variable t is of data type Text and has a maximum length of 6.

Assignment | Result
t := 'AbC' | The variable t now contains "AbC"
t := '123456abx'; | Gives a run-time error because the length (9) exceeds the maximum length (6)

When you use the Text and Code data types, make sure that you distinguish between the maximum length of the string and the actual length of the string. The maximum length is the upper limit for the number of characters in the string. The actual length describes the number of characters that are used in the string. The STRLEN Function (Code, Text) and the MAXSTRLEN Function (Code, Text) illustrate this.

Copy Code
t := 'AbC';
STRLEN(t); // Returns 3.
MAXSTRLEN(t); // Returns 6.
t := '12345';
STRLEN(t); // Returns 5.
MAXSTRLEN(t); // Returns 6.

Boolean Data Type

The possible values of Boolean data types are TRUE or FALSE.

Date Data Type

The Date data type represents dates ranging from January 1, 1753 to December 31, 9999. An undefined date is expressed as 0D. The undefined date is considered to be before all other dates. When you work with dates, you must consider the case in which a date is undefined. For example, if the due date for an invoice is not specified and you create a report that displays all due invoices on a certain date, then you must handle the undefined date. Otherwise, the invoice with the unspecified date will appear to be long overdue, which may not be true.

All dates have a corresponding closing date. The closing date for a given date is regarded as a period following the given date but before the next regular date. A closing date is therefore sorted immediately after the corresponding regular date but before the next regular date.

DateTime Data Type

The DateTime data type represents a date and the time of day. The DateTime is stored in the database as Coordinated Universal Time (UTC). UTC is the international time standard (formerly Greenwich Mean Time, or GMT). Zero hours UTC is midnight at 0 degrees longitude. The DateTime is always displayed as local time in Microsoft Dynamics NAV. Local time is determined by the time zone regional settings that are used by your computer. You must always enter DateTimes as local time. When you enter a DateTime as local time, it is converted to UTC using the current settings for the time zone and daylight saving time.

There is only one constant available when you use this data type: undefined datetime, which is expressed as 0DT.

The earliest permitted DateTime in Microsoft SQL Server is January 1, 1753, 00:00:00.000.

The latest permitted DateTime in Microsoft SQL Server is December 31, 9999, 23:59:59.999.

Any DateTimes that are not within this range and that you try to enter or construct by, for example, adding a DateTime to a Duration, are regarded as undefined DateTimes and give an error message.

Undefined dates in Microsoft Dynamics NAV are stored as January 1, 1753, 00:00:00.000, which is the earliest permitted DateTime in SQL Server.

Time Data Type

The Time data type represents a time ranging from 00:00:00 to 23:59:59.999. An undefined time is expressed as 0T.

Descriptive Data Types

The following table shows the relationship between the descriptive data types and the simple C/AL data types.

Descriptive data type Included system data types

Numeric

  • Byte

  • Char

  • Integer

  • BigInteger

  • Duration

  • Option

  • Decimal

String

  • Text

  • Code

Complex Data Types

Complex data types are used when you want to work with, for example, records in tables, pictures (bitmaps), or disk files. C/AL is object-based so each complex data type can include both member variables and member functions.

C/AL is not object-oriented but object-based. This is an important difference. In an object-oriented language or environment, you can create new types of objects that are based on the ones already in the system. In C/AL, you have the following application objects:

  • Tables

  • Reports

  • Codeunits

  • XMLports

  • MenuSuites

  • Pages

  • Queries

You cannot create any other objects.

Automation Data Type

For more information about the Automation data type, see Extending Microsoft Dynamics NAV Using COM.

BigText Data Type

The BigText data type contains large text documents. Data of the BigText data type cannot be displayed in the debugger or in a message window. However, you can use the BigText functions to extract part of a big text and place it in a typical text string that can be displayed. The BigText functions are as follows:

  • ADDTEXT Function (BigText)

  • GETSUBTEXT Function (BigText)

  • LENGTH Function (BigText)

  • READ Function (BigText)

  • TEXTPOS Function (BigText)

  • WRITE Function (BigText)

The maximum length of a BigText variable is 2147483647 characters. This is the equivalent of 2 gigabytes (GB).

BLOB Data Type

A BLOB is a Binary Large Object. Variables of this data type differ from typical numeric and string data type variables because they have a variable length. BLOBs are used to store memos (text), bitmaps (pictures), or user-defined types. The maximum size of a BLOB is often determined by your system’s disk storage capacity. The upper limit is 2GB.

Codeunit Data Type

The Codeunit data type stores codeunits. A codeunit can contain several user-defined functions.

DateFormula Data Type

The DateFormula data type contains a date formula that has the same capabilities as an ordinary input string for the CALCDATE Function (Date). The DateFormula data type is used to provide multilanguage capabilities to the CALCDATE function.

Dialog Data Type

The Dialog data type stores dialog windows. A number of functions are available for manipulating dialogs.

DotNet Data Type

For more information about the DotNet data type, see Calling .NET Framework Members from C/AL.

File Data Type

The File data type provides access to operating system files.

FieldRef Data Type

The FieldRef data type identifies a field in a table and gives you access to this field. The FieldRef object can refer to any field in any table in the database.

GUID Data Type

The GUID data type gives a unique identifying number to any database object.

The GUID data type is a 16-byte binary data type. This data type is used for the global identification of objects, programs, records, and so on. The most important property of a GUID is that each value is globally unique. The value is generated by an algorithm, developed by Microsoft, which guarantees this uniqueness.

The GUID is a 16-byte binary data type and can be logically grouped into the following subgroups: 4byte-2byte-2byte-2byte-6byte. The standard text representation is {12345678-1234-1234-1234-1234567890AB}.

InStream and OutStream Data Types

The InStream and OutStream data types enable you to read from or write to files and BLOBs. In addition, you can use InStream and OutStream to read from and write to objects of the Automation and OCX data types.

KeyRef Data Type

The KeyRef data type identifies a key in a table and the fields in this key. This gives you access to the key and the fields it contains. The KeyRef object can refer to any key in any table in the database.

OCX Data Type

For more information about the OCX data type, see Extending Microsoft Dynamics NAV Using COM.

Page Data Type

The Page data type stores pages that can contain several simpler elements called controls.

Query Data Type

The Query data type stores queries, which enable you to retrieve data from tables in the database and combine the data in a single dataset.

Record Data Type

The Record data type consists of several simpler elements called fields. A record corresponds to a row in a table. Each field in the record is used to store values of a certain data type. The fields are accessed by using the variable name of the record (often the same as the name of the corresponding table), a dot (a period), and the field name. A record is typically used to hold information about a fixed number of properties.

RecordID Data Type

The RecordID data type contains the table number and the primary key of a table. You can store a RecordID in the database but you cannot set filters on a RecordID.

RecordRef Data Type

The RecordRef data type references a record in a table. Typically you use a RecordRef in functions that must apply to all tables, not to a specific table.

If one RecordRef variable is assigned to another RecordRef variable, then they both refer to the same table instance.

Report Data Type

The Report data type stores reports.

TableFilter Data Type

The TableFilter data type applies a filter to another table. This data type can only be used when you are setting security filters from the Permission table.

Variant Data Type

The Variant data type can contain the following C/AL data types:

  • Record

  • File

  • Action

  • Codeunit

  • Automation

  • Boolean

  • Option

  • Integer

  • Decimal

  • Byte

  • Char

  • Text

  • Code

  • Date

  • Time

  • DateFormula

  • TransactionType

  • InStream

  • OutStream

Arrays of Variables

You can create 10-dimensional variables using the simple and complex data types. There are no limitations on how many elements a dimension can contain but an array variable can never have more than 1,000,000 elements. The physical size of an array is limited to 2 GB (or available memory). Arrays are always indexed with a number for each dimension that ranges from 1 to (and including) the size of the dimension. If you accidentally index outside the range of the dimensions of an array, then a run-time error occurs.

For example, assume that SampleArrayVariable is a one-dimensional array variable of data type Integer, with the dimension 10. To index the first element, use SampleArrayVariable[1]. To index the last element, use SampleArrayVariable[10].

As another example, assume that SampleArrayVariable2 is an array variable of data type Date with the dimensions 2x3x4. SampleArrayVariable2 has 24 elements. To index the first element, use SampleArrayVariable2[1,1,1]. To index the last element, use SampleArrayVariable2[2,3,4].

To declare a variable as an array, open the Properties window for the variable and then set the Dimensions property. For more information, see Dimensions Property.


Type Conversion

This section describes all possible type conversions in C/AL expressions.

To | See
Learn about using expressions to convert types. | Type Conversion in Expressions
Learn about relation operators. | Relational Operators
Learn about Boolean operators. | Boolean (Logical) Operators
Learn about arithmetic operators. | Arithmetic Operators
Gain an overview of type conversion rules for the arithmetic operators. | Type Conversion Rules for Arithmetic Operators

See Also

Concepts

Development


Type Conversion in Expressions

This topic describes type conversions in C/AL expressions.

C/AL Expression Statements and Type Conversion

Consider the following statements.

Copy Code
CharVar := 15; // A char variable
integerVar := 56000; // An integer variable
Sum := CharVar + integerVar;

The last statement involves one or two type conversions. The rightmost statement involves the evaluation of the expression CharVar + integerVar (char + integer). In order to evaluate this expression, the first operand (CharVar) will have to be converted from char to integer. The addition operator will then return an integer result.

If the type of the leftmost variable has been declared as, for example, decimal, the result must be converted from integer to decimal before its value can be assigned to Sum. For more information, see the “Assignment and Type Conversion” section in C/AL Variables.

The following examples illustrate the type conversions which can occur when expressions are evaluated. The following guidelines are used:

  • When asked to evaluate an expression of mixed data types, if it is possible, the system will always convert at least one of the operands to a more general data type.

  • The data types in the two main groups, numbers and strings, can be ranked from "most general" to "least general."

    Data types, grouped from most to least general
  • The most general data types include all the possible values from the less general data types: a decimal is more general than an integer, which is more general than a char.

  • Type conversion can occur in some cases even though two operands have the same type.

These rules can be illustrated by the following examples.

Example 1

The following example shows the evaluation of a numeric expression.

Copy Code
integer + decimal

This expression contains two sub-expressions of different data types. Before it can add these two sub-expressions, the system must convert the leftmost sub-expression to decimal.

Copy Code
decimal + decimal

When the leftmost sub-expression has been converted, the expression can be evaluated, and the resulting data type will be decimal.

Copy Code
decimal + decimal = decimal

Example 2

The following example shows the evaluation of a string expression.

Copy Code
text + code

This expression contains two sub-expressions that must be concatenated. To do this, the system must convert the sub-expression of the least general data type (code) to the most general data type (text).

Copy Code
text + text

When the rightmost argument has been converted, the expression can be evaluated, and the resulting data type will be text.

Copy Code
text + text = text

See Also

Concepts

Type Conversion


Relational Operators

The relational operators are used to compare expressions.

Evaluation Rules for Relational Operators

The following table defines the evaluation rules for relational operators. The rules assume that the data types of the expressions can be compared. For a complete overview of comparable data types, refer to the next section, "Valid Uses of Relational Operators".

Operator | Operator name | Expression | Resulting date type
> | Greater than | Expr > Expr | Boolean
< | Less than | Expr < Expr | Boolean
>= | Greater than or equal | Expr >= Expr | Boolean
<= | Less than or equal | Expr <= Expr | Boolean
<> | Not equal to | Expr <> Expr | Boolean
= | Equal to | Expr = Expr | Boolean
IN | In range | Expr IN [Valueset] | Boolean
Note
When using relational operators, uppercase and lowercase letters in strings are significant. Furthermore, the comparison is based on the built-in character comparison table of the system, that is, not by comparing "true" ASCII characters.

Valid Uses of Relational Operators

The following table describes the valid uses of the relational operators and the data types that result when expressions are evaluated. The invalid combinations of types for relational operators are indicated by a dash. All relational operators are binary infix operators; that is, they take a left and a right argument and are placed between the arguments.

The rows in the table show the type of the left argument and the columns show the type of the right argument. The cells show the resulting data type.

A valid use of the relational operators is, for example, text compared with text or code, while Boolean cannot be compared with anything other than Boolean, and so on.

Relational operator | Boolean | Char | Option | Integer | Decimal | Date | Time | Text | Code
Boolean | Boolean |  |  |  |  |  |  |  |
char |  | Boolean | Boolean | Boolean | Boolean |  |  |  |
option |  | Boolean | Boolean | Boolean | Boolean |  |  |  |
integer |  | Boolean | Boolean | Boolean | Boolean |  |  |  |
decimal |  | Boolean | Boolean | Boolean | Boolean |  |  |  |
date |  |  |  |  |  | Boolean |  |  |
time |  |  |  |  |  |  | Boolean |  |
text |  |  |  |  |  |  |  | Boolean | Boolean
code |  |  |  |  |  |  |  | Boolean | Boolean

See Also

Concepts

Type Conversion


Arithmetic Operators

This topic contains examples of how to use the type conversion rules for arithmetic operators. The examples illustrate how the operators should be used and the effect of the type conversion that the C/AL compiler performs. The examples have been divided into groups corresponding to the data types in C/AL.

Using Type Conversion Rules for Arithmetic Operators

For a full description of the type conversion rules in C/AL, see Type Conversion Rules for Arithmetic Operators, which provides a full description of all the possible uses of C/AL operators and the resulting data types.

Example 1

This table illustrates type conversion in integer operator expressions.

Operator | Name | Expression | Resulting data type
+ | time addition | time + integer | time
- | time difference | time - time | integer

The time unit is milliseconds. If time is undefined (0T), a run-time error will occur.

Example 2

This table illustrates type conversion in text and code (String) operator expressions.

Operator | Name | Expression | Resulting data type
+ | Concatenation | text + text | text
+ | Concatenation | text + code | text
+ | Concatenation | code + text | text
+ | Concatenation | code + code | code

See Also

Concepts

Type Conversion


Boolean (Logical) Operators

Logical operators can only be used with arguments that can be evaluated to Boolean.

Boolean Operators

As the following table shows, the NOT operator is a unary prefix operator. This means that it takes only one argument and is placed in front of the argument. The AND, OR, and XOR operators are binary infix operators; they take two arguments and are placed between the corresponding arguments.

Operator | Name | Expression | Resulting data type
NOT | Logical negation | NOT bool | bool
AND | Logical and | bool AND bool | bool
OR | Logical or | bool OR bool | bool
XOR | Exclusive logical or | bool XOR bool | bool

See Also

Concepts

Type Conversion


Type Conversion Rules for Arithmetic Operators

This topic provides a complete overview of type conversion rules for the arithmetic operators.

Unary Arithmetic Operators

The unary arithmetic operators in C/AL are prefix operators with the following syntax.

Copy Code
PrefixExpression = PrefixOperator Expression

The following table shows the data types for which the unary operators in C/AL are defined, and the resulting data types.

Unary operator | Option | Integer | Decimal
+ | integer | integer | decimal
- | integer | integer | decimal

Binary Arithmetic Operators

The following table shows the data types for which the binary arithmetic operators are defined. The binary arithmetic operators in C/AL are all infix operators.

Copy Code
InfixExpression = LeftExpression InfixOperator RightExpression

Operator | Boolean | Byte | Char | Option | Integer | Decimal | Date | Time | Text | Code
+ | No | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes
- | No | Yes | Yes | Yes | Yes | Yes | Yes | Yes | No | No
* | No | Yes | Yes | Yes | Yes | Yes | No | No | No | No
/ | No | Yes | Yes | Yes | Yes | Yes | No | No | No | No
DIV | No | Yes | Yes | Yes | Yes | Yes | No | No | No | No
MOD | No | Yes | Yes | Yes | Yes | Yes | No | No | No | No

In the table, Yes means that the operator can take at least one operand (left, right, or both) of the given type; No means that the operator cannot be used with the given type.

The following table defines the valid uses of the binary arithmetic operators, and the resulting data types.

Definition of Type Conversion Rules for the "+" Operator

The "+" operator | Boolean | Byte/Char | Option | Integer | Decimal | Date | Time | Text | Code
Boolean |  |  |  |  |  |  |  |  |
Byte/Char |  | Integer | Integer (C) | Integer (C) | Decimal (C) |  |  |  |
Option |  | Integer | Integer (C) | Integer (C) | Decimal (C) |  |  |  |
Integer |  | Integer (C) | Integer (C) | Integer (C) | Decimal (C) |  |  |  |
Decimal |  | Decimal (C) | Decimal (C) | Decimal (C) | Decimal (C) |  |  |  |
Date |  | Date (A) (C) | Date (A) (C) | Date (A) (C) | Date (A) (C) (D) |  |  |  |
Time |  | Time(B) (C) | Time(B) (C) | Time(B) (C) | Time(B) (C) (D) |  |  |  |
Text |  |  |  |  |  |  |  | Text | Text
Code |  |  |  |  |  |  |  | Text | Code

(A) The operation is not defined for the Date 0D.

(B) The operation is not defined for the Time 0T.

(C) Overflow may occur.

(D) The operation is not defined if the Decimal has a fractional part.


Elements of C/AL Expressions

All expressions in C/AL are built from the following:

  • Constants

  • Variables

  • Operators

  • Functions

  • Keywords

The topics in this section describe each of these elements:

  • C/AL Constants

  • C/AL Variables

  • C/AL Operators

  • C/AL Function Calls

See Also

Concepts

C/AL Reserved Words


C/AL Constants

A constant is the simplest type of operand used in C/AL. The value of a constant cannot be changed during the execution of the code. Constants can be defined for each of the simple data types in C/AL.

Note
Numbers such as 2,147,483,647 and 999,999,999,999,999.99 cannot be entered in the C/AL editor in this form that uses commas. The commas are only used to increase the legibility when describing large numbers. If you use commas when you enter numbers in the C/AL editor, a compilation error occurs.

Boolean Constant

A Boolean constant can have either the value TRUE or FALSE.

Integer Constant

An integer constant has a value in the range -2,147,483,647 to 2,147,483,647.

Decimal Constant

A decimal constant must contain a decimal point "." (depending on your regional settings) and have at least one digit to the right of the decimal point (for example, the digit "0"). A constant of type decimal can be used to represent decimal numbers between -999,999,999,999,999.99 and 999,999,999,999,999.99 with 18 significant digits.

Date Constant

A date constant is written as six or eight digits followed by the letter "D." The date constant expressing "undefined date" is entered as "0D." The digits specify the date in the format MMDDYY or MMDDYYYY.

Time Constant

A time constant is written as six or nine digits followed by the letter "T." The "undefined time" constant is entered as "0T." The nine digits specify the time in the format HHMMSS[.XXX], that is, a 24 hour format with an optional part specifying thousandths of a second.

Text Constant

A text constant is a character string. Unique IDs are assigned to text constants so that an ID number represents a specific text constant. Examples of text constants are error messages, messages, and warnings.

Examples

The following table shows examples of different types of C/AL constants.

Note
The format depends on the regional format that is set on your computer. The examples in the table correspond to a computer that has the regional format set to English (United States).

Constant | Description
50000 | Integer constant
-23.7 | Decimal constant
122101D | Date constant (December 21, 2001)
141230T | Time constant (the time 14:12:30)
ABC | Text constant


C/AL Variables

C/AL has the following types of variables:

  • User-defined variables

  • System-defined variables

User-defined variables are variables that you define when you create new C/AL code. You can define variables that are global and apply to all functions in an object, such as a codeunit, or you can define variables that are local and apply to a single function in an object. Both types of user-defined variables are local to the object in which they are defined. These variables can be used to store information at run time, and the values can be changed as desired.

System-defined variables are provided by Microsoft Dynamics NAV. These variables are automatically maintained by the system. Some system-defined variables are Rec, xRec, CurrPage, and CurrReport.

At run time, code is executed in functions and triggers, such as in entry-processing code for a table. Before the code is executed, values are automatically assigned to the associated system-defined variables, and the values of these variables can be used in triggers and local functions.

The values of system-defined variables are not updated when the C/AL code is being executed. Instead, the values are updated before the function or trigger is executed.

Note
The value in a system-defined variable does not propagate backward. A user cannot use a system-defined variable to modify the state of the system.

Variable Names

You must follow the following rules and restrictions when you name variables:

  • Variable names must be unique. A codeunit cannot contain two user-defined variables with the same name in the same scope. You can have a local variable and a global variable with the same name, but we do not recommend this.

  • Uppercase and lowercase letters are not distinct. For example, Smith and SMITH refer to the same variable.

  • In C/AL, you can use special characters such as spaces in the name of a variable (an identifier).

  • The maximum length of a variable name is 128 characters.

  • A variable cannot have the same name as a C/AL function or a reserved word. This applies to both uppercase and lowercase spellings. For example, you cannot use BEGIN or begin as a valid variable name.

All characters in your current ANSI character set are valid in variable names except for the following characters:

  • Control characters (ANSI 0-31, 255)

  • The quotation mark character (") (ANSI 34)

Note
We do not recommend that you use characters that are outside the ASCII characters set, 0-127, because they may display differently on different computers.

Note
Microsoft Dynamics NAV runs on the .NET Framework. Therefore, we recommend that you use variables names that are Common Language Specification (CLS)-compliant. For more information, see Common Language Specification in the MSDN Library.

When you name a variable, you cannot use special characters unless you enclose the variable name in quotation marks, as in "Customer No.". If you do not use double quotation marks, then the following rules apply:

  • The first character must be one of the following:

    • A letter in the range a…z, A…Z (ASCII 97-122, 65-90)

    • An underscore (ASCII 95)

  • The first character is followed by a maximum of 29 characters, which can be any of the following:

    • A letter in the range a…z, A…Z (ASCII 97-122, 65-90)

    • An underscore (ASCII 95)

    • A digits in the range 0…9 (ASCII 48-57)

You can include one or more special characters in a variable name in C/AL. If you include special characters, then the variable name must be enclosed in quotation marks. In this case, the name can contain any mix of letters, digits, and special characters.

Note
The quotation marks are not part of the variable name but are required to successfully compile the codeunit.

Examples

The following examples show valid variable names:

  • Customer

  • StockGroup1

  • "@Vendor"

  • "1st AddressLine"

  • "Purchase/Sales"

  • "Sales in GBP"

  • "Name with Special Characters1Ñ3"

The following examples show incorrect variable names:

  • 34467

  • 23"Tubes

  • Stock Group4

  • "Sale"s in GBP"

  • )-Names

  • END

Initialization

Variables are automatically initialized before C/AL code is executed. A Boolean variable is set to false. Numeric variables are set to the default value zero. Strings (text and code) are initialized to the value '' (an empty string). Date and time variables are set to the undefined time 0T and the undefined date 0D, respectively. Variables of complex data types are also initialized. If a complex data type has multiple components, then each component is initialized to the value that corresponds to the data type for the component.

System-defined variables are automatically handled and initialized. No actions are required by the user before system-defined variables can be used.

Assignment and Type Conversion

You can assign values in the following ways:

  • By using the assignment operator ":=", such as Variable := Expression. The data type that results from the evaluation of the right side expression must be the same data type as the variable (left operand) or have a data type that can be converted automatically to the data type of the left operand.

  • As parameter assignment, such as FUNCTION(Expression). The data type that results from the evaluation of the expression must correspond to a specific data type or have a data type that can be converted automatically to the correct data type. For more information about evaluation and type conversion in expressions, see Type Conversion in Expressions.

Automatic type conversion in assignments occurs when the following events occur:

  • A parameter in a function call does not have the correct data type. For example, this can occur if a function that is supposed to be called by using an integer argument is called by using a DateTime argument.

    Note
    If the value cannot be converted, then a run-time error occurs. If the value can be converted but overflow occurs, then a run-time error occurs.

  • The evaluation of the expression on the right side of an assignment operator (:=) achieves a data type that differs from the data type of the variable on the left side, and the expression can be converted to the data type of the variable.

Automatic type conversion in assignments can occur between the following numeric data types as long as an overflow does not occur:

  • Byte

  • Char

  • Integer

  • Decimal

Automatic type conversion in assignments can occur between the string data types:

  • Code

  • Text

Text can be automatically converted to BigText, but a BigText variable must be split into smaller parts before it can be converted to text.

The same assignment rules apply for arrays in C/AL. Furthermore, if the left operand in an assignment (the variable) is an array, the dimension or dimensions of the right side expression must correspond to the dimension or dimensions of the variable.

Note
The type conversion that occurs in assignments can cause run-time errors even though the data types are convertible. A run-time error can occur in an assignment if the converted value is outside the valid range for the left side variable. Also, a run-time error can occur if the converted value is outside the valid range for a parameter in a function call.

Example 1

The MyVar variable is defined as a one-dimensional array with four text type elements that have the maximum length 15. This example shows that a value can be assigned to the second element in the array.

Copy Code
MyVar[2]:= 'Enter your name';

Example 2

In the following example, the Result variable is an Option variable. The Amount and Total variables are both Decimal variables.

Copy Code
Amount := 10;
Total := 4;
...
Result := Amount + Total;

This code can always be compiled, but a run-time error occurs if the result of the right-side expression "Amount + Total" exceeds the range that is permitted by the data type of the left-side Result variable. For an Option variable, the range is the same as the range of an Integer, which is from -2,147,483,647 to 2,147,483,647. A run-time error also occurs if the result of the right-side expression "Amount + Total" is not an integer.

Valid Assignments

The following tables show whether you can assign the value of an expression of a given type to a variable of the same type or to a variable of a different type.

This table shows the numeric data types.

 | Char expression | Option expression | Integer expression | BigInteger expression | Duration expression | Decimal expression
Char variable | Valid | Valid but overflow may occur | Valid but overflow may occur | Valid but overflow may occur | Valid but overflow may occur | Valid but overflow may occur
Option variable | Valid | Valid | Valid except in a FOR statement | Valid but overflow may occur | Valid but overflow may occur | Valid but overflow may occur
Integer | Valid | Valid | Valid | Valid but overflow may occur | Valid but overflow may occur | Valid but overflow may occur
BigInteger variable | Valid | Valid | Valid | Valid | Valid | Valid but overflow may occur
Duration variable | Valid | Valid | Valid | Valid | Valid | Valid but overflow may occur
Decimal variable | Valid | Valid | Valid | Valid but overflow may occur | Valid but overflow may occur | Valid

This table shows the string data types.

 | Text expression | Code expression | BigText expression
Text variable | Valid but overflow may occur | Valid but overflow may occur | Valid but overflow may occur
Code variable | Valid but overflow may occur | Valid but overflow may occur | Valid but overflow may occur
BigText variable | Valid but overflow may occur | Valid but overflow may occur | Valid but overflow may occur
Note
You can assign the BigText variable with the BigText functions. For more information, see BigText Data Type.


C/AL Operators

Operators can be used in expressions to combine, investigate, and adjust values and data elements.

C/AL Operators and Meaning

The following table shows the valid operators in C/AL.

C/AL operator | Meaning
. | Fields in records, controls on pages, and reports
( ) | Parentheses
[ ] | Indexing
:: | Scope
+ | Addition
- | Subtraction or negation
* | Multiplication
/ | Division
DIV | Integer division
MOD | Modulus
> | Greater than
>= | Greater than or equal to
< | Less than
<= | Less than or equal to
= | Equal to
<> | Not equal to
IN | In range
AND | Logical conjunction
OR | Logical disjunction
NOT | Logical negation
XOR | Exclusive logical disjunction
.. | Range
@ | Case-insensitive

The "+" and the "-" operators can be used both as unary and binary operators. The "NOT" operator can only be used as a unary operator. All the other operators are binary.

Most of the operators can be used on different data types. The action of these operators may depend on the data type of the expression that they are used on.

Example 1

In this example, the "+" operator is used as a binary operator.

Copy Code
number + number

This returns the sum of the numbers, that is, a result of type number.

Example 2

In this example, the "+" operator is used as a binary operator.

Copy Code
string + string

This returns the concatenation of the strings, that is, a result of the type string.

Example 3

In this example, the "+" operator is used as a unary operator to indicate sign.

Copy Code
+34545

Operator Hierarchy

Operators are organized in a hierarchy that determines the order in which the operands in a given expression are evaluated. The following list shows the order of precedence of the C/AL operators:

  1. .(fields in records), [] (indexing), () (parentheses), :: (scope)

  2. NOT, - (unary), + (unary)

  3. *,/,DIV, MOD, AND, XOR

  4. +, -, OR

  5. >, <. >=, <=, = <>, IN

  6. .. (range)

Example 1

Copy Code
2 + 3 * 4

This expression evaluates to 14.

Example 2

Copy Code
(2 + 3) * 4

This expression evaluates to 20.


C/AL Function Calls

C/AL contains several functions that can be used for different purposes, such as string handling, text formatting, database handling, and so on. Some of these functions can use different parameters.

Parameters

In a function call, the parameters are separated by commas, and the optional parameters may be omitted starting from the right. For example, this means that if a function has three optional parameters, then you cannot omit the second parameter without omitting the third parameter.

You can specify that a parameter is passed to a function by value or by reference.

  • If a parameter is passed by value, then a copy of the variable is passed to the function. Any changes that the function makes to the value of the variable are local changes that affect only the copy, not the variable itself.

  • If a parameter is passed by reference, then a reference to the variable is passed to the function. The function can change the value of the variable itself.

For more information about how to specify that a parameter is passed by value or by reference, see How to: Add a Function to a Codeunit.

Example 1

The following shows the syntax for a function.

Copy Code
FUNCTION([Optional1] [, Optional2] [, Optional3])

The function that uses the syntax above can be called by using the following code.

Copy Code
FUNCTION(Optional1, Optional2)

This function cannot be called by using the following code.

Copy Code
FUNCTION(, Optional2, Optional3)

Example 2

ABS is an example of a C/AL function that has a fixed number of parameters (1).

Copy Code
Value := -1033; //A negative integer value
PositiveValue := ABS(Value); //Calculate the positive value 1033

Example 3

The function DMY2DATE is an example of a function that can be called by using a variable number of parameters.

Copy Code
NewDate := DMY2DATE(5, 11, 1992); //Returns the date November 5, 1992

Depending on the use of the DMY2DATE function, 1, 2, or 3 parameters can be passed to the function because the second and third parameters are optional. When the second and third parameters are not used, values from the system date are used as default.

Return Values

A function can return a value. For more information about how to specify that a function has a return value, see How to: Add a Function to a Codeunit.

Example 1

You can assign the return value of a function to a variable.

Copy Code
ReturnVal := MyFunction(Param1);

Example 2

In this example, MyFunction returns a Boolean value. You can use the return value in a conditional statement.

Copy Code
IF (MyFunction(Param1)) THEN
  <Statement1>
ELSE
  <Statement2>


C/AL Simple Statements

C/AL simple statements are single-line statements that are executed sequentially and do not alter the flow of execution of code. The following are the types of simple statements in C/AL:

  • C/AL Assignment Statements

  • C/AL Function Statements

  • C/AL ASSERTERROR Statements

  • C/AL WITH Statements


C/AL Assignment Statements

Assignment statements assign a value to a variable. The value that you assign to the variable is a C/AL expression. It can be a constant or a variable, or it can consist of multiple elements of C/AL expressions. If you use a function call as the value to assign to a variable in an assignment statement, then the value that is assigned is the return value of the function.

You use the ":=" operator for assignment statements.

Example

The following example assigns a constant integer value to an integer variable that you have defined.

Copy Code
Count := 1;

Example

The following example assigns a value that consists of a constant, an operator, and a variable.

Copy Code
Amount := 2 * Price;

Example

The following example assigns the return value of the OPEN Function (File) to a Boolean variable that you have defined.

Copy Code
OK := TestFile.OPEN('C:\temp\simple.xml');

The return value of the OPEN function is optional. If you do not handle the return value in your code, then a run-time error occurs when a function returns FALSE. The following example causes a run-time error if the file C:\temp\simple.xml cannot be opened.

Copy Code
TestFile.OPEN('C:\temp\simple.xml');

You can handle the return value by using an IF-THEN statement.

Copy Code
IF TestFile.OPEN('C:\temp\simple.xml') THEN BEGIN
  // continue running
ELSE
  ERROR(Text001);

See Also

Concepts

C/AL Simple Statements


C/AL Function Statements

You use function statements to execute either built-in system functions or user-defined functions. Function calls may include parameters, which are passed to the function.

If you assign the return value of a function call to a variable, then you use the function statement as part of an assignment statement.

Triggers are C/AL elements that consist of an event and a function. Triggers execute a function when a certain event occurs. For more information, see Triggers Overview and Triggers.

Example

The following example calls the INIT Function (Record) on a record variable. This example requires that you create the following variable.

Name | DataType | Subtype
CustomerRecord | Record | Customer
Copy Code
CustomerRecord.INIT;

Example

The following example calls the CALCDATE Function (Date) and assigns the return value to a variable. The CALCDATE function has two parameters. This example uses the DateExpression and ReferenceDate variables in the function call. The values of the variables are passed to the CALCDATE function.

This example requires that you create the following variables.

Name | DataType | Length
DateExpression | Text | 30
ReferenceDate | Date |
NewDate | Date |
Copy Code
DateExpression := '<-7D>'
ReferenceDate := 112509D;
NewDate := CALCDATE(DateExpression, ReferenceDate);

After you run the code in this example, the NewDate variable represents the date November 18, 2009.

See Also

Concepts

C/AL Functions
Triggers
C/AL Simple Statements


C/AL ASSERTERROR Statements

You use ASSERTERROR statements in test functions to test how your application behaves under failing conditions. The ASSERTERROR keyword specifies that an error is expected at run time in the statement that follows the ASSERTERROR keyword.

If a simple or compound statement that follows the ASSERTERROR keyword causes an error, then execution successfully continues to the next statement in the test function. You can get the error text of the statement by using the GETLASTERRORTEXT Function.

If a statement that follows the ASSERTERROR keyword does not cause an error, then the ASSERTERROR statement causes the following error and the test function that is running produces a FAILURE result:

TestAsserterrorFail: FAILURE

An error was expected inside an ASSERTERROR statement.

Example

To create a test function to test the result of a failure of a CheckDate function that you have defined, you can use the following code. This example requires that you create a function called CheckDate to check whether the date is valid for the customized application and that you create the following text constant and variables.

Text constant | ENU value
Text001 | 'The date is outside the valid date range.'

Name | DataType
InvalidDate | Date
InvalidDateErrorMessage | Text
Copy Code
InvalidDate := 010184D;
InvalidDateErrorMessage := Text001;
ASSERTERROR CheckDate(InvalidDate);
IF GETLASTERRORTEXT <> InvalidDateErrorMessage THEN
  ERROR('Unexpected error: %1', GETLASTERRORTEXT);

See Also

Tasks

How to: Create Test Codeunits and Test Functions

Concepts

Testing the Application
C/AL Reserved Words


C/AL WITH Statements

The following syntax shows a WITH-DO statement.

Copy Code
WITH <Record> DO
  <Statement>

When you work with records, addressing is created as record name, dot (period), and field name:

<Record>.<Field>

If you work continuously with the same record, then you can use WITH statements. When you use a WITH statement, you can only specify the record name one time.

Within the scope of <Statement>, fields in <Record> can be addressed without having to specify the record name.

You can nest several WITH statements. If you have identical names, then the inner WITH statement overrules the outer WITH statement.

Example

This example shows two ways to write the same code that creates a record variable that you can commit later.

Create the following variable.

Variable | Data type | Subtype
CustomerRec | Record | Customer
Copy Code
CustomerRec."No." := '1234';
CustomerRec.Name := 'Windy City Solutions';
CustomerRec."Phone No." := '555-444-333';
CustomerRec.Address := '1241 Druid Avenue';
CustomerRec.City := 'Windy City';
MESSAGE('A variable has been created for this customer.');

The following example shows another way to create a record variable that you can commit later

Copy Code
WITH CustomerRec DO BEGIN
  "No." := '1234';
  Name := 'Windy City Solutions';
  "Phone No." := '555-444-333';
  Address := '1241 Druid Avenue';
  City := 'Windy City';
  MESSAGE('A variable has been created for this customer.');
END;

Programming Conventions

Within WITH-DO blocks, do not repeat the name of the object by using the member variable or function.

If you nest a WITH-DO block within another explicit or implicit WITH-DO block, then the WITH-DO block that you create within another WITH-DO block must always be attached to a variable of the same type as the variable that is attached to the surrounding WITH-DO block. Otherwise, it can be difficult to see what variable that a member variable or function refers to. For example, implicit WITH-DO blocks occur in table objects and in pages that have been attached to a record.

Example

The following example demonstrates nested WITH-DO blocks. Both WITH-DO blocks are attached to a Customer Ledger Entry record variable.

Copy Code
WITH CustLedgEntry DO BEGIN
  INSERT;
  ...;
  WITH CustLedgEntry2 DO BEGIN
    INSERT;
    ...;
  END;
END;

Incorrect Example

The following example demonstrates incorrect code in which you cannot directly tell which record variable that the MyField field refers to.

Copy Code
WITH CustLedgEntry DO BEGIN
  ...;
  WITH VendLedgEntry DO BEGIN
    MyField := <Some Value>;
    ...;
  END;
END;

See Also

Concepts

C/AL Compound Statements
C/AL Conditional Statements
C/AL Repetitive Statements


C/AL Control Statements

All the C/AL programs that you create consist of one or more statements, which are executed sequentially in top-down order. However, you will often need to control the direct top-down flow of the execution. One or more statements may have to be repeated more than once, or you may have to make the execution of a certain statement conditional. To do this, you use control structures.

The control structures in C/AL are divided into the following main groups:

  • C/AL Compound Statements

  • C/AL Conditional Statements

  • C/AL Repetitive Statements


C/AL Compound Statements

A compound statement is one type of control structure in C/AL.

Using Compound Statements

In some cases, the C/AL syntax only lets you use a single statement. However, if you have to execute more than one simple statement, the statements can be written as a compound statement by enclosing the statements between the BEGIN and END keywords.

Copy Code
BEGIN
  <Statement 1>;
  <Statement 2>;
  ..
  <Statement n>;
END

The individual statements are separated by a semicolon. In C/AL, a semicolon is used to separate statements and not, as in other programming languages, as a terminator symbol for a statement. Nevertheless, an extra semicolon before an END does not cause an error because it is interpreted by the compiler as an empty statement.

Blocks

The BEGIN-END structure is also called a block. Blocks can be very useful to refer to the other control structures in C/AL.

When BEGIN follows THEN, ELSE, or DO, it should be on the same line and preceded by one space character.

Example

Copy Code
IF (x = y) AND (a = b) THEN BEGIN
  x := a;
  y := b;
END;

Example

Copy Code
IF (xxx = yyyyyyyyyy) AND
   (aaaaaaaaaa = bbb)
THEN BEGIN
  x := a;
  x := y;
  a := y;
END ELSE BEGIN
  y := x;
  y := a;
END;

See Also

Concepts

C/AL Conditional Statements
C/AL Repetitive Statements
C/AL WITH Statements


C/AL Conditional Statements

A conditional statement is one type of control structure in C/AL.

You use conditional statements to specify a condition and one or more commands to execute if the condition is evaluated as true or false. There are two types of conditional statements in C/AL:

  • IF-THEN-ELSE, where there are two choices.

  • CASE, where there are more than two choices.

IF-THEN ELSE Statements

IF-THEN-ELSE statements have the following syntax.

Copy Code
IF <Condition> THEN
  <Statement1>
[ELSE
  <Statement2>]

If <Condition> is true, then <Statement1> is executed. If <Condition> is false, then <Statement2> is executed.

The square brackets around ELSE <Statement2> mean that this part of the statement is optional. The ELSE statement is used when different actions are executed depending on how <Condition> is evaluated.

You can build more complex control structures by nesting IF-THEN-ELSE statements. The following example is a typical IF-THEN-ELSE statement.

Copy Code
IF <Condition1> THEN
  IF <Condition2> THEN
    <Statement1>
  ELSE
    <Statement2>

If <Condition1> is false, then nothing is executed. If <Condition1> and <Condition2> are both true, then <Statement1> is executed. If <Condition1> is true and <Condition2> is false, then <Statement2> is executed.

Note
A semicolon in front of an ELSE statement is not allowed.

Reading several nested IF-THEN-ELSE statements can be very confusing but generally, an ELSE statement belongs to the last IF statement that lacks an ELSE statement.

Programming Conventions

IF and THEN should be on the same line. ELSE should be on a separate line.

If there are many or long expressions, THEN should be on a new line and be aligned with IF.

When you write IF expressions with THEN and ELSE parts, write them so that the THEN result is more probable than the ELSE one.

If the last statement in the THEN part of an IF-THEN-ELSE statement is an EXIT or an ERROR, do not continue with an ELSE statement.

Example

Copy Code
IF x = y THEN
  x := x + 1
ELSE
  x := -x - 1;

Example

Copy Code
IF (xxxxxxxxxx = yyy) AND
   (aaa = bbbbbbbbbb)
THEN
  x := a
ELSE
  y := b;

Example

Copy Code
IF x <> y THEN
  EXIT(TRUE);
x := x * 2;
y := y - 1;

Incorrect Example

Copy Code
IF x < y THEN
  EXIT(TRUE)
ELSE BEGIN
  x := x * 2;
  y := y - 1;
END;

Example

The following example shows an IF-THEN statement without the optional ELSE statement.

Copy Code
IF Amount < 1000 THEN
  Total := Total + Amount;

Example

The following example shows a nested IF-THEN-ELSE statement.

Copy Code
...
IF Amount < 1000 THEN BEGIN
  IF I > J THEN
    Max := I
  ELSE
    Max := J;
  Amount := Amount * Max;
END
ELSE
...

CASE Statements

CASE statements have the following syntax.

Copy Code
CASE <Expression> OF
  <Value set 1>:
    <Statement 1>;
  <Value set 2>:
    <Statement 2>;
...
...
  <Value set n>:
    <Statement n>;
[ELSE
  <Statement n+1>]
END;

In this definition, <Expression> cannot be a record and <Value set> must be an expression or a range.

CASE statements are also called multiple option statements and are typically used when you must choose between more than two different actions. The function of the CASE statement is as follows:

  • The <Expression> is evaluated, and the first matching value set executes the associated statement, if there is one.

  • If no value set matches the value of the expression and the optional ELSE part has been omitted, then no action is taken. If the optional ELSE part is used, then the associated statement is executed.

The data type of the value sets must be the same as the data type of <Expression> or at least be convertible to the same data type.

In most cases, the data type of the value sets are converted to the date type of the evaluated expression. The only exception is if the evaluated expression is a Code variable. If the evaluated expression is a Code variable, then the value sets are not converted to the Code data type.

Note
This type conversion can cause an overflow at run time if the resulting data type cannot hold the values of the datasets.

For more information about Code variables, see Code Data Type.

Programming Conventions

When you use a CASE statement, indent the value sets by two character spaces. If you have two or more value sets on the same line, then separate them by commas without spaces. The last value set on a line is immediately followed by a colon without a preceding space. The action starts on the line after the value set and is further indented by two character spaces. If there is a BEGIN, then it should be put on a separate line unless it follows ELSE. If a BEGIN follows an ELSE, then it should be on the same line as ELSE.

If there are more than two alternatives, use a CASE statement. Otherwise, use an IF-THEN-ELSE statement.

Example

Copy Code
CASE Field OF
  Field::A:
    BEGIN
     x := x + 1;
     y := -y - 1;
    END;
  Field::B:
    x := y;
  Field::C,Field::D:
    y := x;
  ELSE BEGIN
    y := x;
    a := b;
  END;
END

Example

The following C/AL code prints various messages depending on the value of Number. If the value of Number does not match any of the entries in the CASE structure, then the ELSE entry is used as the default.

Copy Code
CASE Number OF
  1,2,9:
    MESSAGE('1, 2, or 9.');
  10..100:
    MESSAGE('In the range from 10 to 100.');
  ELSE
    MESSAGE('Neither 1, 2, 9, nor in the range from 10 to 100.');
END

Example

The following C/AL code shows how value sets in a CASE statement are evaluated if the expression is a Code data type. This example requires that you create the following variable.

Variable | Data type
MyCode | Code
Copy Code
MyCode := 'ABC';
CASE MyCode OF
  'abc':
    MESSAGE('This message is not displayed.');
  'def':
    MESSAGE('This message is not displayed.);
ELSE
  MESSAGE('The value set does not match the expression.');

The value set 'abc' is not converted because the evaluated expression MyCode is a Code variable.

See Also

Concepts

C/AL Compound Statements
C/AL Repetitive Statements
C/AL WITH Statements


C/AL Repetitive Statements

A repetitive statement is also known as a loop. The following table shows the looping mechanisms in C/AL.

Looping mechanism | Description
FOR | Repeats the inner statement until a counter variable equals the maximum or minimum value specified.
FOREACH | Repeats the inner statement for each element in a .NET Framework collection.
WHILE | Repeats the inner statement as long as the specified condition is TRUE. The statement in a loop of this kind is repeated 0 or more times.
REPEAT | Repeats the inner statements until the specified conditions evaluate to TRUE. The statements in a loop of this kind are always executed at least one time.

FOR-TO and FOR-DOWNTO Control Structure

The following syntax shows the FOR-TO and FOR-DOWNTO statement.

Copy Code
FOR <Control Variable> := <Start Number> TO <End Number> DO
  <Statement>
Copy Code
FOR <Control Variable> := <Start Number> DOWNTO <End Number> DO
  <Statement>

The data type of <Control Variable>, <Start Number>, and <End Number> must be Boolean, number, time, or date.

Use FOR-TO and FOR-DOWNTO statements when you want to execute code a specific number of times. The <Control Variable> controls the number of times that the code of the inner statement is executed according to the following:

  • In a FOR-TO loop statement, the <Control Variable> value is increased by one after each iteration. The inner <Statement> is executed repeatedly until the <Start Number> value is greater than the <End Number> value.

  • In a FOR-DOWNTO loop statement, the <Control Variable> value is decreased by one after each iteration. The inner <Statement> is executed repeatedly until the <Start Number> value is less than the <End Number> value.

Note
When the FOR statement is executed, <Start Number> and <End Number> are converted to the same data type as <Control Variable> if it is required. This type conversion can cause a run-time error.

Note
If the value of the <Control Variable> is changed inside the FOR loop, then the behavior is not predictable. Furthermore, the value of the <Control Variable> is undefined outside the scope of the FOR loop.

Example 1

Create the following variable.

Variable | Data type
Count | Integer

The following code initiates a FOR loop that uses the integer control variable named Count.

Copy Code
FOR Count := 1000 TO 100000000000000 DO

When this statement is executed, a run-time error occurs because the start and end values are converted to the same data type as the Count control variable. Count has been declared as an integer variable. The end number 100000000000000 is outside the valid range for integers, and an error occurs.

Example 2

The following example shows how to nest FOR statements.

Create the following variables.

Variable | Data type
I | Integer
J | Integer

Set the Dimensions property of variable A to 5;7.

The following FOR statements could be used to initialize every element in a 5x7 array with the value 23.

Copy Code
FOR I := 1 TO 5 DO
  FOR J := 1 TO 7 DO
    A[I,J] := 23;

FOREACH Control Structure

You can use the FOREACH statement to iterate through a .NET Framework collection or array object.

The FOREACH statement has the following syntax.

Copy Code
FOREACH <Element> IN <List> DO
  <Statement>

The <List> variable must be a DotNet data type that is set to .NET Framework collection or array type.

Note
The FOREACH statement is not limited to collections and arrays. You can use it with any .NET Framework object that implements the GetEnumerator method, the MoveNext method, and the Current property.

The <Element> variable must be a data type that is compatible with elements in the .NET Framework collection or array that is specified by the <List>.

Example 1

The following code example iterates through a .NET Framework collection that contains a generic list of elements and returns each element as text in a message.

Create the following local variables in a Microsoft Dynamics NAV object, such as a codeunit.

Variable | DataType | Subtype
mylist | DotNet | System.Collections.Generic.List`1.'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
element | DotNet | System.Object.'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'

Add the following C/AL code (for example, on the OnRun trigger of the codeunit).

Copy Code
// Instantiate the .NET Framework collection object
mylist := mylist.List();
// Populate the collection
mylist.Add('Item 1');
mylist.Add('Item 2');
mylist.Add('Item 3');
mylist.Add('Item 4');
// Iterate through the collection
FOREACH element IN mylist DO
  BEGIN
    MESSAGE(FORMAT(element));
  END;

Compile and run the codeunit.

Example 2

The following code example is similar to example 1, except this example iterates on the text string of each element in the .NET Framework collection.

Create the following local variables in a Microsoft Dynamics NAV object, such as a codeunit.

Variable | DataType | Subtype
mylist | DotNet | System.Collections.Generic.List`1.'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
txt | Text |

Add the following C/AL code to objects (for example, on the OnRun trigger of the codeunit).

Copy Code
// Instantiate the .NET Framework collection object
mylist := mylist.List();
// Populate the collection
mylist.Add('Item 1');
mylist.Add('Item 2');
mylist.Add('Item 3');
mylist.Add('Item 4');
// Iterate through the collection
FOREACH txt IN mylist DO
  BEGIN
    MESSAGE(txt);
  END;

Compile and run the Microsoft Dynamics NAV object.

Example 3

The following code example iterates through a .NET Framework collection for a dictionary of keys and values and returns each key/value pair as text in a message.

Create the following local variables in a Microsoft Dynamics NAV object, such as a codeunit.

Variable | DataType | Subtype
mydictionary | DotNet | System.Collections.Generic.Dictionary`2.'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
element | DotNet | System.Object.'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'

Add the following C/AL code (for example, on the OnRun trigger of the codeunit).

Copy Code
// Instantiate the .NET Framework collection object
mydictionary := mydictionary.Dictionary();
// Populate the collection
mydictionary.Add(10, '1');
mydictionary.Add(20, '22');
mydictionary.Add(30, '333');
mydictionary.Add(40, '4444');
mydictionary.Add(50, '55555');
// Iterate through the collection
FOREACH element IN mydictionary DO
  BEGIN
    MESSAGE(FORMAT(element));
  END;

Compile and run the Microsoft Dynamics NAV object.

Example 4

The following code example iterates through a .NET Framework array that contains a list of file names from a local directory and returns each file name in a message.

Create the following local variables in a Microsoft Dynamics NAV object, such as a codeunit.

Variable | DataType | Subtype
strarray | DotNet | System.Array.'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
txt | Text |

Add the following C/AL code (for example, on the OnRun trigger of the codeunit).

Copy Code
strarray := Dir.GetFileSystemEntries('C:\\myfiles\');
FOREACH txt IN strarray DO
  BEGIN
    MESSAGE(txt);
  END;

Compile and run the Microsoft Dynamics NAV object.

WHILE-DO Control Structure

The following syntax shows the WHILE-DO statement.

Copy Code
WHILE <Condition> DO
  <Statement>

If <Condition> is TRUE, then <Statement> is executed repeatedly until <Condition> becomes FALSE. If <Condition> is FALSE from the start, then <Statement> is never executed.

The WHILE DO statement can be used when some code should be repeated as long as an expression is TRUE.

Programming Conventions

When there is only one condition, put WHILE and DO on the same line. Put the statements on separate lines and indented by two spaces.

When there are multiple conditions, put the conditions on separate lines and indented by two spaces and put DO on a separate line that is aligned with WHILE.

Example

Copy Code
WHILE <expr> DO
  <Statement>;

Example

Copy Code
WHILE <expr> DO BEGIN
  <Statement>;
  <Statement>;
END;

Example

Copy Code
WHILE <expr> AND
      <expr> AND
      <expr>
DO BEGIN
  <Statement>;
  <Statement>;
END;

Example

Create the following variable.

Variable | Data type
I | Integer

The following C/AL code increases the variable I until it equals 1000 and displays a message when it is finished.

Copy Code
WHILE I < 1000 DO
  I := I + 1;
Message(format(I));

REPEAT-UNTIL Control Structure

The following syntax shows the REPEAT-UNTIL statement.

Copy Code
REPEAT
  <Statements> UNTIL <Condition>

<Statements> is executed repeatedly until <Condition> is TRUE.

The REPEAT UNTIL control structure resembles the WHILE control structure. The difference is that because the REPEAT UNTIL statement is executed from left to right, the <Statements> is always executed at least one time, regardless of what the <Condition> is evaluated to. This contrasts with the WHILE control structure, which performs the evaluation before the <Statement> is executed. In the WHILE control structure, if the first evaluation of <Condition> returns FALSE, then no statements are executed.

Programming Conventions

Always put REPEAT on a separate line.

Example

Copy Code
IF x < y THEN BEGIN
  REPEAT
    x := x + 1;
    a := a - 1;
  UNTIL x = y;
  b := x;
END;

Example

Create the following variables.

Variable | Data type | Subtype
Count | Integer |
Customer | Record | Customer
Copy Code
Count := 0;
IF Customer.FIND('-') THEN
REPEAT
  Count := Count + 1;
UNTIL Customer.NEXT <= 0;
Message(’The Customer table contains %1 records.’,Count);

This code uses a REPEAT-UNTIL loop to count the number of entries in the Customer table. The FIND function finds the first entry in the table. Each time NEXT is called, it steps one record forward. When NEXT equals 0, there are no more entries in the table. The loop is exited, and a message displays how many entries were found.

EXIT Statement

The EXIT statement is used to control the flow of the execution. The following syntax shows an EXIT statement.

Copy Code
EXIT([<Value>])

An EXIT statement is used to interrupt the execution of a C/AL trigger. The interruption occurs even when the code is executed inside a loop or a similar structure. The EXIT statement is also used when a local function should return a value.

Using EXIT without a parameter in a local function corresponds to using the parameter value 0. The C/AL function will return the value 0 or '' (empty string).

A compile-time error occurs if EXIT is called by using a return parameter from either of the following:

  • System-defined triggers.

  • Local functions that do not return a value.

Example

The following example shows the use of the EXIT statement in a local function. Assume that the IF statement is used to detect an error. If the error condition is met, then execution is stopped and the local function returns the error code 1.

Copy Code
FOR I := 1 TO 1000 DO BEGIN
  IF Amount[I] < Total[I] THEN
    EXIT(1);
  A[I] := Amount[I] + Total[I];
END;

See Also

Concepts

C/AL Compound Statements
C/AL Conditional Statements
C/AL WITH Statements
C/AL BREAK Statement


C/AL BREAK Statement

You use the BREAK statement to terminate the iteration statement in which it appears.

Copy Code
BREAK;

You typically use the BREAK statement in the repeating statements such as FOR, FOREACH, WHILE, or REPEAT to stop an iteration or loop when certain conditions are met.

Example

The following code example loops through a .NET Framework collection that contains a generic list of elements and returns each element as text in a message. However, the BREAK statement terminates the iteration when the text equivalent of the element is Item 2.

Create the following local variables in a Microsoft Dynamics NAV object, such as a codeunit.

Variable | DataType | Subtype
mylist | DotNet | System.Collections.Generic.List`1.'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
element | DotNet | System.Object.'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'

Add the following C/AL code (for example, on the OnRun trigger of the codeunit).

Copy Code
// Instantiate the .NET Framework collection object
mylist := mylist.List();
// Populate the collection
mylist.Add('Item 1');
mylist.Add('Item 2');
mylist.Add('Item 3');
mylist.Add('Item 4');
// Iterate through the collection
FOREACH element IN mylist DO
  BEGIN
    MESSAGE(FORMAT(element));
    IF FORMAT(element) = 'Item 2' THEN
      BREAK;
  END;

Compile and run the Microsoft Dynamics NAV object.

See Also

Concepts

C/AL Repetitive Statements


C/AL Comments

You can insert comments about your C/AL code or comment out parts of your code to prevent execution. The following are the two ways to insert comments in C/AL:

  • Use "//" to insert a single line comment.

    When the "//" symbol is encountered in your code, the rest of the line is interpreted as a comment.

    You can add and remove comment marks manually or use the Comment Selection and Uncomment Selection options in the Edit menu. The Comment Selection and Uncomment Selection options enable you to comment or uncomment multiple lines of code all at once.

    • To comment lines of code, select the lines, and then, in the Edit menu, choose Comment Selection.

    • To uncomment lines of code, select the lines, and then choose Uncomment Selection.

      Note
      To use the Uncomment Selection, all the lines of code that you select must have comment marks.

  • Use "{" and "}" to mark the start and end, respectively, of a block of comments.

You can nest any number of comments. In such cases, the comment runs from the first comment start to the last comment end.

Example 1

Copy Code
{
This is a sample comment which is ignored by the C/AL compiler
}

Example 2

Copy Code
// This is also a sample comment which is ignored by the C/AL compiler

Example 3

Copy Code
{ This comment { is partly inside } another comment }

Example 4

This example shows what you should not do.

Copy Code
A := 34;
B := 56;      {******************
C := 345;      * Don’t do this! *
D := 781;      ******************}

Because the comment is to the right of the C/AL statements, the system assumes that the third and fourth lines are part of the comment. That is, only A and B are assigned values, while C and D are not. Instead you should use single line comments.

Copy Code
A := 34;
B := 56;       //*******************
C := 345;      //* Do it this way! *
D := 781;      //*******************


System-Defined Variables

Microsoft Dynamics NAV automatically declares and initializes several variables that you can use when you develop applications. The following table describes the system-defined variables.

System-defined variable Description

Rec

When a record is modified, this variable specifies the current record, including the changes that are made.

xRec

When a record is modified, this variable specifies the original values of the record, before the changes.

CurrPage

This variable specifies the current page. You can access the controls of the page through this variable and set the dynamic properties of the page and its controls.

The CurrPage.Editable variable reflects the run-time value of the editable property, which can be changed at design time, programmatically, or by the user when switching view modes on a page.

The CurrPage.Update([SaveRecord]) variable can be used to save the current record and then update the controls in the page.

When the View mode on a page is FALSE, then the Edit, New, and Delete modes are TRUE.

CurrReport

This variable specifies the current report.

RequestOptionsPage

This variable specifies the request options page for the current report.

CurrFieldNo

This variable specifies the field number of the current field in the current page. Retained for compatibility reasons.

In addition, some triggers, such as the OnFormat trigger of a control, have a parameter that is defined as a local variable.

Example

The following example shows how to use the Rec and xRec pair of records.

In an application, data is stored in two tables, a header table and a line table. The header table contains general information about, for example, sales orders, while the line table contains the specific order lines. The page that you use to enter information into the header table has fields that contain the customer’s address. These fields are related to the Customer table, and can be filled by using a lookup function in the field that establishes the relationship. In the header table, only the customer number is stored, and the other fields that have customer information, such as name and address, are retrieved from the Customer table when the Customer No. field is validated.

In some situations, the user should be able to change the customer number, and in other situations the user should not be able to change it. For example, if the order has already been shipped, the user should not be able to change the customer number. If there is an incorrect number on an order that has not been processed completely, the user should be able to correct the error.

You could use the Rec and xRec variables to design your application in the following way:

  • When validating the customer number field, check whether the order has shipped.

  • If the order has shipped, compare the customer number fields in the Rec and xRec records. If they differ, reject the change.

See Also

Concepts

C/AL Variables
Properties


Triggers Overview

Triggers activate a function when a certain event occurs. When C/AL functions are executed as a result of a predefined event on either an object or a control, the event triggers the function. Together the event and function make a trigger. You edit triggers in the C/AL editor.

See Also

Concepts

Triggers


Essential C/AL Functions

Although there are more than 100 functions in C/AL, there are several functions that you will use more often than the others. This does not mean that the rest of the functions are obsolete or that you will never use them. However, it does mean that if you are very familiar with this small set of essential functions, you will be able to accomplish many tasks when you are programming in C/AL. When you want to add more specialized functionality to your applications, you can learn about more of the functions.

The topics in this section describe the most common C/AL functions. For more details about all of the C/AL functions, see C/AL Functions.

See Also

Concepts

GET, FIND, and NEXT Functions
SETCURRENTKEY, SETRANGE, SETFILTER, GETRANGEMIN, and GETRANGEMAX Functions
INSERT, MODIFY, MODIFYALL, DELETE, and DELETEALL Functions
LOCKTABLE Function
CALCFIELDS, CALCSUMS,FIELDERROR, FIELDNAME, INIT, TESTFIELD, and VALIDATE Functions
Progress Windows, MESSAGE, ERROR, and CONFIRM Functions
STRMENU Function


GET, FIND, and NEXT Functions

The following functions are used to search for records:

  • GET

  • FIND

  • NEXT

These functions are some of the most frequently used C/AL functions. When you search for records, you must know the difference between GET and FIND and to know how to use FIND and NEXT in conjunction.

GET Function

The GET Function (Record) retrieves one record based on values of the primary key fields.

GET has the following syntax.

Copy Code
[Ok :=] Record.GET([Value],...)

For example, if the No. field is the primary key of the Customer table and if you have created a record variable called CustomerRec that has a subtype of Customer, then you can use GET in the following way.

Copy Code
CustomerRec.GET('4711');

The result is that the record of customer 4711 is retrieved.

GET produces a run-time error if it fails and the return value is not checked by the code. In the previous example, the actual code that you write should resemble the following.

Copy Code
IF CustomerRec.GET('4711') THEN
.... // Do some processing.
ELSE
.... // Do some error processing.

GET searches for the records, regardless of the current filters, and it does not change any filters. GET always searches through all the records in a table.

FIND Function

The FIND Function (Record) locates a record in a table that is based on the values stored in the keys.

FIND has the following syntax.

Copy Code
Ok := Record.FIND([Which])

The Which parameter specifies how to perform the search. You can search for values that are greater than, less than, or equal to the key value, or for the first or last record in a table.

The important differences between GET and FIND are as follows:

  • FIND uses the current filters.

  • FIND can look for records where the key value is equal to, greater than, or smaller than the search string.

  • FIND can find the first or the last record, depending on the sort order defined by the current key.

When you are developing applications in a relational database, there are often one-to-many relationships defined between tables. An example could be the relationship between an Item table, which registers items, and a Sales Line table, which registers the detailed lines from sales orders. One record in the Sales Line table can only be related to one item, but each item can be related to any number of sales line records. You would not want an item record to be deleted as long as there are still open sales orders that include the item. You can use FIND to check for open sales orders.

The OnDelete trigger of the Item table includes the following code that illustrates using FIND.

Copy Code
SalesOrderLine.SETCURRENTKEY(Type,"No.");
SalesOrderLine.SETRANGE(Type,SalesOrderLine.Type::Item);
SalesOrderLine.SETRANGE("No.","No.");
IF SalesOrderLine.FIND('-') THEN
ERROR(Text001,TABLECAPTION,"No.",SalesOrderLine."Document Type");

If you want to find the first record in a table or set, then use the FINDFIRST Function (Record). If you want to find the last record in a table or set, then use the FINDLAST Function (Record).

NEXT Function

The NEXT Function (Record) is often used with FIND to step through the records of a table.

NEXT has the following syntax.

Copy Code
Steps := Record.NEXT([Steps])

In the following example, FIND is used to go to the first record of the table. NEXT is used to step through every record, until there are no more. When there are no more records, NEXT returns 0 (zero).

Copy Code
IF (Rec.FINDSET) THEN
REPEAT
  // process record
UNTIL (Rec.NEXT = 0);


SETCURRENTKEY, SETRANGE, SETFILTER, GETRANGEMIN, and GETRANGEMAX Functions

The following functions are used to filter records in a table:

  • SETCURRENTKEY

  • SETRANGE

  • SETFILTER

  • GETRANGEMIN

  • GETRANGEMAX

These functions are some of the most commonly used C/AL functions. They set limits on the value of one or more specified fields, so that only a subset of the records are displayed, modified, deleted, and so on.

SETCURRENTKEY Function

SETCURRENTKEY selects a key for a record and sets the sort order that is used for the table in question.

SETCURRENTKEY has the following syntax.

Copy Code
[Ok :=] Record.SETCURRENTKEY(Field1, [Field2],...)

When you use SETCURRENTKEY the following rules apply:

  • Inactive fields are ignored.

  • When searching for a key, the first occurrence of the specified fields is selected. This means the following:

    • If you specify only one field as a parameter when you call SETCURRENTKEY, the key that is actually selected may consist of more than one field.

    • If the field that you specify is the first component of several keys, the key that is selected may not be the key that you expect.

    • If no keys can be found that include the fields that you specify, the return value is FALSE. If you do not test the return value, a run-time error occurs. If you do test the return value, the program will continue to run even though no key was found.

SETRANGE Function

SETRANGE sets a simple filter on a field.

SETRANGE has the following syntax.

Copy Code
Record.SETRANGE(Field [,From-Value] [,To-Value]);

In the following example, SETRANGE filters the Customer table by selecting only those records where the No. field has a value between 10000 and 90000.

Copy Code
Customer.SETRANGE("No.",'10000','90000');

When you use SETRANGE the following rules apply:

  • SETRANGE removes any filters that were set previously and replaces them with the From-Value and To-Value parameters that you specify.

  • If you use SETRANGE without setting the From-Value and To-Value parameters, the function removes any filters that are already set.

  • If you only set the From-Value, the To-Value is set to the same value as the From-Value.

SETFILTER Function

SETFILTER sets a filter in a more general way than SETRANGE.

SETFILTER has the following syntax.

Copy Code
Record.SETFILTER(Field, String [, Value], ...]);

Field is the name of the field on which you want to set a filter. String is the filter expression. String may contain placeholders, such as %1 and %2, to indicate where to insert the Value parameter(s) in a filter expression.

The following example selects records where the value of No. is larger than 10000 and not equal to 20000.

Copy Code
Customer.SETFILTER("No.", '>10000 & <> 20000');

If the variables Value1 and Value2 have been assigned "10000" and "20000" respectively, then you can use the following statement to create the same filter.

Copy Code
Customer.SETFILTER("No.",'>%1&<>%2',Value1, Value2);

GETRANGEMIN Function

GETRANGEMIN retrieves the minimum value of the filter range that is currently applied to a field.

GETRANGEMIN has the following syntax.

Copy Code
Record.GETRANGEMIN(Field);

A run-time error occurs if the filter that is currently applied is not a range. For example, you can set a filter as follows.

Copy Code
Customer.SETFILTER("No.",'10000|20000|30000');

With this filter, the following code fails because the filter is not a range.

Copy Code
BottomValue := Customer.GETRANGEMIN("No.");

GETRANGEMAX Function

GETRANGEMAX retrieves the maximum value of the filter range that is currently applied to a field.

GETRANGEMAX has the following syntax.

Copy Code
Value := Record.GETRANGEMAX(Field)


INSERT, MODIFY, MODIFYALL, DELETE, and DELETEALL Functions

The following functions maintain the database by adding, modifying, and removing records:

  • INSERT

  • MODIFY

  • MODIFYALL

  • DELETE

  • DELETEALL

These functions are some of the most frequently used C/AL functions.

Some of these functions return an optional Boolean value that indicates whether the function succeeded. If you do not handle the return value in your code, a run-time error occurs when a function returns FALSE. If you handle the return value by testing its value in an IF statement, no error will occur, and you must take corrective action in the code.

INSERT Function

INSERT inserts a record in a table.

INSERT has the following syntax.

Copy Code
[Ok :=] Record.INSERT([RunTrigger])

The following example inserts a new record, with the No. and Name fields specified in the assigned values, while other fields will have their default values. If the No. field is the primary key of the Customer table, then the record will be inserted in the Customer table unless the table already contains a record with the same primary key. In this case you receive an error message because the return value is not tested.

This example requires that you create the following variable.

Variable | Data type | Subtype
Customer | Record | Customer
Copy Code
Customer.INIT;
Customer."No." := '4711';
Customer.Name := 'Andrew Dixon';
Customer.INSERT;

MODIFY Function

MODIFY modifies a record that already exists.

MODIFY has the following syntax.

Copy Code
[Ok :=] Record.MODIFY([RunTrigger])

MODIFY returns an optional Boolean value. It returns TRUE if the record to be modified exists; otherwise, it returns FALSE.

The following example changes the name of customer 4711 to Richard Roe. This example requires that you create the following variable.

Variable | Data type | Subtype
Customer | Record | Customer
Copy Code
Customer.GET('4711');
Customer.Name := 'Richard Roe';
Customer.MODIFY;

MODIFYALL Function

MODIFYALL performs a bulk update of records.

MODIFYALL has the following syntax.

Copy Code
Record.MODIFYALL(Field, NewValue [, RunTrigger])

MODIFYALL uses the current filters. This means that you can perform the update on a specified set of records in a table. MODIFYALL returns no value, nor does it cause an error if the set of records to be changed is empty.

In the following example, the SETRANGE statement selects the records where Salesperson Code is PS. The MODIFYALL statement changes the Salesperson Code of these records to JR. The example requires that you create the following variable.

Variable | Data type | Subtype
Customer | Record | Customer
Copy Code
Customer.SETRANGE("Salesperson Code",'PS','PS');
Customer.MODIFYALL("Salesperson Code",'JR');

DELETE Function

DELETE deletes a record from the database.

DELETE has the following syntax.

Copy Code
[Ok :=] Record.DELETE([RunTrigger])

The record that you want to delete must be specified by using the values in the primary key fields before you call this function. This means that DELETE does take filters into consideration.

The following example shows how to use DELETE to delete the record for customer number 4711. This example requires that you create the following variable.

Variable | Data type | Subtype
Customer | Record | Customer
Copy Code
Customer."No." := '4711';
Customer.DELETE;

DELETE returns an optional Boolean value. It returns TRUE if the record could be found; otherwise, it returns FALSE. Unless you test this value in your code, a run-time error occurs when DELETE fails

When you are developing your own applications, you should consider the following scenario:

  1. Retrieve a record from the database.

  2. Perform various checks to determine whether the record should be deleted.

  3. If step 2 indicated that you should delete the record, then delete it.

This can cause problems in a multi-user environment. Another user can modify or delete the same record between your performing steps 2 and 3. If the record is modified, then perhaps the new contents of the record would have changed your decision to delete it. If it has been deleted by the other user, you can get a run-time error if you have just verified that the record existed (in step 1). If the design of your application indicates that you can encounter this problem, you should consider using the LOCKTABLE function. LOCKTABLE should be used sparingly because this function degrades performance. For more information about the LOCKTABLE function, see LOCKTABLE Function.

DELETEALL Function

DELETEALL deletes all the records that are specified by the filter settings. If no filters are applied, it deletes all the records in the table.

DELETEALL has the following syntax.

Copy Code
Record.DELETEALL([RunTrigger])

The following example deletes all the records from the Customer table where the Salesperson Code is PS. This example requires that you create the following variable.

Variable | Data type | Subtype
Customer | Record | Customer
Copy Code
Customer.SETRANGE("Salesperson Code", 'PS', 'PS');
Customer.DELETEALL;
Note
When you use DELETEALL(TRUE), Microsoft Dynamics NAV creates a copy of the C/AL variable with its initial values. This means that when you use DELETEALL(TRUE) to run the OnDelete trigger, all the changes that were made to the variables in the function or codeunit that is making the call cannot be seen in the OnDelete trigger. If you want to see the changes that you made to the variables, you must use DELETE(TRUE) in a loop. There is no difference in performance between using DELETEALL(TRUE) and using DELETE(TRUE) in a loop.


LOCKTABLE Function

Ordinarily, when you are developing applications in Microsoft Dynamics NAV Development Environment, you do not want to consider transactions and table locking. However, there are some situations in which you must lock a table explicitly. To do this, use the LOCKTABLE Function (Record).

For example, in the beginning of a function, you inspect data in a table and then use this data to perform various checks and calculations. Finally, you want to insert a record based on the result of these calculations. To make sure that your calculations make sense, you must be certain that the values that you retrieved at the beginning of the transaction are consistent with the data that is in the table now. You cannot allow other users to update the table when your function is performing its calculations.

LOCKTABLE Function

You can use the LOCKTABLE function to lock the table at the start of your function.

LOCKTABLE has the following syntax.

Copy Code
Record.LOCKTABLE


CALCFIELDS, CALCSUMS,FIELDERROR, FIELDNAME, INIT, TESTFIELD, and VALIDATE Functions

The following functions perform various actions on fields:

  • CALCFIELDS

  • CALCSUMS

  • FIELDERROR

  • FIELDNAME

  • INIT

  • TESTFIELD

  • VALIDATE

CALCFIELDS Function

CALCFIELDS updates FlowFields. FlowFields are automatically updated when they are the direct source expressions of controls, but they must be explicitly calculated when they are part of a more complex expression. For more information about flowfields, see FlowFields.

CALCFIELDS has the following syntax.

Copy Code
[Ok :=] Record.CALCFIELDS(Field1, [Field2],...)

When you use FlowFields in C/AL functions, you must use the CALCFIELDS function to update them.

In the following example, the SETRANGE function sets a filter and then the CALCFIELDS function calculates the Balance and Balance Due fields by using the current filter and performing the calculations that are defined as the CalcFormula properties of the FlowFields. This example requires that you create the following variable.

Variable | Data type | Subtype
Customer | Record | Customer
Copy Code
Customer.GET('01454545');
Customer.SETRANGE("Date Filter",0D,TODAY);
Customer.CALCFIELDS(Balance,"Balance Due");
MESSAGE('The Balance is %1 and your Balance Due is %2',Customer.Balance,Customer."Balance Due");

The following message is displayed:

The Balance is 342,529.44 and your Balance Due is 342,529.44

CALCSUMS Function

CALCSUMS calculates the sum of one or more fields that are SumIndexFields in the record.

CALCSUMS has the following syntax.

Copy Code
[Ok :=] Record.CALCSUMS (Field1, [Field2],...)

For CALCSUMS, a key that contains the SumIndexFields must be selected as the current key. Similar to CALCFIELDS, CALCSUMS uses the current filter settings when it performs the calculation.

In the following example, an appropriate key is selected, some filters are set, the calculation is performed and then a message is displayed. This example requires that you create the following variable.

Variable | Data type | Subtype
custledgerentry | Record | Cust. Ledger Entry
Copy Code
custledgerentry.SETCURRENTKEY("Customer No.");
custledgerentry.SETRANGE("Customer No.",'10000','50000');
custledgerentry.SETRANGE("Posting Date",0D,TODAY);
custledgerentry.CALCSUMS("Sales (LCY)");
MESSAGE ('%1 calculated sales',custledgerentry."Sales (LCY)")

FIELDERROR Function

FIELDERROR triggers a run-time error after it displays a field-related error message.

FIELDERROR has the following syntax.

Copy Code
Record.FIELDERROR(Field, [Text])

This function is very similar to the ERROR function. However, in the FIELDERROR function, if the name of a field is changed, for example, translated to another language, in the Table Designer, the message from the FIELDERROR function will reflect the current name of the field.

The following examples show how to use the FIELDERROR function. These examples require that you create the following variable.

Variable | Date type | Subtype
Item | Record | Item
Copy Code
Item.GET('70000');
IF Item.Class <> 'HARDWARE' THEN
   Item.FIELDERROR(Class);

If item 70000 has a Class other than HARDWARE, then you receive the following error message:

Class must not be OTHER in Item No. ='70000'.

If the text or code field contains the empty string, then you receive the following error message:

You must specify Class in Item No.='70000'.

If the field is a numeric field and is empty, it is treated as if it contains the value 0 (zero), and then you receive the following error message:

Class must not be 0 in Item No.='70000'.

You can change the default text that is displayed in the error message. The following example shows how to use the FIELDERROR function and change the default text. This example requires that you create the following variable.

Variable | Data type
Class | Code
Copy Code
IF Item.Class < '4711' THEN
   Item.FIELDERROR(Class,'must be greater than 4711');

The following error message is displayed:

Class must be greater than 4711 in Item No.='70000'.

FIELDNAME

FIELDNAME returns the name of a field. It has the following syntax.

Copy Code
Name := Record.FIELDNAME(Field)

You could just use the name of the field. However, using FIELDNAME lets you create messages that always contain the name of the field, even if the name of the field is changed.

This example shows how to use FIELDNAME together with FIELDERROR.

Copy Code
FIELDERROR(
   Quantity,'must not be less than ' + FIELDNAME("Quantity Shipped"));

INIT

INIT initializes a record. It has the following syntax.

Copy Code
Name := Record.FIELDNAME(Field)

If a default value for a field has been defined by using the InitValue property, this value is used for the initialization. Otherwise, the default value of each data type is used

Note
INIT does not initialize the fields of the primary key.

TESTFIELD Function

TESTFIELD tests whether a field contains a specific value. It has the following syntax.

Copy Code
Record.TESTFIELD(Field, [Value])

If the test fails, that is, if the field does not contain the specified value, an error message is displayed and a run-time error is triggered. This means that any changes that were made to the record are discarded. If the value that you test against is an empty string, the field must have a value other than blank or 0 (zero).

The following example tests the Language Code field for customer number 10000 in the Customer table and tests whether the Language Code is ZX. This example requires that you create the following variable.

Variable | Data type | Subtype
customer | Record | Customer
Copy Code
customer.GET('10000')
customer.TESTFIELD("Language Code",'ZX');

VALIDATE Function

VALIDATE calls the OnValidate trigger of a field. It has the following syntax.

Copy Code
Record.VALIDATE(Field [, NewValue])

When you enter an account number in a ledger, code in a table trigger is executed to transfer the name of the account from the chart of accounts. If you enter an account number in a batch job, the code which transfers the name of the account is not automatically executed. The following example executes the appropriate field-level trigger code. This example requires that you create the following variable.

Variable | Data type | Subtype
GeneralLedgerEntry | Record | G/L Entry
Copy Code
GeneralLedgerEntry.VALIDATE("G/L AccountNo", '100');

This corresponds to the following code.

Copy Code
GeneralLedgerEntry."G/L AccountNo" := '100';
GeneralLedgerEntry.VALIDATE("G/L AccountNo");

The VALIDATE function is useful for centralizing processing, which makes your application easier to maintain.

For example, if the OnValidate trigger of the Total Amount field performs a calculation that uses values from three other fields as operands, the calculation must be performed again if the contents of any one of these fields changes. You should avoid entering the calculation formula in the OnValidate triggers of each field because this can create errors if the calculation formula has to be changed later and you have to update the code in all the triggers. Instead, you should enter the calculation formula in the OnValidate trigger of only one of the fields and call this trigger code from the OnValidate triggers of the other fields.


Progress Windows, MESSAGE, ERROR, and CONFIRM Functions

You can use several specialized functions to display messages and gather input. We recommend that you use pages to ensure that your application has a consistent user interface. However, there are situations where you may want to use the dialog functions instead of pages. The most important uses of the dialog functions are as follows:

  • To display a window that indicates the progress of some processing that may take a long time.

  • To stop the running program to display an error message.

  • To let the user confirm a choice before the program continues running.

You can also use the STRMENU function to create pages that present options to the user. It is much faster to use this function than to design a page which only presents a limited set of options to the user. For more information about the STRMENU function, see STRMENU Function.

Best Practices for User Messages

We recommend the following guidelines for writing messages for end users:

  • Write messages correctly according to the grammatical rules for your language.

  • When you write a message that is similar to one in the .etx file, phrase it to be as similar to the .etx message as possible. This will make messages consistent throughout the system.

  • Do not use backslashes to indicate line breaks in a message. Line formatting is completed automatically. The only exception is in the OPEN Function (Dialog). You must use backslashes for the message to be aligned correctly.

  • Use the FIELDCAPTION Function (Record) and TABLECAPTION Function (Record) whenever possible to return names of fields and tables as strings so that the user can always recognize a term that indicates a field or table name. The only exception to this is in OPEN Function (Dialog). In this function, you can use the field name directly. Otherwise, it can be difficult to align correctly. If you refer to a field name without using the FIELDCAPTION function, then type the field name without any single or double quotation marks.

  • Try to write all messages on only one line. If you want to use more than one line, then start each new line after a period instead of in the middle of a sentence.

  • Do not enter the text directly in the C/AL code. Instead, enter it as a text constant so that the message can be translated.

Creating a Window to Indicate Progress

If you have an application that performs some processing that can take a long time to complete, then you should consider displaying a window that informs the user of the progress that is being made. It is always a good idea to inform the user that processes are still running.

A Cancel button is automatically added to every dialog window and gives the user the opportunity to stop the processing.

In some applications, you may want to create a window in which each field is updated when the program is running. For example, the fields in the window display the count of the number of postings made. In another application, you may want to display information about the record that is currently being processed. For example, the field in the window displays the number of the account that is currently being processed.

To create this kind of progress window, you use the Dialog data type. For more information, see How to: Create a Progress Window.

MESSAGE Function

The MESSAGE Function (Dialog) displays a message in a window that remains open until the user chooses the OK button.

The MESSAGE function has the following syntax.

Copy Code
MESSAGE(String [, Value1, ...])

The MESSAGE function executes asynchronously, which means that MESSAGE is not executed until the function from which it was called ends or another function requests user input. The function is useful for notifying the user that some processing has been successfully completed.

For an example of the MESSAGE function, see codeunit 83 in the CRONUS International Ltd. demonstration database. The code in the OnRun trigger converts a quote into a sales order and then displays a message. The message is generated by the following code.

Copy Code
MESSAGE(Text001,"No.",SalesHeader2."No.");

Text001 is a text constant that contains the following text:

Quote %1 has been changed to order %2.

Note
Unlike the progress window, the MESSAGE function does not require that you first declare a variable of type Dialog. The MESSAGE function creates a window of its own.

ERROR Function

The ERROR Function (Dialog) is very similar to the MESSAGE function except that when the user has acknowledged the message from an ERROR function, execution ends. The ERROR function is also similar to the FIELDERROR function. For more information, see CALCFIELDS, CALCSUMS,FIELDERROR, FIELDNAME, INIT, TESTFIELD, and VALIDATE Functions.

The ERROR function has the following syntax.

Copy Code
ERROR(String [, Value1, ...])

CONFIRM Function

The CONFIRM Function (Dialog) is used just like the MESSAGE function to display a message. However, unlike the MESSAGE function, the CONFIRM function has a required return value.

The CONFIRM function has the following syntax.

Copy Code
Ok := Dialog.CONFIRM(String [, Default] [, Value1] ,...)

The following example shows how to use the CONFIRM function.

Copy Code
IF CONFIRM('Do you want to post the journal lines and print report %1?',FALSE, ReportID) THEN
   MESSAGE('Posting')
ELSE
   MESSAGE('No Posting');
   EXIT;

The FALSE parameter in the CONFIRM statement means that No is the default.


How to: Create a Progress Window

If you have an application that performs some processing which can take a long time to complete, you should consider displaying a window that informs the user of the progress that is being made.

You can create a window in which each field is updated while the program is running. For example, the fields in a window display the count of the number of postings made. You can also display information about the record that is currently being processed. For example, the field in a window displays the number of the account that is currently being processed.

To create a progress window

  1. On the Tools menu, choose Object Designer.

  2. In Object Designer, select Codeunit, and then choose the New button.

  3. On the View menu, choose C/AL Globals.

  4. On the Variables tab, in the Name field, enter ProgressWindow. In the Data Type field, select Dialog from the drop-down list.

  5. On the Variables tab, on a new line in the Name field, enter ChartOfAcc. In the Data Type field, select Record from the drop-down list. In the Subtype field, select G/L Account from the table list.

  6. In the C/AL Editor for the dialog, add the following code.

    Copy Code
    ProgressWindow.OPEN('Processing account number #1#######');
REPEAT
   SLEEP(1000);
   ProgressWindow.UPDATE(1,ChartOfAcc."No.");
   // Process the account.
UNTIL ChartOfAcc.NEXT = 0;
ProgressWindow.CLOSE;

    The first line defines the string that will be displayed in the progress window. The part of the string that contains the number signs (#) and a number defines the field that will be displayed in the window. The number (1) refers to the field.

    In this example, each entry in the G/L Account table is updated and the number of each account is displayed as it is updated.

    The SLEEP(1000); function is necessary only to slow the processing so that you can see the progress window.

See Also

Concepts

Progress Windows, MESSAGE, ERROR, and CONFIRM Functions


STRMENU Function

STRMENU creates and displays a dialog box with an option group and returns the selection that the user makes.

STRMENU has the following syntax.

Copy Code
OptionNumber := Dialog.STRMENU(OptionString [, DefaultNumber]);

OptionNumber is the number of the option that the user chooses. The first option in OptionString is number 1. If the user closes the dialog box with ESC, then STRMENU returns 0 (zero). If it is defined, then DefaultNumber is used to select the default option. If DefaultNumber is not defined, then option number 1 is used as the default.

Example

The following example creates a window with the following options:

  • Save

  • Close

  • Cancel

The window also has an OK button and a Cancel button.

This example requires that you create the following variable.

Variable | Data type
Selection | Integer
Copy Code
Selection := Dialog.STRMENU('Save,Close,Cancel',3);

In this example, the Cancel option is the default because the DefaultNumber parameter was set to 3. We recommend that you set the default to a harmless action, such as cancel, because this option can be selected by pressing Enter. If the user accidentally presses Enter, nothing catastrophic occurs, as might be the case if the default option was "Delete all."

See Also

Reference

STRMENU Function (Dialog)

Concepts

Progress Windows, MESSAGE, ERROR, and CONFIRM Functions


C/AL Reserved Words

C/AL has several reserved words that you cannot use as variable, constant, or function names in your application. Reserved words include the following types:

  • Data types

  • Keywords

  • Functions

  • Operators

  • Properties

  • System variable names

  • Triggers

In some cases, you can use reserved words as variable names if you enclose the variable name in quotation marks. However, we do not recommend this practice.

If you write code on client report definition (RDLC) report layouts, then verify that your code does not use Visual Studio Report Designer reserved words. For more information, see Using Expressions in a Report (Visual Studio Report Designer) and its subtopics.

List of Reserved Words

The following table lists all of the C/AL reserved words.

Reserved word | Type
Abs | Function
Action | Data type
Activate | Function
Active | Function
ActiveControlOnOpen | Property
Addlink | Function
Addtext | Function
AltSearchField | Property
And | Operator
Applicationpath | Function
Array | Functions
ArrayLen | Function
Ascending | Function
AssertError | Keyword
AssistEdit | Property
AutoCalcField | Property
AutoEnter | Property
AutoFormatExpr | Property
AutoFormatType | Property
AutoIncrement | Property
Automation | Data type
AutoPosition | Property
AutoRepeat | Property
AutoReplace | Property
AutoSave | Property
AutoSplitKey | Property
AutoUpdate | Property
BackColor | Property
BackTransparent | Property
BackupKey | Property
Beep | Function
Begin | Keyword
BigInteger | Data type
BigText | Data type
Binary | Data type
Bitmap | Property
BitmapList | Property
BitmapPos | Property
BlankNumbers | Property
BlankZero | Property
BLOB | Data type
Boolean | Data type
Border | Property
BorderColor | Property
BorderStyle | Property
BorderWidth | Property
BottomMargin | Property
Break | Function
CalcDate | Function
CalcField | Function
CalcFields | Function, Property
CalcFormula | Property
CalcSum | Function
CalcSums | Function
CallFieldValidate | Property
Cancel | Property
Caption | Function, Property
CaptionBar | Property
CaptionClass | Property
CaptionML | Property
CardPageID | Property
Case | Keyword
ChangeCompany | Function
Char | Data type
CharAllowed | Property
ChartPartID | Property
CheckLicenseFile | Function
Class | Function
Clear | Function
ClearAll | Function
ClearLastError | Function
ClearMarks | Function
ClearOnLookup | Property
ClientType | Function
Close | Function
ClosingDate | Function
ClosingDates | Property
Clustered | Property
Code | Data type
CodeCoverageLog | Function
Codeunit | Data type
CommandLine | Function
Commit | Function
CompanyName | Function
CompressArray | Function
Compressed | Property
Confirm | Function
Consistent | Function
ContainerType | Property
ContextURL | Function
ControlAddin | Property
ControlType | Property
ConvertStr | Function
Copy | Function
CopyArray | Function
CopyFilter | Function
CopyFilters | Function
CopyLinks | Function
CopyStr | Function
CopyStream | Function
Count | Function
CountApprox | Function
Create | Function
CreateDateTime | Function
CreateGUID | Function
CreateInstream | Function
CreateOutstream | Function
CreateTempFile | Function
CurrentClientType | Function
CurrentDateTime | Function
CurrentExecutionMode | Function
CurrentKey | Function
CurrentKeyIndex | Function
CurrentTransactionType | Function
CurrPage | System Variable
CurrReport | System Variable
Database | Function
DataCaptionExpr | Property
DataCaptionFields | Property
DataItemIndent | Property
DataItemLink | Property
DataItemLinkReference | Property
DataItemSeparator | Property
DataItemTable | Property
DataItemTableView | Property
DataLength | Property
DataPerCompany | Property
Date | Data type
Date2DMY | Function
Date2DWY | Function
DateFormula | Data type, Property
DateTime | Data type
DaTi2Variant | Function
Debugger | Function
Decimal | Data type
DecimalPlaces | Property
DecimalPlacesMax | Function
DecimalPlacesMin | Function
Default | Property
DefaultClientType | Function
DefaultFieldsValidation | Property
DelayedInsert | Property
DelChr | Function
Delete | Function
DeleteAll | Function
DeleteAllowed | Property
DeleteLink | Function
DeleteLinks | Function
DelStr | Function
Description | Property
DeviceFontName | Property
Dialog | Data type
Dimensions | Property
Direction | Property
Div | Operator
Divisor | Property
DMY2Date | Function
Do | Keyword
Download | Function
DownloadFromStream | Function
DownTo | Keyword
DrillDown | Property
DrillDownPageID | Property
DropDown | Property
DT2Date | Function
DT2Time | Function
Duplicate | Function
Duration | Data type
DWY2Date | Function
Editable | Function, Property
Ellipsis | Property
Else | Keyword
Enabled | Function, Property
EnabledIfError | Property
EnabledIfInsertion | Property
EnabledIfSelection | Property
Encoding | Property
End | Keyword
Environ | Function
EOS | Function
Erase | Function
Error | Function
Evaluate | Function
Event | Keyword
Exists | Function
Exit | Keyword
Export | Function
ExportObjects | Function
ExtendedDataType | Property
False | Keyword
Field | Function
Field No. | Property
FieldActive | Function
FieldCaption | Function
FieldClass | Property
FieldCount | Function
FieldEndDelimiter | Property
FieldError | Function
FieldExist | Function
FieldIndex | Function
FieldName | Function
FieldNo | Function
FieldRef | Data type
FieldSeparator | Property
FieldStartDelimiter | Property
FieldValidate | Property
File | Data type
FileFormat | Property
FileName | Function, Property
FilterGroup | Function
Find | Function
FindFirst | Function
FindLast | Function
FindSet | Function
Focusable | Property
FocusOnClick | Property
FontBold | Property
FontItalic | Property
FontName | Property
FontSize | Property
FontStrikethru | Property
FontUnderline | Property
For | Keyword
ForeColor | Property
Format | Function, Property
FreezeColumnID | Property
FunctionType | Property
Get | Function
GetFilter | Function
GetFilters | Function
GetLastErrorText | Function
GetPosition | Function
GetRangeMax | Function
GetRangeMin | Function
GetRecord | Function
GetStamp | Function
GetSubtext | Function
GetTable | Function
GetURL | Function
GetView | Function
GlobalLanguage | Function
GroupTotalFields | Property
GroupType | Property
GUIAllowed | Function
GUID | Data type
HandlerFunctions | Property
HasFilter | Function
HasLinks | Function
HasValue | Function
HeadingHeight | Property
Height | Function, Property
HideValue | Property
HorzAlign | Property
HorzGlue | Property
HorzGrid | Property
Hyperlink | Function
ID | Property
If | Keyword
Image | Property
Import | Function, Property
Importance | Property
ImportObjects | Function
In | Operator
IncludeInDataSet | Property
InColumn | Property
InColumnHeading | Property
IncStr | Function
Indent | Property
Indentation | Property
IndentationColumnName | Property
IndentationControls | Property
InFooterBar | Property
InFrame | Property
Init | Function
InitValue | Property
InlineEditing | Function, Property
InMatrix | Property
InMatrixHeading | Property
InPage | Property
Input | Function
Insert | Function
InsertAllowed | Property
InsStr | Function
InStream | Data type
InstructionalTextML | Property
Integer | Data type
InvalidActionAppearance | Property
IsAction | Function
IsAutomation | Function
IsBinary | Function
IsBoolean | Function
IsChar | Function
IsClear | Function
IsCode | Function
IsCodeunit | Function
IsDate | Function
IsDateFormula | Function
IsDecimal | Function
IsEmpty | Function
IsFile | Function
IsInstream | Function
IsInteger | Function
IsNullGUID | Function
IsOption | Function
IsOutstream | Function
IsRecord | Function
IsText | Function
IsTime | Function
IsTransactionType | Function
KeepWithNext | Property
Key | Property
KeyCount | Function
KeyGroupDisable | Function
KeyGroupEnable | Function
KeyGroupEnabled | Function
KeyGroups | Property
KeyIndex | Function
KeyRef | Data type
Language | Function
LeaderDots | Property
LeftMargin | Property
Len | Function
Length | Function
LinkedInTransaction | Property
LinkedObject | Property
LinkFields | Property
LinksAllowed | Property
LinkTable | Property
LinkTableForceInsert | Property
Local | Keyword
LockTable | Function
LockTimeout | Function
LogHeight | Function, Property
LogWidth | Function, Property
Lookup | Property
LookupPageID | Property
LookupMode | Function, Property
Lowercase | Function
MaintainSIFTIndex | Property
MaintainSQLIndex | Property
Mark | Function
MarkedOnly | Function
MatrixColumnWidth | Property
MatrixSourceTable | Property
Maximizable | Property
MaximizedOnOpen | Function, Property
MaxIteration | Property
MaxLength | Property
MaxOccurs | Property
MaxStrLen | Function
MaxValue | Property
MenuItemType | Property
MenuLevel | Property
Message | Function
Minimizable | Property
MinimizedOnOpen | Function, Property
MinOccurs | Property
MinValue | Property
Mod | Operator
Modify | Function
ModifyAll | Function
ModifyAllowed | Property
MultiLine | Property
MultipleNewLines | Property
Name | Function, Property
Namespaces | Property
NamespacePrefix | Property
NewPagePerGroup | Property
Next | Function
NextControl | Property
NodeName | Property
NodeType | Property
NormalDate | Function
Not | Operator
NotBlank | Property
Number | Function
Numeric | Property
ObjectType | Function
Occurrence | Property
OCX | Data type
Of | Keyword
OnAction | Trigger
OnActivate | Trigger
OnAfterAssignField | Trigger
OnAfterAssignVariable | Trigger
OnAfterExportRecord | Trigger
OnAfterFormatField | Trigger
OnAfterGetField | Trigger
OnAfterGetRecord | Trigger
OnAfterImportRecord | Trigger
OnAfterInitRecord | Trigger
OnAfterInput | Trigger
OnAfterInsertRecord | Trigger
OnAfterModifyRecord | Trigger
OnAfterTestRun | Trigger
OnAfterValidate | Trigger
OnAssistEdit | Trigger
OnBeforeEvaluateField | Trigger
OnBeforeExportRecord | Trigger
OnBeforeImportRecord | Trigger
OnBeforeInput | Trigger
OnBeforeInsertRecord | Trigger
OnBeforeModifyRecord | Trigger
OnBeforePassField | Trigger
OnBeforePassVariable | Trigger
OnBeforePutRecord | Trigger
OnBeforeTestRun | Trigger
OnClosePage | Trigger
OnControlAddin | Trigger
OnDeactivate | Trigger
OnDelete | Trigger
OnDeleteRecord | Trigger
OnDrillDown | Trigger
OnFindRecord | Trigger
OnFormat | Trigger
OnInit | Trigger
OnInitReport | Trigger
OnInitXMLport | Trigger
OnInputChange | Trigger
OnInsert | Trigger
OnInsertRecord | Trigger
OnLookup | Trigger
OnModify | Trigger
OnModifyRecord | Trigger
OnNewRecord | Trigger
OnNextRecord | Trigger
OnOpenPage | Trigger
OnPostDataItem | Trigger
OnPostReport | Trigger
OnPostSection | Trigger
OnPostXMLport | Trigger
OnPreDataItem | Trigger
OnPreReport | Trigger
OnPreSection | Trigger
OnPreXMLItem | Trigger
OnPreXMLport | Trigger
OnPush | Trigger
OnQueryClosePage | Trigger
OnQueryClosePage | Trigger
OnRename | Trigger
OnTimer | Trigger
OnValidate | Trigger
Open | Function
Option | Data type
OptionCaption | Function, Property
OptionCaptionML | Property
OptionString | Function, Property
OptionValue | Property
Or | Operator
Orientation | Property
OSVersion | Function
OutStream | Data type
PadChar | Property
PadStr | Function
Page | Data type
PageNames | Property
PageNamesML | Property
PAGENO | Function
PagePartID | Property
PageType | Property
PaperSize | Property
PAPERSOURCE | Function
PaperSourceDefaultPage | Property
PaperSourceFirstPage | Property
PaperSourceLastPage | Property
PaperSourceOtherPages | Property
ParentControl | Property
PartType | Property
PasswordText | Property
PasteIsValid | Property
Percentage | Property
PermanentAssist | Property
Permissions | Property
PlaceInBottom | Property
PopulateAllFields | Property
Pos | Function
Power | Function
Preview | Function
PrintOnEveryPage | Property
PrintOnlyIfDetail | Function, Property
ProcessingOnly | Property
Promoted | Property
PromotedCategory | Property
PromotedIsBig | Property
ProviderID | Property
PushAction | Property
Query | Object
QueryReplace | Function
Quit | Function
Random | Function
Randomize | Function
Read | Function
ReadConsistency | Function
ReadPermission | Function
ReadText | Function
Rec | System Variable
Record | Data type
RecordID | Data type, Function
RecordLevelLocking | Function
RecordRef | Data type
RecordSeparator | Property
Relation | Function
Rename | Function
Repeat | Keyword
Report | Data type
ReqFilterFields | Property
ReqFilterHeading | Property
ReqFilterHeadingML | Property
RequestOptionsPage | System Variable
Reset | Function
RightMargin | Property
Round | Function
RoundDateTime | Function
RowHeight | Property
Run | Function
RunCommand | Property
RunPageLink | Property
RunPageOnRec | Property
RunPageView | Property
RunModal | Function
RunObject | Property
SaveAsExcel | Function
SaveAsHTML | Function
SaveAsPDF | Function
SaveAsXML | Function
SaveColumnWidths | Property
SaveControlInfo | Property
SavePosAndSize | Property
SaveRecord | Function
SaveValues | Property
SectionHeight | Property
SectionWidth | Property
Seek | Function
SelectLatestVersion | Function
SelectStr | Function
SerialNumber | Function
SetAutoCalcFields | Function
SetCurrentKey | Function
SetFilter | Function
SetPermissionFilter | Function
SetPosition | Function
SetRange | Function
SetRecFilter | Function
SetRecord | Function
SetSelectionFilter | Function
SetStamp | Function
SetTable | Function
SetTableView | Function
SetView | Function
ShapeStyle | Property
Shell | Function
ShortCutKey | Property
ShowAsTree | Property
ShowCaption | Property
ShowPrintStatus | Property
ShowStatus | Property
SID | Function
SignDisplacement | Property
SingleInstance | Property
Sizable | Property
Skip | Function
Sleep | Function
SourceExpr | Property
SourceField | Property
SourceTable | Property
SourceTablePlacement | Property
SourceTableRecord | Property
SourceTableTemporary | Property
SourceTableView | Property
SourceType | Property
SQL Data Type | Property
SQLIndex | Property
StartPos | Property
STARTSESSION | Function
STOPSESSION | Function
StrCheckSum | Function
StrLen | Function
StrMenu | Function
StrPos | Function
StrSubstNo | Function
Style | Property
StyleExpr | Property
SubPageLink | Property
SubPageView | Property
SubType | Property
SumIndexFields | Property
SynchronizeAllLogins | Function
SynchronizeSingleLogin | Function
System | Data type
SystemPartID | Property
TableBoxID | Property
TableCaption | Function
TableFilter | Data type
TableIDExpr | Property
TableName | Function
TableNo | Function, Property
TableRelation | Property
Temporary | Property
TemporaryPath | Function
TestField | Function
TestTableRelation | Property
Text | Data type
TextEncoding | Function
TextMode | Function
TextPos | Function
TextType | Property
Then | Keyword
Time | Data type
TimerInterval | Property
Title | Property
To | Keyword
Today | Function
ToolTip | Property
ToolTipML | Property
TopLineOnly | Property
TopMargin | Property
TotalFields | Property
TOTALSCAUSEDBY | Function
TransactionType | Data type, Property
TransferFields | Function
True | Keyword
Trunc | Function
Type | Function
Until | Keyword
Update | Function
UpdateControls | Function
UpdateEditable | Function
UpdateFontBold | Function
UpdateForeColor | Function
UpdateIndent | Function
UpdateOnAction | Property
UpdateOnActivate | Property
UpdateSelected | Function
Upload | Function
UploadIntoStream | Function
Uppercase | Function
UseRequestPage | Property
UserID | Function
UseSystemPrinter | Property
Validate | Function
ValidateTableRelation | Property
Value | Function
ValuesAllowed | Property
Var | Keyword
VariableActive | Function
VariableName | Property
Variant | Data type
Variant2Date | Function
Variant2Time | Function
VertAlign | Property
VertGlue | Property
VertGrid | Property
Visible | Function, Property
While | Keyword
Width | Function, Property
WindowsLanguage | Function
With | Keyword
WithEvents | Property
WordDate | Function
Write | Function
WriteMode | Function
WritePermission | Function
WriteText | Function
XMLport | Data type
XMLVersionNo | Property
XOR | Operator
XPos | Function, Property
xRec | System variable
Yield | Function
YPos | Function, Property


General C/AL Programming Format

To make it easy to maintain an application, you should follow a few strict guidelines when you write C/AL code. This section describes the general rules for:

  • Spacing and indentation

  • Parentheses

  • Comments

  • Symbolic values

  • Parameters

  • Order in expressions

  • Order of variables

In addition, we recommend that you enter all C/AL code as English (United States). If all code is in the same language, then it is easier to maintain the application.

Spacing and Indentation

The following examples show how to use spacing and indentation.

Example

Use exactly one space character on each side of a binary operator, such as assignment or plus.

Copy Code
y := (a + b) / 100;

Example

Do not have a space between a unary operator and its argument.

Copy Code
y := -x;

Example

Refer to multiple dimensions in a record array by using sets of brackets without space characters between the dimensions.

Copy Code
a[i][j] := b;

Example

Do not use blank lines at the beginning or end of any functions.

Copy Code
PROCEDURE P();
BEGIN
  x := a;
  y := (a + b) / 100;
END;

Example

In general, use an indentation of two character spaces.

Copy Code
IF a <> '' THEN
  Record.TESTFIELD(b);

Example

When you split a C/AL statement into two or more lines, do not align the continuation lines according to user-defined or system-defined variables, functions, field names, object names, and other elements. Instead, indent the continuation lines by two characters. Aligning by variable, function, field name, or object name may look clearer in your program, but the alignment will not hold if the variable name is changed to something shorter or longer. Although the system-defined variable and function names are not likely to change, the rule also applies when you use them.

Copy Code
MyVariable :=
  Variable1 + Variable2 * 2 +
  Variable3 * 3;

Example

Copy Code
MyFunction(
  Expression1,Expression2,
  Expression3,Expression4);

Example

Copy Code
ERROR(
  StringExpression,
  Expression1,Expression2,Expression3);

Example

Copy Code
IF NOT
  SETCURRENTKEY(
    aaaaaaaaaa,bbbbbbbbbb,cccccccccc,
    dddddddddd,eeeeeeeeee)
THEN
  SETCURRENTKEY(bbbbbbbbbb,aaaaaaaaaa);

Parentheses

The following examples show how to use parentheses.

Example

Align a opening parenthesis in an expression with a corresponding parenthesis on the preceding line.

Copy Code
aaaaaaaaaa :=
  ((xxxxxxxxxxx / yyyyyyyyyyyyy) -
   (1 + zzzzzzzzzz / 100)) *
  100;

Example

Do not use parentheses in a function call if the function does not have any parameters.

Copy Code
PostLine;

Use parentheses only to enclose compound expressions inside compound expressions.

Copy Code
IF Boolean1 AND Boolean2 AND (x = y) THEN
  x := a + b
ELSE
  x := b / (a + b);

Comments

The following examples show how to format comments.

Example

Always start comments with // and one space character. Never use braces ({ and }). To emphasize a comment, put it on a separate line and insert one empty line before it.

Copy Code
x := x + 1;
// Comment
x := x * 2;

Example

If the comment is on the same line as the C/AL code, then add one space character before the comment sign.

Copy Code
x := '....'; // Comment

Symbolic Values

When possible, use the name of the Option for a field instead of just an integer for the value.

Example

Copy Code
Table.Field := Table.Field::Option;

Example

Copy Code
IF Table.Field IN[Table.Field::Option1,Table.Field::Option2] THEN
  EXIT;

Incorrect Example

Copy Code
Table.Field := 1;

Example

When possible, use the name of the Option in the conditional possibilities in a CASE statement.

Copy Code
CASE xxx OF
  xxx::aaa,xxx::bbb:
    x := y;
ELSE
  y := x;
END;

Parameters

Use parameters when you want to transfer information to a function.

To use a parameter as an option field, define it in the function. When you call the function, use an integer as parameter in the call.

Example

Copy Code
...
P(0);
...
PROCEDURE P(MyOption : 'Value0,Value1,Value2');
BEGIN
  CASE MyOption OF
    MyOption::Value0:
      x := x * 10;
    MyOption::Value1:
      x := x * 15;
    MyOption::Value2:
      x := x * 20;
  END;
END;

Order in Expressions

The variable that you are operating on or comparing to something else must always come first in expressions.

Example

IF x <> 0 THEN

x := x - 100;

Example

IF (Date < a) OR (Date > b) THEN

Date := c;

Incorrect Example

IF 0 > x THEN

x := x - 100;

Order of Variables

List variables in the following order:

  • Record variables

  • Page variables

  • Report variables

  • XMLport variables

  • Codeunit variables

  • Dialog, file, and BLOB variables

  • Simple variables

Record variables are listed in an order that reflects the hierarchy of the tables that are used in the database. Base tables come before journals and other nonposted lines and headers, which themselves come before ledger entries and posted lines and headers.

Example

Copy Code
VAR
  GLSetup : Record 98;
  UserSetup : Record 91;
  ItemPostingGr : Record 94;
  Item : Record 27;
  ItemJnlTemplate : Record 82;
  ItemJnlBatch : Record 233;
  ItemJnlLine : Record 83;
  ItemReg : Record 46;
  ItemLedgEntry : Record 32;


Programming Best Practices

This topic describes best practices for developing Microsoft Dynamics NAV applications.

Ensuring Simplicity

When you write a solution in Microsoft Dynamics NAV, keep it simple. This applies to everything that becomes visible either to other programmers or to any users. The following are a few examples.

  • If the default value for a property is appropriate for a specific purpose, then do not make the default value explicit.

  • If a variable can be reset with a statement such as a := 0; then do not use a special C/AL function, such as the CLEAR Function, to reset the variable.

  • If the contents of a record can be copied with a statement such as MyRec := MyRec2; then do not use a special C/AL function, such as the TRANSFERFIELDS Function (Record), to copy the contents.

  • The Rec global variable references the source table of a page. When you refer to fields or functions of that table, you do not need to qualify them with Rec.< field> or Rec.< function>. You use <field> or <function>

Activating Objects

If you want to use the value of a field to find a record in a table or if you want to activate an object identified by the field, then ensure that the field contains a value. To do this, use the TESTFIELD Function (Record), as shown in the following example. This produces more informative error messages if the value is zero or blank.

Copy Code
GLEntry.TESTFIELD("Department Code");
Dept.GET(GLEntry."Department Code");
GenJnlTemplate.TESTFIELD("Report ID");
REPORT.RUN(GenJnlTemplate."Report ID")

Setting Properties

To set properties from C/AL, use code that is similar to the following code.

Copy Code
"Customer No.".Visible := TRUE;
Cust.MARK := TRUE;

Do not use the following code.

Copy Code
Customer." No.".Visible(TRUE);
Cust.MARK(TRUE);

Writing Lookups

When writing lookups in C/AL, do not filter records that the user may want to select. Instead, program the record cursor to be positioned on the most relevant record for the search even though it may not be first on the list. When programming the OnLookup trigger for a field, the code in the field’s OnValidate trigger is not called unless you explicitly call Field.VALIDATE. If errors can occur in the validation, then you must operate on a copy of the Rec variable as shown in the following example instead of directly on the Rec variable.

Copy Code
WITH Cust DO BEGIN
  Cust := Rec;
  Dept.Code := "Department Code";
  IF PAGE.RUNMODAL(O,Dept) = Action::LookupOK THEN BEGIN
    "Department Code" := Dept.Code;
    VALIDATE("Department Code");
    Rec := Cust;
  END;
END;

To make Lookup work on a field that has a table relation to a system table, you must always explicitly set the LookupPageID Property on controls that show the field.

Set the LookupPageID Property and DrillDownPageID Property on most tables. You cannot anticipate when a user must activate a Lookup or DrillDown button. For example, if a user creates a report with a filter tab on the table, then the Lookup button on the filter tab will not appear unless the LookupPageID property is set on the table.

Designing Journal Pages

The default order of fields in journals is:

  • Date

  • Document Type

  • Document No.

  • No.

  • Description

  • Amount

The order of fields in ledger entries should be the same. The order of fields in pages and reports should also be the same.

Laying Out Fields on Pages

This section contains guidelines for which fields to include on the following pages:

  • Card pages

  • Worksheet pages.

For each type of page, consistency is important. Similar pages in the application areas must be composed the same way.

Card Pages

Some card pages are related to a table that contains only a few fields. It is not hard to create such pages because it is often obvious where to place the fields on FastTabs on a page and which fields to promote to the FastTab header. Most card pages are related to tables with many fields.

Many pages use several FastTabs. How many FastTabs are needed and what to call them are specific to each page. The following FastTab names are commonly used:

  • General, which is the first tab

  • Invoicing

  • Posting

All relevant fields must be included on a card page. Even card pages with many tabs have a limited space for fields, so you must carefully consider relevancy. Which fields to include depends on the purpose of each page. We recommend using the following guidelines:

  • Always include dimensions, such as department, project, or location.

  • Do not include fields that are automatically filled in and do not need to be changed by the user.

  • Do not place the same field on a page twice, even on different tabs.

  • If two or more fields are related according to source or function, then group them.

On which FastTab to place a field depends on the specific page. Some fields are used on many pages. For consistency, place the following fields on the General FastTab:

  • No.

  • Name

  • Search Name

  • Blocked

  • Last Date Modified

  • Other information about the account

Place the following fields on the Posting or Invoicing FastTab:

  • General Business Posting Group

  • General Product Posting Group

  • Posting group from the actual application area

  • Department Code

  • Project Code

Worksheet Pages

In general, all fields are included on worksheet pages. Some exceptions are mentioned in the following section. The fields are shown or hidden depending on how relevant they are and what the layout of the page is. You must consider the following points when you create worksheet pages:

  • Always include dimensions, such as department or project. The fields should be hidden.

  • Do not include FlowFields on worksheet pages unless the page is seldom used or the field is essential. FlowFields are calculated even when they are hidden.

  • Do not include more than about 25 fields on a page because this can affect performance. Consider carefully which fields, both hidden and visible, that you will include on a page. Because of performance considerations, worksheet pages should not include fields that may be informative but cannot be changed, such as Posting Group, Journal Name, Weights, and Source Type.

  • Never include fields that are used internally in the program, such as Closed by Entry No.

  • Use worksheet pages for all page in the Setup menu. Creating these page does not typically cause problems because they often contain only a code and a few information fields.

Pages such as journals, sales/purchase lines, and ledgers are difficult to create and maintain properly because the related tables contain a lot of functionality and many fields. In an uncustomized application, the same template is used to compose these pages so that they look similar. The following table shows the template. It is divided into sections according to functionality. In each section, the most common field names are mentioned.

Note
The table does not include all functionality. Additionally, the order that is indicated in the table does not always indicate the order in pages.

Section Example fields

Dates

  • Posting Date

  • Document Date

Document

  • Entry Type

  • Document Type

  • Document No.

No. (of Account)

No.

Posting Description

Description

Dimensions

  • Department Code

  • Project Code

  • Business Unit Code

  • Location Code

  • Salesperson/Purchaser Code

  • Work Type Code

  • Phase Code

  • Task Code

  • Step Code

Currency

  • Currency Code

  • Exchange Rate

General Posting Setup

  • General Posting Type

  • General Business Posting Group

  • General Product Posting Group

Quantity

  • Quantity

  • Invoiced Quantity

  • Remaining Quantity

  • Unit of Measure Code

Prices/Cost

  • Direct Unit Cost

  • Indirect Cost %

  • Unit Cost

  • Total Cost

  • Profit %

  • Unit Price

  • Total Price

  • Price Group Code

  • Chargeable

    Note
    The exact name and order depend on the application area.

Amounts

  • Amount

  • Amount Including VAT

  • VAT Amount

  • Remaining Amount

    Note
    Amounts in LCY must follow each amount type.

Balancing Account

Balancing Account Type

Balancing Account No.

Balancing General Posting Type

Balancing General Business Posting Group

Balancing General Product Posting Group

Sales/Purchase and Discount

  • Sales/Purchase (LCY)

  • Profit (LCY)

  • Line Discount %

  • Line Discount Amount

  • Allow Invoice Discount

  • Invoice Discount Amount

Payment Terms

  • Payment Terms Code

  • Due Date

  • Payment Discount Date

  • Payment Discount %

Application

  • Serial No.

  • Applies-To Document Type

  • Applies-To Document No.

  • Applies-To ID

  • Applies-To Item Entry

  • Applies-To Entry

  • Apply and Close (Job)

  • Open

Miscellaneous Information

  • Cost Is Adjusted

  • Cost Posted to G/L

  • On Hold

  • Bank Payment Type

Intrastat

  • Transaction Type

  • Transport Method

  • Country/Region Code

Posting Information

  • Quantity to Ship

  • Quantity Shipped

  • Quantity to Invoice

  • Quantity Invoiced

Audit Information

  • User ID

  • Source Code

  • Reason Code

  • Entry No.

See Also

Concepts

Programming in C/AL


Avoiding Run-Time Errors

Run-time errors occur during program execution. These errors are not detected by the compiler because the code is syntactically correct.

Run-Time Error Example

An example of a run-time error is a statement that causes division by zero. In the following statement, the syntax is correct, but the statement may cause a division by zero error if the variable SecondNumber is assigned a value of 0.

Copy Code
Ratio := FirstNumber / SecondNumber;

The common trait of these errors is that the code works correctly many times, but fails in others. The risk is that because there is nothing syntactically wrong with the code, the error might occur when the program is already being used. Unless you handle the run-time error in your code, default messages will appear.

How to Avoid Run-Time Errors

The following guidelines recommend ways to avoid run-time errors. The conditions under which run-time errors occur depend on the context of your application.

For example, if you use the GET Function (Record) to locate a record, then we recommend that you handle the risk that a run-time error occurs when no record is found. If you are sure that the specific context prevents this situation, then you can omit handling a possible run-time error. For example, the context could be that you verify the existence of a record before you call the GET function.

There are two categories of run-time errors:

  • Errors that are related to the use of data types.

  • Errors that occur if a function is unsuccessful doing what it is supposed to do.

You can prevent some errors from occurring. Other errors cannot always be avoided, but you can write code that shields the user from the error. Instead of the default error handling, which displays a message, closes the page that was active when the error occurred, and rolls back any changes to the database, you can write an error handler that, for example, displays a message that explains why the error occurred and gives the user an opportunity to correct the input that caused the error.

Data Type-Related Errors

The easiest way to avoid data type-related errors is to use the correct data types. You can avoid errors such as the type conversion errors and overflow errors by using the correct data types.

An example of data type-related errors for integer and decimal data types is division by zero errors. You can avoid division by zero errors in several ways, depending on the context where the code fragment is used. If the user enters the denominator (the SecondNumber variable) in a text box immediately before the evaluation of the statement, then you can test the value of SecondNumber before you perform the division and reject a value of 0 (zero).

Copy Code
IF SecondNumber <> 0 THEN
  Ratio := FirstNumber / SecondNumber
ELSE
  MESSAGE(‘SecondNumber must not be 0’);

If SecondNumber is a field in a database table and it should never be allowed to have a value of 0 (zero), then the best place to perform this check is in the OnValidate trigger of the field. This enables you to make sure that a value of 0 (zero) can never be entered in the field.

Other Run-time Errors

Any function that does not accomplish what it is intended to do can cause a run-time error. For example, the GET function, which is used to locate a record in a table according to criteria that you specify, can cause a run-time error in some instances.

The syntax of the GET function is:

[Ok :=] Record.GET([Value1], [Value2 ],...)

The return value of the function is Ok, a Boolean. If a record is found, then the return value is true; otherwise, it is false. This return value is optional, as indicated by the square brackets. If you do not use the return value and the requested record cannot be found, then a run-time error occurs and a system-generated error message is displayed. However, if you use the return value, then it is assumed that you handle any errors.

The C/SIDE Reference Guide provides information about how C/AL functions handle errors. You can also use the syntax description in the Symbol Menu to verify whether a function returns a value called Ok

If you use the return value in either of the following examples, then you shield the user from a run-time error.

Example 1

Copy Code
IF NOT Customer.GET(“No.”) THEN
  Customer.INIT;

Example 2

Copy Code
IF NOT Customer.GET(“No.”) THEN BEGIN
  MESSAGE(‘Customer %1 not found.’, “No.”);
  EXIT;
END;

In the first example, if a customer record with the given number (No.) cannot be retrieved, then an (empty) record is initialized. In the second example, the user is notified that the record cannot be found and the trigger from where the GET function was called is exited. These examples are only general guidelines. You must consider how to handle situations such as these in the context of your own application.

Finding and Correcting Run-time Errors

To determine the cause of a run-time error, you must know the sequence of events that led to the error. The sequence of events should include the following:

  • What the user was doing at the time of the error.

  • What values the user entered.

  • What record caused the error.

If the error was caused by a calculation that failed to check whether a division by zero was about to be performed, then you can find the statement that led to the error. However, if the circumstances that led to the error are more complex and you cannot determine the exact location of the error, then you can use the Microsoft Dynamics NAV debugger.

See Also

Concepts

Debugging


Naming Conventions

Precise and consistent terminology helps the end user work with the application. Rules for naming and abbreviating objects also help developers to understand the CRONUS International Ltd. demonstration database and develop new features faster. This topic contains guidelines for naming objects, table fields, and variables. These guidelines describe naming conventions in English (United States).

The following general guidelines apply throughout your application:

  • Use existing terminology, if possible.

  • Name everything in a set of objects in the same language.

  • When you review the terminology in a set of objects, use the Translate Export and Translate Import items on the Tools menu in the development environment. Export the text strings to a text file to review them, and then import the text file back into the application.

  • Most names in a Microsoft Dynamics NAV application have a limit of 128 characters. This limit applies to the names of objects, functions, variables, properties, COM methods, and text constants. Table field names have a limit of 30 characters.

Visible Named Items

This section describes naming all visible items in an application, such as table fields. This includes all items that are presented to an end user.

  • When you develop your application, set the application language to English (United States) so that the Name Property is the same as the caption in English (United States). This will make it easier to upgrade and reuse modifications. The end user sees the value of the Caption Property but not the Name property.

  • You must follow the naming convention both for the name in English (United States) and for the caption in your local language.

  • Two objects of the same type must not have the same name.

  • Each object must be named in a way that leaves no doubt as to what it applies to. For example, an object can be specifically related to customers, items, or resources. Do not give a table the name “Status,” because the word Status is too general and could refer to something in most tables.

Table Objects

Always make the names of table objects singular. The table name corresponds to what one record in the table is called.

Page Objects

The name of a page depends on the page type. Use the singular form of the table name for a card page. Use the plural form of the table name for a tabular page. This informs end users about the type of page. If you can access a table with both a card page and a tabular page, then the page names should explicitly describe the types. For example, the Item Card and Item List pages both access the Item table and describe the page types. This tells the user that there is more than one way to access the table. Other page types, such as statistics pages, are given names that are as descriptive as possible.

Report Objects

Make the English caption and name of a report descriptive and do not include abbreviations. End users see the caption of a report object in the following instances:

  • On the request page.

  • When they modify a report.

  • When they want to identify an item, such as a sales invoice.

We recommend that you make the caption the same as the heading in the report.

Table Fields

Make the name and caption of a field descriptive. The end user should not have to see the caption in the context of other fields to understand what it is.

Describe the field contents and the field type in the caption. We recommend the following guidelines.

Guideline Examples

Include Date when you include a date field.

Note
Do not include Date for a date interval field.

  • Posting Date field

  • Allow Posting From field

Include a percent sign when the field contains a percentage.

Profit % field

Include Quantity or Qty. when you name a quantity field. Replace Quantity with No. when you refer to the number of entries.

  • Quantity Shipped field

  • No. Printed field

  • No. of New Records field

Include Amount or Amt. when you name an amount field.

Debit Amount field

Distinguish between amount and cost or price. Cost and price are typically used when naming an amount per unit, while amount is cost or price multiplied by quantity.

  • Unit Cost field

  • Unit List Price field

  • Line Amount field

Omit Amount when you include the following words in the caption:

  • Adj. (LCY)

  • Balance

  • Base

  • Charge

  • COGS

  • Discounts

  • Fee

  • Net Charge

  • Payments

  • Profit

  • Purchases

  • Sales

  • Usage

  • Balance at Date field

  • Additional Fee (LCY) field

  • Additional-Currency Net Change field

Use Amounts instead of Amount in FlowFields.

Invoice Amounts field

Name fields in local currency with the ISO currency code for the country/region in parentheses at the end. If a country/region currency has a symbol, use the symbol instead.

Note
In the CRONUS International Ltd. demonstration database, the abbreviation LCY, which means local currency, is used.

  • Sales (DKK) field

  • Sales (LCY) field in the Cust. Ledger Entry table

  • Sales ($) field

If a field contains parentheses, then put a space before the opening parenthesis.

Usage (Price) field

Formulate names for Boolean fields as positive questions or statements.

Cost is Adjusted field

If the primary key of a table is a code, then use Code as the name of the field that contains the code.

When the end user typically uses numeric values as keys, the field is called No. even though the field type is code. The following tables are exceptions where the primary key field is No.:

  • G/L Account

  • Customer

  • Vendor

  • Item

  • Item Group

  • Resource

  • Resource Group

  • Job

  • Purchase Header

  • Sales Header

Code field in the Location table

Base the field name on the related table and its primary key when you work with table relations.

The following instances are exceptions:

  • If a field refers to a general ledger account, end the name with Account or Acc. but not with G/L Account No. unless the field refers to the actual general ledger account.

    For example, in table 5813, Inventory Posting Setup, field 6 has the TableRelation property set to the G/L Account table. The primary key of the G/L Account table is No. However, field 6 in table 5813 is named Inventory Account. In table 17, G/L Entry, field 3 has the TableRelation property set to the G/L Account table. In this case, field 3 is referring to the actual general ledger account, so the name of field 3 in table 17 is G/L Account No.

  • If a field has a table relation to a posting group table, then call the field Posting Group.

In table 38, Purchase Header, field 4 has the TableRelation property set to the Vendor table. The primary key of the Vendor table is No., and the name of field 4 in table 38 is Pay-to Vendor No.

Use From or To when you refer to a line number in a ledger entry table.

From Entry No. field

Use Starting Date to specify the date from which something is valid. Use Ending Date to specify the date until something is valid.

Starting Date field in the Accounting Period table

Use First to mean earliest. Use Last to mean latest.

Last Sales Inv. No. field

Use Before with an amount before a calculation. Use After with an amount after a calculation.

Amount Added Before field

Page Buttons and Menu Items

Captions for command buttons, menu buttons, and menu items depend on whether the control is used as a routing choice to open another page or as a control to activate something.

When a control is used to open another page, its name signifies the page that the control opens. The first menu button on a card, tabular, or list page typically has the name of the corresponding table. We recommend that you name menu items on the menu button with the second part of the full name of the page that will be opened when a user selects the item.

For example, the caption for a menu button on a Customer card page is "Customer.” The caption for one of the menu items is on the Customer menu button is “Statistics.” The Statistics menu item opens the Customer Statistics page. When option buttons are used on the main menu page with the Border property set to Yes, the caption for these controls is the name of the application module.

When a control is used to activate something, the caption for it must be an imperative verb. An example is a control with the caption Check. If a page has many action controls, then they can be gathered as menu items on one menu button, such as Function or Posting.

Other Named Items

This section describes naming of internal items that are not visible to an end user. Because they are never shown to users, they do not have captions.

Codeunit Objects

The name of a codeunit starts with the object that the codeunit processes. The object is usually a record abbreviated as a variable. You can follow the object name with a dash and a description. Write the description of the codeunit in imperative voice without abbreviations. An example is the Purch-Explode BOM codeunit.

Variables

We recommend the following guidelines for naming variables.

Guideline Examples

Omit spaces, periods, and other characters such as parentheses that make quotation marks around a variable necessary.

GenJnlBatch

Replace currency unit signs such as $ with the corresponding currency unit code.

Note
This may not make a variable unique. To be unique, it must be different from the corresponding field name. Also, the variable is not necessarily unique when translated to another language.

AmountUSD

Start variables with uppercase letters.

If a variable is a compound of two or more words or abbreviations, then start each word or abbreviation with an uppercase letter.

Describe the variable usage wherever possible. If possible, start with the table name. If there are several variables in an object that would otherwise have the same name, then use appropriate prefixes or suffixes to differentiate them.

CustInvDiscAmountLCY

EnteredPostingDate (where the prefix is Entered)

Follow country/region-specific rules for abbreviations.

When you set up table and field variables, give the variable the same name as the table or field as described in the Table Fields section.

If a variable with the same name already exists, then add the number 2 to the variable name. If a variable with this name also exists, then use 3, and so on. Use these numbers only if you cannot establish a unique variable in another way.

CustLedgEntry2, NewCustLedgEntry (better than CustLedgEntry2)

Note that parameters and local variables have their own number series. Do not name a parameter GenJnlLine4 because a global variable named GenJnlLine3 already exists.

To use a variable to store a value temporarily, start the variable name with "Temp".

TempType

Use "Old" and "New" as prefixes for record variables when you have old tables and new tables.

Do not use "x" as a prefix. This is used only in table triggers when the record variable is created automatically by the development environment.

Include "Total" in the name of a variable that is used for totaling.

Use "From" or "To" when you are copying from or to a table.

Use "Starting" or "Ending" with dates and positions.

Use "First" or "Last" with the first or last record in a table or line in a journal. You can also use it as a flag to indicate that this is the first record that is processed.

FirstOrder

When a variable is a Record, Page, Report, XMLport, Query, or Codeunit data type and the object has a name that also functions as a field name or local function name, add the suffix Rec, Page, Report, XMLport, Query, or Codeunit.

SourceCodeRec (for a record variable from the Source Code table)

Note
Because "Source Code" is the name of a table and the name of a field in other tables, you should not use "SourceCode" for variables that hold the two different types of information.

User-Defined Functions

When you name user-defined functions, start with an imperative verb, such as ApplyCustLedgEntry. Use the following function name prefixes:

  • If the code posts something, then use “Post” as a prefix.

  • If the code makes something, then use “Make” as a prefix.

  • If the code inserts something, then use “Insert” as a prefix.

  • If something is selected, then use “Check” as a prefix.

Page Controls

Do not give a page control a name unless you want to refer to it in your C/AL code. If you name a page control, then add a prefix to the name with the abbreviated name of the associated table or page.

See Also

Concepts

Object Numbering Conventions


Object Numbering Conventions

Each object and field in Microsoft Dynamics NAV is identified by a number that is stored in its ID Property. This topic describes the numbering scheme for the development environment. Numbering conventions that are used in the CRONUS International Ltd. demonstration database and guidelines for objects and fields that are outside the demo range are described.

The Numbering System

The objects ranges in Microsoft Dynamics NAV are described in the following table.

Object number interval | Description
1 - 9,999 | CRONUS International Ltd. demonstration database design area
10,000 - 49,999 | Country/region design area
50,000 - 99,999 | Customer design area
100,000 - 999,999,999 | Microsoft Certified Partner design area
Note
Do not use the object numbers 99,000 - 99,999 for objects that you create, even though they are in the customer design area. The training material for Microsoft Dynamics NAV uses these numbers.

The fields in Microsoft Dynamics NAV are grouped as indicated in the following table.

Table number | Field numbers | Description
1 - 9,999 | 1 - 9999 | CRONUS International Ltd. demonstration database design area
1 - 9,999 | 10,000 - 49,000 | Country/region design area
1 - 9,999 | 50,0000 - 99,999 | Customer design area
1 - 9,999 | 100,000 - 999,999,999 | Microsoft Certified Partner design area
10,000 - 49,999 | 1 - 49,999 | Country/region design area
10,000 - 49,999 | 50,000 - 99,999 | Customer design area
10,000 - 49,999 | 100,000 - 999,999,999 | Microsoft Certified Partner design area
50,000 - 99,999 | 1 - 999,999,999 | Customer design area
100,000 - 99,999,999 | 1 - 9,999 | Microsoft Certified Partner design area
100,000 - 99,999,999 | 10,000 - 49,999 | Country/region design area
100,000 - 99,999,999 | 50,000 - 99,999 | Customer design area
100,000 - 99,999,999 | 100,000 - 999,999,999 | Microsoft Certified Partner design area
Note
Do not use the field numbers 99,000-99,999 in tables numbered between 1 and 49,999 for fields that you create, even though they lie in the customer design area. The training material for Microsoft Dynamics NAV uses these numbers.

When a Microsoft Certified Partner buys the insert permissions for a table number interval, such as 200,000-200,099, the partner also gets insert permissions for the same number interval (200,000-200,099) for fields in all other tables. If you create a table in the range for which you have insert permissions, then you can create fields in all field number intervals in the table. However, we recommend that you use only the field numbers that are in the same number interval as the table number interval so that fields in solutions from different partners do not interfere with each other.

Objects

The numbering conventions for objects depend on the object type. Conventions for the following types are described in the following sections:

  • Tables

  • Pages

  • Reports

  • Codeunits

Tables

Table object numbers are not divided into intervals in the CRONUS International Ltd. demonstration database. Use the first available object number when you create a table. Try to group related tables together.

Pages

Page object numbers are not divided into intervals in the CRONUS International Ltd. demonstration database. Use the first available object number when you create a page. Try to group related pages together.

Reports

Report objects are numbered in intervals in the CRONUS International Ltd. demonstration database. The following table displays the interval for each application area.

Report number interval | Application areas
1 - 99 | General Ledger, including VAT and Consolidation
100 - 199 | Accounts Receivable
200 - 299 | Sales
300 - 399 | Accounts Payable
400 - 499 | Purchases
500 - 599 | Common to both Purchases and Sales, including Exchange Rate
600 - 699 | Requisition
700 - 799 | Item, including Intrastat
800 - 899 | Bill of Materials
900 - 999 | Item Group
1000 - 1099 | Inventory (common to Item, BOM, and Item Group)
1100 - 1199 | Resource
1200 - 1299 | Job
1300 - 1399 | General
1400 - 9899 | Future areas
9900 - 9999 | Utilities

If you create a new report that does not belong in one of the existing application areas or if you create a new report and the area in which it belongs is full, then use a number from a new interval of length 100 and between 1,400 and 9,899.

If a report object can be printed, then it is called a report. Otherwise, it is called a batch job. Reports are numbered starting at the lower end of the interval. Batch jobs are numbered starting at the higher end of the interval with decreasing numbers.

We recommend that you number reports that are almost identical in the application areas with the same two final digits even if the report name is different. For example, the Sales Invoice report in the CRONUS International Ltd. demonstration database is number 206 and the Purchase Invoice report is number 406. Other examples are the date compression batch jobs for ledger entry tables, which always end with 98, and date compressions for budget entries, which always end with 97. This practice may cause gaps in the numbering sequence, but it helps the developer when adjustments to similar reports in the application are needed.

Codeunits

Codeunit object numbers are not divided into intervals in the CRONUS International Ltd. demonstration database. Use the first available object number when you create a codeunit. Try to group related codeunits together.

The journal posting codeunits follow a pattern that makes it easier to understand a new journal after you are familiar with one group of journal posting codeunits.

A group consists of two parts:

  • Codeunits in the first part post a journal.

  • Codeunits in the second part manage the journals.

Codeunit final digit | Journal posting codeunits
1 | Journal Line-Check
2 | Journal Line-Post
3 | Batch Name-Post

Codeunit final digit | Journal managing codeunits
0 | Journal-Management
1 | Journal-Post
2 | Journal-Post+Print
3 | Journal-Batch Post
4 | Journal-Batch Post+Print
5 | Register-Show Ledger

Codeunits for posting invoices also follow a pattern, which is displayed in the following table.

Codeunit final digit | Sales/Purchase Posting Codeunits
0 | Sales/Purchase Post
1 | Sales/Purchase Post (Yes/No)
2 | Sales/Purchase Post+Print

When you create codeunits for the sales application areas, use the same final digit for similar purchase application areas.

Table Fields

When you assign numbers to new fields in a table, consider whether the table is associated with other related tables. If so, then you may want to also add the fields to these related tables. In this case, the field must have the same field number in all tables. For example, if you add a new field to the Customer table but do not add the field to the Vendor table, then you still must reserve that field number in the Vendor table for the new field from the Customer table. It is easier to maintain the application when the tables look very similar.

Examples of associated tables are as follows:

  • Customer and Vendor tables

  • Journal template tables

  • Batch name tables

  • Journal line tables

  • Sales Header, Sales Shipment Header, Sales Invoice Header, and Sales Credit Memo Header tables

  • Purchase Line, Purchase Receipt Line, Purchase Invoice Line and Purchase Credit Memo Line tables

When you create a new independent table, do not leave gaps in the field numbers.

See Also

Concepts

Naming Conventions
Number Ranges for Text Constants


Sorting Numeric Values

This topic explains how items, such as documents, are numbered in Microsoft Dynamics NAV.

Number Sorting

Code fields in tables can contain both numeric values and text strings. By default, code fields are stored in Microsoft SQL Server using the nvarchar SQL data type. Nvarchar data types are sorted as if they are text strings. The following table illustrates the differences that occur in sorting as numeric values and sorting as text.

Numeric sorting | Text sorting
1 | 1
2 | 10
3 | 100
4 | 2
10 | 3
100 | 4

You can change the SQL Data Type property to specify that a code field is stored as an Integer, BigInteger, or Variant instead of a Varchar. Storing a code field as an Integer, BigInteger, or Variant introduces additional constraints on the data in the field. For more information about these constraints, see SQL Data Type Property.

To avoid sorting problems with code fields, we recommend that you use a numeric series that has a fixed length. You can do this in the following ways:

  • Define a numeric series that consists of a predefined number of digits that start with a digit other than zero. The following are examples of fixed length numeric series:

    • 100-399 (300 numbers)

    • 40000-69999 (30,000 numbers)

    • 7000000-9999999 (3,000,000 numbers)

    The values are sorted the same way whether they are sorted as characters or as numeric values.

    This solution enables you to set the SQL Data Type property to Varchar, Integer, or BigInteger and the sorting is the same.

  • Define a numeric series that consists of a predefined number of digits and that starts with a letter, such as A001-A999. When the series is complete, you can define a new series by starting with a different letter.

    The values in this kind of series always begin with a letter and the sorting is always the same, regardless of the SQL data type.

Important
As a rule, data types that are used in fields that are related to each other must be compatible. Therefore, when you use a SQL data type in a field, you will usually have to change the SQL data type settings of related fields in other tables. For example, in the general ledger application area, if you change the SQL data type of the No. field in the G/L Account table from Varchar to Integer (or if you change the data type from Code to Text), you must change the data type of the G/L Account No. fields in the G/L Entry and G/L Budget Entry tables to the corresponding data type. Failure to do this results in the display of incorrect totals, based on these tables, in the chart of accounts and elsewhere.

Filters

If you do not follow the numbering principles, problems will occur when you apply filters that involve numbers.

An example of this is if you have not used a numeric series that has a fixed length, when you apply a filter, for example, 10...20, the result will be 10,100...20.

When you follow the numbering principles, you must remember to use these principles for filters that you apply. Here are two examples:

  • If you do not follow the numbering principles when you apply a filter, for example, 2...10, the result will contain no records. This is because 2, comes after 10.

  • You have followed the numbering principles and are using three-digit numbers. If you forget to follow the same principles when you apply a filter, for example, 10...20, the result will be 100,101,102...199.


CaptionClass Functionality

This section describes the CaptionClass functionality and explains how the CaptionClassTranslate function trigger with ID 15 in Codeunit 1 handles this functionality. The topics in this section describe the syntax and the function code of the CaptionClass.

When you set the CaptionClass Property on a field or control, users can configure the caption of a text box that is connected to a label or the caption of a check box without having to modify code. If you set the CaptionClass property on other controls, such as Buttons or Menu Items, the caption will not be displayed.

Microsoft Dynamics NAV passes the value of the CaptionClass property to the CaptionClassTranslate function trigger, which has ID 15 on Codeunit 1. This function translates the CaptionClass to a caption that users can see. The following illustration shows this sequence.

Sequence to get value of CaptionClass property

Codeunit 1, function trigger ID 15 is called by using a language and a CaptionClass. The trigger converts the CaptionClass into the specific caption for that language and returns it as a string. Language is specified as an integer. CaptionClass is a text.

See Also

Concepts

CaptionClass Syntax


CaptionClass Syntax

This topic describes the syntax of the CaptionClass functionality.

Syntax

If the CaptionClass property of a field or a control is defined, the function trigger CaptionClassTranslate with ID 15 in Codeunit 1 (ApplicationManagement) is called every time that the field or control is shown. This function replaces the caption, as defined in the design of the field or control, with another string. The following code example shows the syntax for this procedure.

CaptionClassTranslate (<LANGUAGE>;<CAPTIONEXPR>)

LANGUAGE

<DataType> := [Integer]

<DataValue> := ……

CAPTIONEXPR

<DataType> := [String]

<Length> <= 80

<DataValue> := <CAPTIONAREA>,<CAPTIONREF>

Two parameters LANGUAGE and CAPTIONEXPR are passed to this function.

LANGUAGE

The LANGUAGE parameter is automatically mentioned as is the Windows Language ID of the active language in Microsoft Dynamics NAV.

For example, if the active language in Microsoft Dynamics NAV is English (United States), LANGUAGE will hold the value 1033.

CAPTIONEXPR

The CAPTIONEXPR parameter contains the value of the CaptionClass property of the field or control. An example is in table 13 Salesperson/Purchaser, the Global Dimension 1 Code field (Field No. 5050) has the string '1,1,1' as its CaptionClass. You can use the debugger to view the value of the CAPTIONEXPR parameter. Set a breakpoint on the CaptionClassTranslate function in codeunit 1, activate the debugger, and then run page 14, Salespeople/Purchasers. The debugger breaks in the CaptionClassTranslate function. In the debugger, choose Variables. In the Debugger Variable List, you can see that the CAPTIONEXPR parameter holds the string '1,1,1'. For more information about the debugger, see Debugging.

Note
In the About This Page window, you will not find the Global Dimension 1 Code field. Instead you find the Department Code field, which represents the CaptionClass property and the CaptionClassTranslate function trigger.

Function Code

The function trigger CaptionClassTranslate with ID 15 resembles a system trigger. A programmer can intervene here every time that the CaptionClass property (if it is defined) is evaluated.

The following example shows the trigger in the CRONUS International Ltd. database.

CaptionClassTranslate(Language : Integer;CaptionExpr : Text[80] : Text[1024])

CommaPosition := STRPOS(CaptionExpr,',');

IF (CommaPosition > 0) AND (CommaPosition < 80) THEN BEGIN

CaptionArea := COPYSTR(CaptionExpr,1,CommaPosition - 1);

CaptionRef := COPYSTR(CaptionExpr,CommaPosition + 1);

CASE CaptionArea OF

'1' : EXIT(DimCaptionClassTranslate(Language, CaptionRef));

'2' : EXIT(VATCaptionClassTranslate(Language, CaptionRef));

'3' : EXIT(CaptionRef);

END;

END;

EXIT(CaptionExpr);

This standard code analyzes and unravels the CAPTIONEXPR parameter. This parameter has the following syntax.

CAPTIONEXPR := <CAPTIONAREA>,<CAPTIONREF>

Depending on the value of the CAPTIONAREA, different procedures are called.

CAPTIONAREA

The first part of the CAPTIONEXPR parameter, to the first comma, is the CAPTIONAREA, and has the following syntax.

CAPTIONAREA

<DataType> := [SubString]

<Length> <= 10

<DataValue> := 1..9999999999

// 1 for Dimension Area

// 2 for VAT

// 3 to return only the CaptionExpr string

CAPTIONREF

The second part of the CAPTIONEXPR parameter, after the first comma, is the CAPTIONREF, and has the following syntax.

CAPTIONREF

<DataType> := [SubString]

<Length> <= 10

<DataValue> :=

IF (<CAPTIONAREA> = 1)

<DIMCAPTIONTYPE>,<DIMCAPTIONREF>

IF (<CAPTIONAREA> = 2)

<VATCAPTIONTYPE>,<VATCAPTIONREF>

Depending on the value of the CAPTIONAREA, CAPTIONREF can consist of one (VATCAPTIONTYPE) or two references (VATCAPTIONTYPE,VATCAPTIONREF or DIMCAPTIONTYPE,DIMCAPTIONREF.

Note
This is how the standard functionality in Microsoft Dynamics NAV deals with the CaptionClass property. Every field or control with a defined CaptionClass has a string in this property that uses the syntax described earlier. For new functionality, a programmer could define other syntax and add code to the function trigger CaptionClassTranslate with ID 15 to handle this syntax.

Syntax for CAPTIONREF

As described earlier, the CAPTIONREF part of the CAPTIONEXPR parameter can have the following syntax. If CAPTIONAREA equals 1:

CAPTIONREF := < DIMCAPTIONTYPE >,< DIMCAPTIONREF >

Or if CAPTIONAREA equals 2:

CAPTIONREF := < VATCAPTIONTYPE >,< VATCAPTIONREF >

Dimension Area

If the CAPTIONAREA equals 1, the caption of the field or control should be retrieved from the dimensions information.

DIMCAPTIONTYPE

This reference determines where the main part of the new caption should be retrieved from, as shown in the following syntax.

DIMCAPTIONTYPE

<DataType> := [SubString]

<Length> <= 10

<DataValue> := 1..6

// 1 to retrieve Code Caption of Global Dimension

// 2 to retrieve Code Caption of Shortcut Dimension

// 3 to retrieve Filter Caption of Global Dimension

// 4 to retrieve Filter Caption of Shortcut Dimension

// 5 to retrieve Code Caption of any kind of Dimensions

// 6 to retrieve Filter Caption of any kind of Dimensions

DIMCAPTIONREF

DIMCAPTIONREF consists of several sub references:

DIMCAPTIONREF:= < number >,< DIMOPTIONALPARAM1>,

< DIMOPTIONALPARAM2 >

The following syntax describes what < number > can be and what <DIMOPTIONALPARAM1> and <DIMOPTIONALPARAM2> are:

DIMCAPTIONREF

<DataType> := [SubString]

<Length> <= 10

<DataValue> :=

IF (<DIMCAPTIONTYPE> = 1)

1..2,<DIMOPTIONALPARAM1>,<DIMOPTIONALPARAM2>

IF (<DIMCAPTIONTYPE> = 2)

1..8,<DIMOPTIONALPARAM1>,<DIMOPTIONALPARAM2>

IF (<DIMCAPTIONTYPE> = 3)

1..2,<DIMOPTIONALPARAM1>,<DIMOPTIONALPARAM2>

IF (<DIMCAPTIONTYPE> = 4)

1..8,<DIMOPTIONALPARAM1>,<DIMOPTIONALPARAM2>

IF (<DIMCAPTIONTYPE> = 5)

[Table]Dimension.[Field]Code, <DIMOPTIONALPARAM1>,

<DIMOPTIONALPARAM2>

IF (<DIMCAPTIONTYPE> = 6)

[Table]Dimension.[Field]Code, <DIMOPTIONALPARAM1>,

<DIMOPTIONALPARAM2>

DIMOPTIONALPARAM1

DIMOPTIONALPARAM1

<DataType> := [SubString]

<Length> <= 30

<DataValue> := [String]

// A string added before the dimension name.

DIMOPTIONALPARAM2

DIMOPTIONALPARAM2

<DataType> := [SubString]

<Length> <= 30

<DataValue> := [String]

// A string added after the dimension name.

VAT

If the CAPTIONAREA equals 2, the caption of the field or control should be replaced by its original caption plus an extra string. This string should state either 'Excl. VAT' or 'Incl. VAT'. The syntax is described in the following section.

VATCAPTIONTYPE

VATCAPTIONTYPE

<DataType> := [SubString]

<Length> := 1

<DataValue> := '0' -> <field caption + 'Excl. VAT'>

'1' -> <field caption + 'Incl. VAT'>

VATCAPTIONREF

VATCAPTIONREF contains the caption of the field or control.

VATCAPTIONREF

<DataType> := [SubString]

<Length> <= 30

<DataValue> := field caption

See Also

Reference

CaptionClass Property

Concepts

CaptionClass Functionality


File Handling

The walkthroughs in this section provide step-by-step instructions for handling files in Microsoft Dynamics NAV 2016.

Best Practices

The following are recommended best practices for working with files:

  • Use fully qualified paths to eliminate ambiguity.

  • Be aware of operating system file access restrictions when designing applications that use files. Consider which users have access to files and directories and what access control list (ACL) that you need to apply to file directories.

See Also

Tasks

How to: Use Streams to Write to Text Files
How to: Use Streams to Read from Text Files
Walkthrough: Uploading a File from a Client to Microsoft Dynamics NAV Server
Walkthrough: Transferring a File from Microsoft Dynamics NAV Server to the Client


Text Encoding

Text encoding is the process of transforming bytes of data into readable characters for users of a system or program. When you import a file as text or as a stream, the text encoding format ensures that all the language-specific characters are represented correctly in Microsoft Dynamics NAV. When you export a file as text or as a stream, the text encoding format ensures that all the language-specific characters are represented correctly in the system or program that will read the exported file.

Encoding Formats

You can specify text encoding for the following objects.

Object or data type | For more information, see
XMLports | TextEncoding Property (XMLports)
File | OPEN Function (File)
BLOB | CREATEINSTREAM Function (BLOB) CREATEOUTSTREAM Function (BLOB)

There are several industry text encoding formats and different systems support different formats. Internally, Microsoft Dynamics NAV uses Unicode encoding. For exporting and importing data with an XMLport, Microsoft Dynamics NAV supports MS-DOS, UTF-8, UTF-16, and Windows encoding formats. Data is imported and exported as follows:

  • When data is imported from an external file, it is read using the format that is specified by the TextEncoding property or parameter, and then converted to Unicode in Microsoft Dynamics NAV.

  • When data is exported to an external file, it is converted from Unicode in Microsoft Dynamics NAV, and then written to the file in the format that is specified by the TextEncoding property or parameter.

You should set the text encoding to the encoding format that is compatible with the system or program that you will be exporting to or importing from. The following sections describe the available text encoding formats.

MS-DOS Encoding Format

MS-DOS encoding, which is also referred to as OEM encoding, is an older format than UTF-8 and UTF-16, but it is still widely supported. MS-DOS encoding was the only format that was supported by earlier versions of Microsoft Dynamics NAV.

MS-DOS encoding requires a different character set for each language. When the property is set to MS-DOS, text is encoded by using the system locale language of the computer that is running Microsoft Dynamics NAV Server. So if you use MS-DOS encoding, you should set the system locale language of Microsoft Dynamics NAV Server to match the language of the data that is being imported or exported. For example, if an XMLport includes text in Danish, then you should set the system locale language of Microsoft Dynamics NAV Server to Danish before the XMLport is run.

You should choose MS-DOS with XMLports that were created in earlier versions of Microsoft Dynamics NAV.

UTF-8 Encoding Format

UTF-8 encoding is a Unicode Transformation Format that uses one byte (8 bits) to encode each character. UTF-8 is based on the Unicode character set, which includes most characters of all languages in a single character set.

Unlike MS-DOS, when you use UTF-8, you do not have to consider the language settings of Microsoft Dynamics NAV Server or the external system or program that will read or write the data.

UTF-8 is compatible with ASCII so that it will understand files written in ASCII format.

UTF-8 is the most common encoding format and the recommended setting if you are not sure of the format that is supported by the system that you are integrating with.

UTF-16 Encoding Format

UTF-16 encoding resembles UTF-8 except that UTF-16 uses 2 bytes (16 bits) to encode each character. UTF-16 is also based on the Unicode character set, so you do not have to consider the language setting of Microsoft Dynamics NAV Server or the external system or program that reads or writes the data.

UTF-16 includes two encoding schemes which mandate the byte order: UTF-16LE and UTF-16BE. Microsoft Dynamics NAV supports these schemes according to the following:

  • When exporting, the file is written using UTF-16LE encoding.

  • When importing, the file is read using the UTF-16, UTF-16LE, or UTF-16BE, depending on encoding scheme of the file itself.

A UTF-16 encoded file will typically be larger than the same file encoded with UTF-8, except for Eastern language character sets, which will typically be smaller.

UTF-16 is incompatible with ASCII so that it will not understand files written in ASCII format.

Windows Format

Windows encoding is also referred to as ANSI encoding. If you set the text encoding to Windows, you can import and export text files that are based on the Windows codepage on the user’s computer. As a result, you do not have to consider the language setting of Microsoft Dynamics NAV Server or the external system or program that reads or writes the data.

For example, if an XMLport can import bank files from a foreign bank in addition to a domestic bank, use Windows encoding instead of MS-DOS encoding to avoid changing the language of Microsoft Dynamics NAV Server.

Windows encoding is compatible with ASCII so that it will understand files written in ASCII format.

See Also

Reference

TextEncoding Property (XMLports)
OPEN Function (File)
CREATEINSTREAM Function (File)
CREATEOUTSTREAM Function (File)
CREATEINSTREAM Function (BLOB)
CREATEOUTSTREAM Function (BLOB)

Concepts

File Handling


How to: Use Streams to Read from Text Files

The InStream (input stream) and OutStream (output stream) data types are generic stream objects that you can use to read from or write to files. This topic shows you how to use InStream to read from a text file. For information about how to use streams to write text files, see How to: Use Streams to Write to Text Files. You create a codeunit to accomplish this task.

To use a stream to read from a text file

  1. In Object Designer, choose Codeunit, and then choose the New button to open the C/AL Editor.

  2. On the View menu, choose C/AL Globals.

  3. On the Variables tab, in the Name column, declare a variable that represents the text file, and then set DataType to File.

  4. Declare a second variable that represents the input stream that will read the data and set DataType to Instream.

  5. Declare a third variable that receives the data that is read and set the DataType.

  6. In the C/AL Editor, in the OnRun trigger, add code that uses the OPEN Function (File) to open the file that you want to read from. The code will resemble the following code snippet.

    MyFile.OPEN('c:\MyFolder\MyText.txt');

  7. Use the CREATEINSTREAM Function (File) to create the input stream. The code will resemble the following code snippet.

    MyFile.CREATEINSTREAM(MyInstream);

  8. Use the InStream.READTEXT Function to read the data from the stream to a text variable such as a buffer or another object. The code that reads the file to a buffer will resemble the following code snippet.

    MyInStream.READTEXT(Buffer);

    If you are reading from a BLOB, use the InStream.READ Function to read the BLOB.

  9. After all the content of the file is read, use the CLOSE Function (File) to close the file. The code will resemble the following code snippet.

    MyFile.CLOSE;

  10. On the File menu, choose Save to save the new codeunit.

  11. In the Save As window, in the ID text box, enter an ID for the codeunit. In the Name text box, enter a name for the codeunit.

  12. Verify that the Compile field is selected and then choose the Yes button.

Example

The following example reads a file that is named MyText.txt into a buffer and displays the contents of the buffer in a message. The file is read until the end of the file is reached. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType
MyFile | File
StreamInTest | InStream
Buffer | Text
Copy Code
MyFile.OPEN('c:\MyFolder\MyText.txt');
MyFile.CREATEINSTREAM(StreamInTest);
WHILE NOT StreamInTest.EOS DO BEGIN
  StreamInTest.READTEXT(Buffer);
  // Do some processing.
  MESSAGE('Stream is still reading: %1', Buffer);
END;
MyFile.CLOSE;
MESSAGE('End of stream is reached.');

See Also

Tasks

How to: Use Streams to Write to Text Files

Concepts

File Handling


How to: Use Streams to Write to Text Files

The InStream (input stream) and OutStream (output stream) data types are generic stream objects that you can use to read from or write to files. This topic shows you how to use the OutStream object to write to a text file. You create a codeunit to accomplish this task. For information about how to use streams to read text files, see How to: Use Streams to Read from Text Files.

To use a stream to write to a text file

  1. In Object Designer, choose Codeunit, and then choose the New button to open the C/AL Editor.

    You declare variables to represent the text file and output stream object that you want to work with.

  2. From the View menu, choose C/AL Globals to open the C/AL Globals window.

  3. Under the Variable tab, in the Name column, declare a variable that represents the text file and then set DataType to File.

  4. Declare a second variable that represents the output stream that will write the data, then set DataType to OutStream.

    If you want to retrieve the number of characters that are written to the text file, create variable to hold the value.

  5. From the View menu, choose C/AL Code to open the C/AL Editor.

  6. In the C/AL Editor, in the OnRun() trigger, add code that uses the CREATE Function (File) to create the file that you want to write to. The code will resemble following code snippet: MyFile.CREATE('c:\MyNewFolder\MyWriteText.txt');.

  7. Use the CREATEOUTSTREAM Function (File) to create the output stream. The code will resemble the following code snippet: MyFile.CREATEOUTSTREAM(MyOutStream);.

  8. Use the OutStream.WRITETEXT Function to write the data from the output stream to the file. The code will resemble the following code snippet: MyOutStream.WRITETEXT(‘Hello world’);.

  9. From the File menu, choose Save AS.

  10. In the Save As dialog box, in the ID text box, enter an ID for the codeunit.

  11. In the Name text box, enter a name for the codeunit.

  12. Verify that Compile is selected and then choose the Yes button.

Example

The following example shows how to use an output stream to write text to a text file and displays the number of characters that were written to the file. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType
MyFile | File
MyOutStream | OutStream
NumberOfChars | Integer
Copy Code
MyFile.CREATE('c:\MyNewFolder\MyWriteText.txt');
MyFile.CREATEOUTSTREAM(MyOutStream);
NumberOfChars := MyOutStream.WRITETEXT('Hello World!');
MESSAGE('%1 characters were written to the file.', NumberOfChars);

See Also

Tasks

How to: Use Streams to Read from Text Files

Concepts

File Handling


Walkthrough: Uploading a File from a Client to Microsoft Dynamics NAV Server

This walkthrough demonstrates how to use file functions to send a file from a client to the server, use stream functions to read the file, and use an XMLport to load values into the database. Business logic in Microsoft Dynamics NAV runs on Microsoft Dynamics NAV Server instead of on the client. As a result, any business logic that reads data from a file needs to first move a copy of that file from the client to the server.

About This Walkthrough

This walkthrough illustrates the following tasks:

  • Creating an XML file that contains two elements with values.

  • Creating a table in Microsoft Dynamics NAV to hold the data from the XML file.

  • Creating a codeunit that does the following:

    • Sends the file from a user-specified location to a location on the server

    • Reads the data

    • Writes the data to the table

    • Deletes the file from the server

  • Associating the codeunit with an action on a Role Center page.

  • Testing the codeunit.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV installed with a developer license

Creating an XML File

The first step is to create a simple XML file that contains the data that the codeunit will read into the table. This represents the file on a client computer.

To create the XML file

  1. Open Notepad.

  2. Enter the following code.

    Copy Code
    <?xml version="1.0" encoding="UTF-8"?><head><valueI>10</valueI><valueII>11</valueII></head>

  3. Save the file in the root of the My Documents directory. Name the file simple.xml.

  4. Open the file in Internet Explorer to ensure that the XML is well formed.

Creating a Table

The next step is to create the table that will hold the data that is read from the XML file.

To create the table

  1. In Object Designer, choose Table, and then choose New.

    Table Designer opens.

  2. Choose Field Name in the first row and then enter IntA. Set Data Type to Integer.

  3. Choose Field Name in the second row and then enter IntB. Set Data Type to Integer.

  4. Save the table, giving it a name of TestTable and an ID of 50010.

  5. Close Table Designer.

Creating the Codeunit

The next step is to create a codeunit that will prompt the user to specify the location of the XML file, load the XML file into a stream, and then write the values of those variables to the table using an XMLport.

To create the codeunit

  1. In Object Designer, choose Codeunit, and then choose New.

    C/AL Editor opens.

  2. Choose the OnRun() function in the C/AL Editor.

  3. Choose View and then choose C/AL Locals.

    The C/AL Locals window opens.

  4. Choose the Variables tab.

  5. Enter the following local variables.

    Name DataType Length

    TestFile

    File

    TestStream

    InStream

    NVOutStream

    OutStream

    ClientFileName

    Text

    1024

  6. Choose the next empty line to ensure that the local variables are saved.

  7. Close the C/AL Locals window.

  8. Enter the following code in the C/AL Editor for the OnRun function.

    Copy Code
    BEGIN
        IF UPLOADINTOSTREAM(
                       'Select the simple.xml file',
                        'c:\temp',
                        'XML File *.xml| *.xml',
                         ClientFileName,
                         TestStream)
        THEN MESSAGE('File Successfully Uploaded')
        ELSE
            EXIT;
    XMLPORT.IMPORT(50010,TestStream);
END;

  9. Save the codeunit, giving it a name of UploadFile and an ID of 50010.

  10. Close the code editor.

Creating the XMLport

The next step is to create an XMLport.

To create the XMLport

  1. In Object Designer, choose XMLport, and then choose New.

    XMLport Designer opens.

  2. Enter the following information.

    Node Name Node Type Source Type Data Source

    head

    Element

    Table

    <TestTable>(TestTable)

    valueI

    Element

    Field

    TestTable::IntA

    valueII

    Element

    Field

    TestTable::IntB

  3. Indent the valueI and valueII elements one level by choosing the right arrow.

  4. Save the XMLport, giving it a name of UploadFile and an ID of 50010.

  5. Close XMLport Designer.

Testing the Codeunit

The final step is to test the codeunit to ensure that it correctly adds the values from the simple.xml file to the TestTable. To test the codeunit, you will run it from Object Designer.

To test the codeunit

  1. In Object Designer, choose Codeunit, select codeunit 50010 UploadFile, and then choose the Run button.

    The Select the simple.xml file window opens.

  2. Browse to the location of simple.xml and then choose Open.

    The message File Successfully Uploaded appears.

  3. Choose OK.

  4. Open the development environment.

  5. In Object Designer, choose Table, choose 50010 Test Table, and then choose Run.

    The TestTable-Table window opens with the values of 10 and 11 in the IntA and IntB columns, respectively.

See Also

Tasks

Walkthrough: Transferring a File from Microsoft Dynamics NAV Server to the Client

Reference

UPLOADINTOSTREAM Function (File)


Walkthrough: Transferring a File from Microsoft Dynamics NAV Server to the Client

This walkthrough demonstrates how to develop a codeunit that creates a file on Microsoft Dynamics NAV Server, opens the file, writes some data to it, and then downloads that file to a RoleTailored client.

About This Walkthrough

This walkthrough illustrates the following tasks:

  • Creating a codeunit that creates a text file, opens the file, writes some text to the file, and then downloads that file to the client.

  • Testing the codeunit.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 installed with a developer license

Creating the Codeunit

The first step is to create the codeunit. In the codeunit, the toFile variable is initially assigned a value of samplefile.txt. If the user specifies another file name, then this new value and the file path are returned in toFile.

To create the codeunit

  1. In Object Designer, choose Codeunit and then choose New.

    C/AL Editor opens.

  2. Choose the OnRun() function in C/AL Editor.

  3. Choose View and then choose C/AL Locals.

    The OnRun -C/AL Locals window opens.

  4. Choose the Variables tab.

  5. Enter the following local variables.

    Name DataType Length

    Name

    Text

    200

    ReturnValue

    Boolean

    TempFile

    File

    ToFile

    Variant

    NewSteam

    InStream

  6. Choose the next empty line to ensure that the local variables are saved.

  7. Close the C/AL Locals window.

  8. Enter the following code in the C/AL Editor for the OnRun() method.

    Copy Code
    // Create a temporary file on NAV server, write the content
// to the tempoary file, and then create an instream for the
// temporary file.
TempFile.CREATETEMPFILE();
TempFile.WRITE('abc');
TempFile.CREATEINSTREAM(NewStream);
ToFile:='SampleFile.txt';
// Transfer the content from the temporary file on the NAV server to a
// file on the RoleTailored client.
ReturnValue:=DOWNLOADFROMSTREAM(
  NewStream,
  'Save File to RoleTailored Client',
  '',
  'Text File *.txt| *.txt',
  ToFile);
// Close the temporary file and delete it from NAV server.
TempFile.CLOSE();
// Post a message indicating that the file is saved on the client.
MESSAGE(FORMAT(ToFile));

  9. Save the codeunit, giving it a name of FileTransfer and an ID of 50011.

  10. Close the code editor.

Testing the Codeunit

The final step is to test the codeunit.

To test the codeunit

  1. In Object Designer, select the codeunit that you created, and then choose the Run button.

    The Export File dialog box appears.

  2. Choose Save and save to the default location, noting what that location is.

  3. Choose OK.

  4. A message box opens specifying the location of the saved file. Choose OK.

  5. Browse to the specified file location on your client computer.

  6. Open the file.

  7. Note that the file contains the text 'abc'.

See Also

Tasks

Walkthrough: Uploading a File from a Client to Microsoft Dynamics NAV Server


Cryptography Overview

The functions that support cryptography in Microsoft Dynamics NAV provide services that enable developers to add security for encrypting and decrypting data and key management. Each Microsoft Dynamics NAV tenant supports a single encryption key which is used for encrypting and decrypting data stored in the database. Additional functions are provided to assist building robust solutions when working with encryption and for managing the encryption keys.

Flow between plain text and encrypted text

Encryption Keys

To encrypt and decrypt text, we use an encryption key. Microsoft Dynamics NAV stores the key in a secure location and accesses it at runtime when needed. Additional functionality is provided to export and import keys, which is important when moving solutions from one location to another. For more information, see Encryption Key Management and Encryption Functions.

See Also

How to: Export and Import Encryption Keys
How to: Enable and Disable Encryption Keys
Manage Data Encryption

Concepts

Encryption Key Management
Programming in C/AL


Encryption Key Management

The process of encrypting and decrypting data requires a key. An encryption key is typically a random string of bits generated specifically to scramble and unscramble data. Encryption keys are created by using algorithms designed to make sure that each key is unique and unpredictable. The keys that are used by Microsoft Dynamics NAV are generated by the .NET Framework Data Protection API.

Each Microsoft Dynamics NAV tenant supports having a single encryption key. To use the encryption methods, a key must be created. There are two ways of doing this; either by importing a key or by creating a key. The CREATEENCRYPTIONKEY method will create an encryption key in a system that does not have a key present. Alternatively, if a key exists, you can use the IMPORTENCRYPTIONKEY method to introduce a key to a keyless system.

Warning
CREATEENCRYPTIONKEY will fail if the key already exists, you must then call DELETEENCRYPTIONKEY to clear the state. IMPORTENCRYPTIONKEY will throw a warning if a key already exists, regardless of if the key is present on the system or not.

Best Practices

These are some best practices we recommend that you follow:

  • Make sure to always backup your key and store it securely. Use the EXPORTENCRYPTIONKEY method and keep the output file in a secure location.

  • Use the Microsoft Dynamics NAV permission system to restrict access to encryption key logic.

  • Be aware of the difference between the ENCRYPTIONKEYEXISTS and ENCRYPTIONENABLED functions. For more information, see below.

ENCRYPTIONKEYEXISTS versus ENCRYPTIONENABLED

The encryption key is stored in a file in a directory that the Microsoft Dynamics NAV Server has access to. When a key is created or imported, data is recorded in the tenant table registering that encryption has now been enabled. Any subsequent calls to ENCRYPTIONENABLED will return true after the tenant table has been updated with this information. However, if the encryption file is deleted, then ENCRYPTIONENABLED will continue to return true. Use the ENCRYPTIONKEYEXISTS function to perform a file system check to see whether the key is present.

See Also

Concepts

Cryptography Overview
Encryption Functions


Handling Errors by Using Try Functions

Try functions in C/AL enable you to handle errors that occur in the application during code execution. For example, with try functions, you can provide more user-friendly error messages to the end user than those thrown by the system. You can use try functions to catch errors/exceptions that thrown by Microsoft Dynamics NAV or exceptions that are thrown during .NET Framework interoperability operations. Try functions catch errors similar to a conditional Codeunit.Run function call, except with the following differences:

  • Try function calls do not require that write transactions are committed to the database.

  • Changes to the database that are made with a try function are not rolled back.

Creating a Try Function

To create a try function, add a function in C/AL code of an object (such as a codeunit) as usual, and then set the TryFunction Property property to Yes. A try function has the following restrictions:

  • In test and upgrade codeunits, you can only use a try function on a normal function type, as defined by the FunctionType Property (Test Codeunits) or FunctionType Property (Upgrade Codeunits).

  • The try function cannot have a user-defined return value.

Understanding Try Function Behavior and Usage

A function that is designated as a try function has a Boolean return value (true or false). A try function has the construction OK:= MyTryFunction.

  • If a try function call does not use the return value, the try function operates like an ordinary function and errors are exposed as usual.

  • If a try function call uses the return value in an OK:= statement or a conditional statement such as IF-THEN, errors are caught.

Note
The return value is not accessible within the try function itself.

You can use the GETLASTERRORTEXT Function to obtain errors that are generated by Microsoft Dynamics NAV. To get details of exceptions that are generated by .NET Framework objects, you can use the GETLASTERROROBJECT Function to inspect the Expection.InnerException property.

Tip
The CRONUS International Ltd. demonstration database includes codeunit 1291 DotNet Exception Handler that includes several global functions for handling exceptions similar to a try-catch capability in C#. You can use this codeunit together with try functions to handle exceptions and maximize the reuse of code.

Example

The following example illustrates the use of a try function together with codeunit 1291 DotNet Exception Handler to handle .NET Framework Interoperability exceptions. The code is in text file format and has been simplified for illustration. The CallTryPostingDotNet function runs the try function TryPostSomething in a conditional statement to catch .NET Framework Interoperability exceptions. Errors other than IndexOutOfRangeException type are re-thrown.

Copy Code
[TryFunction]
PROCEDURE TryPosting@1);
BEGIN
  CODEUNIT.RUN(CODEUNIT::"Purch.-Post");
END;
PROCEDURE CallTryPostingDotNet @2();
VAR
  MyPostingCodeunit@1 : Codeunit 90;
  MyDotNetExceptionHandler@2 : Codeunit 1291;
  IndexOutOfRangeException@3 : DotNet 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.IndexOutOfRangeException'
BEGIN
  IF TryPostSomething THEN
    MESSAGE('Posting succeeded.')
  ELSE BEGIN
    MyDotNetExceptionHandler.Collect;
    IF MyDotNetExceptionHandler.TryCastToType(IndexOutOfRangeException) THEN
      MESSAGE('The index used to find the value was not valid.')
    ELSE
      MyDotNetExceptionHandler.Rethrow;
  END;
END;

See Also

Concepts

C/AL Function Statements


C/AL Editor Keyboard Shortcuts

The following table describes the keyboard shortcuts that are available from the C/AL Editor window.

Keystroke | Action
Ctrl+G | Open the C/AL Globals window to view and declare the global variables, text constants, and functions in the object.
Ctrl+L | Open C/AL Locals window to view and declare local variables and text constants for the current function or trigger.
Ctrl+Z | Undo the last action.
Ctrl+Y | Redo the last action.
Ctrl+J | List all members (as IntelliSense) for the local scope.
Ctrl+Space | List the members (as IntelliSense) for global scope.
Ctrl+W | Select the word.
Ctrl+U | Make the selected code lowercase.
Ctrl+Shift+U | Make the selected code uppercase.
Ctrl+Shift+N | Expand all collapsed code.
Ctrl+K+I | Display information about C/AL symbol (such as variable, functions, and parameter) in which the cursor is positioned. This displays the same text as when you point to the element.

See Also

Reference

C/AL Editor
C/AL Globals
C/AL Locals

Concepts

Programming in C/AL


Objects

This section contains topics that describe all of the objects that make up the development environment of Microsoft Dynamics NAV 2016.

Defining the Data Model

To | See
Learn about how to define the data model on which you build your application. | Tables

Presenting the Data

To | See
Read about how you create pages and work in Page Designer. | Pages
Read about how to create reports in Report Dataset Designer and Visual Studio Report Designer. | Reports

Writing Code

To | See
Learn about codeunits, modifying codeunits, adding variables, and functions. | Codeunits
Read more about C/AL, the programming language that you use in Microsoft Dynamics NAV. | Programming in C/AL
Learn how to extend Microsoft Dynamics NAV. | Extending Microsoft Dynamics NAV

Getting Data In and Out of the Database

To | See
Learn about Web services. | Web Services
Understand what XMLports are used for and how to create them. | XMLports
Learn how to create and use Query objects. | Queries

Working with Menus

To | See
Learn how to present functionality in menus to the user. | MenuSuites

See Also

Concepts

Development
Data Security


Tables

Tables are the fundamental objects in any database. They are the objects in which you store and manipulate data. This is true no matter what kind of data you need to manage. When you create a new database, you begin by building the tables. Later, you create pages and reports in order to access and view the data in the tables.

The following sections provide an overview of how to locate Help about designing tables in Microsoft Dynamics NAV.

Creating Tables

This section explains how to design tables to store your data and set up table descriptions that can ease sophisticated data manipulation.

To | See
Learn about the Microsoft Dynamics NAV approach to tables in database design. | Overview of Tables
Design and develop a basic table in Microsoft Dynamics NAV. | How to: Create a Table
Decide which field data type to apply to your data. | Field Data Types and Data Format Considerations
Apply table and field properties and create effective table descriptions. | How to: View or Modify Properties on a Table or Field
Connect table data through primary and secondary keys. | Table Keys
Learn about Microsoft Dynamics NAV features designed to speed up data manipulation and computation. | Accessing Microsoft Dynamics NAV Tables with External Tools

Using Triggers in Database Design

Microsoft Dynamics NAV supports setting up actions to take place in response to specific events. These are known as triggers. The following topics help to explain how Microsoft Dynamics NAV implements this feature of database design.

To | See
Learn about the set of triggers that Microsoft Dynamics NAV supports for tables and fields. | Table and Field Triggers
Create a table trigger. | How to: Define or Modify Table or Field Triggers
See reference information about specific triggers. | Triggers

Designing Relationships Between Tables

In Microsoft Dynamics NAV, the primary way to establish a connection between tables is to use the TableRelation property. The following topics go into detail about how this works.

To | See
Get a brief introduction to relational database design in Microsoft Dynamics NAV. | Setting Relationships Between Tables
Understand the extra steps SQL Server requires to use the TableRelation property. | Maintaining Table Relationships on SQL Server

Understanding SQL Server and Linked Objects

Microsoft Dynamics NAV supports special handling for SQL Server Object tables. You can find help on linked objects in the following topics.

To | See
Learn about the LinkedObject table property. | Creating Table Definitions from SQL Server Objects (Linked Objects)
Work with other data sources, including Microsoft Excel and Oracle databases. | Accessing Objects in Other Databases or on Linked Servers

See Also

Concepts

Development

Other Resources

Special Tables


Overview of Tables

The records in the database are stored in tables. A table can be visualized as a two-dimensional matrix, consisting of columns and rows. The following illustration shows a table where each row is a record and each column is a field.

A table consists of two parts: the table data and a table description. The table data is the part users often think of as comprising the database, because it contains the actual records with their data fields. The layout and properties of those fields, however, are specified by the table description. The table description is not directly visible to the user. The following illustration shows how the table data and the table description together form a table.

When you design a table, you assign a number of characteristics to it, such as a name, an ID number, and the fields it contains. You also assign a number of characteristics (such as name, ID number, data type, and initial value) to each field. When you design a new table, you also specify which keys you want the system to maintain. All these characteristics are stored in the table description when you save your table design.

The information in the table description is used by SQL Server and occasionally by database users who need information about the table structure. The table description makes the database flexible, as it lets the system access tables with different structures. The database can extract the definitions of the table structure from the table description and thereby correctly access any table.

The following illustration shows that a table description contains properties, triggers, fields, and keys and shows how these are related.

The table description contains some properties that are related to the table, others that are related to the fields in the table, and other properties related to keys. You can also see that triggers are defined both for the table and for the fields in the table.

See Also

Tasks

How to: Create a Table

Concepts

Table Keys
Table and Field Triggers

Other Resources

Special Tables


How to: Create a Table

When you first create a table, it does not contain any data. Nevertheless, when you create the table you must also decide what types of information you want to store in it. The information is held in fields, and each field can be declared as one of the data types that are available.

To create a table

  1. On the Tools menu, choose Object Designer.

    Object Designer opens.

  2. Choose Table and then choose New.

    Table Designer opens.

In the Table Designer, for each field you add to the table, you enter the field number, name, data type, and optionally, a length and a description.

See Also

Tasks

How to: Add Fields to a Table

Reference

Field Data Types
Table Properties


How to: Add Fields to a Table

Designing a field means assigning a number of characteristics to it. These characteristics depend on what you intend to use the field for. After you have added fields to a table in Table Designer, you must save the table before you can add any records. After you have saved a table, it appears in the list of tables in Object Designer.

All the tables and fields that you create have two forms of identification:

  • A unique identification number (integer). When you access your database, this number uniquely identifies all the tables and fields.

  • A name (an alphanumeric string) that serves as a label (such as CUSTOMER or CITY).

This name appears when you run the table and should be meaningful and easily understood. This name is secondary information and can be changed at any time.

To add a field to a table

  1. On the Tools menu, choose Object Designer.

    Object Designer opens.

  2. Choose Table and then choose New.

    Table Designer opens.

  3. In the first empty row, enter a Field Name and a Field No. Enter a Data type and appropriate Length. Description is optional.

See Also

Reference

Page Properties
Field Data Types


How to: Save a New Table

When you design the fields and keys for a new table, you need to save the table in the database before you can use it. After you have saved a table, it appears in the list of tables shown in Object Designer.

To save a table

  1. With the focus on Table Designer, on the File menu, choose Save.

    The Save As dialog box opens.

  2. In the ID field, enter a number that will serve as a unique table identification.

    Note
    There are restrictions about which numbers you can use. Contact your Microsoft Certified Partner for information.

  3. In the Name field, enter the name of the table.

    Note
    We recommend that you do not use a number at the start of the name or if you do, then do not include a blank space after the number and before any text; otherwise you might experience errors when referencing the table from C/AL code.

  4. Clear the Compiled check box if you do not want the table to be compiled when it is saved.

See Also

Tasks

How to: Create a Table


Field Data Types

After you select an identification number and name for a field, you have to select an appropriate data type. Each of the different field types is designed to hold a specific kind of information, such as text, numbers, or dates. Each field type has a specific size.

Note
Sizes are rounded up to the nearest 4 bytes.

Fields in a record can be of the following types.

Data type Description Size

BigInteger Data Type

A 64-bit integer.

8 bytes

BLOB Data Type

Binary Large Object. Used to store bitmaps and memos. Notice that the BLOB is not stored in the record, but in the BLOB area of the table.

The size of the corresponding SQL data type, IMAGE, is the number of bytes in the field’s value. (A)(B)

8 bytes in the record + size of BLOB data (maximum 2 GB)

Boolean Data Type

Assumes the values TRUE or FALSE. When formatted, a Boolean field is shown as "Yes" or "No". The size of the corresponding SQL data type, TINYINT, is 1 byte. (A)(B)

4 bytes

Code Data Type

An alphanumeric string, which is right-justified if the contents are numbers only. If letters or blanks occur among the numbers, the contents are left-aligned. All letters are converted to uppercase upon entry.

The field must be defined to be between 1 and 250 characters. The number of bytes used by a Code field equals 1 byte + ((number of characters + 1) * 2). The initial byte is for the leading indicator, which specifies the length of a Code value that consists only of integers. The additional character is used for the string terminating character, which is '0' in Unicode. The size of a Unicode character is 2 bytes. Therefore, you multiply the number of characters by two to get the bytes.

For example, if a Code value is 6 characters, then the number of bytes used is the following:

1 + ((6+1)*2) = 15, rounded to the nearest 4 bytes = 16 bytes used.

You can use the SQL Data Type Property to indicate whether Code fields can contain integers or text strings.

For more information about the sorting of numeric values in code fields, see Sorting Numeric Values.

1 byte + ((Number of characters + 1 character) * 2 bytes per character)

Date Data Type

A date value in the range from January 1, 1753 to December 31, 9999. An undefined date is expressed as 0. All dates have a corresponding closing date. The system considers the closing date for a given date as a period that follows the given date but comes before the next normal date; that is, a closing date is sorted immediately after the corresponding normal date but before the next normal date.

The size of the corresponding SQL data type, DATETIME, is 8 bytes. (A)(B)

4 bytes

DateFormula Data Type

Used to verify the date entered by the user. The syntax is for example:

Copy Code
30D (=30 days)
CM+1M (=current month plus one month)
D15 (=on the 15th of each month)

32 bytes

DateTime Data Type

Represents a point in time as a combined date and time. The datetime is stored in the database as Coordinated Universal Time (UTC) and is always displayed as local time in Microsoft Dynamics NAV.

Local time is determined by the time zone regional settings that are used by your computer.

You must always enter datetimes as local time. When you enter a datetime as local time, it is converted to UTC using the current settings for the time zone and daylight saving time.

The DateTime data type does not support closing dates.

Stored as two 4 byte integers

Decimal Data Type

A decimal number between -10^63 and 10^63. The exponent ranges from -63 to 63. Decimal numbers are held in memory with 18 significant digits. The representation of a decimal number is a Binary Coded Decimal (BCD). The size of the corresponding SQL data type, DECIMAL(38,20), is 17 bytes. We recommend that you construct decimals that operate on numbers in the range of +/- 999,999,999,999,999.99. You can construct larger numbers in some cases, but overflow, truncation or loss of precision can occur.

(A)(B)

12 bytes

Duration Data Type

Represents the difference between two points in time, in milliseconds. This value can be negative.

8 bytes

GUID Data Type

Globally unique identifier (GUID).

16 bytes

Integer Data Type

Denotes an integer between -2,147,483,647 and 2,147,483,647. The size of the corresponding SQL data type, INTEGER, is 4 bytes. (A)(B)

4 bytes

Option Data Type

An option field is defined by using an option string, which is a comma-separated list of strings that represent each valid value of the field. This string is used when a field of type Option is formatted and its value is converted into a string.

For example, the Option field "Color" is defined by using the option string "Red,Green,Blue". Valid values of the field are then 0, 1, and 2, with 0 representing "Red" and so on. When the "Color" field is formatted, 0 is converted into the string "Red", 1 into "Green", and 2 into "Blue".

The size of the corresponding SQL data type, INTEGER, is 4 bytes. (A)(B)

4 bytes

RecordID Data Type

Unique record identifier.

TableFilter Data Type

This data type is used to apply a filter to another table.

Currently, this can only be used to apply security filters from the Permission table.

Text Data Type

Any alphanumeric string. The field must be defined to be between 1 and 250 characters. The number of bytes used by a text field equals (number of characters + 1) * 2. The additional character is used for the string terminating character, which is '0' in Unicode. The size of a Unicode character is 2 bytes. Therefore, you multiply the number of characters by two to get the size.

For example, if a Text value is 6 characters, then the number of bytes used is the following:

(6+1)*2 = 14 bytes, rounded up to the nearest 4 bytes = 16 bytes used.

An empty text string has the length zero.

(Number of characters+ 1 character) * 2 bytes per character

Time Data Type

Any time in the range 00:00:00 to 23:59:59.999. A time field contains 1 plus the number of milliseconds since 00:00:00 o'clock, or 0 (zero), an undefined time. A time value is calculated in the following way:

Copy Code
Time = 1 + (number of milliseconds since 00:00:00).

The size of the corresponding SQL data type, DATETIME, is 8 bytes. (A)(B)

A time field is stored as an integer (four bytes)

(A) The calculation of the size of a specific SQL Server record requires more than just summing the sizes of the field values. Refer to Microsoft SQL Server documentation for more information.

(B) This is the SQL Server data type that Microsoft Dynamics NAV uses when it creates the Microsoft Dynamics NAV data type. For more information, see Identifiers, Data Types, and Data Formats.

In addition to the fields discussed in this section, tables can include the following special types of fields that are used to retrieve data:

  • FlowField

  • FlowFilter

For more information, see FlowFields and FlowFilter Overview.

See Also

Concepts

C/AL Functions


Identifiers, Data Types, and Data Formats

This topic describes the identifiers, data types, and data formats that are used in the Microsoft Dynamics NAV 2016.

Naming Identifiers

Identifiers for SQL Server tables and columns are based upon the table names and field names for the corresponding tables and fields of a Microsoft Dynamics NAV table definition. If you set a table’s DataPerCompany property to Yes, the SQL Server table name is prefixed by the company name. The two names are separated by the ($) symbol. For example, the SQL Server table name for the Customer table of the CRONUS International Ltd. company is CRONUS International Ltd_$Customer. If the DataPerCompany property of a table is set to No, there is no prefix.

The primary key of a Microsoft Dynamics NAV table is created in a SQL Server table as a primary key constraint. The name of the primary key is based on the table name with a suffix of $0, for example, CRONUS International Ltd_$Customer$0. Any secondary keys in a Microsoft Dynamics NAV table that must be created and maintained in SQL Server, that is, the MaintainSQLIndex key property is set to Yes, will have SQL Server indexes created that are named after an internal key ID with a $ prefix. Examples of this are $1 and $4.

If the database maintains SQL views for language IDs, the system creates a SQL view by prefixing the SQL Server table name with the Windows language ID. For example, if you want to refer to the Customer table in the CRONUS International Ltd. company in German (standard), the SQL view is DEU$CRONUS International Ltd_$Customer. For more information about multilanguage functionality, see Multilanguage Development.

If the database maintains relationships, Microsoft Dynamics NAV creates foreign key constraints using the SQL Server table name and TableRelation property information. The names of the constraints have the following format:

  • <table name>$FK$T<referencing table ID>_F<referencing field ID>$T<referenced table ID>.

Here is an example using the Customer table:

  • CRONUS International Ltd_$Customer$FK$T18_F107$T308.

When you create a Microsoft Dynamics NAV table with keys that contain SumIndexFields, indexed views are created to hold the precalculated sums. These views are named based on the company, table name, and key number. For example [CRONUS International Ltd_$G_L Entry$VSIFT$8].

Representation of Data Types

Every available Microsoft Dynamics NAV data type is mapped to an appropriate SQL Server data type in the tables for Microsoft Dynamics NAV. The following table shows which SQL Server data type is used for the corresponding Microsoft Dynamics NAV data type.

Microsoft Dynamics NAV data type | SQL Server data type
Integer | INTEGER
Option | INTEGER
Code(n) | NVARCHAR(n) INTEGER SQL_VARIANT
Text(n) | NVARCHAR(n)
Decimal | DECIMAL(38,20)
Date | DATETIME
Time | DATETIME
DateTime | DATETIME
Boolean | TINYINT
BLOB | IMAGE
DateFormula | VARCHAR(32)
TableFilter | VARBINARY(252)
BigInteger | BIGINT
Duration | BIGINT
GUID | UNIQUEIDENTIFIER
RecordID | VARBINARY(n)

Each of the SQL Server data types is created as NOT NULL except the IMAGE type, which allows NULL.

Compatibility of Data Types

Some of the SQL Server data types are compatible with other Microsoft Dynamics NAV data types. The following table shows the extended compatibility of SQL Server data types with Microsoft Dynamics NAV data types.

SQL Server data type | Microsoft Dynamics NAV data type
CHAR (n) | Code(n) Text(n) DateFormula
NCHAR (n) | Text(n)
NVARCHAR (n) | Text(n)
INTEGER | Code
TINYINT | Integer Option
SMALLINT | Integer Option
NUMERIC(p,s), MONEY, SMALLMONEY, REAL, FLOAT(n), DECIMAL | Decimal Integer Option Boolean
SMALLDATETIME | Date
BIT | Integer Option Boolean
TEXT | BLOB
NTEXT | BLOB

See Also

Reference

Field Data Types

Concepts

Developing Multilanguage-Enabled Applications


Data Format Considerations

In Microsoft Dynamics NAV 2016, data formats impact the way your data is compared and sorted

Code Fields

In Microsoft Dynamics NAV 2016 code fields can be represented by several SQL Server data types. Code fields have a property, SQL Data Type, which determines whether they contain integers, text strings, or a mixture of both.

To set code field properties

  1. On the Tools, choose Object Designer.

  2. Choose Table and select the appropriate table.

  3. Choose Design.

  4. Select the field whose data type is defined as code, choose View, and then choose Properties.

You can set the SQL Data Type property to Varchar, Integer, or Variant. Leaving the value as Undefined is the same as selecting Varchar, which is the default value.

Note
When you set the SQL Data Type property to Varchar, the SQL Server data type that is used is NVARCHAR.

When you create a table in Microsoft Dynamics NAV 2016, the code field data is stored in NVARCHAR, INTEGER, or SQL_VARIANT columns in the SQL Server table that correspond to the SQL Data Type property’s values Varchar, Integer, or Variant.

Varchar

When you set the value of the SQL Data Type property of a code field to Varchar, all the values in the field are compared and sorted as character data, including numeric values.

Integer

When you set the value of the SQL Data Type property of a code field to Integer:

  • All the values in the field are compared and sorted as integers. No alphanumeric values can be stored in the field.

  • If you enter negative values in the column outside Microsoft Dynamics NAV using external tools, they cannot be read into Microsoft Dynamics NAV.

  • The value "0" (zero) is used to represent an empty string in Microsoft Dynamics NAV.

  • Nonnumeric code values or any numeric values beginning with "0" (zero) cannot be entered in the code field.

Variant

When you set the value of the SQL Data Type property of a code field to Variant:

  • The values in the field are compared and sorted according to their base data type. Numeric values are sorted after alphanumeric values.

  • Data that is entered into the code field in Microsoft Dynamics NAV is stored as either the NVARCHAR or INTEGER base data type, depending on the value that has been entered.

  • Any value beginning with "0" (zero) can be entered in the code field and is stored as an INTEGER base data type.

Note
Be aware that the Variant data type is not supported by all the third-party tools that can be used to access data in SQL Server databases.

Data and Time Fields

SQL Server stores information about both date and time in columns of the DATETIME and SMALLDATETIME types. For date fields, Microsoft Dynamics NAV uses only the date part and places a constant value for the time. For a normal date, this contains 00:00:00:000. For a closing date, it contains 23:59:59:000 for a DATETIME and 23:59:00:000 for a SMALLDATETIME.

The Microsoft Dynamics NAV undefined date is represented by the earliest valid date in SQL Server: 01-01-1753 00:00:00:000 for a DATETIME, and 01-01-1900 00:00:00:000 for a SMALLDATETIME.

For time fields, only a SQL Server DATETIME type can be used. Microsoft Dynamics NAV uses only the time and places a constant value for the date: 01-01-1754. The Microsoft Dynamics NAV undefined time is represented by the same value as an undefined date.

In order for Microsoft Dynamics NAV to interpret date and time values correctly, the formats mentioned earlier must be used when linking Microsoft Dynamics NAV table definitions to external tables or views. For more information, see Using Linked Objects.

To reformat a DATETIME or SMALLDATETIME column that is to be used as a date field in Microsoft Dynamics NAV, an UPDATE statement can be applied to the table data. The following is an example of such an update statement.

Copy Code
UPDATE [My Table] SET [My Date] = CONVERT(CHAR(10), [My Date], 120)

For a closing date, a CONVERT style of 120 can be used to set the appropriate time part. To reformat a time field, a similar statement can be used.

Copy Code
UPDATE [My Table] SET [My Time] = CAST('1754-01-01 '+CONVERT(CHAR(8), [My Time], 108) AS DATETIME)

As an alternative to modifying the table data, you can create a view that applies the necessary conversion to the column and gives the column an alias. However, you cannot update views that are created in this way and it is more efficient to change the data than to apply conversions for every row.

Note
The information about date and time fields only applies to fields of the Date data type and Time data type; it does not apply to fields of the DateTime data type.

See Also

Reference

Field Data Types

Concepts

Identifiers, Data Types, and Data Formats


Accessing Microsoft Dynamics NAV Tables with External Tools

You can access data in Microsoft Dynamics NAV 2016 tables with external tools, such as Microsoft Enterprise Manager. When you do this, the values in fields that contain the code, date, and time data types with a specific format, must be manipulated correctly for data modification or comparison. When you use external tools, no special processing of code field data is required to join fields in different tables, if you use the same SQL data type value for each code field in a join or CAST the value to the appropriate data type.

In the New Database and Alter Database windows, you can choose to maintain SQL views. If you enable this option, SQL Server will create and maintain a view for each language ID that is added to a table in Microsoft Dynamics NAV. The system creates a SQL view by prefixing the SQL Server table name with the Windows language ID for each CaptionML value.

This means that external tools can use a view of the object in the user’s language, for example, Spanish, rather than the object name. The object name could be in another language, for example, English (United States).

The view is updated by every change in the CaptionML values of a table. For more information, see Multilanguage Development.

See Also

Concepts

Developing Multilanguage-Enabled Applications
Identifiers, Data Types, and Data Formats


How to: View or Modify Properties on a Table or Field

Use the following procedure to view or modify properties for a table or a field.

To view or modify table or field properties

  1. On the Tools menu, choose Object Designer.

    Object Designer appears.

  2. Choose Table to view the list of tables.

  3. Select a table and then choose Design.

    The table opens in Table Designer.

  4. To modify table properties, place the cursor on an empty line in Table Designer. Press F3 to create an empty line if one does not exist.

    -or-

    To modify field properties, place the cursor on the field in the table.

  5. Choose View and then choose Properties.

    The Properties window appears.

  6. To modify a property value, enter the new value in the Properties window. After entering the new value, update the property by pressing ENTER or by choosing outside of the property.

See Also

Reference

Table Properties


How to: View and Sort Table Data

Usually, you use a page to view the data in a table, but you can also view the data directly by running the table from Object Designer.

To view table data without using a page

  1. Open Object Designer and select the table to view.

  2. Choose Run.

    The table data is displayed in the Microsoft Dynamics NAV Windows client.

Changing Table Sort Order

Table data is displayed in the sort order defined by the current key. If more than one key is defined for the table, you can switch between keys to change the sort order.

To view table data with a different sort order

  1. Open Object Designer, choose Table and then select the table that you want to view.

  2. Choose Run to open the table in the Microsoft Dynamics NAV Windows client.

  3. In the drop-down list next to Sorting, select the key by which you want to sort. By default, the current key is selected.

  4. Choose the sort order arrow and select Sort ascending or Sort descending to select a sort order.

See Also

Concepts

Tables


Changing the Design of Tables

When you design the tables in your database, you determine which fields they contain. But you will often need to modify the design of some of the tables after they have been in use for a while. Typically you will want to add or delete fields, or make changes to field names or data types.

Rules for Changing Tables

You can modify tables that do not contain data at any time. However, when the table contains data, a number of restrictions apply. The following table lists some general rules.

Modification | Rule
Change a field name | You can always change the name of a field.
Change a field number | You can always change the number of a field. This causes Microsoft Dynamics NAV to run through all the application objects in order to update all the references to this field. This can be a time consuming process.
Change a field data type | You can change the data type for a field only if there is no data in this field for any of the records in the table. There is one exception to this rule—you can change the data type of a field from Code to Text even if the field contains data for some records.
Add a field to a table | You can always add a field to a table.
Delete a field | To delete a field, you must delete all data from the field in all records in the table. You must also remove all references to the field from other tables, pages, and reports.
Change the length of a String field | You can always increase the length of a String field. Whether you can decrease the length of a String field depends on the contents of all the values in the column in the table. The minimum length of a String field is determined by the longest string in the column.

See Also

Tasks

How to: Add Fields to a Table
How to: View or Modify Properties on a Table or Field


Table Keys

The database management system, which is SQL Server, keeps track of each field by using the field number and the record's primary key. The primary key is composed of up to 16 fields in a record. The combination of values in fields in the primary key makes it possible to uniquely identify each record.

Primary Keys

The primary key determines the logical order in which records are stored, regardless of their physical placement.

Logically, records are stored sequentially in ascending order and are sorted by the primary key. Before adding a new record to a table, SQL Server checks if the information in the record's primary key fields is unique and only then inserts the record into the correct logical position. Records are sorted dynamically so the database is always structurally correct. This allows for fast data manipulation and retrieval.

A table description contains a list of keys. A key is a sequence of one or more field IDs from the table. Up to 40 keys can be associated to a table. The first key in the list is the primary key.

The primary key is always active, and SQL Server keeps the table sorted in primary key order and rejects records with duplicate values in primary key fields. Therefore, the values in the primary key must always be unique. Note that it is not the value in each field in the primary key that must be unique, but it is the combination of values in all fields that make up the primary key.

Secondary Keys

A secondary key uses an additional structure that is called an index. This is like an index that is used in textbooks. A textbook index alphabetically lists important terms at the end of a book. Next to each term are page numbers. You can quickly search the index to find a list of page numbers (addresses), and you can locate the term by searching the specified pages. The index is an exact indicator that shows where each term occurs in the textbook.

When you define a secondary key and mark it as active, an index is automatically maintained and reflects the sorting order that is defined by the key. Several secondary keys can be active at the same time.

A secondary key can be changed into an inactive key, which does not occupy database space, and does not use time during updates to maintain its index. Inactive keys can be reactivated, although this can be time-consuming because SQL Server must scan the whole table to rebuild the index.

The fields that make up the secondary keys do not always contain unique data, and SQL Server does not reject records with duplicate data in secondary key fields. If two or more records contain identical information in the secondary key, then SQL Server uses the primary key for the table to resolve this conflict.

Sort Orders and Secondary Keys

The following example shows how the primary key influences the sort order when a secondary key is active. The Customer table includes four entries (records), and the records in the Customer table have two fields: Customer Number and Customer Name.

The following is the key list for the Customer table.

Key | Key type | Definition
1 | Primary | Customer Number
2 | Secondary | Customer Name

When you sort by the primary key, the Customer table resembles the following table.

Customer Number | Customer Name
001 | Customer C
002 | Customer A
003 | Customer B
004 | Customer C

If you select the secondary key for sorting, then the order is based on the contents of the Customer Name field. Because the contents of these fields are not unique, the records must be subsorted according to the primary key.

Customer Name | Customer Number
Customer A | 002
Customer B | 003
Customer C | 001
Customer C | 004

Note that the two records that have the same Customer Name value are sorted by Customer Number.

How Keys Affect Performance

Searching for specific data is easier if several keys have been defined and maintained for the table that holds the desired data. The indexes for each key provide specific views that enable quick, flexible searches. There are advantages and disadvantages to using many keys, as demonstrated in the following table.

If you | Performance improves when you | Performance slows when you
Increase the number of secondary keys that are marked as active. | Retrieve data in several different sorting sequences because the data is already sorted. | Enter data because indexes for each secondary key must be maintained.
Decide to use only a few keys. | Enter data because a minimal number of indexes are maintained. | Retrieve data. You may have to define or reactivate the secondary keys to get the appropriate sorting. Depending on the size of the database, this can take some time, because the index must be rebuilt.

The decision whether to use a few or many keys is not easy. The choice of appropriate keys and the number of active keys to use should be the best compromise between maximizing the speed of data retrieval and maximizing the speed of data updates (operations that insert, delete, or modify data). In general, it may be worthwhile to deactivate complex keys if they are rarely used.

The overall speed depends on the following factors:

  • Size of the database.

  • Number of active keys.

  • Complexity of the keys.

  • Number of records in your tables.

  • Speed of your computer and its hard disk.

See Also

Tasks

How to: Define Primary and Secondary Keys

Concepts

Table Keys and Performance


How to: Define Primary and Secondary Keys

A maximum of 20 distinct fields can be used to define a primary key. The number of fields used in the primary key limits the number of fields in the secondary keys. Fields used by one key can also be used in another key; however, no more than 20 unique fields can be used to create primary or secondary keys.

This means that if your primary key includes four distinct fields, your secondary keys can include these four fields, and at most 16 other fields. Correspondingly, if your primary key consists of 20 distinct fields, then your secondary keys must consist only of combinations of these fields.

When you create a table in Table Designer, by default Microsoft Dynamics NAV uses the field with the lowest field number as the primary key. Use the following procedure to define a different primary key.

Note
The maximum record size in Microsoft Dynamics NAV is 8000 bytes. Adding a primary key to a table when the record size limit is close to this limit will prevent the table from compiling.

To define a primary key

  1. On the Tools menu, choose Object Designer.

  2. Choose Table.

  3. Select a table from the list and then choose Design.

  4. Select the first empty line and then from the View menu, choose Keys.

    The Keys window appears.

  5. In the first line of the Keys window, enter the primary key as a comma-delimited list; for example, "ID Number, Name".

Defining Secondary Keys

Up to 40 keys can be defined for a table. The first key defined is the primary key. All the other keys are secondary keys and are optional. Secondary keys are used to view records in an order that is different from the order defined by the primary key fields.

To define a secondary key

  1. On the Tools menu, choose Object Designer.

  2. Choose Table.

  3. Select a table from the list and then choose Design.

  4. Select the first empty line and then from the View menu, choose Keys.

    The Keys window appears.

  5. The first line shows the primary key. Enter the secondary keys on the following lines as comma-separated lists; for example: Name, Address.

See Also

Tasks

How to: View or Modify Properties on a Key

Concepts

Table Keys


Key Properties

The keys associated with a table have properties that describe their behavior, just as tables and fields do. When you create a key, Microsoft Dynamics NAV automatically suggests a number of default values for these properties. Depending on the purpose of the key, you will sometimes want to change these default values.

Microsoft Dynamics NAV contains the following properties for keys.

Property Name | Use
Enabled Property | Determines whether the system will maintain an index for the key. You cannot use a key unless it is enabled.
Key Property | Defines the key.
SumIndexFields Property | Determines the fields for which the system will maintain a SumIndex.
MaintainSQLIndex Property | Determines whether a SQL Server index corresponding to the Microsoft Dynamics NAV key should be created.
MaintainSIFTIndex Property | Determines whether SIFT structures should be created in SQL Server to support the corresponding SumIndexFields for the Microsoft Dynamics NAV key.
Clustered Property | Sets a value that indicates whether the index is clustered.
SQLIndex Property | Sets the actual fields that are used in the corresponding index on SQL Server.

See Also

Tasks

How to: View or Modify Properties on a Key

Concepts

Table Keys


How to: View or Modify Properties on a Key

Use the following procedure to view or modify properties for a table or a field.

To view or modify key properties

  1. On the Tools menu, choose Object Designer.

    Object Designer appears.

  2. Choose Table to view the list of tables.

  3. Select a table and then choose Design.

    The table opens in Table Designer.

  4. Choose View and then choose Keys.

    The Keys window opens.

  5. Place the cursor on the line defining the key for which you want to view or modify properties.

  6. Choose View and then choose Properties.

    The Properties window appears.

    To modify a property value, enter the new value in the Properties window. After entering the new value, update the property by pressing ENTER or choosing outside of the property.

See Also

Concepts

Key Properties


Troubleshooting: Cannot compile the table object after adding a primary key

After adding a primary key to a table, you cannot compile the table object.

Resolution

This error can occur when the record size is close to the maximum value. The maximum record size in Microsoft Dynamics NAV is 8000 bytes. To resolve this issue, limit the number of primary keys.

See Also

Tasks

How to: Define Primary and Secondary Keys


xRec and CurrFieldNo

When a user-defined function or a trigger is executed on a table object, xRec and CurrFieldNo are set differently, depending on how the function or trigger is executed. The following tables explain what happens in the different scenarios.

User-Defined Function

The following table explains what happens to xRec and CurrFieldNo when a user-defined function on a table object is called from either external or internal C/AL code. External C/AL code means that the calling code is in a different object. Internal C/AL code means that the calling code is in the same object (another function in the same object).

Execution initiated by | xRec value | CurrFieldNo value
External C/AL code | Empty | 0
Internal C/AL code | Unchanged | Unchanged

Triggers

The following table explains what happens to xRec and CurrFieldNo when a trigger is called from either external or internal C/AL code. External C/AL code means that the calling code is in a different object. Internal C/AL code means that the calling code is in the same object (another function in the same object).

Scenario | xRec value | CurrFieldNo Value
VALIDATE trigger called by external C/AL code that calls the VALIDATE function | Copy of Rec before assignment in VALIDATE trigger | Field number of field being validated
VALIDATE trigger called by internal C/AL code that calls the VALIDATE function | Unchanged | Unchanged
Any table or function called by C/AL that initiates a call to a trigger other than VALIDATE | Copy of Rec before trigger is executed | 0


Compiling Tables

This topic describes requirements and restrictions for compiling a table object after you make changes to a table’s schema, such as adding or removing a table field.

When you compile a table, the validation of changes is performed by Microsoft Dynamics NAV Server. When you compile a table, you will also have to choose how to synchronize the table schema in the database. For more information about table schema synchronization, see Synchronizing Table Schemas.

If you try to compile a table object when your environment does not meet the conditions outlined in this topic, you will get the following error: The specified [service instance] can’t be reached, where [service instance] is the name of the Microsoft Dynamics NAV Server instance.

If you cannot meet the conditions for compiling tables with validation, then you have the option to compile the table object without validation.

Note
The information in this topic does not apply to C/AL code changes made to a table object. With code changes, you can compile the table object like any other object.

Conditions for Compiling Tables with Validation

To compile a table after making schema changes, your environment must meet the following conditions:

  • The development environment can connect to a running Microsoft Dynamics NAV Server instance.

  • The Microsoft Dynamics NAV Server instance is not configured for multitenancy. If it is configured for multitenancy then only a single tenant can be mounted on the server instance.

  • You can be authenticated by the Microsoft Dynamics NAV Server according to one of the following conditions:

    • You are set up as a Microsoft Dynamics NAV user on your Windows account in the Microsoft Dynamics NAVdatabase. This is the recommended option. For more information about setting up a user, see How to: Create Microsoft Dynamics NAV Users.

    • You are set up as an administrator on the computer that is running Microsoft Dynamics NAV Server.

      If the development environment is installed on the same computer as Microsoft Dynamics NAV Server, then you must also run the development environment as an administrator. To do this, right-click the Microsoft Dynamics NAV 2016 Development Environment link on your desktop, and then choose Run as Administrator.


How to: Use a Timestamp Field

Each table in Microsoft Dynamics NAV includes a hidden timestamp field. The timestamp field contains row version numbers for records as maintained in SQL Server. You can expose the timestamp field in a table, and then write code against it, add filters, and so on, similar to any other field in a table. However, you cannot write to the timestamp field.

A typical use of the timestamp field is for synchronizing data changes in tables, when you want to identify records that have changed since the last synchronization. For example, you can read all the records in a table, and then store the highest timestamp value. Later, you can query and retrieve records that have a higher timestamp value than the stored value.

To set up a timestamp field in a table

  1. In the development environment, open the table, and then add a field of the data type BigInteger.

    Specify a name for the field, such as timestamp. You can specify any valid name for field; you are not restricted to use timestamp.

  2. Open the field properties, and then set the SQL Timestamp property to Yes.

See Also

Tasks

How to: Create a Table
How to: Add Fields to a Table

Reference

SQL Timestamp Property


External Tables

You can create tables in Microsoft Dynamics NAV that represent tables in external products, such as Microsoft Dynamics CRM and SQL Server. This is a more dynamic table relationship than creating table definitions from SQL Server objects using linked objects, because the connection to the external table can be changed at runtime. In Microsoft Dynamics NAV 2016 you can define two types of external tables: Microsoft Dynamics CRM tables and SQL Server tables. You create an external table by specifying the type of in the TableType property.

Important
We advise against creating tables of type CRM manually. Instead, use the integration mapping functionality. For more information, see Integration Concepts and Terminology.

Creating and Using External Tables

Microsoft Dynamics NAV commits on all connections at the same time, such as at the same time for the tenant database connection and the application database connection in multitenant deployments. When an external connection is registered, it is joined into this so that any errors will rollback on all connections in use.

To use an external table in your code, you must first register one or more connections to the external database as shown in the following code example.

Copy Code
REGISTERTABLECONNECTION(TABLECONNECTIONTYPE::ExternalSQL, 'ExternalDb1', 'Data Source=ProdServer1;Initial Catalog=ProdDb1;User ID=sqladmin;Password=p@ssword');

When records from external tables are instantiated, the connection is set on them. To set the current table connection, issue the following C/AL command so that different instances can use different connections.

Copy Code
SETDEFAULTTABLECONNECTION(TABLECONNECTIONTYPE::ExternalSQL, 'ExternalDb1');

When done using a set of tables that are connected to a given source, issue the following command. For tables of type ExternalSQL, when UnregisterTableConnection is called, the current transaction will be rolled back.

Copy Code
UNREGISTERTABLECONNECTION(TABLECONNECTIONTYPE::ExternalSQL, 'ExternalDb1');

To see examples of how you can use these functions, see codeunits 5330 and 5331 in the standard version of Microsoft Dynamics NAV.

The actual table connection settings can also be managed using the following new Windows PowerShell cmdlets. In multitenant deployments, information about the connections is added to a table in the application database.

Cmdlet Name | Description
New-NAVTableConnection | Creates a connection to an external table.
Remove-NAVTableConnection | Removes an established connection to an external table.
Get-NAVTableConnection | Gets information about connections to external tables.

If you know that your integration with the external product will be managed by Windows PowerShell cmdlets, your code must call RegisterTableConnection without the actual connection string as shown in the following code example.

Copy Code
REGISTERTABLECONNECTION(TABLECONNECTIONTYPE::ExternalSQL, 'ExternalDb1');

In this scenario, you can write a function that generates a connection string based on the current configuration.

See Also

Reference

TableType Property

Concepts

Overview of Tables
Microsoft Dynamics NAV Windows PowerShell Cmdlets


Dividing the Database into Companies

Microsoft Dynamics NAV can only access one logical database at a time, but this database can be divided into one or more companies. A company is a "subdatabase," and its primary use is to separate and group data in the same database. Fields and tables are identified by a number, but companies are identified by a name. A company bundles one or more data tables together into a logical superstructure that is identified by the company name. Other than the shared company name, the different tables in a company have nothing in common.

Opening a company is the first step that you perform after you open the database or connect to a server.

The following illustration shows a database that has four tables.

The four table descriptions on the left side apply to each of the data tables of three companies. The records in the tables, G/L Account, Customer, and Vendor have the same structure and the same field definitions, even though they belong in three different companies. Only the data stored in the fields differ. The information in a Table Description can be used by tables from more than one company, no redundant information will be stored. This minimizes the size of the database.

Even though you have selected a specific company, you can still access data in any table in any other company. Use the CHANGECOMPANY Function (Record) to explicitly define which other company that you want to access.

See Also

Tasks

How to: Create and Delete a Table Description


How to: Define or Modify Table or Field Triggers

The following procedure describes how to set up a trigger.

To define or modify a table or field trigger

  1. Open Object Designer and then choose Table.

  2. Select a table from the list and then choose Design.

    The table opens in Table Designer.

  3. Choose View and then choose C/AL Code.

    The C/AL Editor opens.

    The position or the cursor in Table Designer determines the order in which triggers are displayed in the C/AL Editors. For example, if you place the cursor on a specific field, the trigger for that field appears at the top of the C/AL Editor. Scroll through the list of triggers displayed to access other triggers.

  4. Enter or modify the appropriate triggers.

See Also

Concepts

Table and Field Triggers
Triggers


Setting Relationships Between Tables

It is common to distinguish among the following types of relationships between tables in relational database design:

  • One-to-many relationships

  • Many-to-many relationships

  • One-to-one relationships

The one-to-many relationship is the most common. If your database design model indicates that you need to set up a many-to-many relationship, then your design is probably inefficient. You can typically break down a many-to-many relationship into two one-to-many relationships. A one-to-one relationship is usually not optimal and can often be avoided by combining the two tables.

Using Relationships

If your database contains tables with related data, then you can define a relationship between them. You relate tables by specifying one or more fields that contain the same value in related records. These matching fields often have the same name in each table. You can use relationships to:

  • Validate data entries.

  • Perform lookup functions in other tables.

  • Propagate changes automatically from one table to other tables.

Note
For performance reasons, in pages that use the Field virtual table, the RelationFieldNo field is blank for fields with complex table relations. To parse all fields that have any table relationships in the Field virtual table is time consuming. Accordingly, data such as complex table relations is not available in windows such as the RapidStart Services configuration worksheet. For more information, see Field Virtual Table.

Table Relationships and the TableRelation Property

Table relationships are defined in Microsoft Dynamics NAV with the TableRelation property. This property allows you to define both simple and advanced table relations.

Note
You can define a relationship only to a field that is a member of the primary key group.

Advanced table relations are typically prefixed with a conditional statement and include filters. The following syntax is for table relations.

Copy Code
<TableRelation> ::=
   <TableNo>[.<FieldNo>] [WHERE ( <TableFilters> )] |
   IF ( <Conditions> ) <TableNo>[.<FieldNo>]
   [WHERE( <TableFilters> )] ELSE <TableRelation>
<Conditions> ::=
   <TableFilters>
<TableFilters>::=
   [<TableFilter> {,<TableFilter>}]
<TableFilter>::=
   <DstFieldNo>=CONST(<FieldConst>) |
   <DstFieldNo>=FILTER(<Filter>)

The following table describes each of the symbols.

Symbol | Description
TableNo | Specifies the related table.
FieldNo | Specifies a field in the related table.
Conditions | Table relations can be conditional.
TableFilters | A list of table filters.
TableFilter | A constant expression or a filter expression.
DstFieldNo | Specifies the destination field number.
Filter | A filter expression, such as 10|20..30.

Examples of Table Relationships

For example, you have an Orders table that stores orders and a Salesperson table that stores the names of all salespeople in your company. In the Orders table, you can include a Salesperson field that identifies the salesperson. By setting up a relationship between these two tables, you can check whether the Salesperson field in the Orders table contains a valid code.

For example, you have a Vendors table with all your vendors and a Currency Code table. You can create a relationship between a Currency Code field in the Vendors table and the Currency Code table. This will allow users to look up information about valid currency codes.

Furthermore, if you change one of the currency codes in the Currency Code table, then the change is automatically propagated to all tables that refer to this code.

See Also

Tasks

How to: Create a Table Relationship
How to: Synchronize Table and SQL Server Relationships

Concepts

Maintaining Table Relationships on SQL Server
Overview of Tables


How to: Create a Table Relationship

Table relationships are defined using the TableRelation Property. This property allows you to define both simple and advanced table relationships. A typical simple table relationship consists of a table name and an optional field name. An advanced table relationship might additionally contain conditions and filters.

To create a table relationship

  1. Open Object Designer and choose Table to see a list of the tables.

  2. Select a table and then choose Design.

    The table opens in Table Designer.

  3. Select the field for which you want to create a relationship and view the Properties window.

  4. Set the TableRelation property value by using the following steps:

    1. In the TableRelation property value, choose the AssistEdit button.

      The Table Relation window opens.

    2. Choose the AssistEdit in the Table cell, select a table, and then choose OK.

    3. Choose the AssistEdit in the Field cell, select a field, and then choose OK.

    4. Set the Condition or Filter fields, as needed.

    5. Choose OK.

See Also

Concepts

Setting Relationships Between Tables


Maintaining Table Relationships on SQL Server

The TableRelation Property in Microsoft Dynamics NAV can be represented in SQL Server by table relationships known as foreign key constraints. These table relationships are metadata about the tables and are only intended for modeling and diagramming; they are not used to enforce data integrity. The foreign key constraints are disabled.

The table relationships in SQL Server can be accessed with external tools that can use this information to generate diagrams illustrating the structure of the database.

You can use the Maintain Relationships option on the Integration tab of the Alter Database window to enable and disable the table relationships on SQL Server. For more information, see Altering Databases - Integration Tab.

Requirements

There are certain requirements that must be met before a TableRelation Property can be represented on SQL Server.

To maintain a table relationship:

  • The fields forming the relationship must be of the same data type in both of the related tables. This also applies to any fields that are specified in the Table Filter field. Text and code fields are compatible as long as they have the same length.

  • The SQL Data Type Property of code fields must be the same in both tables.

  • The table filter that is part of the table relationship must contain only the FIELD filter type. Table filters of the CONST and FILTER filter type cannot be created on SQL Server.

  • Conditional relationships have one SQL Server relationship for each condition, as long as all of the criteria listed here are met by each condition.

See Also

Concepts

Setting Relationships Between Tables


How to: Synchronize Table and SQL Server Relationships

The TableRelation property and SQL Server relationships are automatically synchronized when you create a table and when you redesign a table. However, there are some situations in which you may need to manually synchronize the relationships. Examples include after you have:

  • Deleted a table in the Object Designer.

  • Restored a database backup.

  • Imported a .fob file.

Note
Table relationships are not generated or maintained when you import a .txt file.

To initiate the synchronization process manually

  1. On the File menu, choose Database, and then choose Alter. The Alter Database window appears.

  2. Choose the Integration tab.

  3. Select the Synchronize check box and choose OK.

    This check box is only enabled when there are table relationships that need to be synchronized because of inconsistencies in the TableRelation property.

    If an error occurs during the synchronization process, you receive an error message informing you that a particular table has an invalid relationship. To correct this error, you must modify the TableRelation property of the table in question in the Table Designer and then manually synchronize the relationships again.

See Also

Concepts

Setting Relationships Between Tables


Creating Table Definitions from SQL Server Objects (Linked Objects)

With Microsoft Dynamics NAV, you can create a table definition for a SQL Server object (user table, system table, or view) that already exists in the current database.

Defining Linked Object Table Properties

You use the LinkedObject table property to link to SQL Server objects by changing the value to Yes when creating or modifying a table description in the table designer. When you change this value to Yes, the LinkedInTransaction property becomes available.

The LinkedInTransaction property must be set to No when the Microsoft Dynamics NAV table description refers to a view that depends on objects that are outside the current database or on a linked server.

The LinkedInTransaction property allows you to read and modify data from linked server data sources, such as Microsoft Office Excel, Access, or another SQL Server. This access is not under Microsoft Dynamics NAV transaction control. This means that if a Microsoft Dynamics NAV transaction is stopped, any changes that were made during this transaction to a linked object that is outside the current database or on a linked server will remain in effect.

See Also

Concepts

Accessing Objects in Other Databases or on Linked Servers


Using Linked Objects

When you are using a linked object, you should take the following into account:

  • The name of the SQL Server object that includes any company prefix and ($) separator must match exactly with the name of the Microsoft Dynamics NAV table.

  • You must be a member of the db_owner fixed database role in the current database.

  • The service account of Microsoft Dynamics NAV Server must have permission to access the SQL database table. If accessing objects in other databases or on linked servers, such as a Microsoft Access database or Excel spreadsheet, then the service account must also have permission to access to these sources.

  • As is the case with regular Microsoft Dynamics NAV tables, the object must exist in the current database and be owned by a user in the database who is a member of the db_owner fixed database role. A SQL Server view can be used to access objects outside the current database (including those residing on separate servers) or owned by other users. For more information, see Accessing Objects in Other Databases or on Linked Servers.

  • Microsoft Dynamics NAV will automatically grant the required SQL Server permissions on the object so that you can access it in the same way that regular Microsoft Dynamics NAV tables are accessed. It will then be subject to permissions assigned in the Microsoft Dynamics NAV security system.

  • The object being linked must have a SQL Server table definition that is compatible with the Microsoft Dynamics NAV table definition.

  • A view that cannot be updated in SQL Server (for example one containing computed/converted columns or unions) will also be read-only if it is used as a linked object from Microsoft Dynamics NAV. With SQL Server 2000, you can write Instead-Of triggers to define the logic that allows such a view to be updated. This logic is not part of Microsoft Dynamics NAV.

Rules for Using Linked Objects

Object modification | Rule
Column type | All columns in the object must be type compatible with those named in the Microsoft Dynamics NAV table definition. It is not necessary to name all the columns in the Microsoft Dynamics NAV table definition. For more information about type compatibility, see Identifiers, Data Types, and Data Formats.
SumIndexField technology | SumIndexFields cannot be defined for any object type.
View or system tables | If the object is a view or system table, a primary key must be defined, and any secondary keys may also be defined if required. These keys will only be used in Microsoft Dynamics NAV. They will have no effect on a view, its underlying objects in SQL Server, or on a system table. It is important that the data in the columns named in the primary key is unique. This will not be enforced as a physical constraint by the view or system table in SQL Server. However, Microsoft Dynamics NAV will order the data as though a primary key was physically defined. Microsoft Dynamics NAV relies on this uniqueness in order to correctly identify and order records.
View objects | If the object is a view, it can have only one column of the SQL Server timestamp type, but it does not need to have any unless BLOB fields are present in the Microsoft Dynamics NAV table definition. A timestamp column must exist in a user table.
User table or view | An IDENTITY column can be used in a user table or a view. Microsoft Dynamics NAV will ignore this column when inserting records into the table. This allows the IDENTITY column to be used as intended. Similarly, a computed column in a user table is also ignored. For a view, a column defined on a computed table column cannot be used if insert operations are required.
Temporary table | You cannot link to a SQL Server temporary table.
Multilanguage views | Multilanguage views are not created or maintained for linked objects.

Redesigning a Linked Object Table Definition

After an object has been linked, Microsoft Dynamics NAV treats it like a regular table. However, depending on the object type, SQL Server may prevent certain operations from taking place. For example, a non-updateable view cannot be updated in Microsoft Dynamics NAV, and a SQL Server error message appears if you attempt to do this. The ability to redesign the object from within Microsoft Dynamics NAV is limited; these limitations are as follows:

  • The object cannot be renamed by changing the table definition name or the company name.

  • No fields in the table definition can be renamed.

  • New fields can be added if they exist in the view and existing fields can be deleted. In either case, the definition of the view in SQL Server is not changed.

  • The primary and secondary key definitions can be changed. Also, new keys can be added and existing keys can be deleted.

  • The Microsoft Dynamics NAV field data types can be modified provided that the new type remains compatible with the column type in the view.

  • A linked user table can undergo any design changes that are applicable to a regular table that is created from within Microsoft Dynamics NAV.

  • If the DataPerCompany property of the Microsoft Dynamics NAV table definition is changed, it will result in an attempt to link to a new object. This new object will be based on the new company name. The previously linked SQL Server object will no longer be linked by the table definition.

  • The LinkedObject table property can only be changed from Yes to No for a user table.

See Also

Concepts

Creating Table Definitions from SQL Server Objects (Linked Objects)


How to: Create and Delete a Table Description

You can create different kinds of Microsoft Dynamics NAV table descriptions, depending on the LinkedObject and LinkedInTransaction table property values. You must be a member of the db_owner fixed database role to create a table description.

To create a non-linked table

  1. Set the value of the LinkedObject property to No.

    When you save this table, a SQL Server table that is owned by the db_owner fixed database role is created with the name you have specified (including the company name, if necessary).

    If an object with this name already exists, an error message is displayed and the table is not saved.

To create a linked object that is under transaction control

  1. Set the LinkedObject property to Yes.

  2. Set the LinkedInTransaction property to Yes.

    The table is saved without checking its validity. Microsoft Dynamics NAV will check that the corresponding SQL Server object exists and that it is compatible with the Microsoft Dynamics NAV table description when the table is accessed.

To create a linked object that is not under transaction control

  1. Set the LinkedObject property to Yes.

  2. Set the LinkedInTransaction property to No. Set the LinkedInTransaction property to No when the Microsoft Dynamics NAV table description refers to an object outside of the current database or on a linked server.

To delete a table description

  1. Set the LinkedObject property to No.

When the LinkedObject property is set to No, the SQL Server object is deleted if it is a user table. The SQL Server object is not deleted if it is a system table or a view. It can only be a system table or a view if it has been changed to one of these object types with the aid of an external tool. The LinkedObject property must be set to Yes in order to be able to link to a system table or a view.

When the LinkedObject property is set to Yes, the SQL Server object is not deleted. This means that if you create a Microsoft Dynamics NAV table with the LinkedObject property set to No and then change it to Yes, its corresponding SQL Server object is not deleted.

When you modify the LinkedInTransaction property of a Microsoft Dynamics NAV table, all access to the linked SQL Server object will be made under or outside transaction control, depending on the setting you choose.

  • When you access data in a linked object, if the LinkedInTransaction property is set to Yes, all access to the linked object will be performed under transaction control, within Microsoft Dynamics NAV transactions. If the LinkedInTransaction property is set to No, all access to the linked object will be performed outside transaction control, independent of Microsoft Dynamics NAV transactions.


Accessing Objects in Other Databases or on Linked Servers

You can access objects outside the current database or server from Microsoft Dynamics NAV by linking to an appropriately defined view in the current database. You can create a view definition outside of Microsoft Dynamics NAV that accesses data on SQL Server linked servers, which can access heterogeneous data sources. This could, for example, involve performing a join of an Oracle table, a Microsoft Office Access table, or a Microsoft Office Excel spreadsheet.

To access objects in other databases or on linked servers you must comply with the following rules:

  • You must set the LinkedInTransaction table property to No in order to use a view referring to objects outside of the current database. The ability to modify data in these objects is dependent on the data providers that the objects refer to.

  • You must be a member of the db_owner fixed database permission set in the current database to access objects in other databases or on linked servers.

  • The service account of Microsoft Dynamics NAV Server must have permission to access the SQL database table. If accessing objects in other databases or on linked servers, such as a Microsoft Access database or Excel spreadsheet, then the service account must also have permission to access to these sources.

  • All security permissions for objects in another database or on linked servers must be granted outside Microsoft Dynamics NAV to the appropriate SQL Server logins.

  • If a linked object refers to a view that accesses objects that are stored in another database on the same server, this view must be treated as though it were accessing a linked server.

See Also

Concepts

Creating Table Definitions from SQL Server Objects (Linked Objects)


Special Tables

Microsoft Dynamics NAV has three types of tables that serve special purposes. The types of tables are:

  • Temporary

  • System

  • Virtual

Temporary tables are used as a repository for temporary information at run time. System and virtual tables are system generated tables that provide information about the current state of the system.

In This Section

Temporary Tables

System Tables

Virtual Tables

See Also

Concepts

Tables


Temporary Tables

A temporary table is a temporary variable that holds a table. A temporary table is used as a buffer for table data in your C/AL programs.

You can use a temporary table just like you use a database table. The differences between a temporary table and a database table are as follows:

  • A temporary table is not stored in the database, but is only held in memory until the table is closed.

  • The write transaction principle that applies to a database table does not apply to a temporary table.

Advantage of a Temporary Table

The advantage of using a temporary table is that all the interaction with a temporary table occurs on Microsoft Dynamics NAV Server. This reduces the load on both the network and the SQL database server.

When you want to perform many operations on the data in a specific table in the database, you can load the data into a temporary table when you modify it. Loading the data into a temporary table speeds up the process because all the operations are performed in memory on the Microsoft Dynamics NAV Server.

Defining and Using a Temporary Table

You must define the temporary table before you can use it in your C/AL code. The variable that holds a temporary table is defined just like any other global or local variable.

Note
XMLPort and report objects include a Temporary property that enables you to use temporary tables for storing the elements of data set that is generated by the objects. For more information, see Temporary Property (XMLports) and Temporary Property (Reports).

To define a temporary table

  1. On the Tools menu, choose Object Designer, and then create a new table.

    For information about how to create a table, see How to: Create a Table.

  2. Choose View, and then choose C/AL Globals or C/AL Locals, depending on whether your variable will be global or local.

    If you choose C/AL Globals, the C/AL Globals window appears.

    C/AL Globals window

  3. Enter a name for the temporary table variable, and enter or select Record as the data type. Use the up arrow in the Subtype field to select the table to copy.

  4. With the cursor still on the line that defines the temporary table, choose View, and then choose Properties (Shift+F4) to display the Properties window.

  5. Change the value of the Temporary property to Yes.

After you have created a temporary table, you can use it in your C/AL code. You can apply filters and perform searches just as you can with a database table.

See Also

Concepts

Programming in C/AL

Other Resources

Special Tables


System Tables

System tables are stored in the database just like other database tables. However, unlike other database tables, they are created automatically. The information in system tables is closely related to the Database Management System (DBMS), which uses the system tables to manage, for example, system security and permissions.

You can read, write, modify, and delete the information in system tables.

Important
The system tables are required for Microsoft Dynamics NAV to work as intended. If you modify a system table, programmatically or otherwise, you risk damaging the behavior of Microsoft Dynamics NAV. Also, any changes that you make to a system table may be not valid in a future version of Microsoft Dynamics NAV.

If you change data in the Object table programmatically, such as changing a table definition in your C/AL code, the changes will not take effect. If you want to change an existing object, you must do so in the Microsoft Dynamics NAV Development Environment. For more information, see Designing Application Objects.

See Also

Concepts

Data Security
Object-Level Security
Development

Other Resources

Special Tables


Virtual Tables

A virtual table contains system information. You cannot change the data in virtual tables. You can only read the information. Virtual tables are not stored in the database but are computed by Microsoft Dynamics NAV at run time.

Using Virtual Tables

You can use the same methods to access information in virtual tables as you use when you are working with ordinary tables. For example, you can use filters to get subsets or ranges of integers or dates from the Integer virtual table or the Date virtual table.

A system administrator usually uses these virtual tables. These tables give the system administrator information about the users who are currently connected to the database and the current state of the system.

The virtual tables provide such information as:

  • Integers in the range -1,000,000,000 to 1,000,000,000.

  • Dates in a given period.

  • Overview of the operating system files.

  • Overview of the logical disk drives.

  • Overview of the operating system files that store the database.

Because virtual tables are not stored in the database, you cannot view them directly. To view a virtual table, you must create a list page based on the virtual table. For more information, see How to: Create a Page to View a Virtual Table.


Code Coverage Virtual Table

The Code Coverage virtual table (ID 2000000049) contains data about automated test execution and the extent to which application code is covered by test.

Code coverage is the means of being able to track which part of the application code has been exercised during test activity. In Microsoft Dynamics NAV, code coverage is recorded by C/AL code line and specifies if a code line was exercised by test and the number of times the line of code was recorded.

See Also

Reference

Code Coverage

Concepts

Application Test Automation


Codeunit Metadata Virtual Table

The Codeunit Metadata virtual table (ID 2000000137) contains information about codeunits in the database. The following table describes the fields in the Codeunit Metadata virtual table.

Field | Description
ID | The ID of the codeunit object.
Name | Specifies the name of the codeunit object.
TableNo | Specifies the ID of the source table object, if any.
SingleInstance | Specifies whether a single instance of the codeunit and codeunit variables are instantiated.
SubType | Specifies whether the codeunit acts as a normal, test, test runner, or upgrade codeunit.

The fields in the virtual table correspond to properties on the codeunit objects. For more information, see Codeunit Properties.

To access and view the Codeunit Metadata virtual table, you must create a tabular-type page. For more information, see How to: Create a Page to View a Virtual Table

See Also

Concepts

Virtual Tables


Date Virtual Table

The Date virtual table gives you easy access to days, weeks, months, quarters, and years. The Date virtual table has the following fields.

Field | Description
Period Type | Days, weeks, months, quarters, or years.
Period Start | The date of the first day in the period.
Period End | The date of the last day in the period.
Period No. | The number of the period.
Period Name | The name of the period.

The following illustration shows the Date virtual table. For each period type, there are many records in the Date table.

Date Virtual Table window

You can apply filters to the Period Type, Period Start, and Period End fields to easily get a subset or range of days, weeks, months, quarters, or years to use in your pages or reports.

Date Virtual Table Example

The Date virtual table is most frequently used to provide a range of dates; the Receivables- Payables page is a typical example. The following illustration shows the Receivables-Payables page.

Date Virtual table

See Also

Concepts

Virtual Tables


Drive Virtual Table

The Drive virtual table gives you an overview of the logical drives on your computer. The Drive virtual table contains the following fields.

Field | Description
DriveName | The name of the drive, such as drive C or D.
Removable | Indicates whether the disk is removable (a CD-ROM or similar) or a hard disk.
SizeInKilobyte | The total size of the disk.
FreeInKilobyte | The amount of free space on the disk.

You must create a tabular-type page to access the Drive virtual table.

Note
If there is no disk in your disk drive, the SizeInKilobyte and FreeInKilobyte fields will contain the value -1.

See Also

Concepts

Virtual Tables


Event Subscriptions Virtual Table

The Event Subscriptions virtual table (ID 2000000140) contains data about the event subscriber functions that subscribe to published event functions. For more information about the fields in the table, see Event Subscriptions.

See Also

Concepts

Virtual Tables


Field Virtual Table

The Field virtual table contains information about fields in database tables. The Field virtual table contains the following fields.

Field | Description
TableNo | The ID number for the table.
No. | The number assigned to the field.
Table Name | The name of the table.
FieldName | The name of the field.
Type | The data type assigned to the field, for example, decimal.
Len | The length of the field entry in bytes.
Class | The class of the field, for example, FlowField.
Enabled | Whether the field is enabled.
Type Name | The data type assigned to the field. The length of the field entry in bytes is included for Code and Text data types.
Field Caption | The caption of the field in the language that has been selected.
RelationTableNo | The ID number for the table that the field is related to.
RelationFieldNo | The number of the field in another table that the field is related to.
SQLDataType | The data type assigned to code fields.

You must create a tabular-type page to access the Field table. The following illustration shows the Field virtual table.

Field Virtual table
Note
For performance reasons, in pages that use the Field virtual table, the RelationFieldNo field is blank for fields with complex table relations. To parse all fields that have any table relationships is time consuming. Accordingly, data such as complex table relations is not available in windows such as the RapidStart Services configuration worksheet.

See Also

Concepts

Virtual Tables


File Virtual Table

The File virtual table gives you an overview of the files in a directory on your disk. The File virtual table contains the following fields.

Field | Description
Path | The filter on the Path field determines which directory is shown.
IsFile | The value Yes indicates that the entry is a file; the value No indicates that the entry is a directory.
Name | The name of the file or directory.
Size | The size of the file in bytes.
Date | The date the file was last modified.
Time | The time the file was last modified.
Data | A BLOB field with the contents of the file.

You must create a tabular-type page to access the File virtual table.

See Also

Concepts

Virtual Tables


Integer Virtual Table

The Integer virtual table includes integers in the range -1,000,000,000 to 1,000,000,000. The Integer virtual table contains only one field.

Field | Description
Integer | An integer in the range -1,000,000,000 to 1,000,000,000.

By applying a filter to the Integer virtual table, you can easily get a subset or range of numbers that can be used to control looping in reports.

See Also

Concepts

Virtual Tables


Key Virtual Table

The Key virtual table contains information about the keys that are defined in each table in the database.

The Key virtual table contains the following fields.

Field | Description
TableNo | The ID number for the table.
No. | The number of the key.
TableName | The name of the table.
Key | The fields that make up the key.
SumIndexField | The SumIndexFields that are defined for this key.
SQLIndex | The actual fields that have been defined in Microsoft Dynamics NAV and are used in the corresponding index on SQL Server instead of those defined in the key.
Enabled | Whether the index is enabled. This field can be modified.
MaintainSQLIndex | Whether the MaintainSQLIndex property has been activated. This field can be modified.
MaintainSIFTIndex | Whether the MaintainSIFTIndex property has been activated. This field can be modified.
Clustered | Whether the key is clustered. This field can be modified.

You must create a tabular-type page to access the Key table. The following illustration shows the Key virtual table.

Key Virtual table

See Also

Concepts

Virtual Tables


Page Metadata Virtual Table

The Page Metadata virtual table (ID 2000000138) contains data about the pages in database. The following table describes the fields in the Page Metadata virtual table.

Field | Description
ID | The ID for the page object.
Name | Specifies the name of the page object.
Caption | Specifies the caption of the page in the language that has been selected.
Editable | Specifies whether the page can be edited through the UI.
PageType | Specifies the page type as either Card, List, RoleCenter, CardPart, ListPart, Document, Worksheet, ListPlus, ConfirmationDialog, NavigatePage, or StandardDialog.
CardPageID | Specifies the ID of the Card type page that is associated with items in the page. This is typically used when the page is a List, ListPart or ListPlus page type.
DataCaptionExpr | Specifies a C/AL expression that is evaluated and displayed to the left of the page caption.
RefreshOnActivate | Specifies whether data on the page is automatically refreshed if you leave the page (without closing it), and then return.
SourceTable | Specifies the ID of the table from which this page will display records.
SourceTableView | Specifies the key, sort order, and filter you want to use to determine the view of the source table presented to the user.
InsertAllowed | Specifies whether users can add records while they are using a page.
ModifiedAllowed | Specifies whether users can modify records while they are using this page.
DeleteAllowed | Specifies whether users can delete records while they are using the page.
DelayedInsert | Specifies whether a user must leave a record before it is inserted into the database.
ShowFilter | Specifies whether the filter pane is shown on a page by default.
MultipleNewLines | Specifies whether users can add multiple new lines between records.
SaveValues | Specifies whether user-specific control values are saved for this page.
AutoSplit | Specifies whether a key is automatically created for a new record positioned between the current record and the previous record.
DataCaptionFields | Specifies the fields that appear to the left of the caption on pages.
SourceTableTemporary | Specifies whether the source table is a temporary table.
LinksAllowed | Specifies whether links or notes are allowed on the page.
PopulateAllFields | Specifies whether fields are filled out automatically with a single filter value when a new record is inserted in a table.

The fields in the virtual table correspond to C/AL properties on the page objects. For more information, see Page Properties.

To access and view the Page Metadata virtual table, you must create a tabular-type page. For more information, see How to: Create a Page to View a Virtual Table

See Also

Concepts

Virtual Tables


Report Metadata Virtual Table

The Report Metadata virtual table (ID 2000000139) contains data about the pages in database. The following table describes the fields in the Report Metadata virtual table.

Field | Description
ID | The ID for the report object. Data type: Integer
Name | Specifies the name of the report object. Data type: String
Caption | Specifies the caption of the report in the language that has been selected. Data type: String
UseRequestPage | Specifies whether a request page is presented to the user. Data type: Boolean
UseSystemPrinter | Specifies which printer is suggested when the report is run. Data type: Boolean
EnableExternalImages | Specifies whether external images are allowed on a report. Data type: Boolean
EnableHyperLinks | Specifies whether hyperlinks to URLs are allowed on reports. Data type: Boolean
EnableExternalAssemblies | Specifies whether external Microsoft .NET assemblies can be used on a report. Data type: Boolean
ProcessingOnly | Specifies the value that indicates whether a report produces printed output or only processes data. Data type: Boolean
ShowPrintStatus | Sets whether a window that shows the printing status of a report when it is run is displayed. Data type: Boolean
TransactionType | Sets the transaction type as either UpdateNoLocks, Update, Snapshot, Browse, or Report. Data type: Option
PaperSourceFirstPage | Specifies which paper source to use when printing page one of the report. Data type: Integer
PaperSourceDefaultPage | Specifies whether users can delete records while they are using the page. Data type: Integer
PaperSourceLastPage | Specifies the default paper source to use when printing the report. Data type: Integer
PreviewMode | Specifies how the report opens when you preview it. The options are Normal and PrintLayout. Data type: Option
DefaultLayout | Specifies whether the report uses the built-in RDLC or Word report layout by default. Data type: Option
WordMergeDataItem | Specifies the name of the root-level DataItem that is used for generating separate reports for multiple records. Data type: String
FirstDataItemTableId | Specifies the ID of the table that is associated with the first DataItem that is defined for the report in Report Designer. If there is not table, then this field is 0. Data type: Integer

The fields in the virtual table correspond to C/AL properties on the page objects. For more information, see Report Properties.

To access and view the Report Metadata virtual table, you must create a tabular-type page. For more information, see How to: Create a Page to View a Virtual Table

See Also

Concepts

Virtual Tables


Server Virtual Table

The Server table contains the following fields.

Field | Description
Server Name | The name of the computer on which the server is installed.
My Server | Whether this is the server that you are logged on to.

You must create a tabular-type page to access the Server table.

Server Virtual table

See Also

Concepts

Virtual Tables


Table Information Virtual Table

The Table Information virtual table contains information about database tables. The Table Information virtual table contains the following fields.

Field | Description
Company Name | The name of the company the table belongs to.
Table No. | The ID number for the table.
Table Name | The name of the table.
No. of Records | The number of records in the table.
Record Size | A value expressing the average size of a record. Calculated as 1024 x Size (KB)/Records.
Size (KB) | How much space the table occupies in the database (in kilobytes).

See Also

Concepts

Virtual Tables


Table Metadata Virtual Table

The Table Metadata virtual table (ID 2000000136) contains data about the tables in database. The following table describes the fields in the Table Metadata virtual table.

Field Description

TableNo

The ID for the table object.

Table Name

Specifies the name of the table object.

Caption

Specifies the caption of the table in the language that has been selected.

DataPerCompany

Sets whether the table data applies to only the current company (No) or all companies (Yes) in the database.

LookupPageID

Specifies the ID of the page that is used for lookup.

DrilldownPageID

Specifies the ID of the page that is used for drill down.

DataCaption Fields

Specifies one or more fields that will be used as captions when a record from this table is displayed in a page.

PasteIsValid

Specifies whether inserting records into this table using the paste command is enabled.

LinkedObject

Specifies whether to link to SQL Server objects.

DataIsExternal

Specifies whether the data is from an external table which means that the data is not managed by Microsoft Dynamics NAV.

DataIsExternal is set if the LinkedObject Property is set to Yes or the TableType Property is set to CRM or ExternalSQL .

TableType

Specifies whether the table type is Normal, CRM, or ExternalSQL.

Except for the DataIsExternal field, the fields in the virtual table correspond directly to C/AL properties on the table objects. For more information, see Table Properties.

To access and view the Table Metadata virtual table, you must create a tabular-type page. For more information, see How to: Create a Page to View a Virtual Table

See Also

Concepts

Virtual Tables


How to: Create a Page to View a Virtual Table

Virtual tables are not stored in the database, therefore you cannot view them directly. To view a virtual table, you must create a list page that is based on the virtual table.

To create a page to view a virtual table

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Page, and then choose the New button.

  3. In the New Page window, in the Table field, enter the ID of the virtual table. Virtual tables have IDs in the range 2000000001 - 2000000203.

  4. In the Page section, choose Create blank page, and then choose the OK button.

  5. In Page Designer, in the first row, enter a name for the container, such as VirtualTablePageContainer. Verify that the Type is Container and the SubType is ContentArea.

  6. In Page Designer, in the second row, in the Type column, choose Group and in the SubType column, choose Repeater.

  7. In Page Designer, select the third row.

  8. On the View menu, choose Field Menu.

  9. In the Field Menu window, select all the fields in the virtual table that you want to display on the page, and then choose the OK button.

    Note
    To select multiple fields in the Field Menu window, press the Shift key or the Ctrl key while you select the fields.

  10. On the File menu, choose Save.

  11. In the Save As dialog box, in the ID field, enter an ID for the page object. The ID must be in a valid range for your solution. In the Name field, enter a name for the page. Select the Compiled check box, and then choose the OK button.

  12. To view the data that is stored in the table, in Object Designer, select the page that you created and then choose the Run button.

See Also

Concepts

Virtual Tables


SumIndexField Technology (SIFT)

SumIndexField Technology (SIFT) lets you quickly calculate the sums of numeric data type (Decimal, Integer, BigInteger, and Duration) columns in tables, even in tables with thousands of records. SIFT is used to optimize the performance of FlowFields and query results in a Microsoft Dynamics NAV application. SIFT involves performing a series of database calls and calculations before arriving at a result. The topics in this section describes how SIFT is implemented in Microsoft Dynamics NAV.

See Also

Concepts

FlowFields


SIFT and SQL Server

A SumIndexField is always associated with a key and each key can have a maximum of 20 SumIndexFields associated with it. In this topic, a key that has at least one SumIndexField associated with it is a SIFT key.

Important
Any field that has a numeric data type of Decimal, Integer, BigInteger, or Duration, can be associated with a key as a SumIndexField.

Implementing SIFT

Microsoft Dynamics NAV 2016 uses Indexed Views to maintain SIFT totals. Indexed views are a standard SQL Server feature. An indexed view is like a SQL Server view except that the contents have been materialized (computed and stored) to speed up the retrieval of data. For more information about indexed views, see SQL Server Books Online.

Microsoft Dynamics NAV 2016 creates one indexed view for each SIFT key that is enabled. When you create a SIFT key for a table, you must set the MaintainSIFTIndex property for that key to Yes to enable the SIFT key and create the indexed view. After SQL Server has created the indexed view, it maintains the contents of the view when any changes are made to the base table. If you set the MaintainSIFTIndex property for that key to No, SQL Server drops the indexed view and stops maintaining the totals.

The indexed view that is used for a SIFT key is always created at the level of finest granularity. Therefore, if you create a SIFT key for AccountNo.,PostingDate, the database will store an aggregated value for each account for each date. This means that in the worst case scenario, 365 records must be summed to generate the total for each account for a year.

The following is an example of how Microsoft Dynamics NAV 2016 creates an indexed view for a SIFT key that consists of the AccountNo., PostingDate fields and generates the total for the Amount field.

Copy Code
CREATE VIEW GLEntry$VSIFT$1 AS SELECT SUM(Amount) as SUM$Amount,
AccountNo, PostingDate FROM GLEntry GROUP BY AccountNo,PostingDate*
CREATE UNIQUE CLUSTERED INDEX VSIFTIDX ON
GLEntry$VSIFT$1(AccountNo,PostingDate)*

The following C/AL code example retrieves a total.

Copy Code
GLEntry.SETCURRENTKEY("G/L Account No.","Posting Date");
GLEntry.SETRANGE(GLEntry."G/L Account No.",'1110');
GLEntry.SETRANGE(GLEntry."Posting
Date",DMY2DATE(1,1,2007),DMY2DATE(15,12,2007));
GLEntry.CALCSUMS(Amount);

The following code example shows how the same total is retrieved through an indexed view.

Copy Code
SELECT SUM(SUM$Amount) FROM GLEntry$VSIFT$1 WITH(NOEXPAND) WHERE
AccountNo=? AND PostingDate>=? AND PostingDate<=?

See Also

Concepts

Tuning and Tracing
SIFT and Performance
SumIndexField Technology (SIFT)


Tuning and Tracing

As a result of using indexed views, SIFT keys are exposed to SQL Server tracing and tuning tools. For example, the SQL Server profiler can display information about which indexed views are maintained for a specific table. This makes it easy for you to assess the cost of maintaining SIFT keys and allows you to make informed decisions about any adjustments that might be required.

SIFT Keys

When data is inserted, updated, or deleted in a table, the SIFT keys that have been defined and enabled for that table are maintained. Maintaining these SIFT indexes has performance overhead. The size of the performance overhead depends on the number of keys and SumIndexFields that have been defined for each table. You should therefore give careful consideration to the number of SIFT keys that you define and only maintain the SIFT keys that are important for your application.

There is no need to maintain a SIFT key for a total that is only used periodically and can be easily generated by a report. You can still program Microsoft Dynamics NAV 2016 to calculate the SIFT based totals even if the SIFT key is disabled. The calculation is performed directly on the base table.

You should consider combining indexes wherever possible.

Example

Maintaining two SIFT keys:

  1. Key: "WareHouseId, ItemId, Color" SumField: "OnStock"

  2. Key: "WareHouseId, ItemId, Size" SumField: "OnStock"

If there are only a few combinations of Size and Color (for example, less than 200), then one combined index/SIFT key should be sufficient.

  1. The Combined Key:

  2. "WareHouseId, ItemId, Color, Size" SumFIeld: "OnStock"

When you set the MaintainSIFTIndex property of a key to Yes, this will be the SIFT key and create the indexed view to support it. However, disabling the SIFT key by setting MaintainSIFTIndex to No can improve performance in certain circumstances. Setting this property to No means that the SIFT functionality must be implemented by calculating the totals online instead of using the precalculated sums that are maintained by SIFT.

See Also

Concepts

SumIndexField Technology (SIFT)


SIFT and Performance

This topic looks at the factors you must take into consideration when you deal with SIFT and performance.

Performance Factors to Consider

The factors that you must take into consideration when you deal with any performance problems that arise include:

  • Designing your SIFT indexes optimally.

  • Supporting too many SIFT indexes will affect performance.

  • Having unnecessary date fields in the SIFT indexes of the base table will affect performance because they create three times as many entries as an ordinary field.

  • Supporting too many fields in the SIFT indexes will also affect performance.

  • The fields in the SIFT index that are used most regularly in queries must be positioned to the left in the SIFT index. Usually, the field that contains the greatest number of unique values must be placed on the left, with the field that contains the second greatest number of unique values on the right and so on. Integer fields generally contain the greatest number of unique values and Option fields contain a relatively small number of values.

Consider the costs and the benefits of maintaining SIFT indexes.

Cost | Benefit
Updates to the SIFT indexes | Fast calculation of sums
Potential locking conflicts |

You can prevent the SIFT indexes from being updated by setting the MaintainSIFTIndex property of the index in the base table to No. This means that you no longer benefit from SIFT's ability to calculate sums quickly. However, the SIFT functionality is still available. If the base table does not grow or only grows slowly, there is no need to set MaintainSIFTIndex to Yes for any indexes that contain SumIndexFields. If the base table does grow, you should set MaintainSIFTIndex to Yes for any indexes that contain SumIndexFields.

In Microsoft Dynamics NAV 2016, changes have been made to improve performance when accessing the database. One of these changes is that Microsoft Dynamics NAV automatically maintains a count for all SIFT indexes. For more information about how this affects the Count and Average methods on FlowFields, see CALCFIELDS Function (Record). For more information about other data access changes, see Data Access.

Important
It is important that you remember to perform tests every time you make any changes to the SIFT structures. You must ensure that the changes that you have made do not cause problems in any other areas of the application. You must also ensure that your changes do not have a negative effect on performance.

See Also

Concepts

FlowFields


FlowFields

FlowFields display the result of the calculation described in the CalcFormula Property. For example, the Account Balance field in the General Ledger Account table shows the balance of the account and is calculated as the sum of the NetAmount fields for all General Journal entries in the account.

FlowFields increase performance in activities such as calculating the balance of your customers. In traditional database systems, this involves a series of accesses and calculations before a result is available. By using FlowFields, the result is immediately available.

FlowFields are not physical fields that are stored in the database. They are a description of a calculation and a location for the result to be displayed. Because the information in FlowFields exists only at run time, values in FlowFields are automatically initialized to 0 (zero). To update a FlowField, use the CALCFIELDS Function (Record). If a FlowField is the direct source expression of a control on a page, then the FlowField is automatically calculated when the page is displayed.

FlowField Types

There are seven types of FlowFields. Each is described in the following table.

FlowField type | Field type | Description
Sum | Decimal, Integer, BigInteger, or Duration | The sum of a specified set in a column in a table.
Average | Decimal, Integer, BigInteger, or Duration | The average value of a specified set in a column in a table.
Exist | Boolean | Indicates whether any records exist in a specified set in a table.
Count | Integer | The number of records in a specified set in a table.
Min | Any | The minimum value in a column in a specified set in a table.
Max | Any | The maximum value in a column in a specified set in a table.
Lookup | Any | Looks up a value in a column in another table.

Example

Consider the Customer table in the following illustration. This table contains two FlowFields. The field named Any Entries is a FlowField of the Exist type, and the Balance field is a FlowField of the Sum type.

Table that has two FlowFields

The figure shows that the value in the Balance FlowField for customer number 10000 (Windy City Solutions) is retrieved from the Amount column in the Customer Entry table. The value is the sum of the amount fields for the entries that have the customer number 10000.

Copy Code
Sum = 10 + 20 + 30 = 60.

The values shown in the Balance column in the Customer table for customers 10010, 10020, and 10040 are found in the same way. For customer number 10030 the value is 0 (zero), as there are no entries in the Customer Entry table that have a Customer No. that equals 10030.

In this example, the Balance FlowField in the Customer table reflects the sum of a specific subset of the Amount fields in the Customer Entry table. How the calculation of a FlowField is to be made, is defined in a calculation formula. The calculation formula for the Balance field is:

Copy Code
Sum("Customer Entries".Amount WHERE(CustNo=FIELD(CustNo)))

Correspondingly, the Any Entries field, which indicates whether any entries exist, has the following definition:

Copy Code
Exist("Customer Entries" WHERE(CustNo=FIELD(CustNo)))

See Also

Tasks

How to: Create a FlowField

Reference

FieldClass Property
CALCFIELDS Function (Record)

Concepts

SumIndexField Technology (SIFT)


How to: Create a FlowField

The following procedure describes how to set up a FlowField.

To create a FlowField

  1. On the Tools menu, choose Object Designer. Open the table that you want to add a FlowField to in the Table Designer.

  2. Select the line for the field that you want to define as a FlowField, such as the Amount field.

  3. On the View menu, choose Properties. The Properties window of the Amount field displays.

  4. In the FieldClass property field, select FlowField from the drop-down list.

  5. In the CalcFormula property field, enter the calculation formula for the FlowField.

    For more information, see Calculation Formulas and the CalcFormula Property.

  6. (optional) In the Editable field, select No.

See Also

Tasks

How to: Create, View, and Edit a Calculation Formula


Calculation Formulas and the CalcFormula Property

A FlowField is always associated with a calculation formula that determines how the FlowField is calculated. The following syntax is valid for the CalcFormula property.

Copy Code
<CalculationFormula> ::=
    [-]Exist(<TableNo> [WHERE (<TableFilters>)]) |
    Count(<TableNo> [WHERE (<TableFilters>)]) |
    [-]Sum(<TableNo>.<FieldNo> [WHERE(<TableFilters>)])|
    [-]Average(<TableNo>.<FieldNo> [WHERE (<TableFilters>)]) |
    Min(<TableNo>.<FieldNo> [WHERE (<TableFilters>)]) |
    Max(<TableNo>.<FieldNo> [WHERE (<TableFilters>)]) |
    Lookup(<TableNo>.<FieldNo> [WHERE (<TableFilters>)])
<TableFilters> ::=
    [<TableFilter> {,<TableFilter>}]
<TableFilter> ::=
    <DstFieldNo>=CONST(<FieldConst>) |
    <DstFieldNo>=FILTER(<Filter>) |
    <DstFieldNo>=FIELD(<SrcFieldNo>) |
    <DstFieldNo>=FIELD(UPPERLIMIT(<SrcFieldNo>)) |
    <DstFieldNo>=FIELD(FILTER(<SrcFieldNo>)) |
    <DstFieldNo>=FIELD(UPPERLIMIT(FILTER(<SrcFieldNo>)))

Parts of the formula are described in the following table.

Symbol | Description
<TableNo> | Specifies the table holding the information to be used in the FlowField.
<FieldNo> | Specifies the column from which you want to compute values.
<TableFilters> | A list of filters to be used in the computation of the FlowField.
<TableFilter> | A table filter can be one of the following: a constant expression, a filter expression, a value from ordinary fields, or a FlowFilter field. A key for the other table must exist and include the fields used in the filters.
<DstFieldNo> | Specifies the destination field number.
<SrcFieldNo> | Specifies the source field number.
<Filter> | A filter expression such as 10|20..30.

See Also

Tasks

How to: Create, View, and Edit a Calculation Formula

Concepts

FlowFields
FlowFilter Overview


How to: Create, View, and Edit a Calculation Formula

The following procedure describes the steps to take to create and revise a calculation formula for a FlowField of a table.

To create, view, and edit a calculation formula

  1. On the Tools menu, choose Object Designer. Open the table to which you want to add a calculation formula.

  2. Select the field for which you want to create, view, or edit the calculation formula.

  3. On the View menu, choose Properties to open the Properties window.

  4. Find the CalcFormula property.

  5. Enter the calculation formula directly or choose the AssistEdit button. When you choose the AssistEdit button, the following dialog box is displayed.

    Calculation Forumla window

  6. Choose the drop-down button to select the appropriate calculation method.

  7. Select the Reverse Sign option to reverse the sign of the result (only for Sum and Average).

  8. Use the up arrows to select the table and field from which to get the information.

  9. If necessary, you can add a table filter to specify a limited set of records. Choose the AssistEdit button to the right of the Table Filter field and the Table Filter window opens.

  10. On each line in this window, you can define a field filter. For each field filter, specify a field, a type, and a value. You can also set the OnlyMaxLimit and the ValueIsFilter options.

The following example illustrates where the information in the Table Filter window comes from. The Balance at Date field in the G/L Account table is a decimal type FlowField. This field is calculated from values in the Amount Column in the G/L Entry table.

Some of the fields in the G/L Account table are FlowFilter fields. By entering filter expressions into these fields, the user can affect the calculation of FlowFields field, such as Balance at Date, at run time. The user can enter filter values on a FlowFilter page.

G/L Account FlowFilter window

If the user enters a date filter expression in the Date Filter field, it is transferred via the table filter and used in the Date column in the G/L Entry table.

You can use the OnlyMaxLimit option to remove the lower limit from a range defined by a filter expression. For example, if the filter expression is defined as a range x..y, setting the OnlyMaxLimit option transforms the expression into ..y.

The ValueIsFilter option determines how the system interprets the contents of the field referred to in the Value column in the Table Filter window. For example, if the field contains the value 1000..2000, setting the ValueIsFilter option will cause this value to be interpreted as a filter rather than as a specific value.

See Also

Concepts

FlowFields
FlowFilter Overview


FlowFilter Overview

A user may want to limit calculations to include only those values in a column that have some specific properties. For example, a user may want to sum only the amounts of customer entries that are entered in April. This is possible if the application has been designed using FlowFilter fields in connection with the FlowFields.

You use FlowFilter fields to set ranges on the calculations that are shown in FlowFields. For example, if a FlowField contains the total of customer entries, then you can use a FlowFilter to see the total for a single month or range of months. In this example, the FlowFilter field is a date field. You can set up FlowFilter fields to show information that is based on other filters such as business units, departments, or projects.

The following illustration shows the relationship between various types of database fields and the calculation formula.

The filters defined in the calculation formula can consist of constants, values from ordinary fields, and filters given as parameters in FlowFilter fields. In FlowFilter fields, a user can enter a filter value via the user interface in an application that will affect the calculation of a FlowField.

FlowFilter fields are not saved in the database. Instead, they are stored for each window on an individual computer so users have their own filters.

You cannot have a FlowFilter field as the SourceExpr value for a control on a page. If you do, then the control on the page is not editable, and you cannot select a value and filter the data that is displayed in the page.

To enable filtering data on a page, you can add a Filter pane to the page and use limit totals. For more information, see the Page Controls and Parts section of Touring the RoleTailored Client Pages.

See Also

Concepts

FlowFields


SQL Server Data Types

Every available Microsoft Dynamics NAV data type is mapped to an appropriate SQL Server data type. The following table shows which SQL Server data type is used for the corresponding Microsoft Dynamics NAV data type.

Microsoft Dynamics NAV Data Type | SQL Server Data Type
BigInteger | BIGINT
BLOB | IMAGE
Boolean | TINYINT
Code(n) | NVARCHAR(n), INTEGER, SQL_VARIANT
Date | DATETIME
DateFormula | VARCHAR(32)
Decimal | DECIMAL(38,20)
Duration | BIGINT
GUID | UNIQUEIDENTIFIER
Integer | INTEGER
Option | INTEGER
RecordID | VARBINARY(n)
TableFilter | VARBINARY(252)
Text(n) | NVARCHAR(n)
Time | DATETIME

Each of the SQL Server data types is created as NOT NULL except the IMAGE type, which allows NULL.

There are other SQL Server data types than those listed in the previous table. You can use and modify these from within Microsoft Dynamics NAV when you have created or altered SQL Server tables or views outside Microsoft Dynamics NAV.

Some of the SQL Server data types listed previously are compatible with other Microsoft Dynamics NAV data types. The following table shows the extended compatibility of SQL Server data types with Microsoft Dynamics NAV data types.

Microsoft Dynamics NAV Data Type | SQL Server Data Type
Integer, Option | BIT
DateFormula | CHAR(n)
Code | INTEGER
Text(n), Code(n) | NCHAR(n)
BLOB | NTEXT
Decimal, Integer, Option, Boolean | NUMERIC(p,s), MONEY, SMALLMONEY, REAL, FLOAT(n), DECIMAL
Date | SMALLDATETIME
Integer, Option | SMALLINT
BLOB | TEXT
Integer, Option, Boolean | TINYINT


Synchronizing Table Schemas

When you design a table in Microsoft Dynamics NAV, you define the metadata for the table, such as the name and object ID, and the fields and their data types. This table definition describes the table that must be created in the SQL Server database to store business data. You create and modify the table definition by using the Microsoft Dynamics NAV Development Environment. When you make changes to the table definition in the development environment, or when you upgrade a Microsoft Dynamics NAV database to a newer version, you must synchronize the business database table schema with the new or changed table definition so that the two are the same. Table schema synchronization is performed by the Microsoft Dynamics NAV Server instance that connects to the business database.

Depending on the changes to a table definition, you might have to consider how to handle the existing data in the business data table when synchronizing the schema. For example, you must decide whether to keep or delete the data. Some table definition changes, such as adding and renaming a field, adding a new table, or modifying C/AL code to a table, do not affect data in the database table and are considered to be non-destructive changes. With non-destructive changes, you can synchronize the schema without any special data handling considerations. However, if you make destructive changes to the table definition, such as removing a field, then you will be warned by the development environment when you try to save the changes, and you must specify how to handle the data when synchronizing the schema. For more information about destructive table changes, see Handling Destructive Changes With Table Schema Synchronization.

This topic contains the following sections:

  • Synchronizing Table Schemas with SQL Server

  • Synchronizing the Table Schema for Specific Tables From the Development Environment

  • Synchronizing All Table Schemas From the Development Environment

  • Synchronizing Table Schemas When Importing FOB Files

  • Handling Destructive Changes With Table Schema Synchronization

  • How Microsoft Dynamics NAV Server Validates Table Schema Changes

  • Monitoring the Business (Tenant) Database State During and After Schema Synchronization

Synchronizing Table Schemas with SQL Server

You can synchronize table schemas from the Microsoft Dynamics NAV Development Environment or by using the Sync-NAVTenant cmdlet in the Microsoft Dynamics NAV 2016 Administration Shell.

You typically use the development environment to synchronize the table schema during development while you are making changes to a specific table. In the development environment, you can synchronize table schema changes for a specific table or for all tables. During development, you synchronize the table definitions with a development database that has no active users. This means that you can make destructive changes and create upgrade codeunits to migrate the business data to the new database schema.

You typically use the Sync-NAVTenant cmdlet when you are upgrading the live database from an earlier version of Microsoft Dynamics NAV. For example, the Sync-NAVTenant cmdlet can be used by system administrators who automate the process of applying application updates and upgrades in a multitenant environment. When you apply a new database schema to a business database, you must make sure that existing data is migrated to new version. For example, during development, you have added two new fields to a table, and you have created upgrade codeunits to migrate data from another field in that table to the two new fields. So when you want to apply those changes to an existing business database, you upgrade the database. For more information about synchronizing table schemas by using the Sync-NAVTenant cmdlet, see Sync-NavTenant.

Important
Depending on the size of the tables that you modify and the nature of changes, the schema synchronization process can take anywhere from several seconds to several hours (for example. this can occur when you add multiple fields or keys to a large table). Therefore, it is important that you control when schema synchronization is run.

When synchronizing large tables, you should increase the SQL Command Timeout setting for the Microsoft Dynamics NAV Server instance that connects to the database to avoid timeouts during schema synchronization. The default setting is 30 minutes. For more information, see Configuring Microsoft Dynamics NAV Server.

Synchronizing the Table Schema for Specific Tables From the Development Environment

In the development environment, you can synchronize the table schema for a specific table or for all tables. You have the option to synchronize a table schema when you perform one of the following operations on a table from the development environment:

  • Save

  • Save As

  • Compile (This also pertains when you select multiple tables for compiling from Object Designer).

  • Delete (This also pertains when you select multiple tables for deleting from Object Designer).

Important
Before you can perform table schema synchronization from the development environment, you must make sure that that you have a working connection to a Microsoft Dynamics NAV Server instance. You can see the currently connected Microsoft Dynamics NAV Server instance and change as required in the Database Information window. For more information, see Database Information or How to: Change the Microsoft Dynamics NAV Server Instance.

Schema Synchronization Options

When you perform one of the operations on a table, you can choose from the following schema synchronization options:

Option Description

Now - with validation

Before applying changes to the business data table, Microsoft Dynamics NAV Server validates the changes to the table definitions to check whether they are destructive changes. This includes changes that will delete data in the fields of the business data table which are affected by the changes.

  • If there are no destructive changes to the table, then the schema changes are applied to the business data table immediately.

  • If there are destructive changes, Microsoft Dynamics NAV Server checks that there are table synchronization instructions in an upgrade codeunit. If there are instructions, then the schema changes are applied to the business database table according to the instructions. If there are no instructions, then an error message appears. The table definition changes are not saved and the schema changes are not applied.

For more information about how Microsoft Dynamics NAV Server validates changes, see How Microsoft Dynamics NAV Server Validates Table Schema Changes.

Later

Table definition changes are saved and compiled in the application but the changes are not validated or applied to the business data table. You synchronize the table schema later by doing one of the following:

  • Save or compile the table from Object Designer in development environment and choose either the Now - with validation or Force synchronization option.

  • Use the Sync. Schema for All Tables option on the Tools menu.

  • Run the Sync-NAVTenant cmdlet from the Microsoft Dynamics NAV 2016 Administration Shell.

Force

Table definition changes are applied to the business data table schema without validation. For destructive changes, data in columns of the business data table that are affected by changes will be deleted.

This option ignores any table synchronization instructions for the table in upgrade codeunits.

Synchronizing All Table Schemas From the Development Environment

From the development environment, you can synchronize table schema changes for all tables in the database. This is useful when you upgrade from an earlier version of Microsoft Dynamics NAV or when you made changes to a table or multiple tables previously and chose to synchronize later.

To synchronize schema changes for all tables, on the Tools menu, under Sync. Schema For All Tables, you can choose one of the following options:

Option Description

Check Only

Microsoft Dynamics NAV Server validates the table definition changes but does not apply the schema changes to the business database.

  • If there are no destructive changes to any of the tables, no errors occur.

  • If there are destructive changes, Microsoft Dynamics NAV Server checks that there are table synchronization instructions in an upgrade codeunit. If there are instructions, then no errors occur. If there are no instructions, an error occurs.

For more information about how Microsoft Dynamics NAV Server validates changes, see the How Microsoft Dynamics NAV Server Validates Table Schema Changes section.

With Validation

Before applying changes to the business data table, Microsoft Dynamics NAV Server validates the table definition changes to check for destructive changes to the table.

  • If there are no destructive changes to the table, then the schema changes are applied to the business data table immediately.

  • If there are destructive changes, Microsoft Dynamics NAV Server checks that there are table synchronization instructions in an upgrade codeunit. If there are instructions, then the schema changes are applied to the business database table according to the instructions. If there are no instructions, then an error message appears. Table definition changes are not saved and the schema changes are not applied.

For more information, see How Microsoft Dynamics NAV Server Validates Table Schema Changes.

Force

Table definition changes are applied to the business data table schema without validation. For destructive changes, data in columns of the business data table that are affected by changes will be deleted.

This option ignores any table synchronization instructions for the table in upgrade codeunits. You should use this option only when you are sure that there is no risk of unwanted data loss.

Note
Microsoft Dynamics NAV Server will only synchronize schemas for new tables and tables with changed table definitions.

When you synchronize schemas for all tables, the Synchronize Schema Changes window appears. In this window, you can see the state of the database. For example, whether it is operational or whether schema synchronization is pending or produced errors. If errors occur when you use the Check Only or With Validation synchronization options, the actual error messages are not displayed in the Detailed State field on the Synchronize Schema Changes window. This is because of text display limitations of the development environment. To see the full list of the detected errors you can run the Sync-NAVTenant cmdlet from the Microsoft Dynamics NAV 2016 Administration Shell with -Mode parameter set to CheckOnly.

Synchronizing Table Schemas When Importing FOB Files

You can import a FOB file, which contains Microsoft Dynamics NAV objects, into a database by using the development environment or the Import-NAVApplicationObjects cmdlet that is available in the Microsoft Dynamics NAV 2016 Development Shell.

When you import a FOB file that contains tables, you are prompted to choose a schema synchronization option to perform on tables after the import is finished. We recommend that you back up the application objects before importing the FOB file, and then choose the Now - with validation synchronization option on the confirmation dialog box. You can back up the application objects by exporting all objects to a FOB file or making a full SQL backup of the database.

If you choose to synchronize the schema with validation, after the import is finished, the Microsoft Dynamics NAV Server compares the table definitions that were imported from the FOB file with the table definitions that are currently stored in the database.

  • If Microsoft Dynamics NAV Server detects destructive changes to tables, then it will check whether there is an upgrade codeunit in the application that handles the destructive changes.

  • If an upgrade codeunit is not found in the application, then an error occurs.

  • If there is an upgrade codeunit to handle destructive table changes, then the changes are applied.

When you import objects in FOB files by using the Import-NAVApplicationObjects cmdlet, table schema synchronization is controlled by the SynchronizeSchemaChanges parameter of this cmdlet. By default, the SynchronizeSchemaChanges parameter is set to Yes. This means that during the import process, each table will be checked for destructive changes. If destructive changes are detected, the FOB file import will be canceled, even if an upgrade codeunit for handling the changes is included the FOB file. Therefore, if you want to import a FOB file that contains tables that have destructive changes and upgrade codeunits to handle the changes, you must set SynchronizeSchemaChanges parameter to No, and then call Sync-NAVTenant cmdlet that is available in the Microsoft Dynamics NAV 2016 Administration Shell to synchronize the changes.

Handling Destructive Changes With Table Schema Synchronization

Destructive changes to a table definition are changes that can potentially affect the existing data in the business data table. The following table definition changes are considered destructive changes.

  • Deleting a table.

  • Deleting a field.

  • Changing a field's data type.

  • Changing a field's class.

  • Changing the SQL data type of a field.

  • Decreasing the length of data in a field.

  • Changing the primary key of a table, such as removing a field from the key.

  • Changing the ID of a table field.

To synchronize the business data table with destructive changes to table definition, you must do one of following:

  • Create or import an upgrade codeunit that includes synchronization instructions for the table. For more information, see Upgrade Codeunits.

  • Use the Force option to synchronize the schema. This will apply the table definition changes regardless of existing data the data. Data in fields that are affected by the table definition changes will be deleted.

Tip
When you synchronize destructive changes to a table by using the Now - with validation schema synchronization option, an error occurs and will not let you save the changes. The validation process for destructive change does not consider whether there is data in the fields that are affected by the changes. The validation process determines whether the change is destructive by analyzing actual metadata changes. This implementation helps prevent you from overlooking a destructive change and neglecting to create data upgrade codeunits to handle the changes when you work with development or test databases that do not contain data.

How Microsoft Dynamics NAV Server Validates Table Schema Changes

When you synchronize a table schema and choose a synchronization option that validates the changes, Microsoft Dynamics NAV Server verifies whether the changes can be applied to the business data table without affecting the data in changed columns that are affected by the changes.

The following describes the Microsoft Dynamics NAV Server process for validating the table schema changes:

  1. Compares the content of the Object Metadata and Object Metadata Snapshot system tables to identify differences in the database schemas.

  2. Lists tables with schema changes in the Table Synch. Setup system table.

  3. Identifies the upgrade codeunits with instructions for handling changes and adds the instructions to the Table Synch. Setup table.

  4. Applies the relevant changes according to the upgrade instructions.

During the schema synchronization, each change is applied based on the synchronization mode that was specified in the upgrade codeunits. For more information about the synchronization modes, see TableSyncSetup Modes.

Note
If the change is not a destructive change and has not been handled with an upgrade instruction in an upgrade codeunit, then the default mode is Check.

Monitoring the Business (Tenant) Database State During and After Schema Synchronization

When you synchronize a table schema, the business database passes through various operational states, depending on the outcome of the synchronization. You can use the Get-NAVTenant cmdlet from the Microsoft Dynamics NAV 2016 Administration Shell to view the current state of the database during and after synchronization. For more information, see Get-NAVTenant cmdlet.

You can also view the state of the database from the development environment in the Synchronize Schema Changes window that appears when you choose Sync. Schema For All Tables option on the Tools menu.

The following table describes the states of the database during and after table synchronization.

State Description

Mounted

Indicates that the business (tenant) database is mounted on the Microsoft Dynamics NAV Server instance but is not yet operational. This can occur when Microsoft Dynamics NAV Server is started or when the Mount-NavTenant cmdlet is run from the Microsoft Dynamics NAV 2016 Administration Shell.

You should consider the Mounted state as an intermediate state that only exists right after mount operation is executed. The purpose of this state is to indicate that the Microsoft Dynamics NAV Server knows about this database but has not yet brought the database into an operational state, which includes verifying whether table schemas are synchronized.

With the exception running the Get-NavTenant and Dismount-NavTenant cmdlet, all other operations that access the database will initiate the process of bringing the database into the operational state. This means that the first operation on the database can take some time to complete while the database is validated. The result of the validation will be that the database will change state to Operational, OperationalWithSyncPending, or OperationalWithSyncFailure.

This design enables the Microsoft Dynamics NAV Server to start with multiple tenants. However, if there are only few tenants on the Microsoft Dynamics NAV Server, then you should consider including the Get-NavTenant | Sync-NavTenant command into the script that mounts the database to make sure all the databases reach the operational state at the same time.

Operational

Indicates that the database is fully operational and the table schemas are up to date. This is the normal operating state of a database.

OperationalWithSyncPending

Indicates that the database is operational but schema synchronization is pending on one or more tables. If a table that is pending schema synchronization is accessed by Microsoft Dynamics NAV Server (for example, when user tries to access the table from the Microsoft Dynamics NAV Windows client) an error will be displayed. The error informs the user that the metadata for the table has not been synchronized.

To synchronize table schemas, you can run the Sync-NAVTenant cmdlet from the Microsoft Dynamics NAV 2016 Administration Shell or use the development environment, for example, by saving a table and choosing the Now-with validation synchronize schema option. Either of these operations will initiate the schema synchronization process. If the process is successful, the state will change to Operational. If the process is not successful, the state will change to OperationWithSyncFailure.

In the development environment, the Detailed State field on the Synchronize Schema Changes window will contain the errors that occurred during synchronization. The Sync-NAVTenant cmdlet provides you a more detailed list of any synchronization errors.

OperationalWithSyncInProgress

Indicates that table schemas in database are currently being synchronized. You can use the Get-NAVTenant from the Microsoft Dynamics NAV 2016 Administration Shell to track progress.

Users can continue to work with the application from the Microsoft Dynamics NAV clients. However, if they try to access a table whose schema has not been synchronized, an error will occur. While the synchronization process is running on a Microsoft Dynamics NAV Server instance, the following restrictions apply:

  • Other Microsoft Dynamics NAV Server instances will not be able to start the synchronization process on the same database.

  • If a user changes a table definition in the development environment, he will not be able to save the changes until the synchronization process is finished.

OperationalWithSyncFailure

Indicates that the database is operational but the last attempt to synchronize the table schemas failed.

If Microsoft Dynamics NAV Server tries to access a table that has not been synchronized, an error occurs. For example, this can occur when destructive changes have been made to a table and there is no upgrade codeunit available to handle the changes.

You can run the Get-NAVTenant cmdlet to retrieve a list of all the destructive changes that were detected during the schema synchronization process. The changes are listed in the Detailed State field.

To get the database back to Operational state, you can do one of the following:

  1. Create an upgrade codeunit that has instructions for how to handle the data in the tables where destructive changes were made, then run Sync-NAVTenant cmdlet again.

  2. Run the Sync-NavTenant cmdlet in the Force mode as follows:

    Copy Code
    Sync-NavTenant <serverinstance> -Mode Force.
    This operation will apply changes without validation and delete the data in the table columns that are affected by the changes.

  3. Revert the table to its original structure, and then run the Sync-NavTenant cmdlet.

    Copy Code
    Sync-NavTenant <serverinstance> -Mode Sync

For more information about the Get-NAVTenant cmdlet and how to use the Microsoft Dynamics NAV 2016 Administration Shell, see Get-NAVTenant and Microsoft Dynamics NAV Windows PowerShell Cmdlets.

See Also

Concepts

Upgrade Codeunits
Upgrading Data
Tables
Development
Administration
Microsoft Dynamics NAV Windows PowerShell Cmdlets

Other Resources

Sync-NAVTenant cmdlet


Upgrading Data

This topic describes how to upgrade data in the business database. You perform a data upgrade:

  • After you make changes to tables from the Microsoft Dynamics NAV Development Environment and synchronize the schemas in the database.

  • When you upgrade the database from an earlier Microsoft Dynamics NAV version to Microsoft Dynamics NAV 2016.

The data upgrade process migrates data from upgrade tables to tables in the new or modified database based on the information that is contained in the upgrade codeunits that are available for the application. For more information about upgrade codeunits, see Upgrade Codeunits.

You can run the data upgrade from the Microsoft Dynamics NAV Development Environment or the Microsoft Dynamics NAV 2016 Administration Shell.

Data Upgrade Process

The data upgrade process is controlled by the Microsoft Dynamics NAV Server instance that connects to the database. When you start a data upgrade, the Microsoft Dynamics NAV Server instances runs all upgrade codeunits that are available for the application and calls the CheckPreconditions and upgrade functions, that is UpgradePerCompany and UpgradePerDatabase function types, that are contained in the upgrade codeunits. These functions provide instructions about how to migrate data from the upgrade tables to locations in the business database.

Note
In this topic, UpgradePerCompany and UpgradePerDatabase functions are referred to as Upgrade functions.

The CheckPreconditions and Upgrade functions are called in the following order:

  1. CheckPreconditions functions are called in random order.

  2. Upgrade functions are called in random order.

By default, Upgrade functions are executed in parallel mode (at the same time) unless you choose a different mode. For more information see, Parallel and Serial Execution Modes for Upgrade Codeunit Functions.

Important
Depending on how many tables that must be modified in the business database, the data upgrade process can take several minutes to several hours to finish.

When upgrading a large database, you should increase the SQL Command Timeout setting for the Microsoft Dynamics NAV Server instance that connects to the database to avoid timeouts during schema synchronization. The default setting is 30 minutes. For more information, see Configuring Microsoft Dynamics NAV Server.

Parallel and Serial Execution Modes for Upgrade Codeunit Functions

You can run a data upgrade to execute CheckPrecondition and Upgrade functions in upgrade codeunits in two modes: Parallel and Serial.

Parallel mode runs the CheckPrecondition functions and Upgrade functions for all companies at the same time. The CheckPrecondition functions are run in parallel first, and if this operation is completed successfully, then the Upgrade functions for all companies are run in parallel. This is the default mode. Running the functions in parallel mode can significantly improve the upgrade performance, especially when you have multiple companies in the database. Each function is run using a separate session on the Microsoft Dynamics NAV Server.

Serial mode runs the CheckPrecondition functions and Upgrade functions for all companies one at a time. The CheckPrecondition functions are run first, followed by the Upgrade functions. Functions are run in the same Microsoft Dynamics NAV Server session. Running the functions in serial mode is useful, for example, when you are debugging the data upgrade code.

Error Handling During Data Upgrade

The following describes the process when an error occurs when executing functions in the upgrade codeunits:

  • When an error occurs while executing a function, the execution of the function is stopped and changes that were made by the function are rolled back.

    • If the upgrade data process is set to continue on errors, then remaining functions are executed until the process is completed.

    • If the upgrade data process is not set to continue on errors, then the process is suspended. When functions are executed in parallel mode, functions that are still in progress will be canceled and the changes that were made by the functions will also be rolled back. Changes that were made by functions that were completed are not rolled back.

You can use the Get-NavDataUpgrade to obtain information about the functions that have been successfully executed and those that failed. You can use this information to fix any errors, and then resume the data upgrade to execute the failed and canceled functions.

Running From the Development Environment

The development environment includes several options that enable you to control the data upgrade process. On the Tools menu, choose Data Upgrade, and then choose one of the options that are described in the following table:

Option Description

Start

Starts the data upgrade as described in Data Upgrade Process.

On the Start Data Upgrade window, specify the options for running the data upgrade, and then choose the OK button. For more information about the start data upgrade options, see Start Data Upgrade.

Resume

Restarts a data upgrade process that has been suspended because of an error that occurred when executing one or more functions in the upgrade codeunit.

On the Resume Data Upgrade window, specify whether to re-run all previously failed and canceled functions or a specific function only, and then choose the OK button to continue. For more information about the resume data upgrade options, see Resume Data Upgrade.

Only functions that failed because of an error or were canceled while in-progress during the last data upgrade process will be run again.

You cannot resume a data upgrade process that was stopped.

Note
The resume operation will not execute CheckPreconditions or Upgrade functions that you added to upgrade codeunits while the upgrade process was suspended.

Show Progress

Opens a window that displays information about the data upgrade process that is currently running or the last process that ran. The window provides the current state of the data upgrade and a progress bar that indicates the percentage of the process that has been completed.

The State field in the window indicates the current state of the upgrade process and has the following states:

  • NotStarted indicates that a data upgrade has not been started on the database.

  • InProgress indicates that a data upgrade is currently running in the database.

  • Suspended indicates that the data upgrade processed has been interrupted because an error occurred on a function in an upgrade codeunit.

  • Stopped indicates that the data upgrade was stopped by using the Stop action.

  • Completed indicates that the data upgrade process has been completed.

Stop

Stops the data upgrade process whose state is in progress or suspended because of an error.

Changes that were made by functions that are still in progress will be rolled back.

Running From Microsoft Dynamics NAV 2016 Administration Shell

You can run and manage a data upgrade from the Microsoft Dynamics NAV 2016 Administration Shell by using one of the following cmdlets:

  • Start-NAVDataUpgrade

  • Stop-NAVDataUpgrade

  • Resume-NAVDataUpgrade

  • Get-NAVDataUpgrade

For more information about Microsoft Dynamics NAV 2016 Administration Shell, see Microsoft Dynamics NAV Windows PowerShell Cmdlets.

See Also

Concepts

Upgrading the Data
Synchronizing Table Schemas
Upgrade Codeunits


Creating Filter Pages for Filtering Tables

In C/AL code, you can use the FILTERPAGEBUILDER data type to create a filter page that enables users to set filters on multiple tables. Filter pages contains one or more filter controls, where each filter control can be used to set filters on a specific table. In the Microsoft Dynamics NAV client, filter pages are generated at runtime and run in a modal dialog box. The following figure illustrates a filter page that filters on the Item table.

Shows a filter page for the item table

To create a filter page, you use C/AL code and the functions that are available for the FILTERPAGEBUILDER data type. The following code example shows the C/AL code that creates the filter page in the figure.

Copy Code
FilterPageBuilder.AddRecord('Item Table', Item);
FilterPagebuilder.Addfield('Item Table', Item."No.", '>100');
FilterPageBuilder.PageCaption := 'Item Filter Page';
FilterPagebuilder.RunModal;
Item.SetView( filterPagebuilder.Getview('Item Table'));

FILTERPAGEBUILER Data Type Functions

The following table describes the C/AL functions of the FILTERPAGEBUILER data type.

Function | Description
ADDTABLE Function | Adds a filter control for a table to a filter page.
ADDRECORD Function | Adds a filter control for a table to a filter page as specified by a record data type variable.
ADDRECORDREF Function | Adds filter control for a table to a filter page as specified by a recordref variable.
ADDFIELD Function | Adds a table field to the filter control for a table on filter page.
ADDFIELDNO Function | Adds a table field to the filter control for a table as specified by the field number.
GETVIEW function (FilterPageBuilder) | Gets the filter view (which defines the sort order, key, and filters) for the record in the specified filter control of a filter page.
SETVIEW Function | Sets the current filter view, which defines the sort order, key, and filters, for a record in a filter control on a filter page.
RUNMODAL Function (FilterPageBuilder) | Builds and runs the filter page.
COUNT Function (FilterPageBuilder) | Gets the number of filter controls that are specified in the FilterPageBuilder object instance.
NAME Function (FilterPageBuilder) | Gets the name of a table filter control that is included on a filter page based on an index number that is assigned to the filter control.


Codeunits

A codeunit is a container for C/AL code that you can use in many application objects. This section describes codeunits and explains how to create one. It also shows you how to use the functions in a codeunit from other application objects.

Understanding Codeunits

To | See
Learn the purpose and function of codeunits. | Understanding Codeunits
Learn how to use the C/AL Editor. | Creating and Modifying Codeunits
Learn how to access codeunits and limitations of codeunits. | Using Codeunits
Follow step-by-step procedures that show how to use codeunits. | Walkthrough: Using Codeunits

Developing Codeunits

To | See
Learn how to create a codeunit. | How to: Create a Codeunit
Learn how to modify a codeunit. | How to: Modify an Existing Codeunit and How to: Add a Function to a Codeunit
Learn how to compile and save codeunits. | How to: Compile the Code in a Codeunit and How to: Save a Codeunit


Understanding Codeunits

A codeunit is a container for C/AL code that you can use in many application objects. In simple applications, you can place the code in the object that calls the functions. For example, if you use C/AL code in pages, you can store the code in the page. However, as your application grows in both size and complexity, you will often find that you use the same functions more than once in many different objects. Instead of declaring the same functions repeatedly, you can use a codeunit to define them one time.

What You Can Define in Codeunits

In codeunits, you can define the following.

Codeunits | Description
Functions | A function is a sequence of C/AL statements that you define to create new functionality.
Local Variables | Within each function, you can define variables with scope that is limited to the function in which they are defined. These are known as local variables.
Global Variables | A global variable is a variable whose scope covers all the functions in the codeunit.
Text Constants | A text constant defines a read-only string that you use in your code. A text constant can have multiple values for different languages. You can define both global and local text constants.

Codeunit Sections

Each function that you add to a codeunit is shown in a separate section when you view the file in the C/AL Editor. Every codeunit contains two default sections called Documentation and OnRun. In the Documentation section, you can add descriptive information, such as the purpose of the codeunit or a version number. In the OnRun section, you can include code that you want to be executed when the codeunit is run.

In addition to being a container for functions that can be run individually, a codeunit can itself be run by using <Codeunitname>.Run. When you run a codeunit, the code in the OnRun section of the codeunit is executed.


Creating and Modifying Codeunits

You use Object Designer to create a new codeunit, and you use the C/AL Editor to modify an existing codeunit.

For more information about how to create a codeunit, see How to: Create a Codeunit. For more information about how to modify a codeunit, see How to: Modify an Existing Codeunit.

Working in the C/AL Editor

When you work in the C/AL Editor, you can use the C/AL Symbol Menu window, which helps you use C/AL functions that are available. From the C/AL Symbol Menu window, you can get Help about all C/AL functions. To view Help for a function, select the C/AL function name in the rightmost column, and then press F1.

You can open multiple codeunits. Each time that you create a new codeunit or open an existing one, the codeunit is displayed in a separate window. You can then use standard functions to find code or move and paste lines of code among the codeunits. In the development environment, you can use the Edit menu or the buttons on the toolbar to access the editing functions. On the Edit menu, you can collapse the triggers to hide the code or expand them to show the code.

Note
To collapse or expand a trigger, select the + or - icon next to the trigger and press the Spacebar.

You can also use the following keyboard shortcuts.

Keyboard shortcut | Description
Ctrl+Z | Cancels the last edit.
Ctrl+X | Deletes the selected text and puts it in the Clipboard.
Ctrl+C | Copies the selected text to the Clipboard.
Ctrl+V | Pastes the text from the Clipboard to the codeunit at the cursor position.
Ctrl+A | Selects all text in the current row.
Ctrl+F | Opens the Find window to search for text.
Ctrl+H | Opens the Replace window to search for text and replace it with other text.
Ctrl+M | Toggles between expanding and collapsing the triggers.
Shift+Ctrl+M | Collapses all the triggers and hides all the code.
F3 | Inserts a new line.
F4 | Deletes a line.

Defining Variables, Text Constants, and Functions

After you create a new codeunit, then you must define the global variables, text constants, and functions that you need in the codeunit. To define these elements, in the C/AL Editor, on the View menu, choose C/AL Globals. In the C/AL Globals window, you must choose whether to add a global variable, a text constant, or a function. For more information, see the following topics:

  • How to: Add a Global Variable to a Codeunit

  • How to: Add a Text Constant to a Codeunit

  • How to: Add a Function to a Codeunit

Using the C/AL Symbol Menu Window

When you write C/AL code in the C/AL Editor, you can use the C/AL Symbol Menu window to get an overview of the following:

  • All variables that are defined in the codeunit.

  • All available C/AL functions.

The C/AL Symbol Menu window is divided into the following columns:

  • The first column lists the names of the variables, if you have defined any, and the function categories.

  • The second column lists the subcategories, such as Functions, Properties, Fields, Keys, and Options.

  • The third column lists the items in the subcategory that you selected.

For example, if you select a record variable in the first column and select Keys in the second column, then the third column displays the keys for the table that the record is from.

You can see the syntax and other information, such as the Caption property, that corresponds to the field name that you have selected, in the lower-left corner of the window.

In some cases, such as when a control on a page is a subpage or when a field is a BLOB field, there are more than three columns in the C/AL Symbol Menu window.

In the C/AL Symbol Menu window, choose the OK button or the Apply button to paste the syntax description into the C/AL Editor. If you choose the OK button, then the C/AL Symbol Menu window is closed automatically. If you choose the Apply button, then the window stays open.

For more information, see C/AL Functions.

Compiling and Saving Codeunits

Before you can run the functions in a codeunit, you must save and compile the code. When you compile the code, the syntax of the statements are checked. If the compiler finds any errors in the code it displays an error message. For more information about how to compile the code in a codeunit, see How to: Compile the Code in a Codeunit. For more information about how to save a codeunit, see How to: Save a Codeunit.

See Also

Tasks

Walkthrough: Using Codeunits

Concepts

Understanding Codeunits
Using Codeunits


How to: Create a Codeunit

To create a new codeunit by using Object Designer, use the following procedure.

To create a codeunit

  1. On the Tools menu, choose Object Designer.

  2. In Object Designer, choose Codeunit.

  3. Choose the New button to create a new codeunit.

  4. In the C/AL Editor, add functions.

See Also

Concepts

Codeunits


How to: Modify an Existing Codeunit

To modify an existing codeunit, use the following procedure.

To modify an existing codeunit

  1. In the Tools menu, choose Object Designer.

  2. In Object Designer, choose Codeunit.

  3. Select the codeunit that you want to modify, and then choose Design.

  4. In the C/AL Editor, modify the codeunit by changing the existing functions or by adding new functions.

See Also

Concepts

Codeunits


How to: Add a Global Variable to a Codeunit

To add a global variable to a codeunit, use the following procedure.

To add a global variable

  1. Open the C/AL Editor, choose View, and then choose C/AL Globals.

    Note
    For more information about how to open the C/AL Editor, see How to: Modify an Existing Codeunit.

  2. In the C/AL Globals window, choose the Variables tab.

  3. Enter a name and select a data type.

    If the data type that you select corresponds to an application object, you must also select a subtype, that is, the name of a specific object in the database.

    If you select OCX, Automation, or DotNet, then you must add a subtype. For more information, see the following topics:

    • Extending Microsoft Dynamics NAV Using COM

    • Extending Microsoft Dynamics NAV Using Microsoft .NET Framework Interoperability

    If you select text or code, you must define a length for the variable. The default length is 10 characters for code and 30 characters for text.

See Also

Concepts

Codeunits


How to: Add a Text Constant to a Codeunit

To add a text constant to a codeunit, use the following procedure.

To add a text constant

  1. Select the C/AL Editor, choose View, and then choose C/AL Globals.

    Note
    For more information about how to open the C/AL Editor, see How to: Modify an Existing Codeunit.

  2. In the C/AL Globals window, choose the Text Constants tab.

  3. In the first available Name field, enter the name of the new text constant.

    Note
    There is no naming convention for the text constants. We recommend that you use the unique ID for the name, as described in steps 4 and 5.

  4. Select the line in which you entered the name of the new text constant, and on the View menu, choose Properties. A unique ID number has been automatically assigned to the text constant in the ID field.

  5. Copy the ID number from the Properties window to the Name field in the C/AL Globals window. For example, if the ID number is 1001, specify Text1001, in the Name field.

  6. In the ConstValue field, choose the AssistEdit button.

  7. In the Multilanguage Editor window, enter ENU for the language and then enter the text. For more information, see How to: Enter Text in the Multilanguage Editor

    Note
    If you set the application language to English (United States) before opening Object Designer, you can enter the message string directly into the ConstValue field in the C/AL Globals window. Open the Multilanguage Editor to be sure that the text is saved as English (United States).

  8. In the C/AL Editor, copy the name of the text constant to the place where you want the text value to appear.

Example

In this example, Text1001 is a number that is available in the text constants number series for that object.

Copy Code
IF FileName = ' ' THEN
  ERROR(Text1001);

In the C/AL Editor, when you move the cursor into the new text constant, you see its contents in the status bar.

See Also

Concepts

Codeunits


How to: Add a Function to a Codeunit

To add a function to a codeunit, use the following procedure.

To add a function

  1. Select the C/AL Editor, choose View, and then choose C/AL Globals.

    Note
    For more information about how to open the C/AL Editor, see How to: Modify an Existing Codeunit.

  2. In the C/AL Globals window, choose the Functions tab.

  3. Enter a name for each function that you want to add.

  4. Choose Locals to define the parameters, return value, local variables, and text constants in the C/AL Locals window.

  5. In the C/AL Locals window, choose the Parameters tab and specify the calling method, name, and data type of each parameter. You can also specify a subtype and a length, but this is optional.

    To specify the calling method of a parameter, either select or clear the Var check box. If you select the Var check box, then the parameter is passed by reference rather than by value. The value of a variable can only be changed by a function when it is passed to the function by reference. When the parameter is not specified as Var, only a copy of the variable is passed to the function. If the function changes that value, the change only affects the copy and not the variable itself.

    If the type that you select corresponds to an application object, then you must also add a subtype, that is, the name of a specific object in the database. If you select Text or Code data types, then you must define a length. The default length is 10 characters for Code and 30 characters for Text.

  6. In the C/AL Locals window, choose the Return Value tab and specify the return value for your new function. Enter a name for the return value and select a data type from the drop-down list. If the data type is Text or Code, then you can also select a length.

  7. In the C/AL Locals window, choose the Variables tab and define local variables.

    For each local variable, you must enter a name and select a data type. If the data type that you select corresponds to an application object, then you must also add a subtype, that is, the name of a specific object in the database. If you select Text or Code data types, then you must define a length for the variable. The default length is 10 characters for Code and 30 characters for Text.

  8. In the C/AL Locals window, choose the Text Constants tab and define text constants for the function.

See Also

Concepts

Codeunits


How to: Compile the Code in a Codeunit

To compile the code in a codeunit, use the following procedure.

To compile the code in a codeunit

  1. On the Tools menu, choose Compile.

  2. If any errors are found in your code, you receive an error message. Correct the errors and compile the code again.

See Also

Concepts

Codeunits


How to: Save a Codeunit

To save a codeunit, use the following procedure.

To save a codeunit

  1. Select the C/AL Editor, on the File menu, choose Save As.

  2. In the Save As window, in the ID field, enter an ID number that is used as a unique identification. In the Name field, enter a name that is used as a label.

  3. In the Save As window, choose OK.

  4. In the dialog box, select whether you want to compile the code before it is saved. If you save the codeunit without compiling it, you will not be able to run it or call any of the functions it contains.

    Note
    If you are working on a large and complicated codeunit, you may want to save your work at regular intervals, even though it is not yet finished and cannot yet be compiled. In this case, you must clear the Compiled check box before you save the codeunit.

See Also

Concepts

Codeunits


Using Codeunits

By using codeunits, you eliminate the need to duplicate code and you make the code easier to maintain. For example, if you use the same code repeatedly in your objects, then you should create a global function for the code in a codeunit. After you create a codeunit and a global function in that codeunit, you can access the function from another codeunit by declaring a variable of type Codeunit and specifying the name of the codeunit as the subtype of the variable. You can then access the function by using <CodeunitVariableName>.<FunctionName>.

Note
Unlike a local function, a global function can be accessed from outside the codeunit. To make a global function, you set Local Property of the function to No.

Example

For this example, assume that you have created a codeunit that contains two statistical global functions named F and G. The following example shows you how to access these functions from a page.

Codeunit Named Stat

Copy Code
F(x:integer) a : Integer
Begin
  // Do some processing.
  // a:= ..
End
G(x:integer) a : Integer
Begin
  // Do some processing.
  // a:= ..
End

Page Objects

In the page object, create the following variables.

Variable name | DataType | Subtype
StatVariable | Codeunit | Stat
Result | Integer |
Copy Code
…
Result := StatVariable.F(3425)+StatVariable.G(346);
…

Accessing Codeunits

Using the method in the previous example, from any application object, you can access functions in other application objects by writing the name of the application object that contains the function followed by the name of the function.

You can access codeunits through codeunit variables either by explicitly declaring a variable with the data type codeunit or by setting the RunObject property on pages to a codeunit. A codeunit variable does not contain a codeunit, but only a reference to a codeunit. More than one codeunit variable can refer to the same codeunit, as shown in the following illustration.

Codeunit Variables Codeunit variables

Codeunits contain internal variables that are defined as global variables. These variables cannot be accessed directly from code outside the codeunit, but they can be accessed through user-defined functions on the codeunit. When a codeunit variable is used for the first time, a new instance of the codeunit is created, that is, a new set of internal variables is initialized so that different codeunit variables use different sets of internal variables.

CLEAR on Codeunits

When you use the CLEAR function on a codeunit variable that has a reference to a codeunit instance with two or more references, CLEAR only deletes the reference to the codeunit and not the actual instance of the codeunit. The codeunit stays intact and can still be used by other codeunit variables that may have been assigned a reference to this codeunit.

To delete an instance of a codeunit, you must clear all the references to the codeunit with the CLEAR function. To clear the internal variables in a codeunit, you must call the CLEARALL function from a user-defined function in the codeunit. A local codeunit variable is automatically cleared when it goes out of scope and is no longer used by the codeunit.

For more information, see CLEAR Function and CLEARALL Function.

Single Instance Codeunit

In some cases, only one instance of a codeunit needs to exist. This means that all the codeunit variables of a particular codeunit use the same set of variables. When you set the SingleInstance property of the codeunit to Yes, all the codeunit variables of that codeunit use the same instance. This lets you create global variables.

Note
We recommended that you avoid using global variables for most types of code. However, in certain situations, you may have to use them, for example, to make sure that you are only using one instance of an external variable.

A single instance codeunit is instantiated when you use it for the first time. Typically, codeunit instances (codeunits that do not have the SingleInstance property set) are deleted when the last codeunit variable that uses that codeunit instance goes out of scope. However, single instance codeunits remain instantiated until you close the company.

For an example of a single instance codeunit, see Walkthrough: Using Codeunits.

Limitations on Codeunits

Global variables and temporary tables in a codeunit cannot be accessed directly from other application objects. The only way to access these values is through the functions that you have created in the codeunit.

Every C/AL function can be used in a codeunit. However, you cannot create a function that has the same name as a pre-defined function. Also, two or more user-defined functions cannot have the same name, unless they are part of different application objects.

See Also

Concepts

Understanding Codeunits
Creating and Modifying Codeunits


Walkthrough: Using Codeunits

You can treat codeunits as objects. One codeunit variable can be assigned to another codeunit variable, which creates a new reference to the same codeunit instance. The codeunit variables then use the same set of internal variables.

About This Walkthrough

This walkthough illustrates the following tasks:

  • Creating one codeunit that has two functions: a Set function and a Get function. The Set function sets an internal variable to the value of the parameter given. The Get function returns the value of the internal variable.

  • Creating one codeunit that has two codeunit variables that each call a function in the first codeunit and then assigns the codeunit variables to each other so that they use the same instance of the first codeunit.

  • Modifying one of these codeunits to make it a single instance codeunit.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 installed with a developer license.

  • The CRONUS International Ltd. demo data company.

Story

Viktor is a Microsoft Certified Partner working for CRONUS International Ltd.. To learn about codeunits in Microsoft Dynamics NAV, he plans to create a codeunit that includes Set and Get functions, create a codeunit that calls two instances of the Set_Get codeunit, and finally convert the codeunit to a single instance codeunit.

Creating the First Codeunit

First, you must create a codeunit that includes the Set and Get functions. You must also write the code for these two functions.

To create the first codeunit

  1. Open Microsoft Dynamics NAV Development Environment.

  2. In the development environment, on the Tools menu, choose Object Designer.

  3. In Object Designer, choose Codeunit and then choose New.

  4. On the View menu, choose C/AL Globals.

  5. On the Variables tab, in the Name field, enter InternalInt to create a new variable. In the DataType field, select Integer from the drop-down list.

  6. In the C/AL GLobals window, choose the Functions tab.

  7. On the Functions tab, in the Name field, add two functions called Set and Get.

  8. Select the Set function, in the View menu, choose Properties, and then set the Local property to No.

    Setting this property makes the function accessible from the other codeunit that you will create. For more information about this property, see Local Property.

  9. Select the Set function and then choose Locals.

  10. In the Set -C/AL Locals window, on the Parameters tab, in the Name field, enter input. In the DataType field, select Integer from the drop-down list.

  11. Close the Set -C/AL Locals window.

  12. In the C/AL GLobals window, select the Get function, and then choose Locals.

  13. In the Get - C/AL Locals window, choose the Return Value tab.

  14. In the Name field, enter output. In the Return Type field, select Integer from the drop-down list.

  15. Close the Get -C/AL Locals window.

  16. In the C/AL Editor for the codeunit, in the Set function section, enter the following code.

    Copy Code
    InternalInt := input + 1;
Get;

    The code in the Set function increases the value of the input by one and sets this as the value of the internal variable. It then calls the Get function.

  17. In the C/AL Editor, in the Get function section, enter the following code.

    Copy Code
    output := InternalInt;

    The code in the Get function specifies that the new value of the internal variable is the output value generated by this codeunit.

  18. Close the C/AL Editor. Choose Yes to save your changes to the codeunit.

  19. In the Save As window, in the ID field, enter 70000.

  20. In the Name field, enter Set_Get, select the Compile check box, and then choose the OK button.

Creating the Second Codeunit

The next step is to create the codeunit that calls two instances of the Set_Get codeunit and supplies the input values that these instances should use. This codeunit contains two variables, which are assigned to each other so that they both use the same instance of codeunit 70000.

To create the second codeunit

  1. In Object Designer, choose Codeunit, and then choose New.

  2. On the View menu, choose C/AL Globals.

  3. On the Variables tab, in the Name field, enter CUInstance1 to create a new variable.

  4. In the DataType field, select Codeunit from the drop-down list. In the Subtype field, select codeunit 70000, Set_Get.

  5. In the C/AL GLobals window, on the Variables tab, in the Name field, enter CUInstance2 to create a second variable. In the DataType field, select Codeunit from the drop-down list. In the Subtype field, select codeunit 70000, Set_Get.

  6. Close the C/AL GLobals window.

  7. In the C/AL Editor, add the following code to the OnRun trigger.

    Copy Code
    CUInstance1.Set(1);
CUInstance2.Set(2);
MESSAGE('When running two instances, the value of CUInstance1 is %1 and the value of CUInstance2 is %2.', CUInstance1.Get, CUInstance2.Get);
CUInstance2 := CUInstance1;
MESSAGE('After assigning CUInstance2 to CUInstance1, the value of CUInstance1 is %1 and the value of CUInstance2 is also %2.', CUInstance1.Get, CUInstance2.Get);

    The first two statements in this codeunit call two instances of the Set_Get codeunit and supply the input values that these instances should use. Next, the code prints a message with the return values of the two instances of the codeunit.

    CUInstance1 returns 2.

    CUInstance2 returns 3.

    The next statement assigns the two variables to each other so that they both use the same instance of codeunit 70000 and therefore generate the same return value.

  8. Close the C/AL Editor and choose Yes to save your changes to the codeunit.

  9. In the Save As window, in the ID field, enter 70001. In the Name field, enter Assignment.

  10. Select the Compile check box, and then choose OK.

Testing the Codeunit

You will now test the codeunit that calls two instances of the Set_Get codeunit.

To test the codeunit

  1. In Object Designer, select codeunit 70001, and then choose Run. The following message is displayed: “When running two instances, the value of CUInstance1 is 2 and the value of CUInstance2 is 3.”

  2. On the message box choose OK. A second message box is displayed with the following message: "After assigning CUInstance2 to CUInstance1, the value of CUInstance1 is 2 and the value of CUInstance2 is also 2."

Using a Single Instance Codeunit

In some cases, only one instance of a codeunit needs to exist. This means that all the codeunit variables of a particular codeunit use the same set of variables. You can make a codeunit a single instance codeunit by setting the SingleInstance property to Yes.

To modify a codeunit to a single instance codeunit

  1. In Object Designer, choose Codeunit, select codeunit 70000, and then choose Design.

  2. On the View menu, choose Properties.

  3. In the Set_Get - Properties window, in the SingleInstance field, select Yes from the drop-down list.

  4. Close the Set_Get - Properties window.

  5. On the File menu, choose Save As.

  6. In the Save As window, in the ID field, enter 70002.

  7. In the Name field, enter SingleInst and select the Compile check box, and then choose OK.

  8. In Object Designer, choose Codeunit, select codeunit 70000, and then choose Design.

  9. On the View menu, select C/AL Globals.

  10. On the Variables tab, in the CUInstance1 row, in the Subtype field, select codeunit 70002, SingleInst from the code list and then choose the OK button.

  11. On the Variables tab, in the CUInstance2 row, in the Subtype field, select codeunit 70002, SingleInst from the code list. Choose the OK button.

  12. Close the C/AL Globals window.

  13. In the C/AL Editor, replace the code in the OnRun trigger with the following code:

    Copy Code
    CUInstance1.Set(7);
// A codeunit instance is created if one did not exist.
CUInstance2.Get();
// Returns 8, that is 7 + the 1 added by the Set function in
// codeunit 70002. CUInstance2 uses the same instance as CUInstance1,
// they use the same internal variables.
MESSAGE('The value of CUInstance2 is %1.', CUInstance2.Get);

    CUInstance2.Get returns 8, which is the input value 7 + the 1 added by the Set function in codeunit 70002. CUInstance2 uses the same instance as CUInstance1, therefore, they use the same internal variables.

  14. Close the C/AL Editor.

  15. In the Save Changes window, select the Compiled check box, and then choose the Yes button.

Testing the Single Instance Codeunit

The single instance codeunit variables use the same set of variables.

To test the single instance code unit

  1. In Object Designer, select codeunit 70001, and choose Run. The following message is displayed, "The value of CUInstance2 is 8."

    The CUInstance2 instance of codeunit 70002 is able to access the value of the InternalInt variable that was set by the CUInstance1 instance of codeunit 70002. This is because codeunit 70002 is specified as a single instance codeunit.

    Note
    It is possible to use a single instance codeunit across objects, not just within the same object.

  2. In Object Designer, select codeunit 70002, and then choose the Design button.

  3. On the View menu, choose Properties.

  4. In the SingleInst - Properties window, in the SingleInstance field, select No from the drop-down list.

  5. Close the C/AL Editor.

  6. In the Save Changes window, select the Compiled check box, and choose Yes.

  7. In Object Designer, select codeunit 70001, and then choose Run. The following message is displayed, "The value of CUInstance2 is 0."

    Since codeunit 70002 is no longer a single instance codeunit, the CUInstance2 instance of codeunit 70002 is not able to access the value of the InternalInt variable that was set by the CUInstance1 instance of codeunit 70002.

See Also

Concepts

Using Codeunits


Upgrade Codeunits

You use upgrade codeunits when you make changes to a table definition, either from the Microsoft Dynamics NAV Development Environment or during an upgrade. Upgrade codeunits migrate existing business data from the old table structure into the new table structure. An upgrade codeunit serves the following purposes:

  • Provides instructions for how to handle data changes to a table during schema synchronization. For more information, see Synchronizing Table Schemas.

  • Provides the logic for migrating existing data in the business data table from the old format to the new format after schema synchronization.

  • Provides instructions for updating custom report layouts to dataset changes. For more information, see Updating Custom Report Layouts by Using Upgrade Codeunits.

A typical example of when to use an upgrade codeunit is when you remove a field from a table definition and you do not want to lose the existing data in the business data table. Instead, you want to use it somewhere else in the new application.

You implement upgrade codeunits when you make destructive changes to tables in Microsoft Dynamics NAV Development Environment. For more information about destructive changes, see Handling Destructive Changes With Table Schema Synchronization. After you have created an upgrade codeunit to handle table changes, you can use it when you upgrade data from an earlier version of Microsoft Dynamics NAV to the current version. A single upgrade codeunit will typically contain table schema synchronization instructions and data migration logic for multiple tables that have changed from one version of Microsoft Dynamics NAV to another.

Note
For an example that explains how to create and implement upgrade codeunits, see the Microsoft Dynamics NAV Upgrade Demo Script document at http://go.microsoft.com/fwlink/?LinkID=509977. This document provides step-by-step instructions that support the concepts discussed in this topic.

Upgrade Codeunits Overview

An upgrade codeunit consists of three sections that are defined by specific function types:

  1. Instructions for synchronizing schema changes for tables. These instructions are included in a TableSyncSetup function.

  2. Logic for checking conditions that must be met in order for the data upgrade process is started. This logic is included in a CheckPrecondition function.

  3. Logic for migrating the data from the old table structure into the new table structure and any additional data upgrade logic as required. This logic is included in an upgrade functions, which are functions of the type UpgradePerCompany and UpgradePerDatabase.

To create an upgrade codeunit, you set the SubType Property (Codeunit) of a codeunit to Upgrade. You can create multiple upgrade codeunits.

Upgrade Codeunit Design and Flow

Upgrade codeunits are run by Microsoft Dynamics NAV Server when you synchronize table schemas and when you start the data upgrade process. The following describes the upgrade codeunit process for these operations.

Table Schema Synchronization

When Microsoft Dynamics NAV Server detects an update to a table definition (metadata) that changes the table schema in the database in SQL Server, it will search the TableSyncSetup functions in the upgrade codeunits to collect the schema synchronization instructions for changed tables.

  • If there are instructions for the table, then Microsoft Dynamics NAV Server handles the data according to the instructions. Depending on the synchronization mode, Microsoft Dynamics NAV Server can:

    • Move or copy the data from the old tables into upgrade tables.

    • Delete data in the table fields that are affected by the changes and apply schema changes forcefully.

    • Check whether there is data in the affected fields and then apply schema changes only if they do not contain data.

    For more information about the synchronization modes, see TableSyncSetup Modes.

  • If there are no instructions for the table in the TableSyncSetup functions, then Microsoft Dynamics NAV Server checks whether the changes are destructive.

    • If the changes are destructive, the schema synchronization is cancelled.

    • If the changes are not destructive, they will be applied to the table.

Data Upgrade

After schema synchronization is completed, you must run the data upgrade process to remap any data that was saved in upgrade tables to the new application. If no data was saved during table schema synchronization, then running the data upgrade is not required.

You can start the data upgrade from the development environment or by using the data upgrade cmdlets from the Microsoft Dynamics NAV 2016 Administration Shell. Data upgrade process consists of two phases: running the CheckPrecondition functions and running the upgrade functions (UpgradePerCompany and UpgradePerDatabase type functions) that migrate data from the upgrade tables into the new locations in the application and perform other data upgrade manipulations that are required by the new version of the application.

  1. Running the CheckPrecondition functions.

    When you start the data upgrade, Microsoft Dynamics NAV Server runs the CheckPrecondition functions in upgrade codeunits for all companies in the database. By default, the functions are run in parallel mode, which means that they are run at the same time. If none of the CheckPrecondition functions return errors, then Microsoft Dynamics NAV Server proceeds to run the Upgrade functions in the upgrade codeunit.

  2. Running Upgrade functions.

    After the CheckPrecondition functions are run, the upgrade functions are run as follows:

    • UpgradePerCompany functions are run for all companies in the database, where each function is executed within its own system session on Microsoft Dynamics NAV Server that connects to the company.

    • UpgradePerDatabase functions are executed once, in a single system session on Microsoft Dynamics NAV Server that does not open any company.

      For more information about these type function types, see Upgrade Function Types.

    By default, like the CheckPrecondition functions, the UpgradePerCompany and UpgradePerDatabase functions are run in parallel mode. Because these functions run in parallel, you should design them so that they are independent of each other and do not write to the same table. Running data upgrade functions in parallel can significantly improve the upgrade performance, especially when you have multiple companies in your database. If the functions must be run in a specific order or they write to the same tables, you can change the functions to Normal function types within the upgrade codeunit. Then, create a single UpgradePerCompany or UpgradePerDatabase function that calls the Normal functions in the desired order. With this implementation, you can achieve the same performance level as running multiple upgrade functions in parallel.

    You can choose to run the data upgrade in serial mode, where all functions will be executed one after another. This can be useful, for example, when you are debugging the data upgrade code. For more information about parallel and serial function execution, see Parallel and Serial Execution Modes for Upgrade Codeunit Functions.

Note
You cannot run upgrade codeunits directly. Upgrade codeunits can only be invoked by Microsoft Dynamics NAV Server during a data upgrade.

You can only run the data upgrade process on a database that is in operational state.

For more information about how to run the data upgrade process, see Upgrading Data.

TableSyncSetup Functions

The TableSyncSetup function type provides instructions to Microsoft Dynamics NAV Server about how to process a table for which schema changes have been detected. Microsoft Dynamics NAV Server uses the virtual table 2000000135 Table Synch. Setup to collect the instructions for each table it detects as being changed. Whenever Microsoft Dynamics NAV Server detects an update in the table definition (metadata), it will populate that virtual table with the IDs of the changed tables.

To set up a TableSyncSetup function type, you add a C/AL function and set the FunctionType property of a function to TableSyncSetup. A TableSyncSetup function must have the following signature:

<function name>(VAR <record name> : Record "Table Sync. Setup")

For each table that has been changed, you provide synchronization instructions as C/AL code in the TableSyncSetup function. The instructions specify a mode for handling the data in the changed table. For more information about the modes, see TableSyncSetup Modes. The CRONUS International Ltd. demonstration database (Demo Database NAV (9-0) demonstration database) includes codeunit 9900 Data Upgrade Mgt. that you can use to populate table 2000000135 Table Synch. Setup with the modes for each changed table. In this codeunit, you can add instructions in SetTableSyncSetup function as shown in the following example:

Copy Code
DataUpgradeMgt.SetTableSyncSetup(DATABASE::"Change Log Entry",50000,TableSynchSetup.Mode::Copy);

If fields are removed from the table definition, the data is copied to the specified upgrade table, and then the changes are applied to the table in SQL Server.

Important
Do not add any code to this function other than table synchronization instructions. The TableSyncSetup type function is called automatically by Microsoft Dynamics NAV Server during the schema synchronization process and it is only meant for populating the Table Synch. Setup table with the synchronization instructions.

The TableSyncSetup function is called under the following circumstances:

  1. From the development environment, when you save, compile, or delete a table and set the Synchronize Schema option to Now - with validation.

  2. From the development environment, when you synchronize schemas for all tables and choose the Check Only or With Validation options.

  3. When you run the Sync-NAVTenant cmdlet and set to Mode parameter to CheckOnly or Sync.

TableSyncSetup Modes

There are four modes that specify how to synchronize the changes and handle existing data in the SQL table.

Mode Description

Check

Before applying the schema changes to the business data table, the Microsoft Dynamics NAV Server checks whether there is data in the field of the business data table that is affected by the change. If there is data in the field, then an error occurs, and the schema changes are not applied to the business data table. If there no data in the field, then the changes are applied to the business data table.

This is the default mode.

Move

This mode uses an upgrade table to store existing data from the business data table. You must create the upgrade table manually in advance before introducing the change. To create the upgrade table, you save the table you are about to change as another table with an ID in the upgrade toolkit range. Then, you remove the C/AL code from the triggers, and clean up the properties referencing other tables without the field specification, because all the data will be moved.

Note
The upgrade table must be identical to the existing business data table, including the primary key and the fields.

When the schema is synchronized, if there is data in the field of business data table that is affected by the table definition change, then the data is deleted from the business data table and moved to the upgrade table. Then, the schema changes are applied to the business data table. When the synchronization is completed, the business data table will be empty but its schema will match the table definition. If there is no data in the field that is affected by the table definition change, then the changes are simply applied to the business data table.

If required, you can then write code to copy necessary data from the upgrade table into the new table.

Copy

This mode also uses an upgrade table to store existing data from the business data table. You must create the upgrade table manually in advance before introducing the change.

Note
The upgrade table can only contain the primary key and the fields of the existing business data table that are affected by the data schema change for which you want to preserve the data.

When the schema is synchronized, if there is data in field of business data table that is affected by the table definition change, then data in the business data table is replicated in the upgrade table. Then, the schema changes are applied to the business data table. If no error occurs, then the changes are applied to the SQL table.

Force

The Microsoft Dynamics NAV Server will force the changes on the table and delete any data in fields that are affected by the change. This option is intended to be used for the tables and fields that you want to discontinue. If you want to save the data from this table, you should use the Copy or Move mode.

CheckPreconditions Function Type

CheckPreconditions functions resemble upgrade functions that were used in earlier versions of Microsoft Dynamics NAV. In CheckPreconditions functions, you write C/AL code to verify whether certain upgrade conditions have been fulfilled before the Upgrade type functions are run.

Before Microsoft Dynamics NAV Server calls the Upgrade functions, it executes the CheckPrecondition functions for all companies in the database.

To set up a CheckPrecondition function in the upgrade codeunit, you add a C/AL function and set the FunctionType property of the function to CheckPrecondition.

Upgrade Function Types

There are two types of upgrade functions: UpgradePerCompany and UpgradePerDatabase. These functions are similar to upgrade functions that were used in earlier versions of Microsoft Dynamics NAV. These functions enable you to write C/AL code to migrate data from the upgrade tables into new tables. Additionally, you can add code to perform other operations that are required to align the existing data in tables to the requirements of the new application. The following describes and usage of the upgrade function types.

Function type | Description
UpgradePerCompany | When you perform a data upgrade, these functions are run for all companies in the database, where each function is executed within its own system session on Microsoft Dynamics NAV Server that connects to the specific company. Depending on the number of companies in the database, an UpgradePerCompany function can be executed multiple times during an upgrade process. If the upgrade function execution mode is parallel, this can cause locking errors when the data in the table that you are updating is not company-specific, as specified by the table's DataPerCompany Property. Therefore, you typically use this type of function when the data in the table that you upgrading is company-specific, as specified by the table's DataPerCompany Property.
UpgradePerDatabase | These functions are executed once during an upgrade process, in a single system session on Microsoft Dynamics NAV Server that does not open any company. You typically use an UpgradePerDatabase function when the data in the table that you are upgrading is not company-specific. Using an UpgradePerDatabase function can prevent table locking issues when upgrade functions are run in parallel mode. This is the case, for example, with when upgrading custom report layouts in table 9560 Custom Report Layout. For more information, see Updating Custom Report Layouts by Using Upgrade Codeunits.

To set up an upgrade function in the upgrade codeunit, you add a C/AL function and set the FunctionType property of the function to UpgradePerCompany or UpgradePerDatabase.

Note
You can call Normal type functions from the upgrade functions. However, do not call upgrade functions from other upgrade functions. This is because Microsoft Dynamics NAV Server will execute all the upgrade functions in the upgrade codeunit, which can result in some functions being called more than one time.

See Also

Reference

FunctionType Property (Upgrade Codeunits)
SubType Property (Codeunit)

Concepts

Synchronizing Table Schemas
Upgrading Data


Pages

The following sections provide an overview of how to locate Microsoft Dynamics NAV documentation about developing pages.

In Microsoft Dynamics NAV, pages provide the main way to interact with the RoleTailored client user interface. Pages are XML-based and can be displayed on multiple display targets. They are also role based to the needs of individual users.

Page Development Documentation

This documentation is intended for Microsoft Dynamics NAV developers. It is intended that this topic will help you to quickly find the information that you need.

To | See
Get a general introduction to the page object | Pages Overview
Find out what page types are available and to understand how to choose the right one | Touring the RoleTailored Client Pages
Learn about new and changed properties that are available in Page Designer | Page Properties

Creating Pages

To | See
Learn how to create a card page | Walkthrough: Creating a Customer Card Page in Page Designer
Learn how to create a list page | Walkthrough: Creating a Customer List in Page Designer
Learn how to create a Role Center | Walkthrough: Creating a Role Center
Learn how to create a document page | Walkthrough: Creating a Document Page
Learn how to create a worksheet page | Walkthrough: Creating a Worksheet Page
Learn how to create a wizard using the navigate page type | Walkthrough: Creating a Wizard Page

Modifying Pages

To | See
Add actions to a customer list page | Walkthrough: Adding Actions to a Customer List Page
Add a FactBox to a customer list page | Walkthrough: Adding a FactBox to the Customer List Page

Adding Actions to Pages

To | See
Find the appropriate actions topic | Adding Actions to Pages
Understand how actions are intended to be used in the RoleTailored client | Actions Overview
Learn how to add actions to a page | How to: Add Actions to a Page
Learn how to promote actions to the ribbon | How to: Promote Actions to the Ribbon on Pages
Learn how to create action submenus | How to: Add Action Submenus to Pages

Running Pages

To | See
Preview a page in the RoleTailored client | How to: Run a Page

See Also

Tasks

Page Designer Troubleshooting

Concepts

Development


Pages Overview

In Microsoft Dynamics NAV, pages are the main way to display and organize data. Pages display in the Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client, which offer users a visual experience closely aligned to Microsoft Office and Windows. Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client are RoleTailored clients where every user has a Role Center page, tailored to their individual needs and tasks they perform. Other types of pages, such as List pages might display lists of customers or sales orders, while others such as Document pages, focus on user tasks. Each page has its own set of controls that should only be used with that page type. For example, Cues are only used on Role Center pages, FastTabs are used on Card and Document pages, and Fixed Layout controls are used on Worksheet pages.

The Page Object

In Microsoft Dynamics NAV, a page is basically an XML object composed of controls, properties, actions, triggers, and code. You create page objects in Page Designer and save them in Object Designer in the same way as you save other Microsoft Dynamics NAV objects.

In Page Designer, you can start by creating a blank page or choose from over 10 page types. Pages can be linked to a source table, unless you want to create a Role Center or a blank page not based on a page type data from a table.

In the Page Designer window, you group controls in a hierarchy that reflects the XML structure of the page. To help you to create the correct XML layout, page designer provides you with several new properties called Types and SubTypes. These properties enable you to create controls, specify their position on the page, and how they are grouped. You set types and subtypes using the drop-down menus in Page Designer.

The following table shows Page Designer Types and SubTypes.

Type | SubType
Container | ContentArea FactBoxArea RoleCenterArea
Group | Group Repeater CueGroup FixedLayout
Field | No SubType available for this Type
Part | No SubType available for this Type

When you add controls, each row is automatically indented, although every time you add a row you can adjust indentation manually with right and left indentation controls. If you indent an element in your page incorrectly, you will get an error message when you try to save and compile the page.

Use the Properties window to set your properties on a page. Properties work in the same way for pages as they do for other Microsoft Dynamics NAV objects, although there are several new and changed properties in pages. For more information, see Page Properties.

Use C/AL Globals in Object Designer to define C/AL triggers and functions on a page.

Types of Pages

The following page types are available:

  • Card

  • List

  • Role Center

  • Card Part

  • List Part

  • Document

  • Worksheet

  • Confirmation Dialog

  • List Plus

  • Navigate Page (Wizard)

  • Standard Dialog

For more information about page types, see Touring the RoleTailored Client Pages.

Designing Pages

In Microsoft Dynamics NAV, when you design and create pages you use the Page Designer, which is part of the Object Designer in.

When you design new pages you should start by looking at the wide variety of roles, tasks, and activities in your organization. These tasks and activities should be reflected in the pages that you create, and the navigation that you add to a page. There are several different page types which you can use to help you in this process. Each page type behaves like a container or template on which you can add controls and navigation elements called actions.

Window size and the positioning are controlled automatically, depending on the display device used. The controls that you use on a page are determined by the page type that you select.

Pages are metadata driven making them very flexible. They can be delivered on a wider variety of display targets which makes them more scalable. Pages have been designed to optimize performance and new enhanced controls mean that there are fewer triggers on pages than there were on forms.

You can change the behavior of pages by making changes to the properties sheet, just as you did with forms. For example you save and compile pages just like forms. You can access Properties, C/AL code, the C/AL Symbol Menu, C/AL Globals, and the Field Menu by using the same shortcuts or by using the View menu, as you did in forms.

In Object Designer, all existing page objects, and any new ones that you create are listed under the Pages button. To create a new page, you must first open the New Page dialog box and then select a page type. We recommend that you always select a page type instead of creating a blank page when you design a page.

Page Controls

You can add the following page controls to a page depending on the page type you have chosen:

  • FactBox

  • FastTab

  • Cue

  • HomePart

  • ChartPart

  • PagePart

  • SystemPart

  • Ribbon

  • Filter Pane

For more information about controls, see Touring the RoleTailored Client Pages.

Adding Navigation to Pages

All pages contain menu items and navigation controls called Actions.

In Microsoft Dynamics NAV there are three categories of Actions:

  • Action Items

  • Related Information

  • Reports

Role Center pages have their own navigation pane and the following actions:

  • Activity Buttons

  • Home Items

You can access Action Designer from Page Designer. When you want to add actions to a page, open Page Designer, choose the last available row at the bottom of the page, choose View, and then choose Actions to open Action Designer. You use the Action Designer in the same way as you use Page Designer. You add new actions as rows in the Action Designer window, and set Action Types and SubTypes using the drop-down menus. Each action also has its own set of properties available in the Properties window.

For more information about actions, see Actions Overview.

Best Practices for Designing Pages

We recommend that you simplify the user experience by reducing what users see by default. You can promote the information that the users most frequently need to see and hide the less important information. For example:

  • Place common tasks in the ribbon

  • Organize information pages under FastTabs and, by default, hide the FastTabs that are infrequently visited.

  • Use one to three FactBoxes on a page to provide supplementary information and a place for adding notes.

See Also

Tasks

Touring the RoleTailored Client Pages

Concepts

Actions Overview


How to: Create a Page

Pages are objects for viewing and editing data in the RoleTailored client. When you create a new page, consider the page's business purpose, including which user uses it and what tasks the user must have. There are ten page types from which you can choose, including:

  • Role Center pages, which are home pages for a specific user role such as account manager or sales order processor.

  • List pages, which display multiple records on a page.

  • Card pages, which are used to modify individual customer or item records.

The page type determines which controls, parts, and properties are valid for the page. For example, FactBoxes are not allowed on all page types. For more information about page types, see Touring the RoleTailored Client Pages.

To create a blank page

  1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose the Page button, and then choose the New button. The New Page dialog box appears.

  3. If your page is associated with a table, in the Table text box, choose the AssistEdit button, select a table, and then choose the OK button.

  4. Select Create blank page, and then choose the OK button.

    The new page appears in Page Designer.

    Note
    If you are running Microsoft Dynamics NAV 2016, you can select Create blank page of type, select the page type, and then continue to step 9.

  5. In the Caption field of the first row, which has the type Container and the subtype ContentArea, type some descriptive text, such as contentcontainer.

    Note
    This text is used internally for identification purposes and does not appear in the RoleTailored client.

  6. Choose another row to automatically complete the Name field.

  7. By default, the page is a Card page type. To change to another page type, select a blank row, and on the View menu, choose Properties.

  8. Locate the PageType property, and then set the Value field to the page type you want. For more information about the different page types, see Touring the RoleTailored Client Pages.

  9. Save your page. On the File menu, choose Save As. The Save As dialog box appears.

  10. In the ID field, enter the page ID.

  11. In the Name field, enter a name.

  12. Choose the OK button. Your page is saved.

  13. Complete the page design by adding additional controls, parts, and actions as necessary. For more information, see the following topics:

    • Page Designer Walkthroughs

    • Adding Actions to Pages

    • Creating Activity Buttons for the Navigation Pane

    • How to: Run a Page

Creating a Page Using the Wizard

The development environment includes a wizard that you can use to create specific page types. In the page wizard, you choose a page type, and the page wizard automatically adds some content and controls to the page for you, such as fields, FastTabs, and FactBoxes. The page wizard is designed to help you learn about how to create a page by adding the basic content and controls. The wizard has limitations and may not add all content that you want on a page. For example, you cannot use the wizard to add navigation or actions on your page. Depending on the page's type and complexity, you should manually change a page after you use the wizard.

The following table outlines what the wizard can do for each page type.

What the wizard does | Card | CardPart | Confirmation Dialog | Document | List | ListPart | ListPlus | Navigate | RoleCenter | Standard Dialog | Worksheet
Sets the page type. | X | X | X | X | X | X | X | X | X | X | X
Associates the page with a table. | X | X | X | X | X | X | X | X |  | X | X
Adds FastTabs that include selected fields. | X | X | X | X |  |  | X | X |  |  |
Places fields in a list that has selected fields that define the columns. |  |  |  |  | X | X | X |  |  |  | X
Adds a FactBox that includes page, system, or chart parts. | X |  |  | X | X |  | X | X |  |  | X

To create a page using the wizard

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose the Page button, and then choose the New button. The New Page dialog box appears.

  3. Select Create page using wizard, and then choose the page type from the list.

  4. To specify the table with which your page is associated, in the Table text box, choose the AssistEdit button, select a table, and then choose the OK button.

    Note
    RoleCenter page types are not associated with a table.

  5. Choose the Finish button.

    The new page appears in Page Designer.

  6. Save the page. On the File menu, choose Save As. The Save As dialog box appears.

  7. In the ID field, enter the page ID.

  8. In the Name field, enter a name.

  9. Choose the OK button. Your page is saved.

  10. Complete the page design by adding additional controls, parts, and actions as necessary. For more information, see the following topics:

    • Page Designer Walkthroughs

    • Adding Actions to Pages

    • Creating Activity Buttons for the Navigation Pane

    • How to: Run a Page

See Also

Tasks

How to: Add FastTabs to a Customer Card Page

Concepts

Pages
Pages Overview
Adding a FactBox to Page
Making a Page or Report Available From Search in the Windows Client


How to: Add FastTabs to a Customer Card Page

In this topic you learn how to add a FastTab control to a customer card page. FastTabs replace tabs and enable you to place data in groups on card or task pages. If a group is expanded you see all the fields in a group. If it is collapsed you just see the summary line. The summary line is the header that displays a name for the group, such as 'Communication' and can include promoted fields such as 'E-mail'. Promoting fields to the summary line enables you to present key information to the user, even if the control is collapsed.

Organizing data using FastTabs helps users to find key information quickly, while at the same time giving an overview of areas that otherwise would remain hidden. For example, the customer card page displays customer information in the following categories: General, Communication, Invoicing, Payments, Shipping, and Foreign Trade. Each category is a separate group that can be expanded or collapsed, making it easier for users to focus on one area at a time. On task pages, a FastTab typically represents a single step in a task.

Adding a FastTab Control to a Card Page

To add a FastTab control to a card page

  1. Open Object Designer, choose Page. Select a card page that you have created from the list of available pages, and then choose Design.

    For more information about how to create card pages, see Walkthrough: Creating a Customer Card Page in Page Designer.

  2. In Page Designer, choose the first available row in your blank card page. Type a name for your control in the Name field. Choose the Caption field and the other fields are completed automatically. By default, Type is set to Container and SubType is set to ContentArea. Keep the default values.

  3. In the second row, type a name for your group in the Name field. Set Type to Group and SubType to Group.

  4. In the third row, set Type to Field.

  5. On the View menu, choose Field Menu.

    In the Field Menu window, select fields from the Customer table. Select multiple fields by holding down the CTRL key, while you choose the following fields:

    • No.

    • Name

    • Address

    • City

    • Phone No.

    When you have completed this procedure, these fields will be displayed in your FastTab control.

    If the OK and Cancel buttons are unavailable, see Page Designer Troubleshooting for more information.

    Note
    You can only select fields from the Field Menu if your page has a source table. Remember to select a source table in the New Page dialog when you create your page.

  6. Choose OK. A message box appears with the following message: "Do you want to add the fields that are selected in the field menu?" Choose Yes.

  7. Choose on the View menu, choose Properties. In the Properties window, type a name in Caption. The CaptionML field is completed automatically.

  8. Close the Page Designer window and save your changes. If you created a new page, select a page ID number in the 50000 range, type a name for your page, and then choose OK.

    Repeat the same procedure to add more FastTab groups to your page.

See Also

Tasks

Walkthrough: Creating a Customer Card Page in Page Designer
Page Designer Troubleshooting


Adding a FactBox to Page

A FactBox is the area that is located on the right-most side of a page. This area is used to display content including other pages, charts, and system parts such as Microsoft Outlook, Notes, and Record Links. Typically, you can use a FactBox to display information that is related to an item on the main content page. For example, on a page that shows a sales order list, you can use a FactBox to show sell-to customer sales history for a selected sales order in the list. The following illustration shows a FactBox on sales order page.

Shows FactBox on a sales order

A FactBox is divided into one or more parts that are arranged vertically. Each part can contain one of the following objects:

  • Page of the CardPart or ListPart type.

  • Chart.

  • System part, including Microsoft Outlook, Notes, MyNotes, or RecordLinks. For more information about system parts, see Touring the RoleTailored Client Pages.

Supported Page Types

A FactBox is only supported on the following pages:

  • Card

  • Document

  • List

  • ListPlus

  • Navigate

  • Worksheet

See Also

Tasks

How to: Add a FactBox to a Page


How to: Add a FactBox to a Page

A FactBox is an area on the right side of a page that can display additional pages, charts, or system parts. To add a FactBox to a page, you add the FactBox area, and then add parts that contain charts, system parts, or pages of the ChartPart type or ListPart type.

Tip
When creating a new page, you can use the page wizard to add a FactBox to the page. For more information, see How to: Create a Page.

Adding a FactBox Area to a Page

You define the FactBox by adding a FactBoxArea container control to the page. The FactBoxArea control acts as a placeholder to which you can add different parts for the FactBox. You can add a FactBoxArea control on the following page types only:

  • Card

  • Document

  • List

  • ListPlus

  • Navigate

  • Worksheet

Note
Only one FactBoxArea control is allowed on a page.

To add a FactBox to a page

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Page, select the page you want to modify, and then choose the Design button to open Page Designer.

  3. In Page Designer, select the blank row after the last page control.

  4. In the row, set the Type column to Container and the SubType column to FactBoxArea.

  5. In the Caption column, type the text that you want to appear as the heading for the FactBox.

  6. Choose the left arrow button at the bottom of Page Designer until the FactBoxArea control is at the same level as the ContentArea control.

Adding a Page to the FactBox

You can add a part to the FactBox area that displays an existing page of the CardPart or ListPart type only. If you attempt to use another page type, you will get an error.

Note
This procedure assumes that the page that you want to display in the FactBox already exists. If not, create the page before proceeding. For an example of creating a CardPart page for using in a FactBox, see Walkthrough: Adding a FactBox to the Customer List Page.

To add a page to the FactBox

  1. Add a blank row under the FactBoxArea control.

  2. In the blank row, set the Type column to Part and the SubType column to Page.

  3. Select the row, and on the View menu, choose Properties.

  4. In the Properties window, in the Value column of the PagePartID property, choose the up arrow.

  5. In the Page List window, select the page you want, and then choose the OK button.

  6. Close the Properties window. The selected page now appears in the Name and Caption columns of the Page Designer for the Page row.

Filtering Data that is Displayed on a Page in a FactBox

In many cases, you want to change the content that is displayed on the page in the FactBox based on the content of the main page. For example, if the main page is a Customer List, you can have a FactBox that includes the Customer Details page that shows information about a customer. When a user selects a customer in the Customer List, the Customer Details page displays information about the selected customer. To implement this functionality, you set up a table filter that associates a field in the table that is used by the Customer Details page with a field in the table that is used by the Customer List page. You can also filter on a constant value or set of conditions.

To set up filter on the page in the FactBox

  1. Select the Page row, and on the View menu, choose Properties.

  2. In the Properties window, in the Value field of the SubPageLink property, choose the Assist Edit button.

  3. In the Table Filter window, in the Field column of a row, choose the up arrow.

    The Field List window opens and displays all the fields in the table that are used by the page in the FactBox.

  4. Select the field on which you want to filter, and then choose the OK button.

  5. Set up the filter as follows:

    If you want to Then

    Associate the field with a field in table of the main page

    1. Set the Type column to FIELD.

    2. Set the Value column to the field in the table of the main page.

    Filter on a constant value

    1. Set the Type column to CONST.

    2. In the Value column, type the constant.

    Filter on a set of conditions

    1. Set the Type column to FILTER.

    2. In the Value column, type the conditions.

  6. Choose the OK button. The filter statement appears in the SubPageLink property value of the Properties window.

Adding a Chart to the FactBox

Charts provide a way to display data graphically. You can add any existing chart that is included in table 2000000078 Chart.

Note
Charts are not supported in the Microsoft Dynamics NAV Web client. If the page is displayed in this display target, then the chart part is ignored.

To add a chart to the FactBox

  1. In Page Designer, add a blank row under the FactBoxArea control.

  2. In the blank row, set the Type column to Part and the SubType column to Chart.

  3. Select the row, and on the View menu, choose Properties.

  4. In the Properties window, in the Value column of the ChartPartID property, choose the up arrow.

  5. In the Chart List window, select the chart that you want, and then choose the OK button.

  6. Close the Properties window. The selected chart now appears in the Name and Caption columns of the Page Designer for the Chart row.

Adding a System Part the FactBox

You can add any of the following system parts to a FactBox on a page in the RoleTailored client: Microsoft Outlook, Notes, MyNotes, or RecordLinks.

Note
System parts are not supported in the Microsoft Dynamics NAV Web client. If the page is displayed in this display target, then the system part is ignored.

For more information about system parts, see Touring the RoleTailored Client Pages.

To add a system part to the FactBox

  1. In Page Designer, add a blank row below the FactBoxArea control.

  2. In the blank row, set the Type column to Part and the SubType column to System.

  3. Select the row, and on the View menu, choose Properties.

  4. In the Properties window, in the SystemPartID property, set the Value column to the system part you want.

  5. Close the window. The selected system part now appears in the Name and Caption columns of the Page Designer for the System row.

See Also

Tasks

Walkthrough: Adding a FactBox to the Customer List Page
How to: Create a Page

Concepts

Adding a FactBox to Page


How to: Create a CardPart Page For Displaying Customer Data in a FactBox

A FactBox displays additional information to the user in a pane located on the right of the main page display area.

There are three types of FactBoxes:

  • Page part

  • System part

  • Chart part

For example, on the customer list page you can see four FactBoxes: Customer Sales History - Sell-to Customer, Customer Statistics - Bill-to Customer, Links, and Notes. The first two are page parts based on existing pages. Links and Notes are system parts that are predefined. Other available system parts are Outlook, MyNotes, and Record Links.

FactBoxes can be used with the following page types:

  • Card

  • List

  • Document

  • Worksheet

  • List Plus

  • Navigate

If users do not want to see information displayed in a FactBox, they can collapse the control or hide it. FactBoxes can be hidden or customized to show more or fewer fields, using the customize dialogs.

A FactBox is also a page, so you must first create it in Page Designer, allocate it a source table, and then link it to a page where you want it to appear.

A business user, such as the order processor, can benefit from having additional FactBoxes on a page. For example, when the order processor uses page 22, the Customer list page, it would be useful to see information such as Outstanding Orders when different customers are selected in the list. You can do this by creating a Customer Orders FactBox that only displays specific fields from the Customer table related to outstanding customer orders.

Creating a FactBox to Display Outstanding Customer Orders

To create a FactBox to display outstanding customer orders

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Page, and then choose the New button. The New Page dialog box appears.

  3. Choose Create page using wizard, and then choose CardPart from the list.

  4. To associate the page with the Customer table, in the Table text box, choose the AssistButton, select table 18, and then choose the OK button.

  5. Choose the OK button to continue the wizard.

  6. On the Card Part Page Wizard dialog box, use the arrow keys to move the following fields from Available Fields list to the Field Order list:

    • Outstanding Orders (LCY)

    • Shipped Not Invoiced (LCY)

  7. Choose the Finish button.

    The new page appears in Page Designer.

  8. Save the page. On the File menu, choose Save As. The Save As dialog box appears.

  9. Under ID, enter the page ID.

  10. Under Name, enter Customer Orders Fact Box.

  11. Choose the OK button. Your page is saved.

  12. To run your page, in Object Designer, select the page, and then choose the Run button. The Microsoft Dynamics NAV Windows client opens and displays your new FactBox page.

See Also

Tasks

Walkthrough: Adding a FactBox to the Customer List Page
Page Designer Troubleshooting


Walkthrough: Adding a FactBox to the Customer List Page

In this walkthrough, you will learn how to add a FactBox to the customer list page and use it to display credit information about the selected customer. A FactBox is an area on the page that allows you to display another page that displays targeted, related information about a selection in the main page. A FactBox can only include CardPart and ListPart page types.

About this Walkthrough

This walkthrough provides an overview of how to add a FactBox to another page in Microsoft Dynamics NAV, and demonstrates how to:

  • Create a CardPart page that includes several fields for display in a FactBox.

  • Add the FactBox to the Customer List page.

  • Add the CardPart page to the FactBox of the Customer List page.

  • Associate the selection in the customer list with the information displayed in CardPart page in the FactBox.

Prerequisites

This walkthrough builds on the steps described in Walkthrough: Creating a Customer List in Page Designer and Walkthrough: Adding Actions to a Customer List Page.

Story

Kevin reviews the Customer List page that Simon has created and has one last request. Kevin decides that he would like to display the credit limit and other relevant information for each customer when selected.

Creating a CardPart Page to Display in the FactBox

Simon knows that he can use a FactBox to display the type of information Kevin is asking for on the customer list page. Simon creates a new CardPart page based on the card part page type. He associates the page with the Customer table and then adds the Credit Limit (LCY), Payment Terms Code, and Blocked fields to the CardPart page.

Note
In this walkthrough, to learn about the properties and controls of a FactBox, you will create a CardPart page from a blank page. Object Designer also includes a wizard that you can use to create a CardPart page that sets up many properties and controls for you. For more information about the wizard, see How to: Create a Page.

To create a CardPart page to display credit information

  1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Page, and then choose New. The New Page window opens.

  3. In the Table text box, choose the up arrow, select table 18, Customer, and then choose the OK button.

  4. Choose Create blank page, and then choose the OK button.

    The new page opens in Page Designer.

  5. On the View menu, choose Properties.

  6. In the PageType property, set the Value field to CardPart.

  7. Close the Properties window.

  8. On the first row, in the Name field, type CustomerListFactBoxContainer.
    The Type is preset to Container and the Subtype is preset to ContentArea.

  9. Select the second row. On the View menu, choose Field Menu.

  10. Select multiple fields by holding down the Ctrl key while you choose the following fields:

    • Credit Limit (LCY)

    • Payment Terms Code

    • Blocked

  11. Choose the OK button.

    A message box appears with the following message: "Do you want to add the fields that are selected in the field menu?"

  12. Choose Yes.

  13. Press Ctrl+S to save the FactBox page. The Save As dialog box opens.

  14. In the ID field, type 50001, and in the Name field, type Kevin's Customer List FactBox. Choose OK.

  15. In Object Designer, select the page you just created and choose Run to run the page.

    The Microsoft Dynamics NAV Windows client opens and displays the new FactBox page.

Adding a FactBox to the Customer List Page

Simon is now ready to add the FactBox to the customer list page that he created in Walkthrough: Creating a Customer List in Page Designer. To do this, he first needs to open the Customer List page in Page Designer and then add the FactBox to the bottom of the Customer List page.

To add a FactBox to the customer list page

  1. In Object Designer, choose Page, select page 50000, Kevin's Customer List, and then choose Design.

    The Kevin's Customer List page opens in Page Designer.

  2. Select the first empty line on the page.

  3. In the Name column, type FactBoxArea. Set Type to Container and set SubType to FactBoxArea.

  4. Select the FactBoxArea line and choose the left arrow twice to negative indent this row until it is at the same level as the CustomerListContainer.

Adding a CardPart Page to the FactBox on the Customer List Page

Simon is now ready to add the CardPart page to the FactBox on the Customer List page.

To add a CardPart to the Factbox on the customer list page

  1. On the next empty row in Page Designer after the FactBoxArea control, set the Type to Part and the SubType to Page.

  2. Select the row, and on the View menu, choose Properties.

  3. In the Properties windows, in the Value column of the PagePartID property, choose the up arrow.

  4. In the Page List window, select Kevin's Customer List FactBox(50001) page, and then choose the OK button.

Associating the CardPart Page in the FactBox with the Customer List Page

Simon wants the information displayed in the CardPart page to change based on the customer that is selected in the customer list. To accomplish this, he will associate the No. field of the CardPart page with the No. field of the Customer List page.

To associate the CardPart page in the Factbox with the customer list page

  1. In the Properties window of the FactBox, in the Value field of the SubPageLink property, choose the AssistEdit button.

  2. In the Table Filter window, in the Field column of a row, choose the up arrow.

    The Field List window opens to display all the fields in the Customer table of the CardPard page in the FactBox.

  3. Select the No. field, and then choose the OK button to return to the Table Filter window.

  4. In the Table Filter window, set the Type column to FIELD.

  5. In the Value column, choose the AssistEdit button.

    The Field List window opens to display all the fields in the table of the customer page.

  6. Select the No. field, and then choose OK to return to the Table Filter window.

  7. Save the page and run the page to verify that the FactBox is displayed.

See Also

Tasks

Walkthrough: Creating a Customer List in Page Designer
Walkthrough: Adding Actions to a Customer List Page
How to: Create a Page
Touring the RoleTailored Client Pages
How to: Run a Page


How to: Open a Card Page from an Item in a List

You can associate items in a list page with a related card page so that when a user double-clicks the list item, the card page for that item is opened. The CardPageID property is used to associate an item in a list with a specific card page. For example, you can use it to associate a name in a customer list the related customer card.

To associate a card page with a list page

  1. With the list page open in Page Designer and with the first available empty row in Page Designer selected, on the View menu, choose Properties.

    The Properties window opens.

  2. Locate the CardPageID property, and then choose the AssistButton in the value field.

    The Page List window opens.

  3. Select a page from the list, and then choose OK.

See Also

Tasks

Walkthrough: Creating a Customer List in Page Designer

Reference

CardPageID Property


How to: Run a Page

When you are developing pages, you may want to see how the pages look in the RoleTailored client. You can run and view a page from Object Designer, or you can use command-line arguments at the command prompt, in the Run window, or in a browser. For each method, the RoleTailored client starts and opens the selected page. For command-line arguments, you have various options for opening the RoleTailored client and its pages in different modes. For example, you can specify a specific server or specific language, or you can create hyperlinks to specific pages in Microsoft Dynamics NAV. For more information, see Starting the Windows Client at the Command Prompt and Creating and Running Hyperlinks.

Note
ConfirmationDialog pages cannot be run and previewed by using the methods described in this topic. You can only view ConfirmationDialog pages by invoking them in the RoleTailored client.

To run a page from Object Designer

  1. Open the Microsoft Dynamics NAV Development Environment.

  2. On the Tools menu, choose Object Designer, and then choose Page.

  3. Select the page that you want to view, and then choose Run.

To run a page at the command prompt

  1. At the command prompt, change to the RoleTailored client directory with the following cd command:

    Copy Code
    cd C:\Program Files\Microsoft Dynamics NAV\90\RoleTailored Client

  2. Type the following command:

    Copy Code
    Microsoft.Dynamics.Nav.Client.exe Dynamicsnav:////runpage?page=nn

    Substitute nn with the ID of the page that you want to view.

  3. Press ENTER.

    The RoleTailored client opens and displays the page.

To run a page from the Run window

  1. On the taskbar, choose Start, and then choose Run.

  2. In the Run window, type the following command:

    Copy Code
    Microsoft.Dynamics.Nav.Client.exe Dynamicsnav:////runpage?page=nn

    Substitute nn with the ID of the page that you want to view.

  3. Choose OK.

    The RoleTailored client opens and displays the page.

To run a page from a browser

  1. Open the browser.

  2. In the address bar, type the following command:

    Copy Code
    Dynamicsnav:////runpage?page=nn

    Substitute nn with the ID of the page that you want to view.

  3. Press Go.

    The RoleTailored client opens and displays the page.

See Also

Starting the Windows Client at the Command Prompt

Concepts

Creating and Running Hyperlinks


How to: Preview Pages and Identify Page and Action Controls

In the development environment, you can preview a page directly from Page Designer to see how the page will look in the Microsoft Dynamics NAV Windows client. Unlike running a page from Object Designer, previewing a page does not start the Microsoft Dynamics NAV Windows client, which means that you can keep working in the development environment. The Page Preview window includes the following features:

  • The Page Preview window is automatically updated as you make changes in Page Designer and Action Designer. When you design a page, you can have the page preview open beside Page Designer so that you can see changes as you make them.

  • The Page Preview window is interactive. You can use page preview to identify and learn which controls in Page Designer and Action Designer correspond to the different elements on the rendered page, such as FastTabs, FactBoxes, fields, and actions.

  • The Page Preview window does not require you to save the page before seeing how changes that you make to a page will look in the Microsoft Dynamics NAV Windows client.

Note
The preview is not an active page in the Microsoft Dynamics NAV Windows client, which means that you do not have all functionality in a page preview as you do when you run a page. For example, you cannot edit fields, and you cannot choose actions to open targets because actions are static. To enable this functionality, run the page in the Microsoft Dynamics NAV Windows client. For more information, see How to: Run a Page.

To preview a page

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, select a page, and then choose the Design button.

  3. In Page Designer, choose the Preview button.

Identifying Page and Action Controls

Controls define the content and structure of a page. You can use a page preview to identify controls in Page Designer and Action Designer and their corresponding elements on the rendered page. To identify controls, you can work in Page Designer, Action Designer, or the Page Preview window. If you choose a control in Page Designer or Action Designer, then the corresponding element is highlighted in the Page Preview window. Also, if you choose an element in the Page Preview window, then the corresponding control is highlighted in Page Designer or Action Designer. From the Page Preview window, you can also access the C/AL code for the page and its actions, properties for page and action controls, and Page Designer for a subpage that is contained in a page part.

Important
Some elements on a rendered page in the page preview are added automatically and do not have a corresponding control in Page Designer. You cannot select these elements in the Page Preview window. If you select an element that does not have a corresponding control in Page Designer, then Page Designer highlights the most related control. For example, if you choose an action that has no control in Page Designer, then the ActionContainer control is highlighted in Page Designer.

To identify page controls

  • In the Page Preview window, select an element. The element is surrounded by a blue border, and the control that defines the element is highlighted in Page Designer.

  • In Page Designer, select a control. The element that corresponds to the control is surrounded by a blue border in the Page Preview window.

The following figure shows an example for the Document Date field on page 42, Sales Order.

Page designer and preview with marked field
Note
If you select a part control that contains a subpage, such as a FastTab or FactBox, then the page preview displays the area as gray. To open Page Designer for the subpage, on the shortcut menu of the part, choose Go To Definition.

To identify action controls

  • In the Page Preview window, select an action. The action is surrounded by a blue border, and Action Designer opens with the action’s control highlighted.

  • In Action Designer, select an action control. The element that corresponds to the action control is surrounded by a blue border in the Page Preview window.

The following figure shows an example for the Shipments action on page 42, Sales Order.

Action designer and preview with selected action
Note
In the Page Preview window, you cannot choose actions that are generated automatically on a page, such as New, Edit, and Post, or actions that are contained in a group that is defined by an ActionGroup control.

To open control properties from the Page Preview window

  • In the Page Preview window, right-click the page element or action, and then choose Properties.

To open C/AL code for page or actions from the Page Preview window

  • To open the C/AL code for a page, in the Page Preview window, select anywhere on the content area of the page, and then choose C/AL Code.

  • To open the C/AL code for actions, in the Page Preview window, on the shortcut menu of an action, choose C/AL Code.

To open a subpage in a part from the Page Preview window

  • In the Page Preview window, on the shortcut menu of the part, choose Go To Definition.

See Also

Tasks

How to: Run a Page


Adding Actions to Pages

In the RoleTailored client for Microsoft Dynamics NAV, menu items are called actions. The topics in this section provide information about creating and modifying actions on pages. Creating actions can include adding Action Items to a page, using Action Designer, configuring Home Items on a user Role Center, or adding Reports to a page.

Actions Documentation

This documentation is intended for Microsoft Dynamics NAV developers. It is intended that this topic will help you quickly find the information about actions that you need.

To | See
Learn about actions in the RoleTailored client. | Actions Overview
Learn how to add actions to a page. | How to: Add Actions to a Page
Learn how to add promoted actions to the ribbon. | How to: Promote Actions to the Ribbon on Pages
Learn how to create actions submenus. | How to: Add Action Submenus to Pages

See Also

Tasks

Page Designer Troubleshooting


Actions Overview

In Microsoft Dynamics NAV, actions are displayed at the top of each page in the ribbon or in the navigation pane. In this topic, you learn about different types of actions, and how you can enable users to quickly locate the actions they want to use.

Pages can have the following actions.

Types of actions | Used on | Description | Example
Actions | Role Center, list, card, and task pages | User tasks | Post a sales order
Navigate | List, card, and task pages | Links to other pages in Microsoft Dynamics NAV. | Prices
Reports | Role Center, list, card, and task pages | A list of available reports. | Customer Top 10 List
New | List, card, Role Center pages, and task pages | Actions that appear under the New group. Opens a new Microsoft Dynamics NAV document. | New sales invoice
Promoted Actions | List, card, Role Center pages, and task pages | Provide quick access to common tasks that appear under the Home tab. | Post and print a sales order
Home Items | Role Center pages | Menu items on the Role Center navigation pane. | Customers
Activity Buttons | Role Center pages | Menu buttons for a secondary activity, such as posted documents. | Posted sales invoices
Caution
If you change an object, for example, an action to an action container, you must also change the ID of the action. The ID serves as a reference, and must reflect the object.

Each page has a different set of actions depending on the page type, and the processes that the page supports. In order to create the appropriate set of actions for a particular page, you should have a good understanding of your customer's business processes.

Each process in an organization has several actions associated with it. You should try to create a full set of actions that mirror all tasks and processes that are performed.

Example: The Sales Orders list page at CRONUS International contains all actions related to processing sales orders. During user configuration and personalization, some of these actions may be hidden or promoted to the ribbon. Therefore, you must create a full set of actions for the customer.

Types of Actions

The following sections describe actions available in the Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client.

Actions

The Actions tab is displayed in the ribbon on all page types, and contains relevant tasks for the current page. Some examples from the Customer page are as follows:

  • Sales Invoice

  • Sales Quote

  • Sales Credit Memo

  • Ledger Entries

  • Invoice Discounts

  • Prices

  • Line Discounts

They are regular daily tasks. Therefore, they must be on the Actions menu, and promoted to the ribbon.

You can add actions to the Actions menu, group actions together under action submenus, or promote them to the ribbon. You cannot create submenus or promote actions on a Role Center page.

Navigate

The Navigate tab is displayed after Actions in the ribbon. Rather than providing tasks for the user, this tab provides additional information by taking the user to a specific page in Microsoft Dynamics NAV.

Note
You should not add a Navigate action to a Role Center page.

Report

The Reports tab is displayed after the Navigate tab on the ribbon. The Reports tab lists the reports most relevant to a page. If a user does not require a Reports tab, then the tab is hidden. Sometimes it is relevant to promote the most important reports to the Home tab to save the user from too many clicks.

New Document

The New action is often displayed both in the Home tab and in the Actions tab. You can use this action to open new documents within Microsoft Dynamics NAV. When you create a New action in Action Designer, you must use the NewDocumentItems SubType.

Example: On the Customers page, if the order processor wants to create a new invoice, she can open the New page directly from the Actions tab. This is useful as she creates new sales invoices daily.

Home Items

Home Items are actions displayed on the Home tab, on the Role Center navigation pane. This navigation has a tree structure, and each node in the tree links to a list page.

The user Role Center is like a home page, and home items in the navigation pane are links to the user’s most useful list pages.

Activity Buttons

If there are too many Home items to fit on the Role Center without scrolling, then activity buttons can be used to group other important processes together.

Example: The Order Processor Role Center could have activity buttons called Approving Web Orders, or Sales Forecasting. These are secondary activities for the order processor, so they do not have to be included under the Home button.

Each activity button has its own navigation pane, with links to list pages and can be configured just like the user Role Center.

Promoted Actions

Promoted actions are existing actions in the Actions, Navigate, or Reports tabs that are also displayed in the Home tab in the ribbon. The Home tab is always displayed first.

Promoted actions provide quick access to common tasks, because users do not have to browse through a menu to access them. You can promote any command from the existing actions menus to the ribbon. If there are no promoted actions, the ribbon remains hidden.

Promoted actions can be grouped. For more information, see How to: Define Promoted Action Categories Captions for the Ribbon.

Each promoted action has an icon associated with it. You can accept a default icon for your promoted action or decide to use a larger icon that makes it more prominent to the user. Use the Properties window in the Action Designer to set the size and location of an icon.

Example: On the Sales Orders list page, Post is promoted to the ribbon, and included in the Process group. This helps the order processor in her work, because posting sales orders is one of her most important daily tasks.

Actions at Runtime

An action can trigger code to run, such as posting a document or otherwise modifying a record in a table. When a user chooses an action, one of the following pieces of logic will happen in addition to the code that the action itself triggers:

  • If the page is empty and no longer shows any records, the page is re-initialized with default values.

  • If the page does show records, and the current state is within the page filters boundary, the OnAfterGetRecord trigger is executed on the page.

  • If the current record that the page showed is now outside the filter but there are other records within the filter, the OnFindRecord trigger is called and the OnAfterGetRecord trigger is run on the next record with the given filters.

The logic runs in the transaction that the action triggered. This can cause the application code to result in users locking the whole table when they thought they were only modifying one record.

To avoid users accidentally locking tables, you can use the SetSelectionFilter function before your code passes the record variable to the processing codeunit, for example. The following code example illustrates the code on the OnAction trigger on an action on a page.

Copy Code
IF CONFIRM('Are you sure you want to call this codeunit?', TRUE) THEN
  BEGIN
  CurrPage.SETSELECTIONFILTER(Rec);
  CODEUNIT.RUN(50000, Rec);
  END;
END;

See Also

Tasks

Walkthrough: Adding Actions to a Customer List Page
How to: Add Actions to a Page
How to: Promote Actions to the Ribbon on Pages


How to: Add Actions to a Page

This topic shows how to create new actions, how to add actions to a page, and how to preview them in the Microsoft Dynamics NAV Windows client. In Microsoft Dynamics NAV, actions can be displayed on the menu bar of all pages and grouped together under the following actions buttons:

  • Actions

  • Related Information

  • Reports

Before putting an action on a page you should think about the business processes that the action supports. For example, on page 42, the Sales Orders list page, the Actions button contains actions for all tasks related to processing sales orders. Creating these actions can make it easier for the order processor to perform her daily tasks, such as posting sales orders and creating new customer orders.

For more information, see Actions Overview.

Adding Actions to a Page

To create a new action you must use Action Designer. Action Designer is a tool in Page Designer that enables you to add actions to the menu bar.

To add an action to a page

  1. Open the development environment, and then in the Tools menu, choose Object Designer.

  2. In Object Designer, select a page, and then choose Design to open Page Designer.

  3. To open Action Designer, in the View menu, choose Page Actions.

    Note
    Actions can only be linked to a page, or to a group control that has a subtype of CueGroup. Actions cannot be linked to fields, containers, or parts on a page. For information about adding actions to a CueGroup control, see Walkthrough: Creating a Cue Based on a FlowField.

  4. In Action Designer, select the first blank row, type a Name, and then type a Caption for your action.

    The caption appears on the action on page in the Microsoft Dynamics NAV Windows client.

  5. In the Type field, select one of the following Types:

    • ActionContainer

    • Separator

    • ActionGroup

    • Action

    For example, if you want to create a container for your actions, select ActionContainer.

  6. In the SubType field, select one of the following SubTypes:

    • NewDocumentItems

    • ActionItems

    • RelatedInformation

    • Reports

    • HomeItems

    • ActivityButtons

    For example, if you want to put your action in the Actions menu, select ActionItems.

  7. Choose in the second row, set action Type to Action. Your action is indented automatically under the ActionContainer. Choose the third row, and then choose the second row again. The Name field in this row is filled in automatically.

    You can use the right and left arrow buttons in Action Designer to adjust indentation, and use the up and down arrow buttons to move an action in the hierarchy.

    Note
    If you insert a new row to add a new action to the list, indentation is not automatic, so always check the indentation on your actions. If it is not correct you will get an error when you compile.

  8. With your action selected, choose View, and then choose Properties. Set the RunObject property to create an action that opens another page, for example, page 42, Sales Orders.

    Note
    In Action Designer, actions can be assigned to a page by setting the RunObject property, or by adding a C/AL trigger to a code unit.

  9. Set the Caption and CaptionML properties to make the action visible in the Actions menu.

  10. Save and compile the page.

  11. To preview an action in the Microsoft Dynamics NAV Windows client, in Object Designer, select the page and choose Run. For more information about running a page, see How to: Run a Page.

Note
If the Microsoft Dynamics NAV Windows client is already open, you will not see changes to HomeItems or ActivityButtons until to you close and restart it.

Caution
If you change an object, for example, an action to an action container, you must also change the ID of the action. The ID serves as a reference, and must reflect the object.

See Also

Tasks

Walkthrough: Adding Actions to a Customer List Page

Concepts

Actions Overview


How to: Promote Actions to the Ribbon on Pages

Actions in the ribbon are called promoted actions. Promoted actions are copies of existing actions in the command bar that are displayed in the ribbon and provide quick access to common tasks, because users do not have to look through a menu to find them. For example, on the Customer Card page, you can promote an action to create a new sales order to help the salespeople do their work, because creating sales orders is one of their most important daily tasks.

Promoted actions can be organized under different categories. For example, the categories can be New, Tasks, Reports, and Discounts. The order of actions under a category is determined by its order in the Action Designer. You define the caption for each category. For more information on defining the promoted categories, see How to: Define Promoted Action Categories Captions for the Ribbon.

When you promote an action to the ribbon, you can set up an image that displays with the action. If you do not set up an image yourself, then a default image is used. For more information about promoted action images, see How to: Set an Icon on an Action.

Note
If an action does not already appear in the command bar menu, then it cannot be promoted. Also, if there are no promoted actions, then the ribbon is hidden.

Adding a Promoted Action to a Page

To add a promoted action to a page

  1. In the Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, select a page that already has actions, and then choose Design to open the page in Page Designer. For example, select page 22, which is the Customer List page.

  3. To open Action Designer, in the View menu, choose Page Actions.

  4. In Action Designer, select the action to promote to the ribbon.

  5. In the View menu, choose Properties.

  6. In the Properties window, set the Promoted property value to Yes.

  7. Set the PromotedCategory property to the category under which you want the promoted action to appear.

    Unless you define your own caption, the category name that you select will be used as the category's captions on the page. For more information, see How to: Define Promoted Action Categories Captions for the Ribbon.

  8. To assign an image to the action, set the Image property to the name of the image. For a list of images, see Action Icon Library.

    Note
    To associate a larger icon with your action, set the PromotedIsBig property.

  9. Close the Properties window and exit Page Designer.

  10. Save and compile the page.

  11. To preview your promoted action, in Object Designer, select the page, and then choose Run.

Promoted Action Category Location in the Ribbon

The locations of promoted action categories in the ribbon are determined by their first instance in Action Designer. Starting from top of Action Designer and working down, the category of the first promoted action encountered is located on the far left of the ribbon; the next category encountered is located to the right of the first category, and so on.

Customizing the Ribbon

When customizing the ribbon from the Customize Ribbon window, some actions may not have the sizing button labeled Default Icon Size available. The Default Icon Size button has the options of displaying an action icon as default size, small, or large. The label of the button changes when small or large is selected. In some cases the action can be a promoted action with the property PromotedIsBig set to Yes in the Development Environment. If you set an action to PromotedIsBig, this overrules the choices in the Customize Ribbon window.

See Also

Tasks

How to: Add Actions to a Page
How to: Define Promoted Action Categories Captions for the Ribbon

Concepts

Actions Overview


How to: Define Promoted Action Categories Captions for the Ribbon

Promoted actions are actions that are displayed in the ribbon of the RoleTailored client. You can organize promoted actions into different categories, where each category is indicated by a caption in the ribbon. You define up to 10 categories for a page. The following figure illustrates a page that has promoted actions under the following categories:

  • New

  • Manage

  • Process

  • Report

The following illustration shows the Ribbon with promoted actions under categories.

Action Pane with four categories

You assign a promoted action to a category by setting the PromotedCategory property of the action. You can choose among the following categories:

  • New

  • Process

  • Report

  • Category4

  • Category5

  • Category6

  • Category7

  • Category8

  • Category9

  • Category10

By default, these category names correspond to the captions that are displayed for the category on the page in the Microsoft Dynamics NAV Windows client. You will typically want to change these captions, especially the Category4 through Category10 captions.

You change category captions on a page-by-page basis and for each Microsoft Dynamics NAV Windows client language.

To define promoted action category captions

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Page, select the page, and then choose Design.

  3. In Page Designer, select a blank row, and then in the View menu, choose Properties.

  4. In the Page - Properties window, locate the PromotedActionsCategoriesML property, choose the Value field, and then choose the AssistButton to open the Multilanguage Editor.

  5. In the Multilanguage Editor, set the Language field to the language version of the categories that you want to define.

  6. In the Value field for the language, type the category captions as follows:

    New_caption,Process_caption,Reports_caption,Category4_caption,Category5_caption,Category6_caption,Category7_caption,Category8_caption,Category9_caption,Category10_caption

    Substitute the italic text with the text that you want for each caption. Separate each caption with a comma. The position of the caption in the list determines its corresponding category setting in the PromotedCategory property for actions, as shown in the following table:

    PromotedActionsCategoriesML caption position PromotedCategory property value

    First

    New

    Second

    Process

    Third

    Reports

    Fourth

    Category4

    Fifth

    Category5

    Sixth

    Category6

    Seventh

    Category7

    Eighth

    Category8

    Ninth

    Category9

    Tenth

    Category10

    For example, to define the captions for the figure at the beginning of this topic, you enter the following text:

    New,Manage,Process,Report

    Then, to assign a promoted action to the caption Tasks, in the Action Designer, set the PromotedCategory property value for the action to Process.

    Note
    You only need to define captions for the number of categories that you want to use on a page. You do not need to define captions for all 10 categrories.

  7. Close the page properties and save the page.

See Also

Tasks

How to: Promote Actions to the Ribbon on Pages
How to: Add Actions to a Page
How to: Set an Icon on an Action

Concepts

Actions Overview


How to: Add Action Submenus to Pages

Action submenus can be placed on pages in the Microsoft Dynamics NAV Windows client, under any of the three main actions menus:

  • Actions

  • Related Information

  • Reports

Create an actions submenu if you have too many actions to fit under a single actions menu. Action submenus help you to break down the numerous tasks related to a business process, into smaller, related groups.

For example, on the Customers list page, under Related Information there are two submenus with submenu actions.

Actions menu Submenu Submenu actions

Related Information

Customer

  • Ship-to Address

  • Contact

Sales

  • Prices

  • Line Discounts

The preceding table shows a small selection of submenu actions from the Customers list page. You can see that by grouping related activities together, it is possible to reduce the length of individual action menus, and make it easier for employees to find the actions they want to perform.

Creating an Action Submenu

Use Action Designer to create action submenus and individual actions to place under these menus.

You create action submenus as an Action Group type in Action Designer. Each Action Group can have any number of child elements placed below it in the hierarchy. Each row in Action Designer is indented. It is this indentation that determines the level of the action in the navigation.

To create an action submenu

  1. Open the development environment, choose Tools, and then choose Object Designer.

  2. In Object Designer, select a page, and then choose Design to open Page Designer. For example, select page 22, the Customers list page. You can create a submenu on a new or existing page.

  3. To open Action Designer, on the View menu, choose Page Actions.

  4. In Action Designer, you can see all the existing actions for the page. Use the shortcut menu on any row, and then choose New to create a new row for your action submenu.

  5. Type a Name for your submenu item, and then choose Caption. The other fields are filled in automatically.

  6. Select ActionGroup from the Type drop-down. If you select ActionGroup, the SubType field remains blank.

    You have now created an Action submenu.

  7. To add an action to your action submenu, create a new row below the ActionGroup you just created. Give your action a name, and set Type to Action in the drop-down.

  8. Use the right and left indentation arrows to indent your new action one space below ActionGroup.

    For more information, see How to: Add Actions to a Page.

  9. Save and compile the page.

  10. To preview your action submenu, in Page Designer, choose the Preview button.

See Also

Tasks

How to: Add Actions to a Page

Concepts

Actions Overview


How to: Set an Icon on an Action

The Microsoft Dynamics NAV Windows client includes images that you can use on actions in command bar menus and promoted actions on the ribbon.

You add images to page actions with Action Designer. To add an image to an action, you must provide the name of the image. To view all the available action images, see Microsoft Dynamics NAV 2013 Icon Collection.

By default, the size of images is 16 pixels high by 16 pixels wide. For promoted actions, you can choose to display larger images that are 32 pixels high and 32 pixels wide.

Note
For information on using images on activity buttons in the navigation pane of the Microsoft Dynamics NAV Windows client, see How to: Set an Icon on an Activity Button.

To add an image on an action

  1. To open Object Designer, in the development environment, on the Tools menu, choose Object Designer.

  2. To open Page Designer, in Object Designer, choose Page, select the page, and then choose the Design button.

  3. On the View menu, choose Page Actions.

  4. In Action Designer, select the action for which you want the image.

  5. On the View menu, choose Properties.

  6. In the Properties window, in the Value column of the Image property, choose the AssistEdit button

  7. In the Image List window, select the image that you want to use for the action, and then choose the OK button.

    To view the available images, see Action Icon Library.

  8. In the Properties window, if the action is promoted to the ribbon and you want the image to display a large icon, then set the PromotedIsBig property to Yes.

  9. Close the Properties window, and then save the page.

See Also

Tasks

How to: Add Actions to a Page
How to: Promote Actions to the Ribbon on Pages

Concepts

Action Icon Library
Adding Actions to Pages


Action Icon Library

The Microsoft Dynamics NAV Windows client includes images that you can use on actions that display in the ribbon and command bar menus. To add an image to an action, you must provide the name of the image. For more information, see How to: Set an Icon on an Action.

Action Images

By default, an image’s size is 16 pixels high by 16 pixels wide. For promoted actions, the image size is 32 pixels high and 32 pixels wide.

To view all the available action images, see Microsoft Dynamics NAV 2013 Icon Collection

See Also

Tasks

How to: Set an Icon on an Action

Concepts

Adding Actions to Pages


Creating Activity Buttons for the Navigation Pane

An activity button is a navigation pane button that displays links to additional list pages in the RoleTailored client. The Home and Departments activity buttons are default activity buttons on Role Centers. You can also create activity buttons to organize links to related pages and make it quicker for users to locate pages and minimize scrolling in the navigation pane.

The following illustration shows a navigation pane that has the default activity buttons and two additional activity buttons: Posted Documents and Bank. The Posted Documents button is selected and shows actions that link to pages that are associated with posted documents.

Navigation pane clip that shows Activity buttons

When you create an activity button, you can apply one of the default images that are available for activity buttons. For more information, see How to: Set an Icon on an Activity Button.

Note
You cannot set up an image on the page links of an activity button. All page links in the navigation pane use a default image that cannot be changed.

Setting up Activity Buttons and Page Links in the Navigation Pane

You use Action Designer to set up activity buttons on Role Center pages. The following illustration shows the Action Designer setup for the Posted Documents button.

Action Designer that shows Activity Button setup

The following guidelines apply when working with activity buttons:

  • Activity buttons are only valid on pages that have the type RoleCenter. For more information, see Walkthrough: Creating a Role Center.

  • All activity buttons are set up under a single action of the type ActionContainer and the subtype ActivityButtons. The container's location with respect to other action containers is not significant. Activity buttons are always displayed after the Home button in the navigation pane.

  • An activity button is defined by an action of the type ActionGroup that is indented once from the ActivityButtons row. The order of the activity buttons in the Action Designer determines the default order in the navigation pane.

  • Links to individual pages are defined by actions of the type Action that are indented once from the ActionGroup row. The order of the actions in the Action Designer determines the default order in the navigation pane.

See Also

Tasks

How to: Create an Activity Button and Page Links in the Navigation Pane
How to: Set an Icon on an Activity Button
Walkthrough: Creating a Role Center

Concepts

Setting Up the Home Button and Home Items


How to: Create an Activity Button and Page Links in the Navigation Pane

An activity button in the navigation pane displays a menu of links to additional pages in the RoleTailored client. The following illustration shows activity buttons in the navigation pane.

Navigation pane clip that shows Activity buttons

You create activity buttons and page links for the navigation pane by adding actions on the page that defines the Role Center. For more information, see Creating Activity Buttons for the Navigation Pane.

To create an activity button for the navigation pane

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Page, select the Role Center page, and then choose Design to open Page Designer.

  3. On the View menu, choose Page Actions.

  4. In Action Designer, activity buttons are set up under an action control that has the Type set to ActionContainer and the SubType set to ActivityButtons. If this action control already exists, then go to the next step. Otherwise, do the following to add the activity button container:

    1. Select a blank row.

      To insert a row above another row, right-click the row, and then choose the New button.

      Note
      The location of the activity button container with regard to other containers is not important. However, if you are inserting a row, then insert the container at the end of the actions that belong to the container above.

    2. In the row, set Type to ActionContainer and SubType to ActivityButtons.

    3. Choose another row, and then go back on the row to fill in Name and Caption automatically.

  5. To add an activity button, select a blank row after the ActivityButtons container row.

    The order of the activity buttons in the Action Designer determines the default order in the navigation pane of the RoleTailored client. If there are existing activity buttons, then locate the new activity button where you want it now or you use the UP ARROW and DOWN ARROW keys to move it later.

  6. Set Type to ActionGroup.

  7. In the Caption field, type the text to display on the activity button in the RoleTailored client.

    Note
    You can also include an image on the activity button. For more information, see How to: Set an Icon on an Activity Button

  8. Use the RIGHT ARROW and LEFT ARROW keys to indent the row one level from the ActivityButtons container row.

Note
If the RoleTailored client is currently open, you will not see your changes until you close and restart.

To add a page link to an activity button

  1. In Action Designer, select the action that defines the activity button to which you want to add the page link.

  2. On the View menu, choose Properties.

  3. In the Properties window, set the RunObject property value to page <name> and substitute <name> with either the page name or ID. For example, to link to the page with the ID 142 and name Posted Sales Shipments, you can type page 142 or page Posted Sales Shipments.

    Note
    Instead of typing page, you can just type p followed by the ID or name, such as p421 or Posted Sales Shipments.

  4. Use the RIGHT ARROW and LEFT ARROW keys to indent the row one level from the ActionGroup row.

Note
If the RoleTailored client is currently open, you will not see your changes until you close and restart.

See Also

Tasks

Walkthrough: Creating a Role Center

Concepts

Creating Activity Buttons for the Navigation Pane
Adding Actions to Pages
Pages


How to: Set an Icon on an Activity Button

The Microsoft Dynamics NAV Windows client includes images that you can use on activity buttons in the navigation pane. Images are displayed on the left side of activity buttons, as shown in the following navigation pane example.

Navigation pane clip that shows Activity buttons
Note
You cannot set up an image on the page links of an activity button. All page links in the navigation pane use a default image that cannot be changed.

You set up activity buttons the page that is used as the Role Center. To complete this procedure, you must have the name or ID of the Role Center page.

To set up image on an activity button

  1. To open Object Designer, in the development environment, on the Tools menu, choose Object Designer.

  2. To open Page Designer, in Object Designer, choose Page, select the Role Center page, and then choose the Design button.

  3. On the View menu, choose Page Actions.

  4. In Action Designer, locate the action that has the Type set to ActionContainer and the SubType set to ActivityButtons.

    This defines the activity button container.

  5. Select the ActionGroup row for the activity button on which you want the image. Activity buttons are defined by the actions that have the Type set to ActionGroup.

  6. On the View menu, choose Properties.

  7. In the Properties window, in the Value column of the Image property, choose the AssistEdit button.

  8. In the Image List window, select the image that you want to use for the activity button, and then choose the OK button.

  9. Close the Properties window, and save the page.

Note
If the Microsoft Dynamics NAV Windows client is currently open, you will not see your changes until you close and restart.

See Also

Tasks

How to: Create an Activity Button and Page Links in the Navigation Pane


Setting Up the Home Button and Home Items

Home is a default activity button in the navigation pane of Microsoft Dynamics NAV and displays items that link to List Places.

Adding Items to the Home Button

There are two ways that you can add items to the Home button:

  • Add actions on the Role Center page.

    You use the Action Designer to add actions under the HomeItems control. You set up the actions to open list pages. Each action appears as an item under the Home button. For example, the following illustration shows the Action Designer for the Home button items that are shown in the previous illustration.

    Action Designer showing the HomeItems actions

    For information about how to add an action under the HomeItems control, see How to: Add Actions to a Page.

  • Add Cues on the Role Center page.

    Items from Cues are added to the Home button automatically. When you add a cue, you set the DrillDownPageID Property to a list page for displaying the data. If there is a relevant parent entity to place the Cue item under, that link is automatically added in the navigation pane. For example, if you have a Cue named Sales Return Orders - Open, this item will be added under the parent item Sales Return Orders in the navigation pane. For more information, see Walkthrough: Creating a Cue Based on a FlowField.

Child Items

An item is automatically positioned as a child to another item according to the following conditions:

  • The child item targets a list page that displays filtered data from a table.

  • The parent item targets the same list page as the child item, except that list page data is not filtered.

  • The parent item is defined by an action, not a Cue.

Hiding and Customizing the Home Button and Items in the Microsoft Dynamics NAV Windows client

The Home button is always present in the navigation pane and cannot be removed or modified that included its icon. From the Microsoft Dynamics NAV Windows client, end-users and administrators can use customization to change the items under the Home button including:

  • Removing home items.

    Note
    Home items that are created from Cues cannot be removed using customization. The only way to remove these items is to remove the Cue by using Page Designer.

  • Moving home items to other Activity buttons.

  • Restoring the default Home items as defined in the Action Designer on the Role Center page.

As an end-user, the changes are only implemented on the user’s Role Center. For more information, see Customize the User Interface.

If you are an administrator, then you can open the Microsoft Dynamics NAV Windows client in the Configuration mode and the changes that you make will be implemented on the Role Center for all users. For more information, see How to: Open Microsoft Dynamics NAV in Configuration Mode.

See Also

Customization: Configuration and Personalization

Concepts

Creating Activity Buttons for the Navigation Pane


Creating and Running Hyperlinks

Hyperlinks enable users to send or save quick links to specific pages in Microsoft Dynamics NAV. For example, you can create a hyperlink to a specific list page, such as Customers. You can also use hyperlinks to specify parameters, such as server name, server service, or company. You can enter hyperlinks in the Command Prompt window, in a browser window, or directly in the Run window. You can also generate hyperlinks programmatically as part of your Microsoft Dynamics NAV functionality.

Creating Hyperlinks

You can use hyperlinks as URLs or at a command prompt as arguments to the command to start the Microsoft Dynamics NAV Windows client. At the command prompt, type the name of the Microsoft Dynamics NAV Windows client executable and then, in quotation marks, type the hyperlink. For example:

Copy Code
Microsoft.Dynamics.Nav.Client.exe "DynamicsNAV://MyServer/DynamicsNAV90/CRONUS International Ltd./RunPage?Page=22"

This example specifies a server name, service, company, and page ID. If entered correctly, it opens the Microsoft Dynamics NAV Windows client on page 22, the customer list page.

An equivalent URL that you could type in a browser’s address bar is:

Copy Code
DynamicsNAV://MyServer/DynamicsNAV90/CRONUS%20International%20Ltd./RunPage?Page=22

Note that in a URL, you must use encoding for special characters.

Tip
You can also use the GETURL function to automatically generate URLs when your code runs. For example, if you want to automatically open a specific page when a trigger is called, you can implement this programmatically by using the GETURL function. The URLs are then generated automatically and the Microsoft Dynamics NAV Server instance is automatically inserted. You can generate URLs using this method that will work in the Microsoft Dynamics NAV Windows client, Microsoft Dynamics NAV Web client, and in SOAP and OData web services. For more information, see GETURL Function.

Building a URL

When you build a hyperlink URL, you can specify a page, report, query, XMLport, codeunit, table, or node. The following examples illustrate URLs that open objects in the Microsoft Dynamics NAV Windows client, but you can also generate URLs that open objects in the Microsoft Dynamics NAV Web client:

  • DynamicsNAV://server/instance/company/runpage?page=22&bookmark=0ABA0700235752C7D1

  • DynamicsNAV://server/instance/company/runreport?report=901

  • DynamicsNAV://server/instance/company/runquery?query=5402

  • DynamicsNAV://server/instance/company/runxmlport?xmlport=5050

  • DynamicsNAV://server/instance/company/runcodeunit?codeunit=5845

  • DynamicsNAV://server/instance/company/navigate?node=Home/Items

  • DynamicsNAV://server/instance/company/RunTable?Table=18

The first three parameters that open a Microsoft Dynamics NAV client URL are reserved for server, service, and company. You can omit certain parameters, in which case default values are assumed, but you must leave the correct number of forward slashes to indicate which parameters you have omitted. If you omit just one of these parameters, then it must be company. If you omit two parameters, then they must be company and instance. You can also omit all three parameters. For example, the following URL assumes the default instance and company on the MyServer server:

Copy Code
DynamicsNAV://MyServer///RunPage?Page=22

You can also specify a server port:

Copy Code
DynamicsNAV://MyServer:1234///RunPage?Page=22

This URL omits server, service, and company:

Copy Code
DynamicsNAV://///navigate?node=Home/Items

Specifying Additional Parameters

You can also specify the following additional parameters in a URL.

Parameter | Description | Example
Personalization ID | Specifies the unique identification that is used in personalization to store settings in the User Metadata table. If a personalization ID is not found, the page is opened without personalization. | DynamicsNAV://localhost/DynamicsNAV90/CRONUS%20International%20Ltd./runpage?page=22&personalization=0000232e-0000-001a-0008-0000836bd2d2
Bookmark | Positions the cursor on a single record in a table. Only automatically generated bookmarks should be used. If you enter an incorrect bookmark, you will get an error message. | DynamicsNAV://localhost/DynamicsNAV90/CRONUS%20International%20Ltd./runpage?page=22&bookmark=120000000089083237343
Mode | Enables you to open a page in a specific mode, which include view, edit, create, select, and delete. | DynamicsNAV://localhost/DynamicsNAV90/CRONUS%20International%20Ltd./runpage?page=22&mode=View
Filter | Enables you to open a page with a specific filter applied. In the example, you open the customer list filtered to customer number 10000. | DynamicsNAV://localhost/DynamicsNAV90/CRONUS%20International%20Ltd./runpage?page=22&$filter='No.'%20IS%20'10000'

Understanding Syntax for Creating Hyperlinks

The following table shows some examples of hyperlinks and provides information about how to specify parameters.

Parameters | Description | Syntax | Example
Company name | Enables you to switch a company (case- sensitive). | DynamicsNAV:////<CompanyName>/RunPage?Page=<pageid> | DynamicsNAV:////CRONUS%20International%20Ltd./RunPage?Page=22
Navigate | Enables users to send or save quick links to specific pages. | DynamicsNAV://///navigate?node=<service> | DynamicsNAV://///navigate?node=Home/Items
RunPage | Enables you to run a specific page. | DynamicsNAV:////runpage?page=<page id> | DynamicsNAV:////runpage?page=42
Filter | Enables you to run a specific page with a specific filter applied. | DynamicsNAV////runpage?page=<page id>&$filter='<field>'%20IS%20'<value>'[%20AND%20'<field>'%20IS%20'<value>'] | DynamicsNAV:////runpage?page=22&$filter='No.'%20IS%20'10000'
RunReport | Enables you to run a specific report. | DynamicsNAV:////runreport?report=<report id> | DynamicsNAV:////runreport?report=50000
RunQuery | Enables you to run the About This Query page for a specific query. | DynamicsNAV:////runquery?query=<query id> | DynamicsNAV:////runquery?query=50000
RunXMLport | Enables you to run a specific XMLport. | DynamicsNAV:////runxmlport?xmlport=<xmlport id> | DynamicsNAV:////runxmlport?xmlport=99008500
RunCodeunit | Enables you to run a specific codeunit. | DynamicsNAV:////runcodeunit?codeunit=<codeunit id> | DynamicsNAV:////runcodeunit?codeunit=50000
RunTable | Enables you to run a specific table. | DynamicsNAV:////runtable?table=<table id> | DynamicsNAV:////runtable?table=18
Server name | Enables you to switch servers. | DynamicsNAV://<ServerName>///RunPage?Page=<pageid> | Microsoft.Dynamics.Nav.Client.exe DynamicsNAV://MyServer///RunPage?Page=22
Server port | Enables you to specify an optional server port number in the range 1-65535. The default port is 7046. | DynamicsNAV://<ServerName><:Port>///RunPage?Page=<pageid> | DynamicsNAV://MyServer:1234///RunPage?Page=22
Service instance | Enables you to specify a Service instance. You can find this value in the CustomSettings.config file. If you specify an instance you must also specify a server. | DynamicsNAV://<ServerName>/<ServiceInstance>//RunPage?Page=<pageid> | Microsoft.Dynamics.Nav.Client.exe DynamicsNAV://MyServer/DynamicsNAV//RunPage?Page=22

Specifying Encoding in Company Names

When you enter a company name at a command prompt, enclose it in quotation marks to make sure that spaces and other special characters are read correctly. For URLs, use percent encoding to handle any characters above 127 in the ASCII character set.

Running Hyperlinks

The following table shows the different ways in which you can run hyperlinks.

Warning
Some page links are longer than 255 characters, which is the maximum length for the Windows Run window. A link longer than 255 characters cannot be run from the Run window.

Method | To run a hyperlink
Run window | Choose Start, and then choose Run. Enter the hyperlink in the Run window. Choose the OK button.
Command prompt window | At the command prompt, type the hyperlink directly.
Shortcut | Create a shortcut for the Microsoft Dynamics NAV executable on your desktop. On the shortcut menu, choose Properties, and then enter the hyperlink URL in the Target field of the shortcut. Choose the OK button, and then start Microsoft Dynamics NAV.
Browser window | Use a browser such as Internet Explorer and type the hyperlink URL directly in the address bar. To type hyperlinks in a browser, you must have Microsoft Dynamics NAV installed on your computer.
Web reference for a web service | For more information, see SOAP Web Services and OData Web Services.
Programmatically | Use the GETURL function to generate a URL that opens objects in the Microsoft Dynamics NAV Windows client, Microsoft Dynamics NAV Web client, or a SOAP or OData web service and automatically inserts the Microsoft Dynamics NAV Server configuration. For more information, see GETURL Function.

See Also

Starting the Windows Client at the Command Prompt

Tasks

How to: Run Reports

Reference

GETURL Function

Concepts

SOAP Web Services
OData Web Services


How to: Customize Data Displayed in a Drop-Down Control Using Field Groups

In the Microsoft Dynamics NAV Windows client, some fields are enabled with filter-as-you-type functionality. When you type text into these fields, a drop-down control appears that displays data from a source table. For example, in the sell-to-customer-no field on the Sales Orders page, records from the Customer table are displayed when you use this control.

If you do not define any field groups for the drop-down control, by default you only see data from two fields in the source table; the primary key and description fields, as these are indexed automatically.

To specify which fields are displayed in the drop-down control, you must use field groups. If you select the appropriate fields in the field groups table, you can help users to quickly find the data they need, without scrolling through multiple records. For example, if you define field groups on the Items table you can help the order processor to create new customer orders more easily. On the Sales Order card page, she can find specific items for the order, such as 2-inch nails, by using filter-as-you-type, and the drop-down control linked to the Items table. This could be very useful when creating a new customer order over the telephone.

Adding Fields to the Field Groups Table

You can add or remove field groups from the Field groups table, using Table Designer.

To add fields to the field groups table

  1. In the development environment, on the Tools menu, choose Object Designer to open the Object Designer window.

  2. In Object Designer, choose Tables, select a table, and then choose the Design button to open Table Designer. For example, select table 18, the Customer table.

  3. To open the Field Groups table, select any row, choose View, and then choose Field Groups.

  4. Select the first row in the Field Groups table, and in the Name field, type DropDown.

  5. In the Groups field, choose the AssistButton to open the Field List table.

  6. In the Field List table, make a selection from the fields in the source table. If you want to select more than one row, select a row, and then use the Shift key to select multiple rows. Choose the OK button to add the fields to the Field Groups table.

  7. Close the Field List table, and the Field Groups table. Choose Save and Compile.

  8. Run the Microsoft Dynamics NAV Windows client to view your changes.

    For example, open the Edit Sales Order card page 1003, and then choose Sell-to Customer No. The fields that you added to the Customer table, using field groups, are now displayed in the drop-down control for that field.

    Follow the same procedure to remove fields, or to change the order of fields displayed in the drop-down control.

See Also

Tasks

Walkthrough: Creating a Customer Card Page in Page Designer


How to: Style Field Text on a Page

A page field control includes the Style Property that you use to format the text that displays in a page field. The Style property has ten values that apply different formats to field text.

The following table describes the values and the corresponding format.

Value | Format
Standard | Standard
StandardAccent | Blue
Strong | Bold
StrongAccent | Blue + Bold
Attention | Red + Italic
AttentionAccent | Blue + Italic
Favorable | Bold + Green
Unfavorable | Bold + Italic + Red
Ambiguous | Yellow
Subordinate | Grey

By using the field's StyleExpr Property, you can specify whether formatting is applied to the field based on the field’s data.

Always Applying a Format to Text in a Page Field

Use the following procedure to apply formatting to field text on a page at all times.

To format field text

  1. Open the page in Page Designer.

  2. Select the field that you want to format, and on the View menu, choose Properties.

  3. Set the Style property value to one of the formats that are described in the preceding table.

  4. Set the StyleExpr property value to True.

Applying Conditional Formatting to Text in a Page Field Control

By using a page field's StyleExpr property, you can apply the format that is specified by the Style property to a field based on the field's data. For example, you can display text in red if the value of the field is a negative number, italic red if an item is low in stock, or bold green to indicate a favorable value, such as a high credit limit.

To set up this formatting, you define a Boolean variable and add C/AL code to the page that evaluates the field's data. The C/AL code should return the Boolean variable as True when the data meets the conditions for which you want to apply the formatting. You then set the variable on the field's StyleExpr property.

To define a variable to use to format field text

  1. Open the page in Page Designer.

  2. On the View menu, choose C/AL Globals.

  3. Define the variable, and then set the DataType to Boolean.

  4. On the View menu, choose Properties to open the variable's properties, and then set the IncludeInDataSet to Yes.

    Note
    If the IncludeInDataSet Property is not set to Yes, then when you run the page, you will receive an error that states that the identifier variable could not be found.

  5. On the View menu, choose C/AL Code, and then add C/AL code that sets the variable.

    Note
    The variable must evaluate to True.

To set the variable to the StyleExpr property of the page field

  1. In Page Designer, select the field that you want formatted, and open the Properties window.

  2. Set the Style property value to one of the formats that are described at the beginning of this topic.

  3. Set the StyleExpr property value to the variable that you defined in the previous procedure.

See Also

Reference

Style Property
StyleExpr Property
IncludeInDataSet Property


Field Arrangement on FastTabs

This topic describes how individual fields are arranged on a FastTab and ways that you can change the layout.

How Fields are Arranged on a FastTab of a Page

By default, a FastTab is divided into two columns for containing fields. Fields are automatically distributed between the left and right columns based on their order in Page Designer and height on the rendered page. Starting with the first field in the Page Designer and working downward, fields are positioned in the left column and then in the right column so that the area that is occupied by the fields in each column is as equal as possible. Field captions are positioned to the left of fields.

For example, the following figure shows Page Designer for a FastTab setup with five fields.

Shows FastTab setup in Page Designer

The following figure illustrates the field layout on the rendered page.

Shows a FastTab setup of fields in Page Designer

Grouping Fields on a FastTab

By using the Group subtype control in a FastTab, you can include fields on a FastTab in separate groups. This gives you some control over how fields are distributed between the left and right columns. When you group fields on a FastTab, the groups and not the individual fields are distributed evenly between the left and right columns.

For example, the following figure shows Page Designer for a FastTab setup that includes three groups.

A FastTab setup with field groups in Page Designer

The following figure illustrates the groups and field layout on the rendered page.

Shows how field groups layout in a FastTab

Manually Arranging Fields in Multiple Rows and Columns

Using the GridLayout or FixedLayout controls, you can arrange fields in multiple rows and columns in a grid-like format. For more information, see Arranging Fields in Rows and Columns.


Arranging Fields in Rows and Columns

By default, page fields are arranged automatically in two columns. For more information, see Field Arrangement on FastTabs. You can use a GridLayout control or a FixedLayout control to arrange fields in rows and columns on page. This topic outlines the differences between the two controls to help you determine which control to use.

Comparing GridLayout and FixedLayout Controls

The GridLayout control is a new control and is the preferred method because it gives you more layout options and is generally easier to use. The following table outlines the GridLayout and FixedLayout control characteristics and their differences.

Characteristics | GridLayout | FixedLayout
General usage and field layout | Places fields in a uniform grid. When setting up a grid layout, you can decide to set up fields in a row-by-row or column-by-column basis. | Places fields in a table or matrix-like configuration that has a row and column headings. You can only set up fields on a column-by-column basis. You typically use the FixedLayout control to display statistical data in a FastTab or information in the details section of a Worksheet page. If you are using the CRONUS International Ltd. demonstration database, then you can see examples of these uses in page 151, Customer Statistics, and page 40, Item Journal.
Field captions | Shows or hides captions above each field. Place captions before or above the field. | Shows captions as a heading to the rows and columns. You cannot specify a heading for each field.
Row and column spanning | Can span rows and columns. | Cannot span rows and columns.
Field appearance | Shaded with a border. | No shading or border.

See Also

Tasks

How to: Arrange Fields in Rows and Columns Using the GridLayout Control
How to: Arrange Page Fields in Rows and Columns Using a FixedLayout Control


How to: Arrange Fields in Rows and Columns Using the GridLayout Control

By default, fields in a FastTab are arranged automatically in two columns that are based on the number of fields. You can use the GridLayout control to arrange the fields manually in one or more rows and columns. The GridLayout control gives you the following options:

  • Set up your grid row-by-row or column-by-column.

  • Span a field across multiple rows and columns.

  • Show or hide field captions.

The following figure illustrates a page that uses the GridLayout control to display fields from table 18, Customer, in the CRONUS International Ltd. demonstration database. The fields are arranged in four rows.

Sales order fields in a grid

The following figure shows Page Designer for the GridLayout example.

Page Designer for GridLayout of sales order

Setting Up Fields in Rows and Columns on a Page

To add rows and columns of fields to a page, you set up a GridLayout control in a FastTab of the page. When you set up the GridLayout control, you specify whether fields are arranged in rows or columns. After you set the GridLayout control, you can add fields in rows and columns of fields by adding Group controls under the GridLayout control. Each Group control defines either a row or column, depending on the setup of the GridLayout control.

To set up a GridLayout control in a FastTab

  1. In Page Designer, open a page.

  2. Insert a row, and then set the Type column to Group.

    This defines the FastTab that contains the fields of the grid.

  3. To specify a heading for the FastTab, type the text in the Caption column.

  4. Under the new Group control, insert a row, and then set the Type column to Group and the Subtype column to GridLayout.

  5. Select the new GridLayout control, and on the View menu, choose Properties.

  6. In the Properties window, in the Value column of the Layout property, choose the drop-down arrow. Set the Layout Property as follows:

    1. Select Rows to set up fields row-by-row.

    2. Select Columns to set up fields column-by-column. This is the default setting.

To add a row or column of fields to the GridLayout control

  1. In Page Designer, under the GridLayout control, insert a row, and then set the Type column to Group and the Subtype column to Group.

    This defines a container for the row or column of fields, depending on the value that you set the Layout property to in the previous procedure.

  2. To specify a heading for the row or column, type the text in the Caption field of the Group control.

    Note
    If you are setting up a row, then a colon is automatically added to the end of a row heading on the rendered page.

  3. To add fields to the row or column, do the following:

    1. Under the Group control, insert a blank line, and then set the Type column to Field.

    2. In the SourceExpr column, type the name of the data source, such as a field in the table that is associated to the page.

    3. To include a caption for the field, type the text in the Caption column.

      Note
      By default, field captions display above the field. If you want to hide or reposition the caption, then see Hiding Field Captions.

Setting Fields to Span Multiple Rows and Columns

You can set a field to span multiple rows or columns. When you set a field to span multiple rows, the field occupies the cells in the rows below it, and existing fields in the occupied cells are moved to the right. For example, the following figure illustrates a GridLayout control that consists of six fields arranged in three rows.

GridLayout control with 3 rows and 3 columns

If you set Field 2 to span two rows, then the following layout is displayed:

GridLayout control with field that spans 2 rows

When you set a field to span multiple columns, the field occupies the cells in the columns to the right, and existing fields in the occupied cells are moved to the right. Using the previous GridLayout example, if you set Field 2 to span two columns instead of two rows, the following layout is displayed:

GridLayout control with field that spans 2 columns

You can also set a field to span multiple rows and columns. For example, if you set Field 2 to span two rows and two columns, the following layout is displayed:

GridLayout with field that spans 2 row and column
Important
The Microsoft Dynamics NAV Web client does not support row and column spanning for fields. If the page displays in the Microsoft Dynamics NAV Web client, the fields appear without spanning.

To set a field to span rows and columns

  1. Under the GridLayout control, select the field that you want to set to span rows or columns, and then on the View menu, choose Properties.

  2. In the Properties window, do the following:

    • To set a field to span one or more rows, set the value of the RowSpan Property to the number of rows.

    • To set a field to span one or more columns, set the value of the ColumnSpan Property to the number of columns.

Hiding Field Captions

To hide a field caption

  1. Select the field, and then on the View menu, choose Properties.

  2. In the Properties window, set the value of the ShowCaption Property to No

See Also

Concepts

Arranging Fields in Rows and Columns
Field Arrangement on FastTabs


Arranging Fields in Rows and Columns Using a FixedLayout Control

This topic describes the layout and behavior of fields in a FixedLayout control on a page. You use the FixedLayout control to arrange page fields in rows and columns, similar to a matrix, except that the FixedLayout control contains a specific number of fields, and a matrix can contain an unspecified number of fields. You typically use the FixedLayout control to display statistical data in a FastTab on a page or information in the details section of a Worksheet page. If you are using the CRONUS International Ltd. demonstration database, then you can see examples of these uses in page 151, Customer Statistics, and page 40, Item Journal.

Adding Fields

In Page Designer, you include a FixedLayout control under a group control. You can add fields directly under the FixedLayout control as shown in the following Page Designer example that contains four fields.

FixedLayout without grouping in Page Designer

The following illustration shows the resulting field layout on a page.

FixedLayout illustration of a single row of fields

It is important to notice that there are no captions for the fields.

Grouping Fields in a Fixed Layout Control

By placing the fields in a FixedLayout control throughout a group control, you can define separate rows and columns to create a matrix-like arrangement. The following illustration shows a Page Designer example that adds four fields of the FixedLayout control in a group control.

FixedLayout with grouping in Page Designer

The following illustration shows the resulting field layout on a page.

FixedLayout illustration showing 4 fields

The group control caption appears as the column header, and the field control captions appear as the row headers. If you add two more group controls that contain fields, then the layout on the page will resemble the following illustration.

FixedLayout of fields in multiple groups

Only the field captions for the first group control appear. The field captions in other group controls are ignored.

Multiple Fixed Layouts

You can also set up more than one FixedLayout control in a group control. For example, the following illustration shows the page layout if you have four FixedLayout controls.

FixedLayout of fields in a single group

The page area is divided into two columns that contain the separate FixedLayout fields.

Note
The fields in the FixedLayout controls in the illustration are not in a group control. If they were in a group control, then they would follow the same principle as described in the previous section about how to group fields.

Editing Fields in a Fixed Layout

Fields in a fixed layout are not editable even if the Editable Property property is set to TRUE. However, if the field drills down to a page where the field source is defined, then you can modify the field.

See Also

Tasks

How to: Arrange Page Fields in Rows and Columns Using a FixedLayout Control
How to: Arrange Fields in Rows and Columns Using the GridLayout Control

Concepts

Arranging Fields in Rows and Columns


How to: Arrange Page Fields in Rows and Columns Using a FixedLayout Control

This topic describes how to use a FixedLayout group control on a page to arrange page fields in rows and columns, similar to a matrix. A FixedLayout group control is typically used to display statistical data. The following illustration shows an example of a page that uses a FixedLayout control to show sales totals for different time periods.

Screenshot of a FixedLayout example

Fields in a FixedLayout group control are displayed in a FastTab with a heading for each row and column. For more information about the FixedLayout group control, see Arranging Fields in Rows and Columns Using a FixedLayout Control.

Important
Previous versions of Microsoft Dynamics NAV supported having a FixedLayout control directly under a ContentArea. In Microsoft Dynamics NAV 2013 and later versions of Microsoft Dynamics NAV, you must make sure that the FixedLayout control is nested in a Group control. For more information, see Recommended Usage of GridLayout and FixedLayout.

To arrange page fields in rows and columns

  1. Open the page in Page Designer.

  2. In Page Designer, insert a blank line where you want to locate the fields.

  3. Set the Type and SubType field to Group. In the Caption field, type the text that you want as the heading of the FastTab that contains the fields.

  4. On the next line, set the Type to Group and SubType field to FixedLayout.

  5. On the next line, set the Type and SubType field to Group. This defines the placeholder for the first column of fields. To add a heading to the column, type the text in the Caption field.

  6. On the next line, set the Type to Field. This defines the first field in the column. In the Caption field, type the text that you want to use as the heading for the row.

  7. Specify the data source for the field by doing one of the following:

    • If the data source is a field of the table that is associated with the page, then on the View menu, choose Field Menu, select the field, and then choose the OK button.

    • If the data source is a variable, then on the View menu, choose C/AL Globals or C/AL Locals, and then create the variable. After you create the variable, in the SourceExpr field in Page Designer, choose the AssistEdit button and select the variable.

  8. Repeat steps 6 and 7 to add the remaining fields in the first column.

    The following illustration shows a Page Designer example that has four fields.

    FixedLayout group example in Page Designer

  9. Repeat steps 5 through 8 to add group controls that define the remaining columns.

    Note
    You do not need to specify captions for these fields. Only the captions of fields in the first column define the row headings.

See Also

Tasks

How to: Arrange Fields in Rows and Columns Using the GridLayout Control

Concepts

Arranging Fields in Rows and Columns


Recommended Usage of GridLayout and FixedLayout

This topic explains some important guidelines for working with the GridLayout and FixedLayout controls. For more information about GridLayout, see How to: Arrange Fields in Rows and Columns Using the GridLayout Control. For more information about FixedLayout, see Arranging Fields in Rows and Columns Using a FixedLayout Control.

Required Structure Using a GridLayout or FixedLayout Control

For both the GridLayout and the FixedLayout controls, the following illustration shows the structure that is required to get the layout results that you expect.

The required structure of a GridLayout control
  • The GridLayout and the FixedLayout control must be placed in a Group control in a ContentArea subtype. The Group control does not have to be the first group under the ContentArea.

    Important
    If the GridLayout or FixedLayout control is not placed in a Group control, it will inherit properties as if it were a typical Group control and none of the GridLayout or FixedLayout properties will apply to it.

  • The GridLayout or FixedLayout control must have Group controls as direct children and Field controls as children of those Group controls.

    Important
    If this structure is not in place, the Field controls will not be displayed.

Supported Control Types for a GridLayout Control

The GridLayout control is supported on all page types and for a selected range of control types. The following table lists the types of controls that can be nested in a GridLayout control.

Tip
Although nesting groups such as Group, FixedLayout, and GridLayout is possible, we do not recommend it because of lower UI performance and less optimal layout.

Control Type | Control Subtype
Fields |
Groups | Group
 | Repeater
 | CueGroups
 | FixedLayout
 | GridLayout
Part | Page

The following table lists the types of controls that are not supported in a GridLayout control.

Control Type | Control Subtype
Add-Ins |
Parts | Chart Parts
 | System Parts
Containers (level 0 is supported) |

See Also

Tasks

How to: Arrange Fields in Rows and Columns Using the GridLayout Control
How to: Arrange Page Fields in Rows and Columns Using a FixedLayout Control


Including Microsoft Dynamics Online Connect on Role Centers

Microsoft Dynamics NAV 2016 includes a control add-in that you can use on Role Centers to display role-based content from Microsoft Dynamics Online Connect. Connect is a Web service that distributes Microsoft Dynamics product and business information from sources such as CustomerSource and the Microsoft Dynamics community. The information that Connect provides on a Role Center is based on the Role Center's profile or a profile that the Role Center user chooses. If the content is available in different languages, then content is displayed in the language that matches language that is defined for the Role Center user.

To set up a Role Center with Connect, you create a card part page that contains the Connect control add-in and then use the card part page on the Role Center. For more information, How to: Include Microsoft Dynamics Online Connect on Role Centers.

If you have installed the Microsoft Dynamics NAV demo database, then Connect is already added by default on several Role Centers.

Supported Profiles and Default Role Centers

The following table lists the Role Center profiles that are supported by Connect and the Role Centers that use the profiles by default when you install the Microsoft Dynamics NAV demo database.

Note
Whether the Connect part is visible on a Role Center is specified by the Visible Property of the Role Center page.

Role Center ID | Profile ID | Visible by default
9000 | Shipping and Receiving - WMS | no
9001 | Accounting Manager | yes
9002 | Accounts Payable Coordinator | no
9003 | Accounts Receivable Administrator | no
9004 | Bookkeeper | no
9005 | Sales Manager | yes
9006 | Order Processor | no
9007 | Purchasing Agent | no
9008 | Shipping and Receiving | no
9010 | Production Planner | yes
9011 | Shop Supervisor - Foundation | no
9012 | Shop Supervisor | no
9014 | Resource Manager | yes
9015 | Project Planner | yes
9016 | Dispatcher | no
9018 | IT Manager | yes
9019 | President | yes
9020 | President - Small Business | yes

User Personalization of Connect

If a Role Center is set up with Connect, then a user has the following options to personalize the Role Center:

  • Show or hide the page part that contains Connect.

    The user can do this by choosing the Customize button in the Role Center. For more information, see the Microsoft Dynamics NAV Help from the Microsoft Dynamics NAV Windows client.

  • Change the profile that is used by Connect.

    The user changes the profile from within the Connect content. The profile that the use selects overrides the profile that is assigned to the Role Center.

  • Sign in to Windows Live™.

    When a user signs in to Windows Live, additional content is available that is based on the user's CustomerSource account.

Information Sent from the Role Center to Connect

When a Role Center opens, the Connect control add-in sends the following information about the Microsoft Dynamics NAV software over the Internet to Microsoft:

  • Product name

  • Product version

  • Some license information, but not the license number

  • Country/region version

  • Language

  • Profile, which is based on the Role Center ID

Internet Access and Security

If you make Connect available to users, then they will require Internet access to use the service. If you have not previously offered Internet access to users, then you should consider the security implications before implementing Connect. For more information, see Microsoft Dynamics Online Connect.

See Also

Tasks

How to: Include Microsoft Dynamics Online Connect on Role Centers

Concepts

Installing and Configuring Windows Client Control Add-ins on Pages


How to: Include Microsoft Dynamics Online Connect on Role Centers

The RoleTailored client installation includes a control add-in that you can use on Role Centers to connect to and display information from Microsoft Dynamics Online Connect. The information from Connect is based on the Role Center's profile. The Connect control add-in is provided in the Microsoft.Dynamics.NAV.Client.DynamicsOnlineConnect.dll assembly file. By default, the assembly is installed on the computer running the RoleTailored client in the C:\Program Files\Microsoft Dynamics NAV\90\RoleTailored Client\Add-ins\Connect folder. Setting up the control add-in for Connect is similar to other control add-ins. For more information, see Installing and Configuring Windows Client Control Add-ins on Pages and Including Microsoft Dynamics Online Connect on Role Centers.

Note
If you make Connect available to users, then they will require Internet access to use the service. If you have not previously offered Internet access to users, then you should consider the security implications before implementing Connect. For more information, see Microsoft Dynamics Online Connect.

Setting up Connect with the Demo Database Installed

If you installed the Microsoft Dynamics NAV demo database, then the Connect control add-in is set up by default on several Role Centers that use the profiles that are supported by Connect. To see a list of the profiles and the associated Role Centers, see Including Microsoft Dynamics Online Connect on Role Centers.

The demo database contains the page 9175 Connect, which hosts the Connect control add-in. You use this page to set up Connect on your own Role Centers as described in the following procedure.

To set up a Connect on a Role Center with the demo database installed

  1. Create the Role Center page that has a part that targets the page 9175 Connect.

    For more information, see Walkthrough: Creating a Role Center.

  2. Assign the Role Center to a profile that is supported by Connect.

    Note
    You can also use a profile that is not supported by Connect. In this case, when the Role Center opens, the user is prompted to choose a supported profile.

Setting up Connect Without the Demo Database Installed

Use the procedure in this section to set up Role Centers with Connect if you have not installed the demo database.

To set up Connect on a Role Center without the demo database installed

  1. Register the Connect control add-in in the Client add-in table of the Microsoft Dynamics NAV database. You must provide the following information:

    • Control add-in name - Microsoft.Dynamics.NAV.MicrosoftDynamicsOnlineConnectControl

    • Public token key - 31bf3856ad364e35

    For more information, see How to: Register a Windows Client Control Add-in.

  2. Use the Connect control add-in on a page.

    For more information, see How to: Set Up a Windows Client Control Add-in on a Page.

  3. Create the Role Center page and include a part that uses the Connect page from step 2.

    For more information, see Walkthrough: Creating a Role Center.

  4. Define the Role Center profile that is supported by Connect and assign it your Role Center.

    For more information, see How to: Create a Profile.

    Note
    You can also use a profile that is not supported by Connect. In this case, when the Role Center opens, the user is prompted to choose a supported profile.

See Also

Concepts

Including Microsoft Dynamics Online Connect on Role Centers
Installing and Configuring Windows Client Control Add-ins on Pages


How to: Change Department Icons in the Windows Client

To change an icon that is displayed with a department on the Departments page of the Microsoft Dynamics NAV Windows client, you use the Microsoft Dynamics NAV Development Environment to configure the MenuSuite object that is used by the Microsoft Dynamics NAV Windows client. Each button in the MenuSuite corresponds to a department in the Microsoft Dynamics NAV Windows client and each button includes a Bitmap Property that you use to specify its icon. To display an icon with a department in the Microsoft Dynamics NAV Windows client, you enter a bitmap ID. The bitmap ID corresponds to an icon that is displayed with the department in the Microsoft Dynamics NAV Windows client.

To change a Department icon

  1. In the development environment, open the MenuSuite object for the Microsoft Dynamics NAV Windows client as follows:

    1. On the Tools menu, choose Object Designer, and then choose the MenuSuite button.

    2. In Object Designer, select the MenuSuite that you want to modify, and then choose the Design button.

  2. In navigation pane on the left, select the department menu button that you want to change, and on the shortcut menu, choose Properties.

  3. In the Bitmap field, enter the ID of the icon that you want to appear with the department in the Microsoft Dynamics NAV Windows client. The bitmap ID values that are valid are 0 through 15.

    The following illustration shows the bitmap ID and the corresponding icons that are displayed with the department in the Microsoft Dynamics NAV Windows client.

    Images for departments in RoleTailored client

  4. Choose the OK button.

See Also

Tasks

How to: Modify a Department Menu in a MenuSuite

Reference

Bitmap Property
Menu Properties

Concepts

Designing MenuSuites


Making a Page or Report Available From Search in the Windows Client

The Microsoft Dynamics NAV Windows client includes a Search box that lets users find pages and reports based on the objects name. The search feature finds only pages and reports that can be accessed from the navigation pane, which includes the Home button, Activity buttons, and Departments. If you want to make a page or report available from the Search box, then add it to the Home button, an Activity button, or Departments.

For information about how to add pages and reports to the Home and Activity buttons, see Setting Up the Home Button and Home Items or Creating Activity Buttons for the Navigation Pane.

To include a page or report under Departments, you add the page or report to the MenuSuite of the Microsoft Dynamics NAV Windows client. For more information, see How to: Modify Menu Items in a MenuSuite.

See Also

Concepts

Pages
Reports
MenuSuites


Setting Up Cues

A Cue is a tile on a page in the Microsoft Dynamics NAV client that provides a visual representation of aggregated business data, such as the number of open sales invoices or the total sales for the month. Cues are designed to give users with a quick status of their daily activities, which acts as a prompt them to take action. You typically add Cues on Role Center pages so that they are readily available to users.

The following figure illustrates a couple of the Cues that are available on Order Processor Role Center in the CRONUS International Ltd. demonstration database.

Cues on the Order Processor Role Center

In This Section

Use the following table to help you start creating and modifying Cues.

To | See
Get an overview of Cue design and how to create and customize Cues. | Creating and Customizing Cues
Set up an indicator on a Cue that changes color based on the value in the Cue. | Setting Up Colored Indicators on Cues
Change the icon that appears on the Cue. | How to: Set Up an Image on a Cue
Change the format of data in the Cue. | Formatting the Data in a Field
Learn how to create a Cue by using a FlowField. | Walkthrough: Creating a Cue Based on a FlowField
Learn how to create a Cue by using a query object. | Walkthrough: Creating a Cue Based on a Normal Field and a Query


Creating and Customizing Cues

This topic provides an overview of Cues and the tasks involved in creating and customizing a Cue for displaying on a page the Microsoft Dynamics NAV clients.

This topic contains the following sections:

  • Cue Design Overview

  • Creating a Table for Cue Data

  • Creating a Page for the Cues

  • Specifying an Image on the Cue

  • Setting up a Drill Down Page on the Cue

  • Formatting the Data in the Cue

  • Adding an Action to the Cue

  • Setting up Colored Indicators on Cues

Note
For step-by-step instructions on many of the tasks discussed in this topic, see Walkthrough: Creating a Cue Based on a FlowField and Walkthrough: Creating a Cue Based on a Normal Field and a Query.

Cue Design Overview

The implementation of a Cue involves the following elements:

  • A table object with a field that holds the data that is contained in the Cue at runtime.

  • A page object that contains the table field and displays the Cue in the Microsoft Dynamics NAV client.

  • Logic that calculates the data to display in the Cue at runtime.

    The logic can consist of a combination of C/AL and Microsoft Dynamics NAV objects, such as tables, queries, and codeunits. How and where you implement the logic will depend on whether the Cue is based on a FlowField or Normal field and what you want to achieve.

Supported Data Types

You can only base Cues on integer and decimal data types. Other data types are not supported and will not display in a Cue.

FlowFields versus Normal Fields

A Cue can be based on a FlowField or Normal field. If you base the Cue on a FlowField, then you add the logic that calculates the data for the Cue to the CalcFormula Property of the FlowField. If you use a Normal field, then you will typically add the logic that calculates the Cue data to a C/AL trigger or function. Unlike a FlowField, where data is extracted from tables, a Normal field enables you to extract data from other objects such as queries.

Creating a Table for Cue Data

The first thing that you must do is to create a table that contains fields that will hold the calculated data to display in the Cues at runtime.

Note
If you already have a table for your Cues, then you can just add a new field to the existing table.

Adding a Field for the Cue Data

For each Cue that you want to display on the page, you must add a Field control in the table. When you add the Field control, specify the following properties.

  1. Set the Data Type Property to Decimal, Integer, or Text, depending on the type of data the Cue will display.

  2. Set the FieldClass Property to FlowField or Normal.

    If field is a FlowField, then set the CalcFormula Property to calculate the Cue data. For more information, see and How to: Create, View, and Edit a Calculation Formula.

Adding a Primary Key Field for FlowFields

A table must have at least one data field. Because a FlowField is based on a calculation, it not considered an actual data field. Therefore, if the Cue table only includes FlowFields, you must add "dummy" primary key field that does not yield any data.

To add primary key, for example, add a field with the name Primary Key, and then set its data type to Code.

Creating a Page for the Cues

After you have a table for holding the Cue data, you create a page that you associate the table, and then add fields on the page for the Cues. Typically, you will create Card Part type page that will be part of the Role Center page.

Adding the Cue Fields

To setup the Cues on a page, you add a CueGroup control, and then for each Cue that you want to display, you add a Field control. The following figure illustrates the Page Designer for a page that contains two Cues.

Page Designer showing cues

Initializing the Cue Fields

You must initialize the Cue fields on the page. To do this, for example, you can add the following C/AL code to the OnOpenPage Trigger.

Copy Code
RESET;
IF NOT GET THEN BEGIN
  INIT;
  INSERT;
END;

Customizing a Cue

This section contains information about how you can change the appearance of the Cues.

Specifying an Image on the Cue

You can specify an image to display on the Cue or you can choose not to display an image at all. You can select from several available images.

For more information, see How to: Set Up an Image on a Cue.

Setting up a Drill Down Page on the Cue

You can set up a Cue to link to a page that displays details about the transactions that make up the data in the Cue. This page is referred to as a drill down page. For example, if the Cue displays the number of open sales orders, then you can set up the Cue to link to list page that includes the sales orders. The page opens when a user selects the Cue.

To set up a drill down page, you can do one of the following:

  • Set the DrillDown Property of the Cue field on the page to the ID of the page that you want to open from the Cue.

  • You can add code to the OnDrillDown Trigger of the Cue field on the page that contains the Cue.

    The OnDrillDown trigger takes precedent over the DrillDown property.

Note
When the Cue is on a Role Center page type, an item that links to the drill down page will automatically appear in the navigation pane of the Role Center under Home if the navigation pane contains an entity of the same type. For example, if you have a Cue named Sales Return Orders - Open, this item will be added to the Sales Return Orders in the navigation pane.

Formatting the Data in the Cue

If the data type on the Cue is a decimal, then you can change how the data is displayed, including converting amounts and unit amounts to another currency, specifying the number of decimal places and thousand separator, and adding characters before or after the value.

For more information, see the Formatting the Data in a Field.

Adding an Action to the Cue

When the Cue is displayed in the Microsoft Dynamics NAV Windows client client, you can add an action next to the Cue that opens a related task. For example, if the Cue displays the open sales orders, then you can add an action the opens the Sale Order card page for creating a new sales order.

To set up an action, open the page that contains the Cue in the development environment, and then add a Control action on the CueGroup control that contains the Cue field. Set the RunObject Property of the action to the object, such as a page, that you want to target.

Note
This is not supported in the Microsoft Dynamics NAV Web client or Microsoft Dynamics NAV Tablet client.

Setting up Colored Indicators on Cues

You can set up Cues to include a colored bar along the top border, which changes color based on the data in the Cue.

For more information, see Setting Up Colored Indicators on Cues.

See Also

Concepts

Setting Up Cues
FlowFields


Setting Up Colored Indicators on Cues

You can set up Cues with an indicator that changes color based on the data values in the Cues. The indicator appears as a bar along the top border of the Cue tile. It provides a visual signal of the status of the Cue's activity, which can indicate various conditions such as favorable or unfavorable to prompt the user to take action.

Cues on the Order Processor Role Center

For example, if a Cue displays open sales quotes, you can set up the indicator to appear green (favorable) when total number of open sales quotes is below 10, and appears red (unfavorable) when the total is greater than 20.

There are two ways that you can set up indicators.

  • Using the Style or StyleExpr property of the Field control that defines the Cue.

    With this method, you set up predefined indicators on a Cue-By-Cue basis.

    For more information, see How to: Set Up Colored Indicators on Cues by Using the Style and StyleExpr Property.

  • Coding the GetCueStyle trigger in codeunit 1

    With this method, you define the logic for the indicators for all Cues in one place. Using the GetCueStyle trigger also enables you to provide customization of the indicators from the Microsoft Dynamics NAV clients.

    For more information, see Setting Up Colored Indicators on Cues by Using Codeunit 1.

See Also

Tasks

Walkthrough: Creating a Cue Based on a FlowField
Walkthrough: Creating a Cue Based on a Normal Field and a Query

Concepts

Creating and Customizing Cues


How to: Set Up Colored Indicators on Cues by Using the Style and StyleExpr Property

You can configure a cue with a colored indicator that appears along its top border to provide a visual indication to users about the value of data in the cue. You can configure the indicator to behave in the following ways.

  • The indicator has a static color.

    In this case, the indicator appears with a specified color at all times. For more information, see Configuring Static Color Indication on a Cue .

  • The indicator changes color conditionally, based on the data in the cue.

    This is the most typical behavior. When the data in the cue hits a specified value, the indicator changes color. There are 4 colors to choose from, which enables you to configure different colors for different data intervals. For more information, see Configuring Conditional Color Indication on a Cue.

You set up the indicator by using the StyleExpr Property and Style Property for the field that defines the cue and, in most cases, by adding C/AL code to the page object.

The following table describes the values of the Style property and the corresponding indicator color. You will need to know these values for whichever behavior that you implement.

Value | Color
Standard | None (uses the background color of cue)
Favorable | Green
Unfavorable | Red
Ambiguous | Yellow
Subordinate | Grey

Configuring Static Color Indication on a Cue

Use the following procedure to configure a colored indicator on the cue that appears at all times.

To configure a static color on a cue

  1. Open the page in Page Designer.

  2. Select the field that you want to format, and on the View menu, choose Properties.

  3. Set the Style property value to one of the formats that are described in the preceding table.

  4. Set the StyleExpr property value to True.

Configuring Conditional Color Indication on a Cue

To configure the indicator to change color conditionally based on the data in the cue field, you use a combination of C/AL code and the StyleExpr property and/or Style property. In the C/AL code of the page which contains the cue, you add code that evaluates the cue field's data and sets a variable based on the evaluation. A typical place to add the code is on OnAfterGetRecord Trigger. The variable can have a data type of Boolean, Codeunit, or Text. You will use the variable on the StyleExpr property of the cue field to determine which color to apply to the indicator. The data type that you use for the variable will depend on what you want to achieve, and it will also influence the configuration. The following table describes the differences when using a Boolean data type compared to a Text or Codeunit data type.

Variable Data Type Description

Boolean

If you use a Boolean variable, you can only configure one color condition for the cue. When the StyleExpr property set to a variable that has a Boolean data type, and the variable is true, then indicator uses the color that is specified by Style property value.

Text or Codeunit

If you use a Text or Codeunit variable, you can configure up to four different color conditions for the indicator.

When the StyleExpr property is set to a variable of the Text or Codeunit data type, the Style property is not used. Instead, the variable must be explicitly set in C/AL code to one of the following values that specify the color: Favorable, Unfavorable, Ambiguous, and Subordinate. These values correspond to the values of the Style property.

To configure color indication by using a Boolean variable

  1. Add C/AL code that evaluates the cue field data and sets a Boolean variable to True when the data meets the conditions for which you want to apply the indicator.

    For example, page 9060 SO Processor Activities in the CRONUS International Ltd. demonstration database contains the cue field "Sales Quotes - Open". You want the indicator to turn red when the number of open sales quotes exceeds 10. To do this, you can add a variable called ColorVar that has the data type Boolean, and then add the following code to the OnAfterGetRecord trigger.

    Copy Code
    IF ("Sales Quotes - Open" > 10) THEN
    ColorVar := TRUE;

  2. Set the cue field's StyleExpr property to the variable.

    For the example in the step 1, you set the property to ColorVar.

  3. Set the Style property on the cue field to the value that corresponds to the color indication that you want.

    For the example, you set the value Unfavorable to configure the color to red.

To configure color indication by using a Text or Codeunit variable

  1. Add C/AL code that evaluates the cue field data and sets a Text or Codeunit variable to one of the following values for each condition that you want color indication: Favorable, Unfavorable, Ambiguous, and Subordinate. For the corresponding colors for these values, see the table in the introduction of this topic

    For example, page 9060 SO Processor Activities in the CRONUS International Ltd. demonstration database contains the cue field "Sales Quotes - Open". You want the indicator to have the following color conditions:

    • Green when the number of open sales quotes is 10 or less

    • Yellow when open sales quotes is greater than 10

    • Red when open sales quotes is greater than 20

    To do this, you can add a variable called ColorVar that has the data type Text or Codeunit, and then add the following code to the OnAfterGetRecord trigger.

    Copy Code
    IF ("Sales Quotes - Open" <= 10) THEN
    ColorVar := 'Favorable'
ELSE IF("Sales Quotes - Open" > 20) THEN
    ColorVar := 'Unfavorable'
ELSE ("Sales Quotes - Open")
    ColorVar := 'Ambiguous';

  2. Set the cue field's StyleExpr property to the variable.

    For the example in the step 1, you set the property to ColorVar.

See Also

Reference

Style Property
StyleExpr Property
IncludeInDataSet Property


Setting Up Colored Indicators on Cues by Using Codeunit 1

Codeunit 1 Application Management includes the GetCueStyle trigger that enables you to set up Cues with indicators that change color based on the value in the Cue.

The GetCueStyle trigger provides a more dynamic way of setting up colored indicators than using the Style and StyleExpr field properties. For example, the CRONUS International Ltd. demonstration database uses the GetCueStyle trigger, together with various pages, tables and codeunits, to give end-users the capability to set up colored indicators directly from the Microsoft Dynamics NAV client.

GetCueStyle Trigger Overview

By default, GetCueStyle trigger has the following definition in codeunit 1 Application Management.

GetCueStyle(TableId : Integer;FieldNo : Integer;CueValue : Decimal) : Text

The GetCueStyle trigger is called when the page that contains the Cue is run.

Important
The trigger is only called if the Style and StyleExpr properties are set to their default values <None> and <FALSE> respectively. If you set these parameters to any value other than the default values, then the GetCueStyle trigger is not called and the Cue indicator is configured according to the Style and StyleExpr properties.

Parameters

The following table describes the parameters of the GetCueStyle trigger.

Parameter | Description
TableId | The ID of the table object that contains the field that holds the Cue value.
FieldNo | The number that is assigned to the table field. This is specified by the field's Field No. Property.
CueValue | The calculated value in the Cue that is stored in the table field at runtime.

Return Value

The GetCueStyle trigger returns a value that has the data type Text. To set the colored indicator, you add C/AL code that sets the return value to one of the following values.

Value | Color
Standard | None (uses the background color of cue)
Favorable | Green
Unfavorable | Red
Ambiguous | Yellow
Subordinate | Grey

Example

To illustrate the use of the GetCueStyle trigger, consider a simple example where you have a Cue on the Role Center that displays the number of open sales quotes. You want to set up the indicator to change color according to the following characteristics:

  • Green when the number of open sales quotes is less than or equal to 10

  • Yellow when open sales quotes is greater than 10

  • Red when open sales quotes is greater than 20

To do this, in Microsoft Dynamics NAV Development Environment, you modify the GetCueValue trigger in codeunit 1 Application Management. First, you assign the return value the name Color, and then you add the following code to the trigger.

Copy Code
IF (CueValue <= 10) THEN
    Color := 'Favorable'
ELSE IF(CueValue > 20) THEN
    Color := 'Unfavorable'
ELSE
    Color := 'Ambiguous';

To see how you can achieve the same results by using the Style and StyleExpr properties for comparison, see How to: Set Up Colored Indicators on Cues by Using the Style and StyleExpr Property.

Note
This is a simple example to illustrate how to use the GetCueSetup trigger to configure colored indicators on a Cues. This example sets up the colored indicators to behave the same for Cues on all Role Centers. In a production environment, you will typically add logic that sets the colored indicators differently for each Cue.

Example from CRONUS International Ltd. demonstration database

CRONUS International Ltd. demonstration database includes the following objects that enable the customization of indicators from the Microsoft Dynamics NAV client. You can use this implementation for your solution as-is or modify it as required.

Microsoft Dynamics NAV object | Description
Codeunit 9701 Cue Setup | This codeunit is called from the GetCueStyle trigger in codeunit 1 Application Management and sets the color of the Cue indicators at runtime.
Page 9701 Cue Setup Administration | This page is used to set up indicators on Cues that are available in the Microsoft Dynamics NAV database. From this page you can set up an indicator for the entire company or for specific users only. This page is typically used by an administrator to specify default settings for the indicators. If the page that contains the Cues is set up with the an action that accesses that opens page 9702 Cue Setup End User, then a user can change or personalize the indicator on a Cue.
Page 9702 Cue Setup End User | This page is used by the end user to personalize the indicators that appear on a page of the Microsoft Dynamics NAV client, such as the Role Center.
Table 9701 Cue Setup | This table stores the customization settings for the individual Cues.

See Also

Concepts

Creating and Customizing Cues
Setting Up Colored Indicators on Cues


How to: Set Up an Image on a Cue

When a field that defines the data in a cue has an integer data type, you can set up the cue to include an image. There are several images from which to choose. For example, if the cue shows the total count of an item such as open sales orders, then you can set the cue to include the stack image, which depicts that total count as a stack of paper. This is the default image. You can also set up the cue so that it does not to include an image.

To set up an image on the cue, you set the Image Property (Fields) of the field that defines the cue as described in the following procedure.

To set up an image on a cue

  1. In the development environment, open the page that contains the cue as follows:

    1. On the Tools menu, choose Object Designer.

    2. In Object Designer, choose Page, select the page, and then choose the Design button.

  2. In Page Designer, select the field that defines the cue, and then on the View menu, choose Properties.

  3. In the Properties window, set the Image property as follows:

    1. Choose the AssistEdit button in the Value field.

    2. In the Image List window, select the image that you want to use for the cue, and then choose the OK button.

      If you do not want to include an image on the cue, then select None.

      To view all the available action images, see Microsoft Dynamics NAV Icon Collection.

  4. Close the Properties window, and then save the page.

See Also

Tasks

Walkthrough: Creating a Cue Based on a FlowField


Formatting the Data in a Field

This topic describes how you can format the appearance of decimal data types in fields of a table, report, or page. For example, you can change how the data appears in a Cue on the Role Center page. To format data, you use a combination of the AutoFormatType Property, AutoFormatExpr Property, and DecimalPlaces Property of the field. These properties work together to enable you to specify the following:

  • Display amounts and unit amounts in another currency.

  • Specify the number of decimal places.

  • Specify whether to display a thousand separator.

  • Specify characters before and after the value, such as currency signs or %.

Implementation Overview

When you use the AutoFormatType and AutoFormatExpr properties to format a field, a trigger called AutoFormatTranslate in codeunit 1 is called. AutoFormatTranslate has ID 12 and takes two parameters: one from the AutoFormatType property and one from the AutoFormatExpr property. The AutoFormatType property can contain one of the following integers: 0, 1, 2, or 10. These settings are described in the next section.

When a field appears on a page or report, you can set the AutoFormatType and AutoFormatExpr properties directly on the page field or report field (column), or you can set them on the underlying table field. If you specify the properties on the table field, then format applies wherever the field is used. Specifying the properties on the page or report field will only apply the format on the specific page or report. If you specify the properties on the table field and the page or report field, then the settings on the page or report field take precedence.

You can see an example implementation of the AutoFormatType logic in the CRONUS International Ltd. demonstration database. In the CRONUS International Ltd. demonstration database, the AutoFormatTranslate trigger calls codeunit 45 AutoFormatManagement which handles the formatting.

Setting up Data Formatting

The settings for the AutoFormatType, AutoFormatExpr, and DecimalPlaces properties will depend on the type of data that is displayed, such as currency amounts and unit amounts or other types of data, such as simple decimals or ratios. For the most part, the AutoFormatType property is the primary setting which determines the options for setting the DecimalPlaces and AutoFormatExpr properties.

The following table describes how to set each of the properties to achieve the format that you want.

AutoFormatType Property DecimalPlaces Property AutoFormatExpr Property Usage Description

0

Set to the number of decimal places that you want to display for the value.

Not applicable. This property is ignored.

Use this configuration when you want to format the decimal value according the Standard Format 0 (which is the default format) with a specific number of decimal places.

For example, if the value is a US decimal -76543.21 and you set the DecimalPlaces property to 0, then the value appears as 76,543.

1

Not applicable. This property is ignored.

Set to return a currency code (the blank currency code denotes LCY).

Use this configuration when you want to format the data as an amount. For example, a sales order will use two decimals when the currency is defined as US dollar and 0 decimals when the currency is defined as IDR (Indonesian rupiah).

2

Not applicable. This property is ignored.

Set to return a currency code (the blank currency code denotes LCY).

This is similar to the previous configuration where the AutoFormatType property is set to 1, except you use this configuration when you want to format the data as a unit amount.

10

Not applicable. This property is ignored.

Set to the property according to the following syntax:

Copy Code
'[Characters]<precision, N:N><standard format, N>[Characters]'

Replace [Characters] with the text that you want before or after the value, such as $ or %.

<standard format, N> specifies which of the standard formats to use. Replace N with the format that you want. For more information, see Standard Formats.

<precision n:N> species the decimal places, where n is the minimum number of decimal places and N is the maximum number of decimal places.

Use this configuration if you want to customize the format based on one of the standard formats. This option enables you to specify characters before and after the decimal value, such as currency signs ($) and percent (%).

For example, if you want to prefix the decimal value with a "$", include a thousand separator, and have a maximum of two decimal places (such as $76,543.21), then you can set the property to the following:

Copy Code
'$<precision, 2:2><standard format, 0>'

If you want to display the decimal value as a percentage, then you can add "%" at the end of the setting, for example, '<precision,1:1><Standard Format,0>%'. When you include a "%" at the end of the setting, then the decimal value is assumed to be a ratio and the decimal value will be multiplied by 100. For example, a value of 0.98 will be formatted to 98%.

Standard Formats

The following table describes the standard formats that are available for the AutoFormatExpr property when the AutoFormatType property is set to 10.

Standard Format | Format Description | Europe Decimal Example | US Decimal Example
0 | <Sign><Integer Thousand><Point or Comma><Decimals> | -76.543,21 | -76,543.21
1 | <Sign><Integer><Point or Comma><Decimals> | -76543,21 | -76543.21
2 | <Sign><Integer><Point or Comma><Decimals> | -76543.21 | -76543.21
3 | <Integer Thousand><Point or Comma><Decimals><Sign> | 76.543,21- | 76,543.21-
4 | <Integer><Decimals><Point or Comma><Sign> | 76543,21- | 76543.21-
9 | XML format | -76543.21 | -76543.21

See Also

Reference

AutoFormatType Property
AutoFormatExpr Property
DecimalPlaces Property

Concepts

Creating and Customizing Cues


CueGroup and Action Behavior

Cues are used on the UI to visually provide a way to show the number of entities in a table and view the entities in a filtered list. For example, the Cue can show the total number of open invoices, sales orders, or credit memos.

In the development environment Cue fields can be grouped inside a CueGroup and appear on, for example, a CardPart page.

Note
It is a best practice to place Actions in the ribbon. If you, however, decide to place Actions on a CardPart page, be aware of the differences in behavior on the display targets as stated in the table below.

Display target CueGroup behavior

Microsoft Dynamics NAV Windows client

  • CueGroup fields are always shown as Cue tiles.

  • Actions are always shown as hyperlinked text.

Microsoft Dynamics NAV Web client

  • CueGroup fields are always shown as Cue tiles.

  • Actions are only shown if there are no Cue fields and then they are shown as Action tiles.

See Also

Tasks

Walkthrough: Creating a Role Center

Reference

Adding the Cue CardPart Page on the Role Center Page


Walkthrough: Creating a Cue Based on a FlowField

This walkthrough demonstrates how to add a Cue on the RoleTailored client. A Cue provides a way to graphically show the number of entities in a table and view the entities in a filtered list. For example, the Cue can show the total number of open invoices, sales orders, or credit memos. As shown in the following illustration, a Cue is an icon that depicts a stack of papers on the page, where the height of the stack indicates the approximate number of entities in an underlying table. A number value on each Cue gives the precise number of entities. The Cue provides a shortcut link to a filtered list page for displaying the entities. You can add actions to a Cue to open related tasks that a user of the Role Center will typically perform.

Shows a Cue in the RoleTailored client

About This Walkthrough

This walkthrough illustrates the following tasks:

  • Creating the Table Field for Cue Data

  • Creating a Cue on a Card Page for the Role Center

  • Adding an Action to the Cue

  • Adding the Cue CardPart Page on the Role Center Page

Roles

This walkthrough demonstrates tasks that are performed by the following user roles:

  • Microsoft .NET developer

  • Microsoft Dynamics NAV developer and IT professional

Prerequisites

To complete this walkthrough, you need:

  • Microsoft Dynamics NAV 2016 with a developer license.

  • All Microsoft Dynamics NAV 2016 requirements met. For more information, see System Requirements for Microsoft Dynamics NAV 2016.

  • The CRONUS International Ltd. demonstration database. The walkthrough uses the following objects:

    • Table 36, Sales Header

    • Page 9006, Order Processer Role Center

    • Page 9301, Sales Invoice List

    • Page 43, Sales Invoice

Story

Viktor is a software developer who is working for CRONUS International Ltd. He has been asked to add a Cue to the Role Centers of sales order processors. The Cue will show how many open sales invoices they have. To accomplish this, Viktor will create a Cue that extracts the number of open sales invoices from the Sales Header table. He will place the Cue in a part on the Order Processor Role Center page. He will also add an action that allows users to create a new sales invoice from a link on the Cue. The Cue will look similar to the illustration earlier in this document.

Creating the Table Field for Cue Data

To calculate the number of open sales invoices, Viktor creates a table that includes a FlowField that extracts data from the Sales Header table and calculates how many opens sales invoices exist. Because a table must have at least one data field, and a FlowField is based on a calculation and not considered an actual data field, Viktor adds a dummy primary key field that does not yield any data. For more information about FlowFields, see FlowFields.

To create a table for the Cue data field and set the primary key

  1. In the Microsoft Dynamics NAV 2016 Development Environment, on the Tools menu, choose Object Designer.

  2. Choose Table, and then choose New.

  3. In the first empty row, in the Field Name column, enter Primary Key and set the Data type to Code.

  4. To set the primary key, select an empty row, and then on the View menu, choose Keys.

  5. In the Keys window, select the first line, and then in the Key column, select the AssistEdit button.

  6. In the Field List window, select the first row, and then choose the up arrow.

  7. Select the Primary Key field, and then choose OK until you return to the Keys window.

  8. Close the Keys window to return to Table Designer.

To add the Cue data field as a FlowField with filters

  1. In Table Designer, in the next empty row, in Field Name, enter Sales Invoices - Open and set the Data type to Integer.

    This defines the Cue data field.

  2. Select the Sales Invoices - Open field row, and then on the View menu, choose Properties.

  3. In the Properties window, set the FieldClass property to FlowField.

  4. In the CalcFormula property, choose the AssistEdit button to open the Calculation Formula window.

  5. In the Calculation Formula window, set the Method field to Count and the Table field to Sales Header.

  6. In the Table Filter field, choose the AssistEdit button to open the Table Filter window.

  7. In the first line of the Table Filter window, choose the up arrow.

  8. In the Sales Header - Field List window, select Document Type, and then choose OK to return to the Table Filter window.

  9. In the Document Type row, set the Type column to FILTER and enter Invoice in the Value column. This filters the Sales Header table on sales invoices.

  10. On the next empty row, and in the Field column, choose the up arrow.

  11. In the Sales Header - Field List window, select Status, and then choose the OK button to return to the Table Filter window

  12. In the Status row, set the Type column to FILTER and enter Open in the Value column. This filters the Sales Header table on open sales invoices.

    The Table Filters window will look similar to the following illustration.

    Shows the table filter setup for a Cue

    Important
    You cannot define a table filter that filters explicitly on a date because you will get an error when you try to open the Cue group in the Microsoft Dynamics NAV Windows client. For example, you cannot define a field that has the Type set to CONST or FILTER and the Value set to 21/03/2011. If you do, when you try to open the Cue group from the page in the Microsoft Dynamics NAV Windows client, you get an error that states that ‘2011-03-21’ is not a valid date.

  13. Choose the OK button until you return to the Properties window, and then close the Properties window to return to Table Designer.

To save the table

  1. On the File menu, choose Save.

  2. In the ID field, enter a number that will serve as a unique table identifier. For example, you can enter 50001.

    Note
    There are restrictions about which numbers you can use. Contact your Microsoft Certified Partner for information.

  3. In the Name field, enter Sales Invoice Cue.

  4. Select the Compiled check box.

  5. Choose the OK button.

Creating a Cue on a Card Page for the Role Center

To display the Sales Invoices - Open Cue on the Role Center, Viktor creates a CardPart page type that has a CueGroup control that includes the Sales Invoices - Open field of the Sales Cue table. Viktor also needs to initialize the data field on the Cue with a record, so he adds code to the OnOpenPage trigger of the CardPart page type.

Important
The CaptionClass property on a field in a CueGroup is not supported.

Warning
While removing cues is possible when customizing the Role Center, activity items cannot be removed.

To create the CardPart page for the Sales Invoice Cue

  1. In the Microsoft Dynamics NAV development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Page, and then choose New. The New Page window opens.

  3. In the Table text box, choose the up arrow to open the Table List window.

  4. Select the Sales Cue table that you created in the previous procedure, and then choose the OK button.

  5. Choose Create blank page, and then choose OK.

    The new page opens in Page Designer.

  6. In the Caption field of the first row, which has the Type set to Container and the Subtype set to ContentArea, enter SalesCueContainer.

  7. Select a blank row, and then on the View menu, choose Properties.

  8. Locate the PageType property, and then set the field to CardPart.

  9. Close the Properties window to return to Page Designer.

To add the Sales Cue on the CardPart page

  1. In the row following the ContentArea row, set Type to Group and set SubType to CueGroup.

    In the Caption column, enter Sales Invoices. The Caption value defines the heading for the Cue that appears on the Role Center.

  2. On the next row, set the Type column to Field.

  3. With the row selected, on the View menu, choose Field Menu.

    The Field Menu window opens and displays the list of available fields from the Sales Invoice Cue table.

  4. Select the Sales Invoices - Open field, and then choose the OK button.

    In the Caption column, enter Open. The Caption value defines the text that appears below the Cue.

    Page Designer should look similar to the following illustration.

    Shows Page Designer setup for a Cue

  5. To create a link from the Cue to the Sales Invoice List page for displaying the open invoices, select the Sales Invoices - Open field row, and then on the View menu, choose Properties.

  6. In the Properties window, set the DrillDownPageID property to Sales Invoice List (9301) and choose the OK button.

  7. Close the Properties window.

  8. To initialize the Cue with a record when the page opens, you must add code to the page's OnOpenPage trigger. In Page Designer, select an empty row, and then on the View menu, choose C/AL Code.

  9. In the C/AL Editor, add the following code in the OnOpenPage trigger:

    Copy Code
    RESET;
IF NOT GET THEN BEGIN
  INIT;
  INSERT;
END;

  10. Close the C/AL Editor.

To save the Sales Invoice Cue CardPart page

  1. On the File menu, choose Save.

  2. In the ID field, enter a number that will serve as a unique page identifier. For example, you can enter 50001 for the ID.

    Note
    There are restrictions about which numbers you can use. Contact your Microsoft Certified Partner for information.

  3. In the Name field, enter Sales Invoice Cue.

  4. Select the Compiled check box.

  5. Choose the OK button.

  6. In Object Designer, select the page 50001, Sales Cue, and choose Run to view the page.

  7. The Microsoft Dynamics NAV Windows client opens and displays the new page.

Adding an Action to the Cue

Viktor wants to add a link on the Cue that allows the user to create a new sales invoice. To accomplish this, he creates an action on the CueGroup control that targets the Sales Invoice page.

To add actions to the Sales Order Cue page

  1. In Object Designer, select the Sales Cue page, and choose the Design button.

    Select the row that contains the CueGroup control Sales that contains the Sales Invoices - Open Cue field.

  2. On the View menu, choose Control Actions.

  3. In the first row of Cue Group Action Designer, in the Caption column, enter New Sales Invoice and set the Type column to Action.

  4. With the first row selected, on the View menu, choose Properties.

  5. In the Properties window, set the values for the following properties:

    • Set the RunPageMode property to Create.

    • Set the RunObject property to page 43, Page Sales Invoice.

  6. Close the Properties window, and then close Action Designer.

  7. Save the page.

Adding the Cue CardPart Page on the Role Center Page

To display the Sales Invoice Cue on the Role Center, Viktor must add the Sales Invoice Cue CardPart page to the Role Center page for sales order processors. To do this, he adds a part to the Order Processor Role Center page that targets the new Sales Invoice Cue page.

To add the Sales Cue part page to the Role Center page

  1. In Object Designer, choose Page to display the list of pages.

  2. Locate page 9006, Order Processor Role Center, and then choose Design.

  3. In Page Designer, locate the Group control in which you want to include the Sales Cue page. For example, you can place the Sales Cue page above the <Connect Online> part.

  4. In Page Designer, select the <Connect Online> part row, and on the shortcut menu, choose New to insert a new row in the group. This will place the Sales Cue part above the <Connect Online> part.

  5. In the new row, set the Type column to Part.

  6. On the View menu, choose Properties.

  7. Set the PartType property to Page.

  8. In the PagePartID property, set the Value column to page 50009, Sales Invoice Cue.

    The Sales Cue page is the CardPart page that you created earlier in this walkthrough.

  9. Choose the OK button, and close the Properties window.

  10. On the File menu, choose Save to save the page.

  11. In Object Designer, with the Order Processor Role Center page selected, choose Run. Notice that the Sales Invoice Cue part is displayed in the Role Center - Order Processor Role Center column and above the Connect Online part.

See Also

Tasks

Touring the RoleTailored Client Pages
Walkthrough: Creating a Role Center

Concepts

Pages Overview
Tables


Walkthrough: Creating a Cue Based on a Normal Field and a Query

This walkthrough demonstrates how to create a Cue that is based on a normal field that derives data from a Microsoft Dynamics NAV query object. The following figure illustrates the Sales This Month Cue that is added by this walkthrough.

Example of a Cue showing sales this month
Note
This walkthrough is a continuation of Walkthrough: Creating a Cue Based on a FlowField.

About This Walkthrough

This walkthrough illustrates the following tasks:

  • Creating a query object for calculating Cue data.

  • Adding a field for a new Cue in an existing table, and adding C/AL code to the field to get the data from the query object.

  • Adding a new Cue to an existing page for displaying the Cue in the Microsoft Dynamics NAV client.

  • Formatting the data in the Cue.

Roles

This walkthrough demonstrates tasks that are performed by the following user roles:

  • Microsoft .NET developer

  • Microsoft Dynamics NAV developer and IT professional

Prerequisites

To complete this walkthrough, you need:

  • Cue table 50001 Sales Invoice Cue and page 50001 Sales Invoice Cue page from Walkthrough: Creating a Cue Based on a FlowField.

    This walkthrough uses these objects which you can create by using the instructions in the Walkthrough: Creating a Cue on a Role Center topic. The actual IDs and names of these objects might be different.

  • Microsoft Dynamics NAV 2016 with a developer license.

  • The CRONUS International Ltd. demonstration database. This walkthrough uses the following objects:

    • Table 21, Cust. Ledger Entry

    • Page 25, Customer Ledger Entries

Story

Viktor is a software developer who is working for CRONUS International Ltd. He has been asked to add a Cue to the Role Centers of sales order processors that shows the total sales for the month. To accomplish this, Viktor will create a Cue that is based on a query object that extracts the total sales for the month from table 21 Cust. Ledger Entry. The company already has a table (50001 Sales Invoice Cue) and page (50001 Sales Invoice Cue) that are used to display open sales invoices on the Order Processor Role Center. Viktor will add the new Cue to these objects.

Creating a Query for Calculating the Cue Data

First, Viktor creates a query object to calculate the number of open sales invoices from table 21 Cust. Ledger Entry.

To create a query for calculating the Cue data

  1. In the Microsoft Dynamics NAV 2016 Development Environment, on the Tools menu, choose Object Designer, choose Query, and then choose New.

  2. In Query Designer, on the first line, set Type column to DataItem, and then set the Data Source column to Cust. Ledger Entry (table ID 21).

  3. Under the DataItem, add a Filter control for the Document Type field and a Filter control for Posting Date field of the Cust. Ledger Entry table. Then, add a Column control for Sales (LYC) field that uses a Totals method type to return a sum from the table. The Query Designer will look similar to the following table.

    Type Data Source Name Method Type Method

    DataItem

    Cust. Ledger Entry

    <Cust. Ledger Entry>

    Filter

    Document Type

    <Document Type>

    Filter

    Posting Date

    <Posting Date >

    Column

    Sales (LYC)

    <Sum_Sales_LCY>

    Totals

    Sum

  4. Save the query as follows:

    1. On the File menu, choose Save.

    2. In the Save As window, in the ID field, enter an ID for the query object, such as 50001. The ID must be in a valid range for your solution.

    3. In the Name field, enter Cust. Ledg. Entry Sales Query.

      Select the Compiled check box, and then choose the OK button.

Adding the Table Field for the Cue Data

Viktor will add a normal field to the table 50001 Sales Invoice Cue for holding the Cue data. He will add a global function that returns the total amount of sales invoices for the current month from the query object that he created in the previous procedure.

To add a field for the Cue data

  1. In the Microsoft Dynamics NAV 2016 Development Environment, open table 50001 Sales Invoice Cue from Object Designer.

  2. Add a new field for the Cue. In the Field Name, enter Sales This Month and set the Data type to Decimal.

    This defines the Cue data field.

    Note
    By default, fields are normal fields as defined by the field's FieldClass Property.

To add C/AL code to the table calculate the Cue data

  1. On the View menu, choose C/AL code to open the C/AL code for the table.

  2. Add a global function that is called CalcSalesThisMonthAmount as follows:

    1. On the View menu, choose C/AL Globals.

    2. On the Functions tab, in the Name column, enter CalcSalesThisMonthAmount.

      By default, all functions are set to local functions as specified by the Local Property, so you must change the function to be global as described in the following steps.

    3. Select the new function, and then in the Tools menu, select Properties.

    4. Set the Local property to No.

  3. In the C/AL Globals window, select the new function, and then choose Locals.

    The C/AL Locals window appears. From her you will add a return value and variables.

  4. On the Return Value tab, set Name field to Amount and the Return Type field to Decimal.

  5. On the Variables tab, add two variables as shown in the following table:

    Name DataType Subtype

    CustLedgerEntry

    Record

    Cust. Ledger Entry

    CustLedgEntrySales

    Query

    Cust. Ledg. Entry Sales

  6. In C/AL code, add the following code on the CalcSalesThisMonthAmount function:

    Copy Code
    CustLedgEntrySales.SETRANGE(Document_Type,CustLedgerEntry."Document Type"::Invoice);
CustLedgEntrySales.SETRANGE(Posting_Date,CALCDATE('<-CM>',WORKDATE),WORKDATE);
CustLedgEntrySales.OPEN;
IF CustLedgEntrySales.READ THEN
  Amount := CustLedgEntrySales.Sum_Sales_LCY;

To save the table

  1. On the File menu, choose Save.

  2. Select the Compiled check box.

  3. Choose the OK button.

Adding the Cue to the Role Center Page

To display the Sales This Month Cue on the Role Center, Viktor adds a new field for the Cue to the existing page 50001 Sales Invoice Cue.

To add the Sales This Month Cue to a page

  1. In Object Designer, open the page 50001 Sales Invoice Cue.

    To add a Cue, you add Field control under a CueGroup control. For this walkthrough, you will add the new Cue under the existing CueGroup control for Sales Invoices, after the Sales Invoices - Open field.

  2. In a blank row under the existing CueGroup control, set the Type to Field, and then set the SourceExpr column to the "Sales This Month" field as follows.

    1. Select the row, and then on the View menu, choose Field Menu.

      The Field Menu window opens and displays the list of available fields from the Sales Invoice Cue table.

    2. Select the Sales This Month field, and then choose the OK button.

      In the Caption field, enter Sales This Month. The Caption value defines the text that appears below the Cue.

      Page Designer should look similar to the following illustration.

      Page Designer showing cues

  3. Open the C/AL code for the page, and then add the following code to the OnAfterGetRecord Trigger to assign the Sales This month field to the CalcSalesThisMonthAmount function of table 50001 Sales Invoice Cue:

    Copy Code
    "Sales This Month" := CalcSalesThisMonthAmount;

  4. To set up a link (drill down) from the Cue to page 25 Customer Ledger Entries, do the following:

    1. Select the Sales This Month field row, and then on the View menu, choose Properties.

    2. In the Properties window, set the DrillDownPageID property to Customer Ledger Entries (ID 25) and choose the OK button.

    3. Close the Properties window.

  5. Save and compile the page.

The Cue is now available on the page. To view the page, in Object Designer, select the page 50001 Sales Invoice Cue, and the choose Run.

Formatting the Cue Data

Viktor wants to display the amount in the Cue so that it is preceded with "kr", which indicates Danish Krone is the currency. Additionally, he does not want to display any decimal places. To achieve this, he sets the AutoFormatType Property and AutoFormatExpr Property of the Cue field on the page.

To change the data format

  1. In Page Designer, to open the properties for the Cue field, select the field, and then on the View menu, choose Properties.

  2. In the Properties window, set the AutoFormatType property to 10.

    This enables you to create a custom data format.

  3. Set the AutoFormatExpr property to the following text.

    Copy Code
    'kr <precision,0:0><standard format,0>'

    <precision,0:0> specifies not to display any decimals places.

    <standard format,0> specifies to format the data according to standard format 0.

    For more information about the precision and standard formats, see Formatting the Data in a Field

  4. Close the Properties windows, and then save and compile the page.

See Also

Tasks

Touring the RoleTailored Client Pages
Walkthrough: Creating a Role Center

Concepts

Creating and Customizing Cues
Setting Up Colored Indicators on Cues
Pages Overview
Tables
Queries


Page Designer Walkthroughs

The walkthroughs in this section provide step-by-step instructions on how to create pages for the RoleTailored client. Each walkthrough presents a different scenario intended to help you understand how different page types can be used to build a selection of page objects.

Pages are XML based and require less design considerations and more understanding of how XML elements work together. In these walkthroughs you will see how page parts and controls can be arranged in the Page Designer window to create a hierarchy of XML elements that result in pages.

Page controls contain properties, triggers, functions, and codeunits in just the same way as forms but for the purposes of these walkthroughs, creating the basic structure of the page is the focus, not how to add codeunits or triggers. For more detailed information about these issues, see the appropriate section in the Getting Started.

In This Section

Walkthrough: Creating a Customer Card Page in Page Designer

Walkthrough: Creating a Customer List in Page Designer

Walkthrough: Adding Actions to a Customer List Page

Walkthrough: Adding a FactBox to the Customer List Page

Walkthrough: Creating a Role Center

Walkthrough: Creating a Wizard Page

Walkthrough: Creating a Document Page

Walkthrough: Creating a Worksheet Page

Walkthrough: Creating a Cue Based on a FlowField

See Also

Concepts

Pages Overview
Adding Actions to Pages


Walkthrough: Creating a Customer Card Page in Page Designer

In this walkthrough, you learn how to create a card page to display customer details. A card page is used to display more detailed information than is available on a list page. You can link a list page to a card page so that when you select a customer in the list, you open a specific customer card page.

About This Walkthrough

This walkthrough provides an overview of how to create a card page in Page Designer, how to add controls, and how to preview the page in the Microsoft Dynamics NAV Windows client.

This walkthrough illustrates the following tasks:

  • Creating a card page.

  • Adding controls.

  • Saving the page.

  • Promoting customer data to the FastTab header.

  • Running the page.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 installed with a developer license.

  • CRONUS International Ltd. demonstration database.

Story

Simon is a partner working for CRONUS International Ltd. Kevin, the Sales Manager, has asked Simon to create a card page to store customer information. He wants to be able to view the details of each customer in a card page when he chooses a customer in the customer list.

Creating a Card Page

To create a customer card page to run on the Microsoft Dynamics NAV Windows client, Simon knows that he must use the Microsoft Dynamics NAV Development Environment Object Designer.

Note
In this walkthrough, to learn about the properties and controls of a card page you will create a card page from a blank page. Object Designer also includes a wizard that you can use to create a card page that sets up many properties and controls for you. For more information about the wizard, see How to: Create a Page.

To create a card page

  1. In Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Page, and then choose New. The New Page window opens.

  3. In the Table text box, choose the up arrow, select the Customer table, and then choose the OK button.

  4. Choose Create blank page, and then choose the OK button.

    The new page opens in Page Designer.

  5. On the View menu, choose Properties.

  6. In the PageType property, and set the Value column to Card.

  7. Close the Properties window.

  8. In Page Designer, in the first row, and in the Name column, enter CustomerCardContainer, and accept the default values for Type and Subtype fields.

You have now successfully created a card page. However, you cannot save your card page until you have added at least one control to your page.

Adding a Control to Display Customer Details

Simon wants to add a basic control to his card page to display a selection of fields from the customer table in a group that can be expanded or collapsed. He knows that all card pages use the FastTab control to display data in this way, so he decides to add a FastTab control to his blank card page.

To add a control to display customer details

  1. In the second row, in the Name column, enter CustomerCardGroup, and in the Caption column, enter General. Set Type to Group and set SubType to Group.

  2. In the third row, set Type to Field. On the View menu, choose Field Menu.

  3. In the Field Menu window, select fields from the Customer table.

    Select multiple fields by holding down the Ctrl key while you select the following rows:

    • No.

    • Name

    • Search Name

    • Name 2

    • Address

    • Address 2

    • City

    • Contact

    • Phone No.

  4. Choose the OK button. A message box appears with the following message: "Do you want to add the fields that are selected in the field menu?" Choose Yes.

    If the OK and Cancel buttons are unavailable, see Page Designer Troubleshooting for more information.

    In Page Designer, your card page should now look something like the following illustration.

    Customer Card page in Page Designer

  5. Select the next available blank row on your page, below Phone No., and on the View menu, choose Properties.

  6. In the Properties window, in the Caption property, enter Kevin's Customer Card.

  7. In the CaptionML property, accept the default value and close the Properties window.

Saving the Page

Simon thinks it would be a good idea to save the page before making any further changes.

To save the page

  1. When you close Page Designer, the Save As dialog box is displayed.

  2. In the ID field, enter 50002, and in the Name field, enter Kevin's Customer Card. For the ID, you can choose any number in the 50000 range.

  3. Leave the Compiled check box selected and choose the OK button.

    Note
    You can clear the Compiled check box to save your page, but your page will not run. You can compile only if there are no errors on the page.

Promoting Customer Data to the FastTab Header

Now Simon wants to highlight key customer information on his customer card page. He can do this by making the contents of some fields visible on the FastTab header, even when a FastTab is in its collapsed state.

To promote key customer data to the FastTab header

  1. Open Object Designer if it is not already open.

  2. In Object Designer, select page 50002, Kevin's Customer Card, which you created earlier, and choose Design to open the card page.

  3. In Page Designer, under CustomerCardGroup, select a field in one of the FastTab groups. For example, in the General group, you can select Contact. This field will be displayed on the General FastTab.

  4. With this row selected, on the View menu, choose Properties.

  5. In the Importance property, set the Value field to Promoted.

  6. Close the Properties window and close Page Designer. The Save Changes dialog box is displayed.

  7. Choose Yes to save and compile Kevin's Customer Card page.

You have now successfully promoted Contact to the FastTab header.

Running the Page

Test your new card page by running the RoleTailored client.

To run the page

  1. In Object Designer, select page 50002, Kevin's Customer Card, and then choose Run.

    The Microsoft Dynamics NAV Windows client opens and displays the new card page with all the fields you selected.

  2. Collapse the General FastTab on your card page and notice that the contact field you selected is displayed.

Next Steps

Simon wants to create a customer list page for his customers and to create a link from the list page to Kevin's Customer Card page.

See Also

Tasks

Walkthrough: Creating a Customer List in Page Designer
How to: Create a CardPart Page For Displaying Customer Data in a FactBox
How to: Add FastTabs to a Customer Card Page
Page Designer Troubleshooting
How to: Create a Page
Touring the RoleTailored Client Pages
How to: Run a Page


Walkthrough: Creating a Customer List in Page Designer

In this walkthrough, you will learn how to create a basic page that displays a list of customers.

Pages are used in Microsoft Dynamics NAV 2016 the same way that forms are used in earlier versions. Unlike forms, pages can be displayed on multiple clients, including the Microsoft Dynamics NAV Windows client. This flexibility lets you display the same information in different clients. Pages cannot be viewed in the Microsoft Dynamics NAV Development Environment.

About this Walkthrough

This walkthrough provides an overview of how to create and run a simple list page in Microsoft Dynamics NAV, and demonstrates how to:

  • Create a list page.

  • Add controls to the page to display specific fields from a table.

  • Save the page.

  • Run the page in the RoleTailored client.

Prerequisites

The following prerequisites are required for this walkthrough:

  • Microsoft Dynamics NAV 2016 installed with a developer license.

  • CRONUS International Ltd. demonstration database

Story

Simon is a partner working for CRONUS International Ltd. Kevin, the Sales Manager at CRONUS, has contacted Simon and asked him to create a customer list.

Creating a List Page

To create Kevin's customer list, Simon knows that he needs to create a list page. Simon also needs to ensure that the card for a specific customer will open when Kevin selects the customer from the list.

Note
In this walkthrough, to learn about the properties and controls of a list page you will create a list page from a blank page. Object Designer also includes a wizard that you can use to create a list page that sets up many properties and controls for you. For more information about the wizard, see How to: Create a Page.

To create a List page

  1. Open the Microsoft Dynamics NAV Development Environment, and then on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Page, and then choose New. The New Page window opens.

  3. In the Table text box, choose the up arrow, select the Customer table, and then choose the OK button.

  4. Select Create blank page, and then choose OK.

    The new page opens in Page Designer.

  5. In the Name column of the first row, enter CustomerListContainer and accept the defaults values for the Type and the SubType fields.

  6. Select a blank row, and on the View menu, choose Properties.

  7. In the PageType property, set the Value field to List.

  8. In the CardPageID property, set the Value field to 21 Customer Card.

  9. Close the Properties window.

Adding Customer Information to the Page

Now that Simon has created a basic list page, he wants to add a control and the appropriate fields so that the page will display the number, name, address, city, and phone number for each customer in the list.

To add controls to the page

  1. In Page Designer, in the Name column in the second row, type CustomerListGroup. Set Type to Group and set SubType to Repeater.

    Note
    The CustomerListGroup is indented one level below the CustomerListContainer, indicating that it is a child of, and will be displayed within, the CustomerListContainer.

  2. Select the third row.

  3. On the View menu, choose Field Menu.

    The Field Menu window opens, displaying the list of available fields from the Customer table (Table 18).

  4. Select multiple fields by holding down the Ctrl key while you select the following rows:

    • No.

    • Name

    • Address

    • City

    • Phone No.

  5. Choose the OK button.

    A message box appears with the following message: "Do you want to add the fields that are selected in the field menu?"

    Note
    If the OK button in the Field Menu window is inactive, you can commit the field changes by choosing Page Designer.

  6. Choose Yes.

    The following illustration shows the Page Designer window.

    Page Designer window

Saving and Running the Page

Now that Simon's page is complete, he wants to see how it looks. Eventually, he will add an action to another page so Kevin can access the page. But while he is still working on it, Simon can save the page and then quickly run it in the RoleTailored client using the following procedure.

To save and run the page

  1. From the File menu, choose Save, or press Ctrl + S.

    The Save As dialog box opens.

  2. In the ID field, enter 50000.

  3. In the Name field, enter Kevin's Customer List.

  4. Make sure Compile is selected and choose the OK button.

    This name is displayed in the page's ribbon.

  5. In Object Designer, select the page 50000 Kevin's Customer List, and then choose Run to view the page.

    The RoleTailored client opens and displays the customer list page. The following illustration shows a customer list page.

    Customer List page

Next Steps

Next, Simon needs to add actions to the customer list page. He decides that he wants to add a Sales Order action. When selected, this action will create a new sales order.

See Also

Tasks

Walkthrough: Adding Actions to a Customer List Page
Walkthrough: Adding a FactBox to the Customer List Page
How to: Create a Page
Touring the RoleTailored Client Pages
How to: Run a Page


Walkthrough: Adding Actions to a Customer List Page

In this walkthrough, you will learn how to add a new item to an Action tab and then display that item as an icon on the ribbon. The ribbon is located at the top of most pages and is used to provide users with easy access to common or important actions. Action tab items are referred to as actions. Actions that are displayed on the ribbon are referred to as promoted actions.

About this Walkthrough

This walkthrough provides an overview of how to create and run a simple list page in Microsoft Dynamics NAV, and demonstrates how to:

  • Add an action to the customer list page to create a new sales order.

  • Display the Sales Order action on the Actions tab.

  • Promote the Sales Order action so it is displayed in the ribbon.

  • Modify the Sales Order action so it creates a new sales order for the customer currently selected in the customer list.

Prerequisites

This walkthrough builds on the steps described in Walkthrough: Creating a Customer List in Page Designer. If you have not created a customer list page, you must create it before you continue this walkthrough.

Story

Simon shows the customer list page that he created to Kevin, the Sales Manager at CRONUS International Ltd. who contracted him to create this page. Kevin likes how the customer list looks, but he would like Simon to add a menu item on the Actions tab to create a new sales order for the currently selected customer.

Adding an Action to the Customer List

Simon looks at the customer list that he created earlier and adds a new action to the page to create a sales order.

To add an action to the customer list page

  1. In the Microsoft Dynamics NAV Development Environment, choose Tools, and then choose Object Designer.

  2. In Object Designer, choose Page, select page 5000 Kevin's Customer List, and then choose Design.

    The Kevin's Customer List page opens in Page Designer.

  3. Select the first empty line on the page, which is located immediately below the <Phone No.> field.

  4. With focus on Page Designer, in the View menu, choose Page Actions.

    Action Designer opens. For this walkthrough, Action Designer will be used to set actions on the page.

  5. In Action Designer, in the Name column in the first row, type CustomerListActions.

    The relevant ActionContainers for a list page are:

    • NewDocumentItems

    • ActionItems

    • RelatedInformation

    • Reports

    • HomeItems

    • ActivityButtons

    For more information about the different types of actions, see Actions Overview.

  6. Set the SubType column to ActionItems.

    Actions with a SubType of ActionItems are displayed on the General action group in the ribbon.

  7. In the Caption column in the second row, type Sales Order.

  8. Set the Type to Action.

  9. This action is indented one level below the ActionContainer to indicate that it is contained by ActionContainer.

  10. On the View menu, select Properties.

  11. Set the RunObject property to Page Sales Order.

  12. Save the page.

  13. To run the page, in Page Designer, select the page 5000 Kevin's Customer List, and then choose the Run button.

    The Sales Order action now displays in the Actions tab.

Promoting an Action

When Simon opens the page, he realizes that he would like to promote the Sales Order action so that it displays on the ribbon in the New group. Promoted actions are displayed as icons within the ribbon located at the top of the page.

To promote an action

  1. With the first empty line selected in Page Designer, open Action Designer.

  2. Select the Sales Order action and, on the View menu, choose Properties.

  3. Set the Image property to Document.

  4. Set the Promoted property to Yes.

  5. Set PromotedCategory property to New.

  6. Set PromotedIsBig property to Yes.

  7. Set the Caption property to Sales Order.

  8. Save the page.

  9. In Object Designer, choose the Run button to run the page.

    The Sales Order command is now displayed in the ribbon, as shown in the following screen shot.

    Kevin's Customer List page

Linking an Action with a Specific Item in a List

Simon verifies that the Sales Order action now displays in the ribbon. However, when he selects the Sales Order action, the Sales Order card opens and displays the first sales order in the database. Simon remembers that Kevin asked him to have the Sales Order action open a new sales order for the currently selected customer, instead. Simon opens the customer list page and starts making this change.

To add an action

  1. In Action Designer, select the Sales Order action from the View menu, and then choose Properties to view the Properties window.

  2. Set the RunPageMode property to Create.

    The default value for this property is Edit. By setting this property to a value of Create, a sales order page will open in create mode, enabling the end user to create a new sales order.

  3. Set the RunPageLink property value to Sell-to Customer No.=FIELD(No.) using the following steps:

    1. In the RunPageLink property value, choose the Assist-Edit button (ellipsis).

      The Table Filter window appears.

    2. In the Field cell, choose the AssistButton button, choose Sell-to Customer No., and then choose OK.

    3. In the Type cell, choose the drop-down list box and then select FIELD.

    4. In the Value cell, choose the AssistButton button, thenselect No., and then choose OK.

    5. Choose the OK button.

      The customer number in the customer list is now linked to the Sell-to Customer number in the sales order. This means that when the Sales Order action is chosen, a new sales order will be created for the customer that is currently selected in the customer list.

  4. Save the page.

  5. In Object Designer, choose the Run button to run the page.

    To test the new functionality, select a customer from the list and then choose the Sales Order action. A new sales order appears.

  6. Press the Tab key twice, or choose any field on the page for customer information to populate the fields.

Next Steps

Next, Simon will add a FactBox to the customer list page. Simon will use this FactBox to display additional information about the currently selected customer in the list.

See Also

Tasks

Walkthrough: Adding a FactBox to the Customer List Page
Walkthrough: Creating a Customer List in Page Designer


Walkthrough: Creating a Role Center

In this walkthrough, you will learn how to create a new Role Center for the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client. In Microsoft Dynamics NAV 2016, a Role Center is a type of page on which you can place different parts. Each part is a container in which you can host other pages or predefined parts, such as an Outlook part or parts for adding tasks, notifications, or notes.

Important
Only system parts, card parts, and list parts are supported page types for the Role Center.

Important
While removing cues is possible when customizing the Role Center, activity items cannot be removed.

About This Walkthrough

This walkthrough illustrates the following tasks:

  • Creating a Role Center page.

  • Creating a CardPart page that displays a visual representation of work queues.

  • Adding actions to the CardPart page.

  • Adding the CardPart page to the Role Center page.

  • Adding the MyNotes system part to the Role Center page.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 installed with a developer license.

  • CRONUS International Ltd. demonstration database.

Story

Simon is a partner working for CRONUS International Ltd. Susan, the Order Processor at CRONUS, has contacted Simon and asked him to create her a new Role Center that will show her work queue, give her easy access to common actions like creating a new sales order, and will also display a list of current notifications.

Creating a Role Center Page

Simon creates a new Role Center using Page Designer. Simon knows that because Role Centers can contain several different parts, they are not tied to a specific source table. As a result, when Simon creates the Role Center page, he does not select a table in the New Page window.

To create a Role Center page

  1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Page, and then choose New. The New Page window opens.

  3. Choose Create blank page, and then choose the OK button.

    The new page opens in Page Designer.

  4. On the first row, in the Name field, type RoleCenterContainer.
    The Type column is preset to Container and the Subtype column is preset to ContentArea.

  5. Select a blank row, and on the View menu, choose Properties.

  6. In the Properties window, in the PageType property, set the Value field to RoleCenter.

  7. Close the Properties window.

  8. On the File menu, choose Save. Set Name to Sales Order Proc. Role Center, and set ID to 50005. Choose the OK button.

Creating a Sales Order Processor Queue Page

Simon needs to create a page that provides a visual indicator of the work Susan has to do each day. He wants to host this page in a part on Susan's Role Center so he will need to create it before he can add it to the Role Center page that he just created. He has already created a table that contains the fields that he wants to use, so he only needs to create the page. Simon knows that to create a queue, he must use the CardPart page type.

To create a Sales Order Processor Queue page

  1. In Object Designer, choose Page, and then choose New.

  2. In the Table text box, choose the up button, select table 9053, Sales Cue, and then choose the OK button.

  3. Choose Create blank page, and then choose OK.

    The new page opens in Page Designer.

  4. On the first row, in the Caption column, type SalesOrderContainer.
    The Type column is preset to Container and the Subtype column is preset to ContentArea.

  5. Select a blank row, and on the View menu, choose Properties.

  6. In the PageType property, set the Value field to CardPart.

  7. Close the Properties window.

  8. In the second row, in the Caption column, enter For Release, and then set Type to Group and SubType to CueGroup.

  9. Choose the next empty line, and on the View menu, choose Field Menu.

    The Field Menu window opens, displaying the list of available fields from the SalesCue table (Table 9053).

  10. Select the following fields:

    • Sales Quotes - Open

    • Sales Orders - Open

    Tip
    You can select multiple fields by holding down the Ctrl key.

  11. Choose the OK button.

    A message box appears with the following message: "Do you want to add the fields that are selected in the field menu?"

  12. Choose Yes.

  13. On the next empty line, in the Caption column, enter Sales Orders Released Not Shipped, then set Type to Group and SubType to CueGroup.

  14. Select the next empty line and, on the View menu, choose Field Menu.

  15. Select the following fields:

    • Ready to Ship

    • Delayed

    • Partially Shipped

  16. Choose OK and confirm the selection.

  17. On the next empty line, in the Caption column, enter Returns, then set Type to Group and set SubType to CueGroup. Choose the left arrow to negative indent this line one level.

  18. Select the next empty line and, on the View menu, choose Field Menu.

  19. Select the following fields:

    • Sales Return Orders - All

    • Sales Credit Memos - All

  20. Choose OK and confirm the selection.

  21. On the File menu, choose Save, name your new page Sales Order Processor Queue and set the ID to 50006. Choose the OK button.

  22. In Object Designer, select the page, and then choose Run.

    The RoleTailored client opens and displays the new page.

Adding Actions to the Sales Order Queue Page

Simon now needs to add actions to the Sales Order Processor Queue page. He knows that the CardPart page type is special in that he can include actions on individual groups within the page. These actions will then be displayed immediately adjacent to the queues on the page. He also adds code to the OnOpenPage() method to ensure that the work queues update to reflect Susan's current work when the Role Center opens.

To add actions to the Sales Order Processor Queue page

  1. In Object Designer, select page 50006, Sales Order Processor Queue, and choose Design.

  2. In Page Designer, choose the For Release group line, and on the View menu, choose Control Actions.

    The Action Designer opens.

  3. In Action Designer, on the first row, in the Caption column, enter New Sales Quote, and set the Type column to Action.

  4. With the first row selected, on the View menu, choose Properties.

  5. Set the following properties.

    Property Value

    RunPageMode

    Create

    Image

    Quote

    RunObject

    Page Sales Quote

  6. Close the Properties window.

  7. In Action Designer, on the second row, in the Caption column, enter New Sales Order, and then set the Type column to Action.

  8. With the second row selected, open the Properties window.

  9. Set the following properties.

    Property Value

    RunPageMode

    Create

    RunObject

    Page Sales Order

  10. Close the Properties window.

  11. In Page Designer, choose the Sales Orders Released Not Shipped group line, and on the View menu, choose Control Actions.

  12. In Action Designer, in the first row, in the Caption column, enter Navigate, and set the Type column to Action.

  13. With the first row selected, open the Properties window.

  14. Set the following properties.

    Property Value

    Image

    Navigate

    RunObject

    Page Navigate

  15. Close the Properties window.

  16. In Page Designer, choose the Returns group line, and on the View menu, choose Control Actions.

  17. In Action Designer, on the first row, in the Caption column, enter New Sales Return Order, and set the Type column to Action.

  18. With the first row selected, open the Properties window.

  19. Set the following properties.

    Property Value

    RunPageMode

    Create

    RunObject

    Page Sales Return Order

  20. Close the Properties window.

  21. In Action Designer, in the second row in the Caption column, enter New Sales Credit Memo, and then set the Type column to Action.

  22. With the second row selected, open the Properties window.

  23. Set the following properties.

    Property Value

    RunPageMode

    Create

    RunObject

    Page Sales Credit Memo

  24. Close the Properties window.

  25. In Page Designer, select the first empty line, and on the View menu, choose C/AL code.

  26. Enter the following code in the OnOpenPage() method:

    Copy Code
    RESET;
IF NOT GET THEN BEGIN
  INIT;
  INSERT;
END;
SETRANGE("Date Filter",0D,WORKDATE - 1);
SETFILTER("Date Filter2",'>=%1',WORKDATE);

  27. Save the page.

  28. Close the C/AL Editor and then close Page Designer.

  29. In Object Designer, choose Run to view the page.

Adding Parts to the Role Center Page

Simon now needs to add his new sales order queue page to Susan's new Role Center. Simon knows that he can create multiple groups with multiple parts on the Role Center, but he will have to create one group that contains two parts, the Sales Order Processer Queue page and a notifications page.

To add parts to the Role Center page

  1. In Object Designer, select page 50005, Sales Order Proc, Role Center, and choose Design.

  2. On the first row, in the Name column, enter SalesOrderRoleCenterContainer, and set the SubType column to RoleCenterArea. This replaces the value in the field.

  3. In the Name column in the second row, enter PartOneGroup, set Type to Group and then set SubType to Group.

  4. In the Type column in the third row, set Type to Part.

  5. On the View menu, choose Properties.

  6. In the PagePartID property, set the Value column to 50006 Sales Order Processor Queue .

  7. In the Page Designer for page 50005, in the fourth row, set the Type column to Part.

  8. On the View menu, choose Properties.

  9. Set the following properties.

    Property Value

    PartType

    System

    SystemPartID

    MyNotes

  10. Close the Properties window.

  11. Save the page.

  12. In Object Designer, choose Run to view the page.

Next Steps

Simon's next steps are to add the My Customers and My Items parts to the page. For more information, see How to: Create a CardPart Page For Displaying Customer Data in a FactBox.

See Also

Tasks

How to: Create a Page
Touring the RoleTailored Client Pages
How to: Run a Page

Concepts

Page Designer Walkthroughs


Walkthrough: Creating a Wizard Page

In Microsoft Dynamics NAV, you can use the Navigate page type to create a wizard page. A wizard page consists of a number of user input screens or steps linked together, enabling users to carry out infrequently performed tasks, such as configuration or specific business tasks.

In Microsoft Dynamics NAV, examples of wizard pages include:

  • Create Interaction, page 5077

  • Create To-do, page 5097

  • Create Opportunity, page 5126

In Microsoft Dynamics NAV, the Navigate page type is also used for page 344, Navigate.

About This Walkthrough

This walkthrough provides an overview of how to create the basic elements in a To-do wizard page using Page Designer.

This walkthrough illustrates the following tasks:

  • Creating a wizard page.

  • Adding steps to a wizard page.

  • Adding the attendee subpage.

  • Adding wizard buttons.

  • Running the page.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 installed with a developer license.

  • The CRONUS International Ltd. demonstration database.

Story

Simon is a partner working for CRONUS International Ltd. Benjamin, the marketing manager at CRONUS, wants Simon to create a wizard page that will enable him to create To-dos for his team of salespeople. Simon must create a wizard page that makes it easy to link a To-do with a sales campaign or sales opportunity. Simon knows that he can do this successfully if he uses the Navigate page type to create a To-do wizard.

Creating a Wizard Page

Simon must first create a new wizard page in Page Designer.

Note
In this walkthrough, to learn about the properties and controls of a wizard page, you will create a wizard page from a blank page. Object Designer also includes a wizard that you can use to create a wizard page that sets up many properties and controls for you. For more information about the wizard, see How to: Create a Page.

To create a wizard page

  1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Page, and then choose New. The New Page window opens.

  3. In the Table text box, choose the up arrow, select the table 5080, To-do, and then choose the OK button.

  4. Choose Create blank page, and then choose the OK button.

    The new page appears in Page Designer.

  5. On the first row, ensure that the Type column is set to Container and that the SubType column is set to ContentArea. In the Name column, type Ben's To-dos.

  6. Select a blank row, and on the View menu, choose Properties.

  7. In the PageType property, set the Value field to NavigatePage.

  8. Close the Properties window.

  9. Close the Page Designer window.

  10. In the Save As dialog box, in the Name text box, enter Ben's To-dos and enter a page ID, for example, 50015. Choose the OK button.

You have successfully created and saved a Navigate page, which you will use to create a To-do wizard. Next you must add steps to the wizard.

Adding Steps to a Wizard Page

In a wizard page, steps are controls that you place on a Navigate page to enable it to work like a wizard. These controls initially appear as tabs in the content area of the page. Simon can create steps in Page Designer by adding a different group element for each step that he wants to create. Each control is displayed as a separate step to the user. The following procedure shows how to create the first step in a To-do wizard that has four steps.

To add steps to a wizard page

  1. In Page Designer, select your new Ben’s To-do wizard page, 50015, and choose Design to open it.

  2. On the second row, in the Name column, type Step1. Set Type to Group and SubType to Group.

  3. In the next empty row, leave the Name field blank and set Type to Field.

  4. On the View menu, choose Field Menu.

    In the Field Menu window, select fields from the table 5080, To-do.

  5. Make your selection by holding down the Ctrl key while you select the following fields:

    • Type

    • Date

    • Description

    • Start time

    • Ending Date

    • Ending Time

    • Duration

    • All Day Event

    • Team To-do

  6. Choose the OK button. A message box displays the following message, "Do you want to add the fields that are selected in the field menu?" Choose Yes.

  7. In the Caption column for each of the fields you added, type the following captions:

    Field Caption

    Type

    What is the type of the to-do?

    Date

    What is the starting date of the to-do?

    Description

    Describe your to-do

    Start time

    What is the start time of the to-do?

    Duration

    What is the duration of the to-do?

    Team To-do

    Team to-do

    All Day Event

    All Day Event

    Ending Date

    What is the end date of the to-do?

    Ending Time

    What is the end time of the to-do?

    All the fields that you add must be indented one space below Step 1. Remember to check indentation on all elements that you create, and adjust with the left and right arrows if necessary.

  8. When you have added all the necessary steps, close the Page Designer, and save your page.

    In the Microsoft Dynamics NAV Windows client, each step is displayed like a tab control until you add Back, Next, and Finish buttons to the lower part of the page. You will read about this in Adding Wizard Buttons.

Adding the Attendee Subform

When Ben opens his new wizard page for the first time, he wants to be able to choose a salesperson to create a To-do for. Simon must add a control to Step 1 of the wizard, which allows him to select attendees from table 5080, Attendees.

To add the attendee subform

  1. In Object Designer, select your new wizard page, 50015, and choose Design to open it.

  2. Insert a row right below the Step1 row.

  3. Type AttendeeSubForm in the Name column. This row should be indented to match the other field elements in the Step 1 group. Set Type to Part.

  4. On the View menu, choose Properties. Set the PagePartID property to Attendee Wizard Subform (5198). This will ensure that Ben can select attendees for his To-dos in the first step of the wizard.

  5. Close the Properties window, save your page, and in Page Designer, choose Preview to view your changes in the Microsoft Dynamics NAV Windows client and then close the Preview window.

    The following illustration shows the indentation of elements on the wizard page after adding steps and the attendee subform.

    Wizard page in Object Designer

Adding Wizard Buttons

Simon has now successfully created a basic wizard page. To make his page appear more like a wizard he must add Next, Back, and Finish buttons. To do this, Simon must add a new set of actions to his wizard page using the Action Designer.

To add wizard buttons

  1. In Page Designer, select your To-to wizard page, 50015, and choose Design to open it.

  2. Select the first empty row below the steps that you have already created, and on the View menu, choose Control Actions to open Action Designer.

  3. On the first empty row in Action Designer, set Type to ActionContainer and SubType to ActionItems.

  4. In the next available row, type Back in the Name field, and set Type to Action. Do the same in the next two available rows except enter Next and Finish in the Name fields.

  5. When you have added all the buttons you need, select the row with the Back button control, and open the Properties window.

  6. In the Properties window, set the following properties on the Back button.

    Property Value

    Enabled

    BackEnable

    For the Next button, set NextEnable

    For the Finish button, set FinishEnable

    Visible

    True

    Caption

    &Back

    For the Next button, set &Next

    For the Finish button, set &Finish

    RunPageMode

    Edit

    InFooterBar

    Yes

  7. On the View menu, choose C/AL Globals, and on the Variables tab, declare the following variables:

    Variable DataType

    BackEnable

    Boolean

    NextEnable

    Boolean

    FinishEnable

    Boolean

  8. To make sure the controls are visible on the page, from the Action Designer window, open the C/AL Code window.

  9. In the OnAction() trigger for Back, enter the following line of code CurrPage.UPDATE(TRUE);

  10. Repeat this for the OnAction() triggers for Next and Finish.

  11. Close the C/AL Code window.

  12. Save and compile your page.

To enable the wizard buttons

  1. In Page Designer, select your To-to wizard page, 50015, and choose Design to open it.

  2. On the View menu, choose C/AL Globals, and on the Functions tab, create a new function named DoStep.

  3. Choose the Locals button, and then, on the Parameters tab, enter step in the Name field, and choose Integer in the DataType field.

  4. Close the C/AL Locals window and the C/AL Globals window.

  5. On the View menu, choose C/AL Code, and scroll down until you locate the DoStep function.

  6. In the DoStep function, insert the following lines of code:

    Copy Code
    BEGIN
CASE step OF
        0:
          BEGIN
            BackEnable := FALSE;
            NextEnable := TRUE;
            FinishEnable := FALSE;
          END;
        1:
          BEGIN
            BackEnable := TRUE;
            NextEnable := FALSE;
            FinishEnable := TRUE;
          END;
        2:
          BEGIN
            BackEnable := FALSE;
            NextEnable := FALSE;
            FinishEnable := FALSE;
          END
        ELSE
          ERROR('invalid button state/step, choose 0-2');
      END;
      CurrPage.UPDATE(TRUE);
END;

  7. Now scroll to the OnInit function and enter the following line of code:

    Copy Code
    BEGIN
  DoStep(0);
END;

  8. Close the C/AL Code window.

  9. Save and compile the page.

Running the Page

Test your new wizard page in the Microsoft Dynamics NAV Windows client.

To run the page

  1. In Object Designer, select page Ben's To-dos, and then choose Run.

    The Microsoft Dynamics NAV Windows client opens and displays the new wizard page.

Next Steps

Simon has now created a basic wizard page.

For more information about adding variables, constants, and functions, see Codeunits.

See Also

Tasks

How to: Add Actions to a Page
How to: Promote Actions to the Ribbon on Pages
How to: Create a Page
Touring the RoleTailored Client Pages
How to: Run a Page


Walkthrough: Creating a Document Page

In Microsoft Dynamics NAV 2016, a document page consists of two separate pages, with one page nested inside the other page.

You can create a document page if you have two tables that are linked. For example, page 42, Sales Order, has two source tables: Sales Header and Sales Lines. These two tables are linked in a one-to-many relationship and are source tables for the Sales Order page.

The sales order document page consists of a series of FastTabs that display customer, invoicing, shipping, and other relevant information. The source table for this information is table 36, Sales Header. The lines that show items that are associated with each customer are based on table 37, Sales Lines.

The following illustration shows a document page.

In this walkthrough, you will create a sales order document page. This page will contain useful secondary information, such as customer statistics, in FactBoxes to the right of the main content area. The FactBox is updated every time that you select a line.

About This Walkthrough

This walkthrough provides an overview of how to create a sales order document page with Page Designer.

The walkthrough illustrates the following tasks:

  • Creating a document page

  • Adding controls to display fields from the Sales Header table

  • Adding a Part Control to display sales lines.

  • Adding a FactBox that is linked to sales lines.

  • Running the page.

Story

Simon is a partner working for CRONUS International Ltd.. Susan, the order processor, asks Simon to create a sales order page that can display each of her orders and any associated lines. This page is essential to Susan’s daily work, because she uses sales orders to create and track all her customer orders from the creation of the first quote to when the order is shipped. Simon knows that this page must be based on two related source tables and that he must create a page by using the document page type.

Prerequisites

The following prerequisites are required for this walkthrough:

  • Microsoft Dynamics NAV 2016 installed with a developer license.

Creating a Document Page

First, Simon creates a new document page that is based on table 36, Sales Header.

Note
In this walkthrough, you learn about the properties and controls of a document page, and you will create document page from a blank page. If you are using Microsoft Dynamics NAV 2016, Object Designer includes a wizard that you can use to create a document page that will set up many properties and controls for you. For more information about the wizard, see How to: Create a Page.

To create a document page

  1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Page, and then choose the New button. The New Page dialog box appears.

  3. In the Table text box, select the table 36, Sales Header, and then choose the OK button.

  4. Select Create blank page, and then choose the OK button.

    The new page appears in Page Designer.

  5. In the Name field of the first row, which has the type Container and the subtype ContentArea, enter Susan's Sales Order Page.

  6. Select a blank row, and on the View menu, choose Properties.

  7. Locate the PageType property, and then set the Value field to the page type Document.

  8. Close the Properties window.

  9. In the next row in Page Designer, in the Name field, enter General.

  10. Set the Type property to Group and the SubType property to Group.

  11. On the File menu, choose Save. Name your new page Susan's Sales Order Page. Set the ID field to 50006 and choose the OK button.

Adding a Control to Display Fields from the Sales Header Table

Simon now wants to add fields to his document page. He creates a group named General and adds fields from the Sales Header table. He knows that the main content area on a document page displays fields as FastTabs in the Microsoft Dynamics NAV Windows client.

To add a control to display fields from the Sales Header table

  1. In Page Designer, select the next empty row below the General group and set the Type property to Field.

  2. Select the row, and on the View menu, choose Field Menu. The Field Menu displays all the fields that are available in the Sales Header table.

  3. Press the Ctrl key and select the following rows:

    • Sell-to Customer No.

    • No.

    • Sell-to Customer Name

    • Sell-to Address

    • Sell-to Address 2

    • Sell-to City

    • Sell-to Contact

  4. Choose the OK button, and then choose Yes in the dialog box to add the fields to your page.

    Note
    If the OK and Cancel buttons are unavailable, see Page Designer Troubleshooting for more information.

  5. On the File menu, choose Save.

  6. In the Save dialog box, make sure Compiled is selected, and then choose the OK button.

Adding a Part Control to Display Sales Lines

Simon's next task is to add a nested control to display lines from the Sales Lines table and the Sales Order Subform page. To do this, he must add a Part control to his page and link both objects by using the Properties window.

To add a part control to display sales lines

  1. In Page Designer, select the next empty row below the General group and set the Type property to Part.

  2. In the Name field, enter Sales Lines. Place the cursor anywhere outside this field, and Caption will be filled in automatically.

  3. Select the Sales Lines row, and on the View menu, choose Properties.

    You will set the following properties to configure a link to the Sales Lines table and page 46, Sales Order Subform:

    • PagePartID

    • SubPageLink

  4. Locate the PagePartID property, in the Properties window, and use the drop-down arrow next to this property to display the page list.

  5. In the Page List window, select page 46, Sales Order Subform, and then choose the OK button.

  6. Locate the SubPageLink property and select the drop-down arrow to open the Table Filter window.

  7. In the first row, choose Field to open the Sales Line - Field List window. This window lets you to set a table filter on the Sales Lines table.

  8. Select Document No. and then choose the OK button.

  9. In the Type drop-down list box, choose FIELD.

  10. In the Value field, select No., and then choose the OK button.

  11. In the Table Filter window, choose the OK button to add this filter value to the SubPageLink property.

  12. Use the left and right arrows to indent Sales Lines so that it matches the General group element.

Adding a FactBox That Is Linked to Lines

Simon has already created two FactBoxes for his Sales Order page. He now wants to link the Sales Line FactBox to the Sales Lines table on his document page. To do this, he must change the ProviderID property on his FactBox part after he has added it to the page.

To add a FactBox that is linked to lines

  1. In Page Designer, select the next empty row.

  2. Set the Type field to Container, and then set the SubType field to FactBoxArea. Accept the default values for the Name and Caption fields.

  3. In the next row, enter SalesLineFactBox in the Name field, and then set the Type field to Part.

  4. On the View menu, choose Properties.

  5. In the Properties window, select the PagePartID property, and then choose the field. Select page 9087, Sales Lines FactBox, from the Page List window, and then choose the OK button.

  6. To create a link between the FactBox and Sales Lines, you must first find the ID property of the Sales Lines row. To do this, select the Sales Lines row, and view the Properties window. In this example, the ID property of the Sales Lines row is 10.

  7. Select the SalesLineFactBox and set the ProviderID property to 10.

    Note
    The ID property of the Sales Lines row can vary, so check this carefully.

  8. In the SubPageLink property, enter the following table filter.

    Document Type=FIELD(Document Type),Document No.=FIELD(Document No.),Line No.=FIELD(Line No.)

  9. Close the Properties window.

  10. Check the indentation on your FactBox. Indentation of your FactBox container should match the first element in the page so that there is no indentation. Your SalesLineFactBox part should be indented by one space below the FactBox container.

    The illustration shows a Page Designer.

  11. Close Page Designer, and then choose Yes to save your page.

Running the Page

Test your new document page in the Microsoft Dynamics NAV Windows client.

To run the page

  1. In Object Designer, select Susan’s Sales Order Page (50006) and then choose the Run button.

  2. Alternatively, you can run the page by using the task bar. On the taskbar, choose Start, and then choose the Run button.

  3. Enter the following command to display your page:

    DynamicsNav:////runpage?page=<pageid>. In this case pageid is 50006

    The Microsoft Dynamics NAV Windows client opens and displays the new document page.

Next Steps

Simon now wants to add actions to Susan's document page and promote some of these actions to the ribbon. For more information, see How to: Promote Actions to the Ribbon on Pages.

See Also

Tasks

How to: Add Actions to a Page
How to: Promote Actions to the Ribbon on Pages
How to: Create a Page
Touring the RoleTailored Client Pages
How to: Run a Page

Concepts

Pages Overview


Walkthrough: Creating a Worksheet Page

In Microsoft Dynamics NAV, you can use a worksheet page type to create two types of pages:

  • Worksheet pages - Used to present data in a list and offer a choice of actions to the user. For example, page 5841, Standard Cost worksheet, in Object Designer is a worksheet page.

  • Journal pages - Used to perform tasks, such as posting transactions. For example, page 40, the Item Journal, in Object Designer is a journal page.

    The following illustration shows an Item Journal page.

Worksheet pages always open in edit mode and can display lists of data in a grid control and in lines. Lines can be filled in by a user or by running a batch job. You can add other controls such as a filter or FactBox to a worksheet page but you cannot add a chart pane. As part of user personalization options, these controls can be added or removed by the user. Actions can be added to the navigation of a worksheet page, and may be promoted by the user to the ribbon.

In this walkthrough, you learn how to create a new Item Journal worksheet that displays item journal lines.

About This Walkthrough

This walkthrough provides on overview of how to create a journal worksheet page and how to add controls to display items from a table. In this walkthrough, you will display items from table 83, Item Journal Line.

This walkthrough illustrates the following tasks:

  • Creating a worksheet page.

  • Adding a batch name control.

  • Adding a field repeater control.

  • Adding a fixed layout control.

  • Adding FactBoxes.

  • Running the page.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 installed with a developer license.

  • The CRONUS International Ltd. demonstration database.

Story

Simon is a partner working for CRONUS International Ltd. Susan, the order processor asks Simon to create an Item Journal worksheet page for her, which she can use to keep her item inventory up to date. Susan often uses the posting action on the Item Journal page to adjust her inventory in relation to purchases and sales.

Creating a Worksheet Page

Note
In this walkthrough, you will create a worksheet page from a blank page and learn about the properties and controls of a worksheet page. Object Designer includes a wizard that you can use to create a worksheet page that sets up many properties and controls for you. For more information about the wizard, see How to: Create a Page.

To create a worksheet page

  1. In Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Page, and then choose New. The New Page window opens.

  3. In the Table text box, choose the up arrow, select the table 83, Item Journal Line, and then choose the OK button.

  4. Select Create blank page, and then choose the OK button.

    The new page appears in Page Designer.

  5. On the first row, ensure that the Type column is set to Container and that the SubType column is set to ContentArea. In the Name column, type Susan's Item Journal.

  6. Select a blank row, and on the View menu, choose Properties.

  7. In the PageType property, set the page type to Worksheet.

  8. Close the Properties window.

Adding a Batch Name Control

First, Simon needs to add a batch name control to the top of his worksheet page, so Susan can select which batch item she wants to run from the Item Journal Batch table.

To add a batch name control

  1. In Page Designer, select the second row, type CurrentJnlBatchName in the Name field, and set Type to Field. This element is automatically indented one space below your Container element.

  2. With the second row still selected, open the Properties window, and set the SourceExpr property to CurrentJnlBatchName.

  3. Set the LookUp property to Yes.

  4. On the View menu, choose C/AL Globals.

  5. In the Name field, enter CurrentJnlBatchName, then in the DataType field, choose Text, and then close the C/AL Globals window.

  6. Save your new page and name it Susan's Item Journal. Set the page ID to 50007 or another value in the 50000 range.

Adding a Field Repeater Control

Next, Simon must add fields to Susan's Item Journal page. In a worksheet page these fields are displayed horizontally, like lines.

To add field repeater controls

  1. In Page Designer for the page you just created, select a blank row. Set the Type column to Group and the SubType column to Repeater, and accept the default for the name. You can enter a name for control instead of accepting the default.

  2. In the next blank row, set Type to Field. You cannot set a SubType when you select Field.

  3. With the new Field row selected, on the View menu, choose Field Menu. The Field Menu window displays fields available from table 83, Item Journal Line.

  4. Select multiple fields from this table by holding down the Ctrl key while you make your selection. For this walkthrough select the following fields:

    • Item No.

    • Posting Date

    • Entry Type

    • Document No.

    • Description

    • Document Date

    • External Document No.

    • Variant Code

  5. Choose the OK button to add the fields and then choose Yes in the dialog box that appears.

    You have now successfully added a Repeater control to your worksheet page.

  6. Close Page Designer and save your changes.

Adding Fixed Layout Controls

Next, Simon needs to create a Fixed Layout control. On an Item Journal page, this type of control can be used to show a description at the bottom of the page for the item displayed in the batch line.

To add a fixed layout control

  1. Select page 50007, Susan's Item Journal and choose Design to open it in Page Designer, if it's not already open.

  2. In the next available row below the repeater controls, set Type to Group and SubType to Group. Use the arrows provided in Page Designer to move this row to the left one space. The fixed layout control should be indented at the same level as your Repeater control.

  3. On the next row, set Type to Group and SubType to FixedLayout.

  4. In the next available row, set Type to Group and SubType to Group.

  5. Finally, in the next available row, set Type to Field. Type Item Description in the Name field and accept the default indentation as you add these elements to the page.

  6. Save and preview your page. You can now see that Item Description is displayed at the bottom of your worksheet page.

    Note
    To link Item Description to Batch Lines you must add the variable Item Description to C/AL Globals in Object Designer.

Adding FactBoxes

Simon has decided to add three FactBoxes to Susan's worksheet page:

  • Item Replenishment

  • RecordLinks

  • Notes

Item Replenishment is a FactBox in an existing page, while RecordLinks and Notes are both system FactBoxes. Simon wants all these FactBoxes to be hidden unless Susan decides to show them as part of her personalization options.

To add FactBoxes to a worksheet page

  1. Select page 50007, Susan's Item Journal and choose Design to open it in Page Designer.

  2. In the first available empty row, set Type to Container and SubType to FactBoxArea. Accept the default value in the Name column.

  3. Use the left indentation arrow to negative indent the FactBox control until it has zero indention and matches the top level ContentArea container element.

  4. In the next row, set Type to Part, and accept all other default values in this row.

  5. With the same row selected, on the View menu, choose Properties. In the PagePartID property, choose the up arrow and select the Item Replenishment FactBox (9090) page from the Page List window.

  6. Set the Visible property to FALSE. This FactBox remains hidden until the user adds it to the page.

  7. Close the Properties window.

  8. In the next available empty row, add another Part for the RecordLinks system FactBox.

  9. From the View menu, select Properties.

  10. In the Properties window, set the following properties.

    Property Value

    SystemPartID

    RecordLinks

    PartType

    System

    Visible

    FALSE

  11. In the next available empty row in Page Designer, add another Part for the Notes system FactBox.

  12. Select the row, and open the Properties window.

  13. In the Properties window, set the following properties.

    Property Value

    SystemPartID

    Notes

    PartType

    System

    Visible

    FALSE

  14. Go to the next available empty row in Page Designer, and open the Properties window if it is not already open.

  15. Locate the DelayedInsert property and choose Yes.

  16. Close the Properties window.

  17. Check the indentation of your page elements and adjust if necessary.

  18. The following illustration shows the indentation of elements on the worksheet page after adding FactBoxes.

Running the Page

You will now test your new worksheet page in the Microsoft Dynamics NAV Windows client.

To run the page

  1. In Object Designer, select the page Susan’s Item Journal, page 50007, and then choose Run.

    The Microsoft Dynamics NAV Windows client opens and displays the new worksheet page. Notice that no FactBoxes are displayed.

  2. From the main menu, select Customize, then choose Choose FactBoxes. The Customize Action Tab window opens.

  3. In Available FactBoxes, select the Item Details-Replenishment FactBox, and choose Add

  4. Use the same procedure to add the RecordLinks and Notes FactBoxes. Choose the OK button, and then run the page again. Notice that the hidden FactBoxes you added are now displayed on the page.

Next Steps

Simon has now created a basic worksheet page. He must remember to add the variables, constants, and functions necessary to make the worksheet page function correctly. He knows that he add variables, constants and functions in the C/AL Globals or C/AL Locals window. For information about C/AL Globals window, see C/AL Globals. For information about C/AL functions, see C/AL Functions.

For more information about adding variables, constants, and functions, see Codeunits.

See Also

Tasks

How to: Add Actions to a Page
How to: Promote Actions to the Ribbon on Pages
Page Designer Troubleshooting
How to: Create a Page
Touring the RoleTailored Client Pages
How to: Run a Page


Page Designer Troubleshooting

This topic contains information about known troubleshooting issues in Page Designer.

OK and Cancel Button Unavailable in the Field Menu Window

The Field Menu window enables you to add fields and source expressions to a page. There are two ways in which you can use the Field Menu window:

  1. You can select a row of Type Field, choose View, and then choose Field Menu. Choose the field or fields that you want to be a source expression for the field and choose OK or Apply. You will see a message box asking, “Do you want to add the fields that are selected in the field menu?”

  2. You can open the Field Menu window, select the fields that you want to add, and then select the row in the page where you want to insert fields. If you choose this method, the OK and Cancel buttons are unavailable in the Field Menu window. If you click anywhere in the Page Designer window, you will see a message box asking, “Do you want to add the fields that are selected in the field menu?”

See Also

Concepts

Pages


Reports

You can use reports to print or display information from a database. You can use a report to structure and summarize information and to print documents, such as invoices. For example, you can create a report that lists all customers and all orders that have been added by each customer. You can also create a report that is automatically filled with the relevant information for an invoice.

You can also use reports to process data without printing or displaying content. For example, you can use a report to automate updating all prices in an item list. It can be easier to create a report to process data instead of a codeunit to do the same processing because you can use:

  • Request page functionality to select options and filters for data items, which are available in a report but are difficult to add to a codeunit.

  • Report data items instead of writing code to open tables and retrieve records.

  • Data modeling, which is available when you design reports.

Creating a report involves two primary tasks. First you design the data model, or dataset, by using Report Dataset Designer. The dataset determines the data that is extracted or calculated from the Microsoft Dynamics NAV database tables that can be used in a report. After the dataset has been designed, you design the visual layout of the report. There are two types of report layouts that you can create: client report definition (RDLC) report layouts and Word report layouts. You create RDLC report layouts by using Visual Studio Report Designer or SQL Server Report Builder. You create Word report layouts by using Microsoft Word 2013.

The following table includes links to information to help you get started designing reports.

To | See
Understand the difference between designing a data model for a report and designing the layout for a report. | Report Design Overview
Understand the different types of reports. | Types of Reports
Learn how to design reports. | Designing Reports
Learn the system requirements for Microsoft Dynamics NAV 2016 reports. | System Requirements for Microsoft Dynamics NAV 2016
Upgrade a Microsoft Dynamics NAV 2009 report to a Microsoft Dynamics NAV 2016 report. | Upgrading Reports from Earlier Versions
Add a report to the ribbon in the RoleTailored client. | How to: Make a Report Available from a Page
Learn about the different ways to run a specific report. | How to: Run Reports Printing Reports
Learn about report triggers and when they are called during report processing. | Report Triggers
Learn about how to design request pages for reports. | Request Pages
Step through detailed examples of creating reports | Report Design Walkthroughs
Use Visual Studio Report Designer to design the layouts of reports | Report Designer

See Also

Concepts

Objects


Report Design Overview

A report object is composed of a the following items:

  • Report dataset.

  • Report layout.

  • Request page.

  • Properties, triggers and code.

You design a report by first defining the dataset, and then designing the visual layout.

Report Dataset

You use Report Dataset Designer in the Microsoft Dynamics NAV Development Environment to define the dataset of a report. The dataset determines the data that is extracted or calculated from the Microsoft Dynamics NAV database tables that can be used in a report. You build the report dataset by adding data items and columns. Typically, data items and columns correspond to fields in a table. When the report is run, each data item is iterated for all records in the underlying table. Filters are applied and the dataset is created.

For more information, see Defining the Report Dataset.

Report Layout

The visual layout determines the content and format of a report when it is viewed and printed. You build the layout of a report by arranging data items and columns and specifying the general format, such as text font and size. A report that is viewed, printed, or saved from a Microsoft Dynamics NAV client must have a report layout. There are two types of report layouts: client report definition (RDLC) layouts and Word layouts. layouts.

RDLC Report Layouts

To create an RDLC layout, you use Visual Studio Report Designer or Microsoft SQL Server Reporting Services Report Builder. For more information, see Designing RDLC Report Layouts.

Word Report Layouts

You create Word layouts by using Word 2013. Word layouts are based a Word document that includes a custom XML parts that represents the report dataset. For more information, see Designing Word Report Layouts.

See Also

Reference

Report Data Type

Concepts

Reports
Designing Reports
Report Triggers
Request Pages


Types of Reports

This topic describes the types of reports that are available in Microsoft Dynamics NAV.

List Reports

A list report contains a single data item that corresponds to the table that is listed. The table can be either a master table or a supplemental table. Each column contains a field from the table. The data is printed from that table, instead of from other tables or calculated from other tables. The name of the report is usually the name of the table followed by the word "List". The following are examples of list reports:

  • Customer - List

  • Insurance - List

  • Vendor - List

Test Reports

A test report is a report that is printed from a journal table. Its purpose is to test each line in the journal according to the same criteria that will be used for posting. You can use test reports to find and fix any errors that exist before the lines are posted. This is useful because if an error is found during posting, processing stops and the error must be fixed before posting can be resumed. The name of the report is usually the name of the corresponding journal page followed by the word "Test". The following are examples of test reports:

  • General Journal - Test

  • Resource Journal - Test

Posting Reports

A posting report can be printed as part of the "post and print" option on a journal. This report is printed from the register and has the same name as that register. It lists all the transactions, that is, ledger entries, which have been posted into that register. The following are examples of posting reports:

  • G/L Register

  • Vendor Register

Transaction Reports

A transaction report contains two data items. The first data item is a master table, and the second data item is the corresponding ledger table. Usually, a transaction report lists all of the ledger entries for each record in the ledger table. There is a subtotal for each master table record, and a grand total for all the tables that are printed.

This type of report is used to view all the transactions for a particular master record. There is no standard name for this kind of report. The following are examples of transaction reports:

  • Trial Balance

  • Vendor - Trial Balance

Document Reports

Document reports differ from other reports, in that, many of the fields are not displayed in columns. An example of a document report is an invoice, where the header information is printed as if filling out an invoice document and this information is repeated at the top of each page. No page contains information from more than one header. The lines for the invoice are printed like a standard report in rows and columns. The lines correspond to the header on the same page, and lines from different invoices are not displayed on the same page. The following are examples of document reports:

  • Sales - Invoice

  • Purchase - Invoice

Processing-Only Reports

Processing-only reports only do processing. They do not output or print a report. You use the ProcessingOnly Property of the report to make the report a non-printing report. You can use the request page and let the user filter data before you run the report and begin the processing.

Other Reports

Reports are more loosely defined than other application objects because they are often customized for a particular client. However, most reports consist of a tabular list that has records listed horizontally and each field displaying in its own column. There is often a group heading or total to split the lines among various categories and subtotal the lines according to the categories. The following are examples of other reports:

  • Vendor Item Catalog

  • Customer/Item Sales

See Also

Concepts

Reports


Report Triggers

When you run a report, the report triggers are called in a specific order.

The following illustration describes the order of report triggers.

Order of report triggers

Report Triggers

When you initiate the report run, the OnInitReport Trigger is called. If the OnInitReport does not end the processing of the report, then the request page for the report is run, if it is defined. The page triggers for the request page are called. On the request page, you select the options that you want for this report. You can also decide to cancel the report run. If you decide to continue, then the OnPreReport Trigger is called. At this point, no data has yet been processed. When the OnPreReport trigger has been executed, the first data item is processed provided that the processing of the report was not ended in the OnPreReport trigger.

When the first data item has been processed, the next data item, if there is any, is processed in the same way. When there are no more data items, the OnPostReport Trigger is called to do any necessary post processing, for example, removing temporary files.

Important
If you define two functions that have the same name, one defined in a report and the other in a table that is referenced by the report, you cannot invoke the function defined in the report directly. By default, a call to the function invokes the function that is defined in the table. This behavior occurs when the function is called from a source expression or a trigger.

How a Data Item is Processed

Before the first record is retrieved, the OnPreDataItem Trigger is called, and after the last record has been processed, the OnPostDataItem Trigger is called.

Between these two triggers, the data item records are processed. Processing a record means executing the record triggers and outputting data. After a record is retrieved from the data item, the OnAfterGetRecord (Data Items) Trigger is called.

If there is an indented data item, then the records in this data item are processed.

When there are no more records to be processed in a data item, control returns to the point from which processing was initiated. For an indented data item, this means the next record of the data item on the next highest level. If the data item is already on the highest level, then control returns to the report.

See Also

Concepts

Designing Reports


Request Pages

A request page is a page that is run before the report starts to execute. Request pages enable end users to specify options and filters for a report.

You design the Options FastTab of a request page by using Request Options Page Designer in the development environment. To access Request Options Page Designer, open Report Dataset Designer, choose View, and then choose Request Page.

You design the filters on request pages by using the following report properties:

Property | Description
ReqFilterHeading Property | Sets a caption for the request page tab that is related to this data item.
ReqFilterHeadingML Property | Sets the text used as a ReqFilterHeading Property for a request page tab.
ReqFilterFields Property | Sets which fields are automatically included on the tab of the request page that is related to this data item. The user can set filters on these fields.

In addition to specifying options and filters, users can choose from the following actions on a request page:

  • Print

  • Preview

  • Cancel

  • Help

Filtering on Request Pages

The fields that you define as ReqFilterFields are shown on the request page. In addition, an end user can add more fields on which to filter to the request page.

Note
We recommend that you add fields that the end users of the report will frequently set filters on.

By default, for every data item in the report, a FastTab for defining filters and sorting is created on the request page. To remove a FastTab from a request page, do not define any ReqFilterFields for the data item and set the DataItemTableView property to define sorting. The request page is displayed but there is no tab for this data item.

If a DataItemTableView is not defined, then end users can select a sort field and sort order at runtime.

If you set UseReqPage to No, then the report will start to print as soon as it is run. In this case, end users cannot cancel the report run. It is still possible to cancel the report, but some pages may print.

In a complex report that uses data from several tables, the functionality may depend on a specific key and sort order. Design your reports so that end users cannot change the sort order in a way that affects the functionality of the report.

See Also

Concepts

Reports
Report Design Overview


Designing Reports

You design a report by first defining the dataset and then designing the visual layout. You design the dataset for reports in Report Dataset Designer of the Microsoft Dynamics NAV Development Environment. When designing the layouts, there are two different types: RDLC report layouts and Word report layouts. You design RDLC report layouts in Visual Studio Report Designer. You design Word report layouts in Word. After you design a report's dataset and layout, you can make it available for running and printing in Microsoft Dynamics NAV client applications.

The following table describes where to find information about how to design reports.

To | See
Learn about how to create a report dataset | How to: Create a Report Dataset How to: Create Labels for a Report
Learn general information about report layouts | Designing Report Layouts from the Microsoft Dynamics NAV Development Environment
Learn about how to design a RDLC report layout | Designing RDLC Report Layouts How to: Create an RDLC Report Layout How to: Integrate Report Dataset Designer and Visual Studio Report Designer
Learn about how to design a Word report layout | Designing Word Report Layouts
Walk through examples of designing reports that use the CRONUS International Ltd. demonstration database | Report Design Walkthroughs

See Also

Concepts

Report Design Overview
Reports
Running Reports
Printing Reports


Defining the Report Dataset

You use Report Dataset Designer in the Microsoft Dynamics NAV Development Environment to define the data model, or dataset, of a report. The dataset determines the data that is extracted or calculated from the Microsoft Dynamics NAV database tables that can be used in a report.

You build the report dataset from data items and columns. A data item is a table. A column can be:

  • A field in a table.

  • A variable.

  • An expression.

  • A text constant.

Typically, data items and columns correspond to fields in a table. When the report is run, each data item is iterated for all records in the underlying table. Filters are applied and the dataset is created.

When a report is based on more than one table, you must set relations between the data items so that you can retrieve and organize the data. In Report Dataset Designer, you indent data items to establish a hierarchy of data items and control how the information is gathered.

Example

To create a report that displays a list of customers and lists the sales orders that were placed by each customer, you must define the following data items:

  • A data item that corresponds to the Customer table.

  • A data item that corresponds to the Sales Order table.

You indent the second data item, which is the Sales Order table. As the report works through the records in the Customer table, it finds each customer's sales orders by examining the records in the Sales Order table.

For more information about how to create a dataset, see How to: Create a Report Dataset.

See Also

Concepts

Designing Report Layouts from the Microsoft Dynamics NAV Development Environment


How to: Create a Report Dataset

A dataset determines the data that displays on a generated report. You build the report dataset from data items and columns, where a data item is a Microsoft Dynamics NAV table and a column can be a field the table, a variable, an expression, or a text constant.

After you create the dataset, you can design the report layout.

To create a blank report and add items to the dataset

  1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report, and then choose New.

  3. In Report Dataset Designer, the first line contains DataItem in the Data Type column. In the Data Source column, either enter a table name or table number, or choose the Assist button to select a table from the table list.

  4. In the Name field of the DataItem line, either enter a name or verify the default name. The name must be a Common Language Specification (CLS)-compliant name. For more information, see the "Naming" section in Common Language Specification in the MSDN Library.

  5. In Report Dataset Designer, on the first blank line, in the Data Type column, select Column from the drop-down list.

  6. In the View menu, choose Field Menu.

    The Field Menu window opens, displaying the list of available fields from the data item.

  7. In the Field Menu window, select one or more fields that you want to add to the report dataset. Select multiple fields by holding down the SHIFT key or the CTRL key. Choose the OK button to add the selected fields to the dataset.

  8. If you want to include the caption of a column in the dataset, then select the Include Caption check box in Report Dataset Designer. The caption is included as a parameter in Visual Studio Report Designer.

    Note
    If the Include Caption column is not visible in Report Dataset Designer, then on the View menu, choose Show Column, select Include Caption, and then choose the OK button.

  9. In Report Dataset Designer, enter data items and columns until you have added all fields from all the tables that you want to include in the report.

  10. If you want to add a label to the report, such as a caption for a table header or a title for the report, then add a label to the dataset. For more information, see How to: Create Labels for a Report.

  11. If you want to include a variable in the report dataset, then do the following:

    1. In Report Dataset Designer, on a blank line, in the Data Type column, select Column from the drop-down list.

    2. In the Data Source column, enter the variable. You can use the up arrow to open the C/AL Symbol Menu dialog box and view the variables for the report.

    3. In Report Dataset Designer, in the Name column, enter a CLS-compliant name for the variable. This name is used in the dataset in Visual Studio.

  12. If you want to include a calculation or other source expression in the report dataset, then do the following:

    1. In Report Dataset Designer, on a blank line, in the Data Type column, select Column from the drop-down list.

    2. In the Data Source column, enter the source expression, such as 8*125.

    3. In the Name column, enter a CLS-compliant name for the variable. This name is used in the dataset in Visual Studio.

  13. On the File menu, choose Save.

  14. In the Save As dialog box, in the ID field, enter an ID for the report object. The ID must be in a valid range for your solution. In the Name field, enter a name for the report. Select the Compiled check box, and then choose OK.

See Also

Concepts

Designing Reports


How to: Create Labels for a Report

Whether you are using an RDLC report layout in Visual Studio or a Word report layout, if you want to add a label to the report layout, such as a caption for a field, a title for a chart, or a title for the report, then the label must be included in the report dataset. You add labels to the dataset by using Report Dataset Designer in Microsoft Dynamics NAV Development Environment. You can either add labels that are related to column of a data item in the dataset, such as the caption for a table field, or labels that are not related to a column of a data item, such as the title of the report. After you add a label to the dataset, you add to the report layout.

To add a label that is related to a column of a data item

  1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report.

  3. Select a report, and then choose the Design button.

  4. In Report Dataset Designer, do one of the following:

    • Select the Include Caption check box for a Column data type row to add a label for the column.

    • Select a Column data type row for which you want to add a label to the dataset, and on the View menu, choose Properties. In the Properties window, set the IncludeCaption property to Yes.

  5. Compile and save the report.

  6. To add the label to a report layout, see one of the following procedures.

    • How to: Add Labels to an RDLC Report Layout

    • How to: Add Fields to a Word Report Layout

To add a label that is not related to a column of data item

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report.

  3. Select a report, and then choose the Design button.

  4. In Report Dataset Designer, on the View menu, choose Labels.

  5. In Report Label Designer, in the Name field, add a Common Language Specification (CLS)-compliant name for the label. This name is used in the Visual Studio dataset. For more information, see the "Naming" section in Common Language Specification in the MSDN Library.

  6. In the Caption field, enter the caption.

    Note
    The default language of the caption depends on the current language of the development environment. For more information, see Caption Property.

  7. On the View menu, choose Properties.

  8. If you have a multilanguage application, then in the Properties window, specify values for the CaptionML property.

  9. Compile and save the report.

  10. To add the label to a report layout, see one of the following procedures.

    • How to: Add Labels to an RDLC Report Layout

    • How to: Add Fields to a Word Report Layout

See Also

Tasks

How to: Create a Report Dataset

Reference

IncludeCaption Property
CaptionML Property
Caption Property

Concepts

Designing Reports


Designing Report Layouts from the Microsoft Dynamics NAV Development Environment

After you have created a dataset for a report, you design the report layout. The report layout determines how the report looks when it is viewed, printed, and saved from the Microsoft Dynamics NAV client. The report layout specifies which fields of the dataset are included in the report and how they are arranged, the format of text that appears on the report (such as font type and color), margins, background images, and more.

You generally display most data in the body of a report, and you use the header to display information before any dataset fields are displayed. For example, you can display a report title, company, and user information in the header of a report.

Report Layout Types

There are two types of report layouts: Word and Client Report Language Definition (RDLC). Word report layouts are based on a Word document (.docx file type) and are created and modified by using Word 2013. RDLC report layouts are .rdlc or .rdl file types that are created and modified by using Visual Studio 2013 or SQL Server Report Builder 3.0.

Built-in and Custom Report Layouts

In the Microsoft Dynamics NAV Development Environment, you can create both an RDLC report layout and Word report layout on a report. These layouts are referred to as built-in layouts because they are part of the report object in the database. This means, for example, if you export the report object as a .fob or .txt file, the RDLC report layout and Word report layout are included. A report can only have one built-in RDLC report layout and one built-in Word report layout. By default, the built-in RDLC report layout is used when the report is run in the Microsoft Dynamics NAV client unless there is only a built-in Word report layout, in which case, the built-in Word report layout is used.

Microsoft Dynamics NAV users can specify whether to use the built-in RDLC or Word report layout on a report from the Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client. From the client, users can also create custom report layouts that are based on the built-in report layouts. This enables users to have several different layouts for the same report which they can switch among. Custom report layouts are managed from page 9650 Report Layouts in the Microsoft Dynamics NAV client. Unlike built-in report layouts, which are part of the report object, custom report layouts are stored in table 9650 Report Layouts of the database. For more information about setting up report layouts from the Microsoft Dynamics NAV clients, see Managing Report Layouts From the Microsoft Dynamics NAV Clients in the Application Help for Microsoft Dynamics NAV 2016.

Report Layouts in a Multitenant Deployment

In a multitenant Microsoft Dynamics NAV deployment, the built-in report layouts are stored in the application database because they are part of the report objects. Therefore, built-in report layouts are available to all tenants. Custom report layouts are stored in the business data database; therefore they are specific to the tenant. This enables you to create separate report layouts for each tenant.

See Also

Concepts

Designing RDLC Report Layouts
Designing Word Report Layouts


Designing RDLC Report Layouts

To create an RDLC layout, you use Visual Studio Report Designer or Microsoft SQL Server Reporting Services Report Builder from the Microsoft Dynamics NAV Development Environment. With RDLC layouts, you can add useful features to your report layouts, such as:

  • Links from a field on a report to either a page or another report.

  • Images and graphs.

  • The ability to toggle columns so that you can hide or display data.

  • The ability for users to interactively change the column on which data in the report is sorted.

You generally display most data in the body of a report, and you use the header to display information before any dataset fields are displayed. For example, you can display a report title, company, and user information in the header of a report.

For general information about Visual Studio Report Designer, see Report Designer (Visual Studio).

For general information about SQL Server Report Builder, see Report Design View (Report Builder).

Working with SQL Server Report Builder or Visual Studio Report Designer

By default, Visual Studio Report Designer is used when you work with RDLC layouts if it is installed on the computer that is running the development environment. Otherwise, SQL Server Report Builder is used. SQL Server Report Builder is installed with the development environment.

If your computer is running both Visual Studio Report Designer and SQL Server Report Builder, you can configure the development environment to use SQL Server Report Builder when you design layouts instead of Visual Studio Report Designer.

To configure the development environment to use SQL Server Report Builder

  1. In the development environment, on the Tools menu, choose Options.

  2. Set the Use Report Builder field to Yes.

  3. Choose the OK button.

See Also

Tasks

How to: Add and Identify Hidden Fields
How to: Add Totals in Visual Studio
How to: Apply Conditional Visibility Controls
How to: Conditionally Change a Row to Bold Font
How to: Change the Printed Values of Boolean Variables
How to: Create New Pages per Record
How to: Format Date Values
How to: Conditionally Display Filter Headers
How to: Print Report Header Information on Multiple Pages
How to: Use Option Strings in Multilanguage Implementations
How to: Reset Report Page Numbers
How to: Specify Rounding Precision
Troubleshooting: Visual Studio Report Designer provided metadata is not valid

Concepts

Understanding Headers and Footers


How to: Create an RDLC Report Layout

To create an RDLC report layout, you use Visual Studio Report Designer.

To create an RDLC report layout

  1. Open the report for which you want to create the layout as follows.

    1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

    2. In Object Designer, choose Report, select the report, and then choose the Design button.

  2. On the View menu, choose Layout.

    Visual Studio opens. The dataset in Visual Studio contains the dataset items that you added in Report Dataset Designer.

  3. Use Visual Studio Report Designer to add items from the dataset to the report and design the layout of the report. For more information, see Defining a Report Layout (Visual Studio Report Designer).

  4. In Visual Studio, on the File menu, choose Save report.rdlc, and then close Visual Studio.

  5. In Report Dataset Designer, select a new row. A dialog box shows the following message:

    The layout of report id: '<report ID>' is changed by another application.

    Filename of the changed RDLC: ‘<filename>’

    Do you want to load the changes?

  6. In the dialog box, choose Yes to load the changes that you made to the RDLC layout into the report.

  7. In the development environment, on the File menu, choose Save.

  8. In the Save dialog box, select Compiled, and then choose OK.

  9. To run the new report, in Object Designer, select the report and then choose Run.

See Also

Tasks

How to. Specify the Default Built-in Report Layout

Concepts

Designing Reports
Designing Word Report Layouts
Defining the Report Dataset


How to: Integrate Report Dataset Designer and Visual Studio Report Designer

To create and modify client report definition (RDLC) report layouts, you must use Visual Studio. When you create an RDLC layout for a report, you may have to perform some steps in Report Dataset Designer in the Microsoft Dynamics NAV development environment to modify the dataset, and some steps in Visual Studio Report Designer to modify the layout. To work with both Report Dataset Designer and Visual Studio Report Designer, you must know when and where to save your work and how to switch between them efficiently.

You can save changes to the RDLC report layout of the report in Visual Studio multiple times and then return to Report Dataset Designer and load the changes that you made to the layout into the report. You can save and compile changes to the report dataset in Report Dataset Designer multiple times and then return to Visual Studio Report Designer and reload the dataset into the report layout.

To switch between Report Dataset Designer and Visual Studio Report Designer, we recommend that you follow these steps:

  • Before you switch from Visual Studio Report Designer to Report Dataset Designer, save the report.rdlc file. You can also build the report in Visual Studio before you switch to the Report Dataset Designer, but this is not required.

  • Before you switch from Report Dataset Designer to Visual Studio Report Designer, save and compile the report.

  • After you update the dataset in Report Dataset Designer, you must refresh the dataset result in Visual Studio Report Designer. On the View menu, choose Report Data. In the Report Data pane, expand DataSets, right-click DataSet_Result, and then choose Refresh.

  • Before you rename a column in Report Dataset Designer, you must close Visual Studio Report Designer.

  • If you delete a field in Report Dataset Designer, then you must delete all instances of that field in the Visual Studio Report Designer layout. Otherwise, the report will not successfully compile.

The following procedure describes how to switch between Report Dataset Designer and Visual Studio Report Designer.

To work with both Report Dataset Designer and Visual Studio Report Designer

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. To modify an RDLC report, in Object Designer, choose Report, select the report that you want to modify, and then choose Design.

  3. On the View menu, choose Layout.

  4. After you make changes in the RDLC layout, in Visual Studio, on the File menu, choose Save Report.rdlc.

  5. In Report Dataset Designer, select an empty line in the report. A dialog box opens with the following message:

    “The layout of report id: '<report ID>' is changed by another application.
    Filename of the changed RDLC: <filename>
    Do you want to load the changes?”

  6. Choose Yes to load the changes that you made to the RDLC layout into the report.

  7. In Microsoft Dynamics NAV development environment, on the File menu, choose Save.

  8. In the Save dialog box, select Compiled, and then choose OK.

    Note
    If you try to close the report in the Microsoft Dynamics NAV development environment, then you see the following error: “You must close the Visual Studio Designer window before closing the report object.”

    Note
    If you try to view the layout when the report layout is already open, then you see the following error: “The report layout is already open in Visual Studio.”

  9. In Report Dataset Designer, make some additional changes to the report dataset.

  10. In the Microsoft Dynamics NAV development environment, on the File menu, choose Save.

  11. In the Save dialog box, select Compiled, and then choose OK.

    Important
    If you save the report but do not compile it, or if you compile the report but do not save it, then you cannot load the changes into the RDLC report layout in the following step. You must both save and compile the report.

  12. Go to the Visual Studio Report Designer. You see the following message: “This file has been modified outside of the source editor. Do you want to reload it?” Choose Yes or Yes to All to reload the changes from Report Dataset Designer into the RDLC report layout.

  13. In Visual Studio, on the View menu, choose Report Data. In the Report Data pane, expand DataSets, right-click DataSet_Result, and then choose Refresh. The additional items that you added to the dataset in Report Dataset Designer in the Microsoft Dynamics NAV development environment are displayed in the Visual Studio dataset.

  14. You can continue making changes in either Visual Studio Report Designer or Report Dataset Designer without having to close either designer. You must save and compile the report object after you make changes and load the changes into the report object or the RDLC report layout when you are prompted.


Understanding Headers and Footers

Headers and footers in client report definition (RDLC) report layouts have the following limitations:

  • From the header, you cannot refer to group-specific information in the body.

  • You can have only one report header, one body, and one report footer in a report.

    Note
    You can have group headers and footers and table headers and footers.

    Note
    Report Viewer 2015 does not render hidden expressions in headers or footers.

The following topic describes modifications that require creating a new hidden text box so that the data can be used in a header or footer:

  • How to: Print Report Header Information on Multiple Pages

For more information about Visual Studio report layouts, see Defining a Report Layout.


How to: Add and Identify Hidden Fields

If you have hidden fields on a report, we recommend that you mark them so that they are easy to identify. Additionally, you may want to move hidden fields to a different location in the layout to avoid problems with formatting.

To add and identify a hidden field

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report, select the report to which you want to add a hidden field, and then choose the Design button.

  3. On the View menu, choose Layout.

  4. In Visual Studio Report Designer, on the View menu, choose Toolbox.

    From the Toolbox, under Report Items, drag a Text Box to the report layout.

    Tip
    If the hidden text box is in a table data region, we recommend that you insert a new row in the table and add the hidden text box to this new row. In the Properties window of the row, under Layout, you can change the value of the Height property to a value that is large enough so that you can view the row when you are designing the report, but small enough that it will not cause formatting problems when you print the report, such as 0.2cm.

  5. Select the text box that you created. On the View menu, choose Properties Window.

  6. In the Properties window, under Font, set the Color property to Yellow, or select the yellow square from the drop-down list.

  7. In the Properties window, under Position, expand Size, and then set the Width property to a small width, such as 0.15cm.

  8. In the Properties window, under Visibility, set the Hidden property to True.

  9. On the File menu, choose Save Report.rdlc.

See Also

Concepts

Understanding Headers and Footers
Designing Reports


How to: Add Totals in Visual Studio

Totals are an important element of creating useful reports. By totaling data, your report can help the user analyze data that is not otherwise readily available. For example, totals provide a useful overview of the total sales for a given month. Reports can be created with Microsoft Dynamics NAV 2016 and later designed using Visual Studio. This topic describes how to add totals to a report in Visual Studio.

To add totals in Visual Studio

  1. In Visual Studio, select the total field on the report and on the shortcut menu, select Expression.

  2. In the Expression window, enter the following expression: =SUM(Fields!<tablefield>.Value)
    For example: =SUM(Fields!Sales_Line_Amount.Value)

  3. Save the report in Visual Studio.

  4. Compile and save the report in Microsoft Dynamics NAV 2016. A message informs you that the .rdlc file for this report has changed and asks if you want to load the changes. Choose Yes to save the changes in the database.

See Also

Tasks

Walkthrough: Designing a Report with Images, Interactive Sorting, and Visibility Toggle
Walkthrough: Creating a Link from a Report to a Page
How to: Make a Report Available from a Page


How to: Add Labels to an RDLC Report Layout

When you create a client report definition (RDLC) report layout in Visual Studio, you add data items and columns from the report dataset to the layout. If you want to add a label to the report layout, such as a caption for a field, a title for a chart, or a title for the report, then you must include the label in the report dataset, and then add the label to the report layout. You add labels to the dataset by using Report Dataset Designer. You add labels to the RDLC report layout by using Visual Studio.

To add a label to an RDLC report layout

  1. If not already done, add the labels to the report dataset.

    For more information, see How to: Create Labels for a Report.

  2. Open the report layout in Visual Studio as follows.

    1. In the development environment, on the Tools menu, choose Object Designer.

    2. In Object Designer, choose Report, select the report for which you want to modify, and then choose the Design button.

    3. On the View menu, choose Layout.

      The RDLC layout opens in Visual Studio. The labels that you included are available in the Report Data pane in Visual Studio, under Parameters.

      Note
      To view the Report Data pane, in Visual Studio, on the View menu, choose Report Data.

  3. Drag the labels from the parameters list to the layout to add labels to the report.

    The actual text that appears for the label in the report is the value of the Caption property for either a field in the data item table, if the label is related to column in the report dataset, or a label in the Report Label Designer, if the label is not related to a column in the dataset.

    The language of the label that is displayed when you run the report depends on the language setting of the report object. For more information, see Multiple Document Languages and Viewing the Application in Different Languages.

See Also

Concepts

Designing Word Report Layouts
Designing RDLC Report Layouts


How to: Apply Conditional Visibility Controls

Some reports have data that is printed conditionally. For example, if the request page for the report has a Show Address Details check box, then the address details are printed only if the check box is selected. Another example is a report that could show data based on a value such as a balance. If the balance is 0, then the report does not show the balance. To specify conditional visibility in an RDLC report layout, use an expression on the Visibility property of the report item or table row.

To specify conditional visibility controls

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report, select the report that you want to modify, and then choose Design.

  3. On the View menu, choose Layout.

  4. In Visual Studio, in the Report.rdlc file, select the control or table row that you want to show conditionally.

  5. On the View menu, choose Properties Window.

  6. In the Properties window, expand Visibility.

  7. Under Visibility, in the Hidden field, select <Expression…> from the drop-down list.

  8. In the Expression window, enter the conditional statement for when the control or row is hidden, and then choose the OK button.

    The following illustration shows an example of a conditional visibility expression on report 116, Statement, in the CRONUS International Ltd. demonstration database.

See Also

Tasks

How to: Conditionally Display Filter Headers

Concepts

Designing Reports


How to: Conditionally Change a Row to Bold Font

In some reports, you may want to format rows as bold based on the value of a field in the row. For example, in the CRONUS International Ltd. demonstration database, on report 1, Chart of Accounts, you could conditionally specify that rows whose account type is Posting are bold and rows whose account type is anything other than Posting are not bold.

To conditionally change rows to bold font

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report, select the report that you are modifying, and then choose Design.

  3. On the View menu, choose Layout.

  4. In Visual Studio, create a hidden text box. The hidden text box should contain the field on which you will determine whether the row is bold. For example, in the Chart of Accounts report, the hidden field contains the account type field. For more information, see How to: Add and Identify Hidden Fields.

  5. In design view, select the data row that you want to appear as bold.

  6. In the Properties window, expand Font. In the FontWeight field, select <Expression…> from the drop-down list.

  7. In the Expression window, clear the expression text box, and then select Fields(DataSet_Result) from the Category list. Under Values, double-click the field on which you will determine whether the row is bold.

  8. In the text box at the top of the Expression window, use the field that you selected in step 7to create a conditional statement. For example, the following is a conditional statement for report 1.

    =IIf(Fields!G_L_Account___Account_Type_.Value="1","Normal","Bold")

  9. On the File menu, choose Save Report.rdlc.

See Also

Concepts

Designing Reports


How to: Change the Printed Values of Boolean Variables

In a client report definition (RDLC) report layout, when a Boolean value appears on a report, the value is printed as "True" or "False" in the target language.

In some cases, you may want to change the printed value of a Boolean variable or field in an RDLC report layout. You can change the value to "Yes" or "No" instead of "True" or "False."

To change the printed value of a Boolean field

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report, select the report for which you want to change the printed values of Boolean variables or fields, and then choose the Design button.

  3. In Report Dataset Designer, find the Column for the Boolean variable or field that you want to change.

  4. In the Data Source field, change the <BooleanVariable> to FORMAT(<BooleanVariable>).

  5. On the File menu, choose Save.

  6. In the Save window, select the Compiled check box, and then choose the OK button.

See Also

Concepts

Designing Reports


How to: Create New Pages per Record

For some reports, you may want to print a new page for each new record.

An example of a report that begins a new page for each new record is report 205, Order Confirmation, in the CRONUS International Ltd. demonstration database.

To create a new page for each record

  1. Create a report dataset that includes the data items and columns that you want in the report. For more information, see How to: Create a Report Dataset.

  2. In Report Dataset Designer, on the View menu, choose Layout.

  3. In Visual Studio Report Designer, on the View menu, choose Toolbox, and then drag a List to the report layout.

  4. Below the layout, under Row Groups, right-click Details, and then choose Group Properties.

  5. In the Group Properties window, in the Name field, specify a name for the group. Under Group expressions, choose the Add button. In the Group on drop-down list, choose the field that you want to group on. For example, choose the primary key field so that you create a group for each record.

  6. In the Group Properties window, choose the Page Breaks tab. Under Page break options, select Between each instance of a group.

  7. Choose the OK button to close the Group Properties window.

  8. Design the layout of the report by dragging items to the layout within the List item, so that they are grouped. For example, a table that you add to the List item will be grouped as specified in the group properties for the List item and will have a page break at the end of each group.

In earlier versions of Microsoft Dynamics NAV, in Classic report layouts, you used the NewPagePerRecord property, the NewPagePerGroup property, or the CurrReport.NEWPAGE function to specify that you wanted a new page. In Microsoft Dynamics NAV 2016, the NewPagePerRecord property, NewPagePerGroup property, and the CurrReport.NEWPAGE function are not supported. Instead of the NewPagePerRecord property and the NewPagePerGroup property, you create groups in Visual Studio Report Designer, as described in this topic. Instead of the CurrReport.NEWPAGE function, you can create a new page number variable that you increment each time you used CurrReport.NEWPAGE, and then group data based on the new page number variable and add a page break at the end of each group.

See Also

Concepts

Designing Reports


How to: Format Date Values

You can modify date values in Report Dataset Designer to specify how they are formatted in the layout of a report.

To format date values

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report, select a report that you want to modify, and then choose Design.

  3. In Report Dataset Designer, in the Data Source field of a Column that contains a date, use the FORMAT Function (Code, Text) with the date. For example, instead of entering TODAY in the Data Source field, enter FORMAT(TODAY,0,4).

    Use the parameters of the FORMAT function to specify the length and the exact format that you want for the date.

  4. On the File menu, choose Save.

  5. In the Save window, select the Compiled check box, and then choose the OK button.

See Also

Concepts

Designing Reports


How to: Format Decimal Values

When you create a client report definition (RDLC) layout for a report, a format variable is created for each decimal variable. The format information from the Column properties in Report Dataset Designer is stored in the format variable. Decimal values are formatted in the RDLC layout by using the format variable. If you create controls that use decimal values in an RDLC report layout, then you must manually specify in Visual Studio Report Designer to use the format variable for the formatting.

To format decimal values

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report, select a report that you want to modify, and then choose Design.

  3. On the View menu, choose Layout.

  4. In Visual Studio, in the report.rdlc file, right-click the text box that displays a decimal value, and then choose Text Box Properties.

  5. In the Text Box Properties window, choose the Number tab.

  6. In the Category list, choose Custom, and then choose the Function button (fx) next to the Custom format field.

  7. In the Expression window, select Fields (DataSet_Result), select the format variable from the list, and then choose OK. For example, if the Value field on the General tab is =Fields!Customer__Sales__LCY__.Value, then the expressions for the format on the Number tab should be =Fields!Customer__Sales__LCY__Format.Value.

See Also

Concepts

Designing Reports


How to: Conditionally Display Filter Headers

If you apply a filter to the data in a report, then we recommend that you create an additional header row in the report to display the filter. You display this header row only if the user specifies a filter. If no filter is specified, then the filter header is not displayed.

To conditionally display the filter header, you must add a filter variable to the report dataset. Next, in the RDLC report layout, you must create a conditional expression on the visibility of the filter header that uses the filter variable that you added to the dataset.

An example of a report that has additional header rows to display filter information is report 113, Customer/Item Sales.

To hide non-filtered headers

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report, select the report that you want to modify, and then choose Design.

  3. On the View menu, choose C/AL Globals.

  4. In the C/AL Globals window, on the Variables tab, add a new variable for the filter. The DataType of the variable is Text.

  5. On the View menu, choose C/AL Code.

  6. In the C/AL Editor, in the OnPreReport trigger, add code to get the filters. For example, if you have a filter on the Customer table and the filter variable that you created is named CustFilter, then add the following code.

    Copy Code
    CustFilter := Customer.GETFILTERS;

  7. In Report Dataset Designer, under the DataItem for the table to which a filter can be applied, add a new line.

  8. In the Data Type field of the new line, choose Column.

  9. In the Data Source field of the new line, enter the name of the filter variable.

  10. On the File menu, choose Save. In the Save dialog box, verify that Compiled is selected, and then choose OK.

  11. On the View menu, choose Layout.

  12. In Microsoft Visual Studio, on the View menu, choose Toolbox.

    From the Toolbox, under Report Items, drag a Text Box to the report layout.

  13. Select the filter header text box that you created in step 12, and then on the View menu, choose Properties Window.

  14. In the Properties window, expand the Visibility field. In the Hidden field, select <Expression…> from the drop-down list.

  15. In the Expression window, create a conditional statement. For example, the following are the conditional statements for the two filter text boxes on report 113.

    Copy Code
    =IIF(First(Fields!CustFilter.Value) = "",TRUE,FALSE)
    Copy Code
    IIF(First(Fields!ItemLedgEntryFilter.Value) = "",TRUE,FALSE)

  16. Save and compile the report. For more information, see How to: Integrate Report Dataset Designer and Visual Studio Report Designer.

See Also

Concepts

Designing Reports


How to: Print Report Header Information on Multiple Pages

If the table data region in a report layout spans more than one page, then you must use the SetData and GetData functions on reports that have dynamic headers so that the header information is displayed on subsequent pages, not only on the first page.

For reports, such as document reports, that have table data regions that span more than one page and require dynamic header information on each page, you must do the following:

  • Create one or more hidden text boxes in the body of the report to get the data.

  • Add code for the SetData function, which saves the data, and which you call from the Hidden property of a visible text box in the header section.

  • Add code for the GetData function, which retrieves the data, and which you call from the text box in the header section where you want to display the data.

An example of a report that has multiple table data regions and uses functions to save and get header data is report 206, Sales - Invoice, in the CRONUS International Ltd. demonstration database.

To print report header information on multiple pages

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report, select a report that you want to modify, and then choose the Design button.

  3. On the View menu, choose Layout.

  4. In Microsoft Visual Studio, on the Report menu, choose Report Properties.

  5. In the Report Properties window, on the Code tab, add the following code to the Custom code text box.

    Note
    This example groups the data into four groups. You can modify the code if you need a different number of groups.

    Note
    To view this code in a report in the CRONUS International Ltd. demonstration database, see report 206, Sales - Invoice.

    Visual Basic Copy Code
    Shared Data1 as Object
Shared Data2 as Object
Shared Data3 as Object
Shared Data4 as Object
Public Function GetData(Num as Integer, Group as integer) as Object
if Group = 1 then
   Return Cstr(Choose(Num, Split(Cstr(Data1),Chr(177))))
End If
if Group = 2 then
   Return Cstr(Choose(Num, Split(Cstr(Data2),Chr(177))))
End If
if Group = 3 then
   Return Cstr(Choose(Num, Split(Cstr(Data3),Chr(177))))
End If
if Group = 4 then
   Return Cstr(Choose(Num, Split(Cstr(Data4),Chr(177))))
End If
End Function
Public Function SetData(NewData as Object,Group as integer)
  If Group = 1 and NewData > "" Then
      Data1 = NewData
  End If
  If Group = 2 and NewData > "" Then
      Data2 = NewData
  End If
  If Group = 3 and NewData > "" Then
      Data3 = NewData
  End If
  If Group = 4 and NewData > "" Then
      Data4 = NewData
  End If
  Return True
End Function

  6. In the body of the report.rdlc file, create one or more hidden text boxes to get the header data. For example, in report 206, a hidden text box starts with the following:

    =Cstr(Fields!CustAddr1.Value) + Chr(177) + Cstr(Fields!CustAddr2.Value) + Chr(177) + Cstr(Fields!CustAddr3.Value) + Chr(177) + Cstr(Fields!CustAddr4.Value) + Chr(177) + Cstr(Fields!CustAddr5.Value) + Chr(177) + Cstr(Fields!CustAddr6.Value) + Chr(177) + Cstr(Fields!CustAddr7.Value) + Chr(177) + Cstr(Fields!CustAddr8.Value) + Chr(177) + Cstr(Fields!BilltoCustNo_SalesInvHdr.Value) + Chr(177) + Cstr(Fields!VATRegNo_SalesInvHdr.Value) + Chr(177) + …

    Note
    Chr(177) is used in this example to separate the data. When you call the GetData function, it splits the data by using Chr(177) as a separator.

    For more information about how to create hidden fields, see How to: Add and Identify Hidden Fields.

  7. In the header of the report.rdlc file, create one or more text boxes to save the data from the hidden text box in the body section. For example, in report 206, a blank text box is in the header section. It has the following expression as the value of its Hidden property:

    =Code.SetData(ReportItems!CustAddr.Value,1)

    The first parameter in the SetData function call corresponds to the name of the text box in the body section. The second parameter corresponds to the group number.

  8. In the header section of the report.rdlc file, create the text boxes for displaying data. The source expression for each text box must call the GetData function with the following two parameters:

    • The number of the variable in the group.

    • The number of the group.

    For example, Code.GetData(2,1) gets the second piece of data from group 1, which is CustAddr2.Value in group 1.

  9. Save and compile the report.

See Also

Concepts

Designing Reports


How to: Use Option Strings in Multilanguage Implementations

In a client report definition (RDLC) report layout, an option variable is handled as a normal string, not an option string. If you have a multilanguage application, handling the option as a normal string will cause problems in the displayed report. You must manually convert the option string to an integer variable and then use the integer variable in the RDLC report layout.

An example of a report with an option variable that is converted to an integer variable is report 111, Customer - Top 10 List. The request page has an option variable, ShowType, that allows the user to choose to display either Sales (LCY) or Balance (LCY) in the report. The value of the ShowType variable is assigned to an integer variable, ShowTypeNo, in the OnAfterGetRecord trigger.

To assign the option string to an integer variable

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report, select the report that you want to modify, and then choose the Design button.

  3. On the View menu, choose C/AL Globals.

  4. In the C/AL Globals window, on the Variables tab, add an integer variable. You use this variable for the integer value of an existing option variable.

    For example, in report 111, Customer - Top 10 List, you have an option variable on the request page named ShowType. On the report, you create an integer variable called ShowTypeNo.

  5. Close the C/AL Globals window to save your changes.

  6. On the View menu, choose C/AL Code.

  7. In the C/AL Editor, add a line of code to the OnAfterGetRecord trigger to assign the option string to an integer value.

    For example, in report 111, you have the following line of code.

    Copy Code
    ShowTypeNo := ShowType;

  8. In Report Dataset Designer, add a Column with ShowTypeNo as the value of the Data Source field.

  9. On the File menu, choose Save.

  10. In the Save window, select the Compiled check box, and then choose the OK button.

To use the integer variable instead of the option string in the layout

  1. In Object Designer, choose Report, select the report that you want to modify, and then choose the Design button.

  2. On the View menu, choose Layout.

  3. In Microsoft Visual Studio, in the Report.rdlc file, use the integer variable instead of the option variable, such as in expressions.

    In report 111, the ShowTypeNo integer variable is used in expressions on the bar chart and the pie chart.

See Also

Concepts

Designing Reports


How to: Reset Report Page Numbers

On some reports, you may want to group sets of data together and reset the page number after each group. For example, in the CRONUS International Ltd. demonstration database, report 206, Sales Invoice, displays sales invoices that are grouped by sales invoice number. To reset the page number to 1 for each group of data, you must modify code on the client report definition (RDLC) report layout.

To reset page numbers

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report, select a report that you want to modify, and then choose the Design button.

  3. On the View menu, choose Layout.

  4. In Microsoft Visual Studio, in the Report.rdlc file, on the Report menu, select Report Properties.

  5. In the Report Properties window, select the Code tab.

  6. Add the following code in the Custom code text box:

    Visual Basic Copy Code
    REM Reset Page Number:
    Shared offset As Integer
    Shared newPage As Object
    Shared currentgroup1 As Object
    Shared currentgroup2 As Object
    Shared currentgroup3 As Object
    Public Function GetGroupPageNumber(ByVal NewPage As Boolean, ByVal pagenumber As Integer) As Object
        If NewPage Then
            offset = pagenumber - 1
        End If
        Return pagenumber - offset
    End Function
    Public Function IsNewPage(ByVal group1 As Object, ByVal group2 As Object, ByVal group3 As Object) As Boolean
        newPage = False
        If Not (group1 = currentgroup1) Then
            newPage = True
            currentgroup1 = group1
            currentgroup2 = group2
            currentgroup3 = group3
        Else
            If Not (group2 = currentgroup2) Then
                newPage = True
                currentgroup2 = group2
                currentgroup3 = group3
            Else
                If Not (group3 = currentgroup3) Then
                    newPage = True
                    currentgroup3 = group3
                End If
            End If
        End If
        Return newPage
    End Function
    Note
    This code is also available in report 206, Sales Invoice.

  7. Choose the OK button.

  8. In Visual Studio, in the Report.rdlc file, create a hidden text box in the data region that contains the data on which you have a group. For example, create a hidden text box on the table or list that contains the sales invoice number. For more information, see How to: Add and Identify Hidden Fields.

  9. Right-click the text box, and then choose Text Box Properties. In the Properties window, on the General tab, set the name of the text box to NewPage.

  10. In the Properties window, on the General tab, enter the following code in the Value field.

    Copy Code
    =Code.IsNewPage(Fields!<grouping field1>[,<grouping field2>,<grouping field3>])

    For example, if you are grouping by document type, then grouping field1 is Fields!Document_Type.Value.

    Note
    If you want to use more than three groupings, you can modify the code in the IsNewPage function. If you want to use fewer than three groupings, you can either modify the code in the IsNewPage function or use a static value for one or more of the parameters when you call the IsNewPage function.

  11. In the Text Box Properties window, choose the OK button.

  12. In Visual Studio, in the Report.rdlc file, right-click the text box in the header that displays the page number, and then select Expression.

  13. In the Expression window, enter the following expression.

    Copy Code
    =Code.GetGroupPageNumber(ReportItems!NewPage.Value,Globals!PageNumber)

    The ReportItems!NewPage.Value parameter is the value of the NewPage text box, which you created in step 8.

  14. In the Expression window, choose the OK button.

See Also

Concepts

Designing Reports


How to: Add Page Number "X" of "Y" to a Report Page Header

In Microsoft Visual Studio 2012 and Microsoft Visual Studio 2013, page breaks on tablix data regions, groups, and rectangles give you better control of report pagination. When you add page breaks to a report page, each page can have different page names and page numbering can be reset between pages. By using expressions, the page names and numbers can be dynamically updated when a report is run. You can also disable page breaks, or use an expression value to determine whether a page break should be inserted.

For some document reports, you may want to add page number “X” of “Y” in a report page header. This topic uses the Order report as an example to show how you can add page number “X” of “Y”.

Important
The following procedure illustrates how page number “X” of “Y” is added to report 405, Order. You can use similar steps to add the same page numbering to other reports that have a similar layout, but the exact names of controls, text constants, functions, and expressions vary from one report to another.

To change the page numbering caption

  1. Start the Microsoft Dynamics NAV Development Environment.

  2. On the Tools menu, choose Object Designer.

  3. Choose Report, and from the list select the Object ID 405.

  4. Choose Design, and on the View menu, choose C/AL Globals.

  5. Open the Text Constants tab. Find the text constant PageCaptonLbl, which is used as the report page caption.

  6. In the ConstValue field, replace the text with Page %1 of %2, where %1 and %2 are the placeholders for the current page and total page numbers.

  7. On the View menu, choose Layout.

    This opens the report layout in Microsoft Visual Studio.

To add page number “x” of “y” in a report page header

  1. In Microsoft Visual Studio, on the View menu, choose Other Windows, and then choose Document Outline.

  2. Under Body, choose List1 tablix, which controls an instance of a report.

  3. In the Row Groups pane, verify in the Group Properties that the list1 tablix for the Order report has a single row group, which is grouped by No_PurchHeader, DocType_PurchHeader, and OutputNo.

    Note
    If some reports have several tablix row groups, you should merge them into a single row group.

  4. In the Row Groups pane, choose the group, and then, in the Properties window, under Group, fill in the PageBreak properties as described in the following table.

    Property Value

    BreakLocation

    Between

    ResetPageNumber

    True

  5. In the Document Outline pane, under Page Header, choose the PageCaption1 text box, which displays page numbers.

    This selects the text box in the report designer.

  6. Right-click the text box, and then choose Expression. Replace the existing code with the following code.

    Copy Code
    =Replace(Replace(Code.GetData(31,1), "%1", Globals!PageNumber), "%2", Globals!TotalPages)
    Note
    The Replace function expands the placeholders in the %1 and %2 caption text with actual values.

  7. In the Document Outline pane, under Body, navigate to the NewPage text box under the table11 tablix.

    The text box is not visible in the report layout.

  8. Right-click the NewPage text box and choose Cut and then on the Page Header node, choose Paste.

  9. Replace the existing expression for the NewPage text box with the following code.

    Copy Code
    =Code.GetData(31,1) & " " & Code.GetGroupPageNumber(ReportItems!NewPage.Value,Globals!PageNumber)

  10. Save your changes and close Visual Studio.

  11. Return to the development environment, then save and compile the report.

See Also

Concepts

Designing Reports


How to: Specify Rounding Precision

In Visual Studio Report Designer, you can use the ROUND function to round a double-precision floating point value to the nearest integer. However, this function does not have options for changing the precision to which you want to round. For example, you cannot round to the nearest tenth or nearest hundredth of a number, only to the nearest integer. To specify precision when using the ROUND function, you must multiply the number by a factor of 10, call the ROUND function, and then divide the rounded number by the same factor of 10. The factor that you choose depends on the degree of precision that you want. For example, if you want to round the number 12.3456 to the nearest hundredth, you would multiply 12.3456 by 100 to get 1234.56. Next, call the ROUND function on 1234.56. The ROUND function rounds to the nearest integer, resulting in the number 1235. Finally, divide the rounded number, 1235, by the factor, 100, to get 12.35. This result is the same as rounding the original number, 12.3456, to the nearest hundredth.

To specify precision when you use the ROUND function on a client report definition (RDLC) report layout, you must do one of the following:

  • Use an expression, such as =ROUND(100*<Value>)/100 on the value in a text box.

  • Add code to functions that call the ROUND function.

An example of a report in the CRONUS International Ltd. demonstration database that uses the ROUND function and specifies a degree of precision is report 111, Customer - Top 10 List.

To use an expression to specify rounding precision

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report, select a report that contains a number that you want to round with precision greater than the nearest integer, and then choose Design.

  3. In the View menu, choose Layout.

  4. In Visual Studio, in the Report.rdlc file, right-click the text box with the number that you want to round, and then choose Expression.

  5. In the Expression window, change the expression to the following.

    Copy Code
    =ROUND(<MyField.Value>*<Factor>)/<Factor>

    In this example, MyField.Value is the numerical value that you want to round. Factor is a factor of 10, and depends on the degree of precision that you want.

  6. Choose the OK button to close the Expression window.

  7. Save and compile the report. For more information, see How to: Integrate Report Dataset Designer and Visual Studio Report Designer.

To add code to specify rounding precision

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report, select a report that contains a number that you want to round with precision greater than the nearest integer, and then choose Design.

  3. On the View menu, choose Layout.

  4. In Visual Studio, in the Report.rdlc file, on the Report menu, choose Report Properties.

  5. In the Report Properties window, select the Code tab.

  6. Add the following lines of code to the function in which you want to specify rounding precision. The code that you add may vary, depending on the degree of precision that you want. In this example, the rounding precision is 0.01.

    Copy Code
    REM Rounding precision = 0.01
Return ROUND(100*Pct)/100

  7. Save and compile the report. For more information, see How to: Integrate Report Dataset Designer and Visual Studio Report Designer.

Example

The following code example shows a function that calls the ROUND function and uses the preceding procedure to specify precision.

Copy Code
Shared Pct as Decimal
Public Function CalcPct(Amount1 as Decimal, Amount2 as Decimal) as Decimal
   if Amount2 <> 0 then
      Pct = Amount1 / Amount2 * 100
   else
      Pct = 0
   end if
   REM Rounding precision = 0.1
   Return ROUND(10*Pct)/10
End Function

The following illustration shows how to call the CalcPct function for the value of a text box.

Copy Code
=Code.CalcPct(Sum(Fields!BalanceLCY_Customer.Value), First(Fields!TotalBalance.Value))

See Also

Concepts

Designing Reports


How to. Specify the Default Built-in Report Layout

You can specify whether a report uses a built-in RDLC or Word report layout as the default layout.

To specify the default report layout

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report, select the report that you want to modify, and then choose Design.

  3. In Report Dataset Designer, select a blank row, and then on the View menu, choose Properties.

  4. In the Report - Properties window, set the DefaultLayout property to RDLC or Word.

  5. Save and compile the report.

See Also

Concepts

Designing RDLC Report Layouts
Designing Word Report Layouts


Troubleshooting: Visual Studio Report Designer provided metadata is not valid

You cannot open Visual Studio Report Designer and get the following error:

The provided metadata is not valid.

This error can occur when the following conditions are true:

  • You are using Windows 7 or Windows Vista and User Access Control (UAC) is turned on.

  • The executable file that runs the Visual Studio development environment (devenv.exe) is set to run as an administrator.

  • The executable file that runs the Microsoft Dynamics NAV Development Environment (finsql.exe) is not set to run as an administrator.

To resolve this issue, set both finsql.exe and devenv.exe to run as an administrator.

To set a program to run as an administrator

  1. Right-click the .exe file, and then select Properties.

  2. In the Properties window, on the Compatibility tab, in the Privilege Level section, select Run this program as an administrator.

See Also

Tasks

How to: Integrate Report Dataset Designer and Visual Studio Report Designer


Designing Word Report Layouts

A Word report layout is a based on Word document (.docx file type) that acts as a template for viewing and printing reports from Microsoft Dynamics NAV clients. Word report layouts enable you to design report layouts by using Word 2013. Word report layouts are built on custom XML parts in Word. A custom XML part is structured XML that represents the dataset of a Microsoft Dynamics NAV report. The custom XML part is used to map the data into a report at run time.

From the Microsoft Dynamics NAV Development Environment, you can create and modify built-in Word report layouts on reports. The layouts that you create on reports in the development environment become part of the report objects in the database.

From the Microsoft Dynamics NAV clients, Microsoft Dynamics NAV users you can manage the Word report layouts that are used on reports. This includes adding a built-in Word report layout, creating custom Word report layouts on a report, and changing which report layout is currently active on a report. For more information about how to manage Word report layouts from the Microsoft Dynamics NAV clients, see Managing Report Layouts From the Microsoft Dynamics NAV Clients in the Application Help for Microsoft Dynamics NAV 2016.

See Also

Tasks

How to: Create a Word Report Layout for a Report
How to: Modify a Word Report Layout
How to: Add Fields from a Report Dataset to a Word Report Layout
How to: Import and Export a Word Report Layout

Reference

Built-in and Custom Report Layouts


How to: Create a Word Report Layout for a Report

After you design a dataset for a report, you can create a Word report layout that can be used when you view and print a report from the Microsoft Dynamics NAV client. This topic describes how to create blank a Word report layout on a report from the Microsoft Dynamics NAV Development Environment. After you create the layout, you can modify the layout to include dataset fields and define the general format.

To create a Word report layout for a report

  1. In the development environment, open the report in Report Dataset Designer as follows.

    1. On the Tools menu, choose Object Designer.

    2. In Object Designer, choose Report, select the report, and then choose the Design button.

  2. On the Tools menu, choose Word Layout, and then choose New, and then choose the OK button.

    Note
    If the New item is inactive, then the report already has a Word report layout.

  3. Save the report object.

A blank Word report layout is created on the report object. The report layout includes a custom XML part for the current report dataset. You can now design the layout in Word. For more information, see How to: Modify a Word Report Layout.

See Also

Concepts

Designing Word Report Layouts


How to: Modify a Word Report Layout

This procedure describes how to modify a Word report layout on report from the Microsoft Dynamics NAV Development Environment. A Word report layout determines the content and format of a report when it is viewed and printed from the Microsoft Dynamics NAV client. When you modify a Word report layout, you specify the fields of the report dataset to include on report and how the fields are arranged. You also define the general format of the report, such as text font and size, margins, and background images. You will typically arrange the content of the report by adding tables to the layout.

You insert dataset fields in the layout by using a custom XML part that is automatically generated for the report when you create the Word report layout. For more information about custom XML parts, see Custom XML Part Overview for Word Report Layouts.

To modify the Word report layout

  1. In the development environment, export the Word report layout as a Word document file to your computer or network.

    For more information see To export a Word report layout document from a report to a file.

  2. Open the Word document file in Word 2013 and make changes.

    • To make basic layout changes, such as adding or removing tables and cells, formatting text, or changing margins, use the editing features of Word.

    • To add fields from the report dataset to the layout, use the custom XML part for the report to add content controls that map to the fields. For more information, see How to: Add Fields from a Report Dataset to a Word Report Layout.

    Tip
    Show the table gridlines so that you see the boundaries of table cells. Remember to hide the gridlines when you have finished editing. To show or hide table gridlines, select the table, and then under Layout on the Table tab, choose View Gridlines.

  3. Save your changes, and then close the Word report layout document.

  4. Import the Word document into the report.

    For more information, see To import a Word report layout document from a file into report.

Removing Label and Data Fields

Label and data fields of a report are contained in content controls in Word. The following figure illustrates a content control when it is selected in the Word document.

Content control for field in Word report layout

The name of the label or data field name displays in the content control. In the example, the field name is CompanyAddr1.

To remove a label or data field

  1. Right-click the field that you want to delete, and then choose Remove Content Control.

    The content control is removed, but the field name remains as text.

  2. Delete the remaining text as needed.

See Also

Concepts

Designing Word Report Layouts
Defining the Report Dataset
Designing RDLC Report Layouts


How to: Add Fields from a Report Dataset to a Word Report Layout

A report dataset can consist of fields that display labels, data, and images. This topic describes procedure for adding fields of a report dataset to an existing Word layout of a report. You add fields by using the Word custom XML part for the report and adding content controls that map to the fields of the report dataset. For more information about custom XML parts, see Custom XML Part Overview for Word Report Layouts.

To display the Custom XML part for the Report in Word

  1. Open the Word report layout document in Word for editing.

  2. Show the Developer tab in the ribbon of Word.

    By default, the Developer tab is not shown in the ribbon. For more information, see How to: Show the Developer Tab on the Ribbon.

  3. On the Developer tab, choose XML Mapping Pane.

  4. In the XML Mapping pane, in the Custom XML Part list, choose the XML part for Microsoft Dynamics NAV report. The name of the XML part has the following format:

    urn:microsoft-dynamics-nav/reports/report_name/ID

    report_name is the name that is assigned to the report as specified by the report's Name Property.

    ID is the identification number of the report.

    After you select the XML part, the XML Mapping pane displays the labels and field controls that are available for the report.

To add a label or data field

  1. Place your pointer in the document where you want to add the control.

  2. In the XML Mapping pane, right-click the control that you want to add, choose Insert Content Control, and then choose Plain Text.

    Note
    You cannot add a field by manually typing the dataset field name in the content control. You must use the XML Mapping pane to map the fields.

To add repeating rows of data fields to create a list

  1. If not already existing, add a table row that includes a column for each field that you want repeated.

    This row will act as a placeholder for the repeating fields.

  2. Select the whole row.

  3. In the XML Mapping pane, right-click the control that corresponds to the report data item that contains the fields that you want repeated, choose Insert Content Control, and then choose Repeating.

  4. Add the repeating fields to the row as follows:

    1. Place your pointer in a column.

    2. In the XML Mapping pane, right-click the control that you want to add, choose Insert Content Control, and then choose Plain Text.

    3. For each field, repeat steps a and b.

Adding Image Fields

A report dataset can include a field that contains an image, such as a company logo or a picture of an item. To add an image from the report dataset, you insert a Picture content control.

Images align in the top-left corner of the content control and resize automatically in proportion to fit the boundary of the content control.

Important
You can only add images that have a format (such as .bmp, .jpeg, and .png file types), which that is supported by Word. If you add an image that has a format that is not supported by Word, you will get an error when you run the report from the Microsoft Dynamics NAV client.

To add an image

  1. Place your pointer in the document where you want to add the control.

  2. In the XML Mapping pane, right-click the control that you want to add, choose Insert Content Control, and then choose Picture.

  3. To increase or decrease the image size, drag a sizing handle away from or towards the center of the content control.

See Also

Tasks

How to: Modify a Word Report Layout
How to: Create a Word Report Layout for a Report

Concepts

Designing Word Report Layouts


Custom XML Part Overview for Word Report Layouts

Word report layouts are built on custom XML parts. A custom XML part is structured XML that represents the dataset of a Microsoft Dynamics NAV report. The custom XML part is used to map the data into a report when the report is run from a Microsoft Dynamics NAV client.

XML Structure of Custom XML Part

A custom XML part for a Microsoft Dynamics NAV report consists of elements that correspond to the data items, columns, and labels that comprise the report's dataset as defined in the Report Dataset Designer in Microsoft Dynamics NAV Development Environment.

The following table provides a simplified overview of the XML of a custom XML part.

XML Elements Description

<?xml version="1.0" encoding="utf-16"?>

Header

<NavWordReportXmlPart xmlns="urn:microsoft-dynamics-nav/report/<reportname>/<id>/"

XML namespace specification. <reportname> is the name that is assigned to the report object in Microsoft Dynamics NAV Development Environment. <id> is the ID that is assigned to the report.

..<Labels>

....<ColumnNameCaption>ColumnNameCaption</ColumnNameCaption>

....<LabelName>LabelCaption</LabelName>

..</Labels>

Contains all the labels for the report. The element includes labels that are related to columns that have the IncludeCaption Property set to Yes and labels that are defined in Report Label Designer.

  • Label elements that are related to columns have the format <ColumnNameCaption>ColumnNameCaption</ColumnNameCaption>, where ColumnName is determined by the column's Name Property.

  • Label elements from Report Label Designer have the format <LabelName>LabelName</LableName, where LabelName is determined by the label's Name Property.

  • Labels are listed in alphabetical order.

..<DataItem1>

....<DataItem1Column1>DataItem1Column1</DataItem1Column1>

Top-level data item and columns. Columns are listed in alphabetical order.

The element names and values are determined by the Name Property of the data item or column.

....<DataItem2>

......<DataItem2Column1>DataItem2Column1</DataItem2Column1>

....</DataItem2>

....<DataItem3>

......<DataItem3Column1>DataItem3Column1</DataItem3Column1>

....</DataItem3>

Data items and columns that are nested in the top-level data item. Columns are listed in alphabetical order under the respective data item.

..</DataItem1>

</NavWordReportXmlPart>

Closing element.

Custom XML Part in Word

In Word, you open the custom XML part in the XML Mapping pane, and then use the pane to map elements to content controls in the Word document. The XML Mapping pane is accessible from the Developer tab (for more information, see How to: Show the Developer Tab on the Ribbon).

The elements in the XML Mapping pane appear in a structure that is similar to the XML source. Label fields are grouped under a common Labels element and data item and columns are arranged in a hierarchal structure that corresponds to the XML source, with columns listed in alphabetical order. Elements are identified by their name as defined by the Name property in Report Dataset Designer in development environment.

The following figure illustrates the simple custom XML part from the previous section in the XML Mapping pane of a Word document.

Clip of the XML Mapping pane in word
  • To add a label or field to the layout, you insert a content control that maps to the element in the XML Mapping pane.

  • To create repeating rows of columns, insert a Repeating content control for the parent data item element, and then add content control for the columns.

  • For labels, the actual text that appears in the generated report is the value of the Caption property for the field in the data item table (if the label is related to the column in the report dataset) or a label in the Report Label Designer (if the label is not related to a column in the dataset).

  • The language of the label that is displayed when you run the report depends on the language setting of the report object. For more information, see Multiple Document Languages and Viewing the Application in Different Languages.

For information about how to open the custom XML part in Word and add fields, see How to: Add Fields to a Word Report Layout.

See Also

Managing Report Layouts From the Microsoft Dynamics NAV Clients
About Report Layouts
How to: Create a Custom Report Layout
How to: Add Fields to a Word Report Layout
How to: Modify a Custom Report Layout


How to: Import and Export a Word Report Layout

From the Microsoft Dynamics NAV Development Environment, you can import and export built-in Word report layouts of report objects as Word document files (.docx file type). This enables you to modify a built-in Word report layout on a report. For example, you can export a built-in Word report layout to a file on your computer or network. Then, you open the file in Word and modify the report layout. Finally, you import the file back to the report object. The existing built-in Word report layout on the report is overwritten by the content in the imported file.

To export a Word report layout from a report to a file

  1. In the development environment, open the report in Report Dataset Designer as follows.

    1. On the Tools menu, choose Object Designer.

    2. In Object Designer, choose Report, select the report, and then choose the Design button.

  2. On the Tools menu, choose Word Layout, and then choose Export.

  3. Browse to the location where you want to save the exported file, and then choose the Save button.

To import a Word report layout from a file into report

  1. In the development environment, open the report in Report Dataset Designer as follows.

    1. On the Tools menu, choose Object Designer.

    2. In Object Designer, choose Report, select the report, and then choose the Design button.

  2. On the Tools menu, choose Word Layout, and then choose Import.

  3. Locate the file that you want to import, and then choose the Open button.

See Also

Tasks

How to: Modify a Word Report Layout
How to: Create a Word Report Layout for a Report

Reference

Built-in and Custom Report Layouts

Concepts

Designing Word Report Layouts


Updating Report Layouts to Dataset Changes

When you make changes to the report dataset, the report layouts that are used on the report must to be updated to the changes. The process for updating report layouts is different for built-in layouts and custom layouts.

Updating Built-in Report Layouts

With most changes to a report dataset, such as adding or renaming a field, the built-in report layout will automatically be updated to the changes when you compile the report. However, there are certain dataset changes, such as deleting a field or changing a field's ID, which cannot be updated in the built-in report layout automatically. With these types of changes, you will get an error, which includes a description of the problem, when you try to compile the report. To update a built-in report layout to dataset changes in these cases, you must manually modify the report layout in Word, Visual Studio, or SQL Report Builder, depending on the report layout type, and fix any errors that are caused by the changes. After you modify the built-in layout, you can compile the report.

For more information, see How to: Modify a Word Report Layout or Designing RDLC Report Layouts.

Updating Custom Report Layouts

The process for updating custom report layouts is different than for built-in report layouts because custom report layouts are stored in the Microsoft Dynamics NAV database for a company and are not part of the report object like built-in report layouts. There are two ways to update custom report layouts. You can use the report layout update feature from the Microsoft Dynamics NAV client or you can programmatically update the custom reports layouts by upgrade codeunits.

  • Updating custom report layouts from the Microsoft Dynamics NAV client

    The report layout update feature in the Microsoft Dynamics NAV client enables end-users to update the custom reports layouts. The report update feature can handle many types of changes to a report dataset, such as adding or renaming a field (column). However, similar to built-in report layouts, there are some changes that cannot be handled by the report update feature. To fix these changes from the client, the user will have to open and modify the report layout manually.

    For more information about updating custom report layouts from the Microsoft Dynamics NAV client, see Updating Report Layouts in the Application Help for Microsoft Dynamics NAV 2016.

  • Programmatically updating custom report layouts using upgrade codeunits

    Using C/AL code and the report update API enables you to accomplish two things. You can handle report dataset changes that cannot be done by the report update feature from the client, such as deleted columns in the dataset. It also enables you to update custom report layouts with minimal end-user interaction.

    For more information, see Updating Report Layouts to Dataset Changes.

See Also

About Report Layouts

Concepts

Designing RDLC Report Layouts
Designing Word Report Layouts


Updating Custom Report Layouts by Using Upgrade Codeunits

You can update custom report layouts by creating upgrade codeunits to handle changes in report datasets that affect the report layouts. Upgrade codeunits enable you to programmatically update multiple custom report layouts in the database to changes in report datasets. Although report layout updates can be done from the Microsoft Dynamics NAV client, there are certain changes to the dataset that require the user to manually modify report layouts before they can be used. These types of changes include, for example, deleted fields or field name conflicts as a result of renaming. Upgrade codeunits enable you handle these breaking changes to report datasets and layouts without requiring end-user interaction.

To design the report upgrade logic in an upgrade codeunit, you add C/AL code that implements the report upgrade API (through .NET Framework interoperability) and a set of functions that are available in codeunit 9651Document Report Mgt.. In the Microsoft Dynamics NAV application, codeunit 9651Document Report Mgt. is the main component for running and maintaining customized report layouts.

For general information about upgrade codeunits, see Upgrade Codeunits.

Report Upgrade API Overview

The upgrade and maintenance of report layouts in the databases is controlled by the following .NET Framework assemblies on the Microsoft Dynamics NAV Server:

  • Microsoft.Dynamics.Nav.DocumentReport.dll

  • Microsoft.Dynamics.Nav.Types.Report.dll

Microsoft.Dynamics.Nav.Types.Report Assembly

The Microsoft.Dynamics.Nav.Types.Report assembly contains the following types that you can use to for programmed report layout upgrades in upgrade codeunits.

DeleteAction Enumeration

The DeleteAction enumeration determines how content controls for fields (data items and columns of the report's dataset) in a report layout are deleted. The following table describes the members of the DeleteAction enumeration:

Member name | Description
DeleteNode | Deletes the entire XML node that is contained in the content control or the tablix that is associated with the field.
DeleteContent | Deletes the content control that is associated with the field, but leaves a blank text string in the text element (keep including paragraph formatting).
DeleteRepeater | Deletes the repeater content control, but leaves the table structure (rows) that is contained in the content control or the tablix.
DeleteRepeaterAndContent | Deletes the repeater content control and the table structure that is contained in the control.
ReplaceWithText | Deletes the content control for the field and replaces it with a text constant.

IReportUpgradeSet Interface

The IReportUpgradeSet interface provides an interface to the object that stores all changes that must be applied to a specific report layout in the current database.

Properties

The following table describes the properties of the IReportUpgradeSet interface.

Property name | Type | Description
ReportId | Integer | Gets the ID of the application report object that pertains to set of changes.
ErrorCount | Integer | Gets the number of errors that occurred during the upgrade.
ChangeCount | Integer | Gets the number of changes that are required for the report layout as a result of dataset changes.
ChangeList | IList | Gets the list of changes to report layouts.

Methods

The following table describes the methods of the IReportUpgradeSet interface. You use the methods to specify whether to delete or modify the content controls for data items and columns (fields) in a report layout. The behavior is controlled by the DeleteAction enumeration parameter.

Method name | Description
DeleteField | Deletes a content control for data field or label field from the report layout that is associated with a column in the dataset. The method can completely remove the content control or it can replace it with a text constant as specified by the DeleteAction enumeration parameter. void DeleteField(string name, string parentPath, DeleteAction action, string replacement);
DeleteDataItem | Deletes the content control from the report layout that references a data item in the dataset. The content control is deleted according to the behavior that is specified by the DeleteAction enumeration parameter. This pertains to Word layout types only. void DeleteDataItem(string name, string parentPath, DeleteAction action);
ChangeField | Renames a content control for data field or label field. You can also use this method to move the content control to a different XML path in the dataset. void ChangeField(string fromName, string toName, string fromParent, string toParent);
ChangeDataItem | Rename a control for a data item, and optionally move it to a different XML path in the dataset. This pertains to Word layout types only. void ChangeDataItem(string fromName, string toName, string fromParent, string toParent);

All methods with matching names and paths will overwrite existing change definitions in the collection for the same item.

Parameters

The following table describes the parameters of the IReportUpgradeSet interface methods.

Parameter name | Type | Description
name | String | The name of the data item, column, or label in the dataset.
fromName | String | Original name of the data item, column, or label in the dataset.
toName | String | New name of the data item, column, or label in the dataset.
parentPath | String | Path of the data item that contains the data item or field. The path is the hierarchy of the data item which contains the data item or field. The path is used to identify the content control's data bindings in Word report layouts.
fromParent | String | Original parent path that you want to change.
toParent | String | New parent path. If this parameter is left empty, then this parameter uses the value of the fromParent by default.
Replacement | String | Text constant to use in place of the deleted field in the layout.

Microsoft.Dynamics.Nav.DocumentReport Assembly

The Microsoft.Dynamics.Nav.DocumentReport assembly contains several types for creating and managing report layouts. With regards to upgrading report layouts, only the ReportUpgradeCollection class is relevant.

ReportUpgradeCollection Class

The ReportUpgradeCollection class stores sets of changes that have been calculated or specified for reports in the current database.

The ReportUpgradeCollection class has only the AddReport method. This method adds a new report to the upgrade collection.

public IReportUpgradeSet AddReport(int reportId)

This method instantiates a new object for the report ID that is specified by the reportId parameter. If the report already exists in the collection, the existing object will be returned.

Custom Report Layout Upgrade Example

This example illustrates how you can update custom report layouts to dataset changes by using C/AL code, the report update API, and upgrade codeunits. This example will update a custom report layouts for report ID 1306 Mini Sales - Invoice. The following table describes the changes to the report dataset and how to the handle the updates in the custom report layouts:

Dataset change | Report Layout Update
Removed the CompanyIBAN column | Remove the content control and text for the associated field in the report layout.
Removed the Unit Price column | Remove the associated field control in the report layout and replace it with the text "deleted".
Removed the Quantity_ShipmentLine column | Remove the associated field control and replace it with the text "Deleted".
Renamed the VariantCode_AssemblyLine column to VariantCode_NewAssemblyLine. | Rename the VariantCode_AssemblyLine field to VariantCode_NewAssemblyLine.
Tip
This example is based on the codeunit 104060 Report Layout Upgrades that is available in the Upgrade800800.fob file of the Microsoft Dynamics NAV 2016 upgrade toolkit.

To create the upgrade codeunit

  1. Create a codeunit and set the SubType Property (Codeunit) to Upgrade.

  2. Create a new local function called UpgradeReportLayout, and then do the following:

    • Define a parameter that has the name TestMode and datatype Boolean.

    • Define the following variables:

      Name DataType SubType

      ReportUpgradeSet

      DotNet

      Microsoft.Dynamics.Nav.Types.Report.IReportUpgradeSet.'Microsoft.Dynamics.Nav.Types.Report, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

      ReportUpgradeCollection

      DotNet

      Microsoft.Dynamics.Nav.DocumentReport.ReportUpgradeCollection.'Microsoft.Dynamics.Nav.DocumentReport, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

      DeleteAction

      DotNet

      Microsoft.Dynamics.Nav.Types.Report.ReportChangeOptions+DeleteAction.'Microsoft.Dynamics.Nav.Types.Report, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

      DocumentReportMgt

      Codeunit

      Document Report Mgt.

  3. Add the following code to the UpgradeReportLayout function.

    Copy Code
    // Instantiate the ReportUpgradeCollection variable
ReportUpgradeCollection := ReportUpgradeCollection.ReportUpgradeCollection;
// Calculate the set of changes for all layouts in the current database
DocumentReportMgt.CalculateUpgradeChangeSet(ReportUpgradeCollection);
// Example code snippet for applying a "breaking" change to a report design.
// The example uses report 1306 Mini Sales - Invoice.
ReportUpgradeSet := ReportUpgradeCollection.AddReport(1306);
IF NOT ISNULL(ReportUpgradeSet) THEN BEGIN
  // Delete the text content control for the CompanyIBAN column and replace with empty text string)
  ReportUpgradeSet.DeleteField('CompanyIBAN',
                               '/Header',
                               DeleteAction.DeleteContent,
                               '');
  // Delete the text content control for the UnitPrice and replace the control with the text Deleted.
  ReportUpgradeSet.DeleteField('UnitPrice',
                               '/Header/Line',
                               DeleteAction.ReplaceWithText,
                               'Deleted');
  // Delete the control containing the field.
  ReportUpgradeSet.DeleteField('Quantity_ShipmentLine',
                               '/Header/Line/ShipmentLine',
                               DeleteAction.DeleteNode,
                               '');
  // Rename the VariantCode_AssemblyLine field
  ReportUpgradeSet.ChangeField('VariantCode_AssemblyLine',
                               'VariantCode_NewAssemblyLine',
                               '/Header/Line/AssemblyLine',
                               '/Header/Line/AssemblyLine');
END;
// Apply the upgrade steps to the report layouts
DocumentReportMgt.ApplyUpgradeToReports(ReportUpgradeCollection,TestMode);

    The UpgradeReportLayout function instantiates a report upgrade collection object and calculates the change set based on the current report dataset designs and the XML documents that are stored with the custom report layouts in the application database. Then, it adds additional changes to the custom report layouts for report 1306, including deleting fields and renaming a field.

    Finally, the DocumentReportMgt.ApplyUpgradeToReports method applies all the updates to report layouts in the current database. If the TestMode parameter is True, the layout changes are only tested and will not be committed to the database.

  4. Add a function called TestLaypoutUpgrade and set the FunctionType Property (Upgrade Codeunits) to CheckPrecondition. Add the following code:

    Copy Code
    UpgradeReportLayout(FALSE);

    The defines a CheckPrecondition function type, which is the first function that is executed when the codeunit is run. This function will test the report layout changes before they are applied to the layouts in the database. If an error occurs when this function is run, then the changes are not applied.

  5. Add a function called RunLayoutUpgrade and set the FunctionType Property (Upgrade Codeunits) to UpgradePerDatabase. Add the following code:

    Copy Code
    UpgradeReportLayout(TRUE);

    This function is run after the CheckPrecondition function to perform the upgrade the report layouts.

  6. Save and compile the codeunit.

  7. Perform a data upgrade to run the upgrade codunit.

    Open development environment as an administrator. On the Tools menu, choose Data Upgrade, and then choose Start and follow the instructions.

    Note
    You can also perform the data upgrade by running the Start-NavDataUpgrade cmdlet from the Microsoft Dynamics NAV 2016 Administration Shell.

See Also

Concepts

Updating Report Layouts to Dataset Changes
Designing Word Report Layouts
Designing RDLC Report Layouts


Report Design Walkthroughs

The following topics describe end-to-end processes that you can follow to design and modify reports.

In This Section

Documentation | Description
Walkthrough: Designing a Customer List Report | This walkthrough describes how to create a simple report based on one table with Microsoft Dynamics NAV and design this report using Visual Studio Report Designer.
Walkthrough: Creating a Link from a Report to a Page | Describes how to modify the Customer - Top 10 List report to include a link to the customer card.
Walkthrough: Creating a Link from a Report to a Report | Describes how to modify the Customer - Top 10 List report to include a link to the Customer - Detail Trial Bal. report.
Walkthrough: Designing a Report with Images, Interactive Sorting, and Visibility Toggle | Describes how to create a report that displays images, allows interactive sorting, and visibility toggle.
Walkthrough: Creating a Nonprinting Report | Describes how to create a report that only does processing without outputting or printing a report.
Walkthrough: Running a Report Offline | Describes how to view a report datatset and report layout on a computer that does not have Microsoft Dynamics NAV installed
Walkthrough: Designing a Report from Multiple Tables | Describes how to create a report that combines data from four tables.
Walkthrough: Adding Company Information, Custom Filters, and Formatting to a Report | Describes how to modify a report to add filters and format the layout.

See Also

Concepts

Reports


Walkthrough: Designing a Customer List Report

In Microsoft Dynamics NAV 2016, creating new reports is divided into the following phases:

  • Defining the dataset on which the report is based.

  • Designing and editing the visual layout of the report by using Visual Studio Report Designer.

About This Walkthrough

This walkthrough provides an overview of how to create a report that is based on one table with Microsoft Dynamics NAV and design this report using Visual Studio Report Designer. This walkthrough illustrates the following tasks:

  • Create a report in Microsoft Dynamics NAV.

  • Apply sorting criteria and filters on the report in Microsoft Dynamics NAV.

  • Design the layout of the report in Visual Studio.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV with a developer license.

  • The CRONUS International Ltd. demo data company.

  • Microsoft Visual Studio installed. For more information about which version of Microsoft Visual Studio you need, see System Requirements for Microsoft Dynamics NAV 2016. This walkthrough assumes that Microsoft Visual Studio 2012 or Microsoft Visual Studio 2013 is used.

Defining the Dataset

When you create a new report, you must define where the data that the report will display should come from. You define the dataset in Microsoft Dynamics NAV Report Dataset Designer.

To define the dataset

  1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report, and then choose the New button to open the Report Dataset Designer.

  3. In the first row, in the Data Source field, choose the AssistEdit button. In the Table List window, select table 18, Customer, and then choose the OK button.

  4. In Report Dataset Designer, on the first row, verify that the Data Type column is set to DataItem.

  5. On the View menu, choose Field Menu.

  6. In the Field Menu window, select the No., Name, Address, Phone No., and Country/Region Code fields, and then choose the OK button.

    You can select multiple items by holding down the Ctrl key while you select.

  7. When prompted to add these fields, choose Yes.

  8. On the File menu, choose Save As.

  9. In the Save As dialog box, in the ID field, enter 55551, and in the Name text box, enter Customer List.

  10. Make sure the Compile check box is selected and choose the OK button.

Applying Sorting Criteria and Filters

Next, you will set the sorting criteria and filters that you want to use in the report. This report will sort the customers in ascending order by customer number. You will also provide filters on the request page that will enable users to filter the data based on the No. and Country/Region code.

To set the report properties

  1. In Report Dataset Designer, select the DataItem row.

  2. On the View menu, choose Properties.

  3. In the Properties window, select the DataItemTableView property, and then, to open the Table View property window, choose the Value field.

  4. In the Table View window, fill in the fields as shown in the following table.

    Field Description

    Key

    Specify the field to sort the data items by, in this case the No. field.

    Order

    Specify the sort order, in this case Ascending.

  5. Choose the OK button.

    You will now add filters to the request page that will enable users to filter the data based on the No. or Country/Region Code, or both by default.

  6. In the Properties window for the Customer data item, select the ReqFilterFields property, and then choose the Value field to open the Field List property window.

  7. In the Field List window, specify the two fields that the data can be filtered by as shown in the following table.

    Field

    No

    Country/Region Code

  8. Choose the OK button.

  9. On the File menu, choose Save.

  10. In the Save window, make sure Compile is selected, and then choose the OK button.

  11. Close the Properties window.

Designing the Report Layout

After you have saved and compiled the report in Report Dataset Designer, you must design the layout in Visual Studio. For this report, you will display all the fields that you selected, and display the company name in a larger font and set it to bold. You will also display the date, time, and username of the person who runs the report.

To design the layout of the report

  1. On the View menu, choose Layout.

    The report opens in Visual Studio. The report layout is empty.

  2. In Visual Studio, on the View menu, choose Toolbox to open the toolbox.

  3. From the Toolbox, drag a Table control to the report layout.

    The table has only three columns, therefore, you will add two more columns to accommodate all the fields in the dataset.

  4. Select the third column, open the shortcut menu, choose Insert Column, and then choose Right to add a new column. Repeat to add another column.

    The next step is to populate the table with the data from the dataset.

To populate the list with data from the dataset

  1. On the View menu, choose Report Data.

  2. In the Report Data window, under Datasets, and under DataSet_Result, select each field and drag them from the dataset to the second row of the Data section of the report layout as described in the following table.

    Field Column

    No_Customer

    First

    Name_Customer

    Second

    Address_Customer

    Third

    PhoneNo_Customer

    Fourth

    CountryRegionCode_Customer

    Fifth

  3. From the Toolbox, drag three text boxes and put them above the table in the report designer. These text boxes will display the date and time, the username, and the company name.

  4. Select the first text box, open the shortcut menu, and then choose Expression to open the Expression Properties window.

  5. Under Category, choose Built-in Fields, double-click ExecutionTime, and then choose the OK button.

    This expression displays the time the report was executed.

  6. Select the second text box, open the shortcut menu, and then choose Expression to open the Expression Properties window.

  7. Under Category, choose Built-in Fields, double-click UserID, and then choose the OK button.

    This expression displays the user ID of the user who runs the report.

  8. Select the third text box, open the shortcut menu, and then choose Text Box Properties to open the Text Box Properties window.

  9. On the General tab, in the Value field, enter the company name. For this walkthrough, you can enter CRONUS International Ltd..

  10. In the Textbox Properties window, on the Font tab, set the font size to a larger font, such as 14pt, and under Style, select Bold, and then choose the OK button.

    You will format the text boxes for the field captions in the table to display in bold font.

  11. On the report layout, resize the three text boxes to an appropriate size.

  12. Select the No Customer caption text box, and choose Text Box Properties to open the properties window.

  13. On the General tab, in the Value field, change the value to Customer No.

  14. On the Font tab, and under Style, select Bold, and then choose the OK button.

  15. Set the remaining caption text boxes to bold.

  16. Save the Report.rdlc file, and then close Visual Studio.

Loading the Design Changes from Visual Studio and Running the Report

Now you will load the changes that you made in Visual Studio to Microsoft Dynamics NAV to apply the changes to the Customer List report.

To load the design changes from Visual Studio and run the report

  1. In Microsoft Dynamics NAV Development Environment, close Report Dataset Designer. A message informs you that the .rdlc file for this report has changed and asks if you want to load the changes. Choose Yes to save the changes in the database.

  2. In the Save Changes window, make sure Compile is selected, and then choose Yes to save the report.

  3. In Object Designer, select the report (55551) and choose Run. The request page is displayed.

  4. In the request page, on the Customer tab, set the Country/Region Code filter to a country/region code and choose Preview to view the report. The report displays all the customers in the country/region code you selected.

    You can filter the report by No. or Country/Region Code or both.

Next Step

  • Now you have created a report that lists customers by customer number or country/region code, and you have added changes to the report layout in Visual Studio. The next step is to add the customer list report to a page in the RoleTailored client from where it can be run. For more information, see How to: Make a Report Available from a Page.

See Also

Tasks

How to: Make a Report Available from a Page
Walkthrough: Creating a Link from a Report to a Page
Walkthrough: Designing a Report with Images, Interactive Sorting, and Visibility Toggle


Walkthrough: Designing a Report with Images, Interactive Sorting, and Visibility Toggle

In Microsoft Dynamics NAV 2016, creating new reports is divided into the following phases:

  • Defining the data model on which the report is based.

  • Defining grouping and totaling for the report.

  • Designing the visual layout of the report.

With Microsoft Dynamics NAV, you can use Visual Studio Report Designer to design and modify the visual layout of a report.

About This Walkthrough

This walkthrough provides an overview of how to create a report that displays images, allows interactive sorting, and provides visibility toggling. This walkthrough illustrates the following tasks:

  • Defining the data model in Microsoft Dynamics NAV.

  • Designing the report layout and adding an image using Visual Studio Report Designer.

  • Synchronizing the report layout with Microsoft Dynamics NAV and running the report.

  • Applying interactive sorting to the report layout using Visual Studio Report Designer.

  • Resynchronizing the report layout with Microsoft Dynamics NAV and running the report.

For more information about how to design the layout of a report by using Visual Studio, see Defining a Report Layout (Visual Studio Report Designer).

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV with a developer license.

  • The CRONUS International Ltd. demo data company.

  • Microsoft Visual Studio installed. For more information about which version of Microsoft Visual Studio you need, see System Requirements for Microsoft Dynamics NAV 2016. This walkthrough assumes that Microsoft Visual Studio 2012 or Microsoft Visual Studio 2013 is used.

Defining the Data Model

When you create a new report, you must define where the data that the report will display should come from. You define the data model in Microsoft Dynamics NAV.

To define the data model

  1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report, and then choose New to open the Report Dataset Designer window.

  3. In the first row, in the Data Source field, select table 27, choose the AssistEdit button. In the Table List window, select table 27, Item , and then choose the OK button.

  4. In Report Dataset Designer, on the first row, verify that the Data Type column is set to DataItem.

  5. On the View menu, choose Field Menu.

  6. In the Field Menu window, select the No., Description, and Picture fields, and then choose the OK button.

    You can select multiple items by holding down the Ctrl key while you select.

  7. When prompted to add these fields, choose Yes.

  8. On the File menu, choose Save As.

  9. In the Save As dialog box, in the ID field, enter 50000, and then in the Name text box, enter ItemReport.

  10. Make sure Compile is selected, and then choose the OK button.

Designing the Report Layout and Adding an Image

Now that you have defined the data model for the report in Microsoft Dynamics NAV, you can design and refine the layout in Visual Studio.

To design the report layout and add an image in Visual Studio

  1. On the View menu, choose Layout.

    The report opens in Visual Studio. The report layout is empty.

  2. In Visual Studio, on the View menu, choose Toolbox to open the toolbox.

  3. From the Toolbox, drag a Table control to the report designer.

  4. On the View menu, choose Report Data. The Report Data window opens.

  5. From the Report Data window, under Datasets, and under DataSet_Result, drag the No_Item field to the first column, second row of the table in the Data section of the report layout.

  6. Under Datasets, and under DataSet_Result, drag the Description_Item field to the second column and second row of the table in the Data section.

  7. From the Toolbox, drag an Image control to the third column, second row of the table. The Image Properties window opens.

  8. In the Image Properties window, on the General tab, in the Select the image source, choose Database.

    When you change the source, the values in the MIMEType property change.

    Property Setting

    Source (On the General tab, under Select the image source)

    Database

    Value (On the General tab, under Use this field)

    [Picture_Item]

    Note
    This is the Name of the Item.Picture column in Report Dataset Designer.

    MIMEType (On the General tab, under Use this MIME Type)

    image\bmp

  9. On the General tab, in the Use this field field, choose ƒx to open the expression window for the picture field and then verify that the Set expression for: value text box contains the following value: =Fields!Picture_Item.Value. Choose the OK button to close the windows.

  10. In the Image Properties window, on the General tab, in the Use this MIME type field, choose image/bmp.

    This value is only available if the image source is set to Database.

  11. Optionally, resize the data row of the table to the appropriate size for the pictures.

  12. In the third column, first row of the table, enter Picture. This is the caption of the column.

  13. In the File menu, choose Save Report.rdlc, and then close Visual Studio.

Synchronizing and Running the Report

Now you will load the changes that you made in Visual Studio to Microsoft Dynamics NAV to synchronize the two versions of the ItemReport.

To synchronize and run the report

  1. In the development environment, close ItemReport in Report Dataset Designer. A message informs you that the .rdlc file for this report has changed and asks if you want to load the changes. Choose Yes to save the changes in the database.

  2. In the Save Changes window, make sure Compile is selected and then choose Yes to save the report.

  3. In the Object Designer, select the report (50000) and choose Run.

  4. Choose Preview to view the report. The report displays all in the items table.

  5. Close the report and run the report again.

  6. You can filter the report to only view items that have a picture associated with them by setting a filter for picture field.

    In the request page for the Item Report, under Show results, choose Add Filter. In the Where drop-down list box, select Picture, and in the Enter Value text box, enter 1. Choose Preview. Now, only items that have pictures are displayed.

  7. Close the report.

Setting Up Interactive Sorting and Visibility Toggle

Now you will add interactive sorting to the ItemReport. Interactive sorting will enable users to interactively change the sort order for the data columns. By using the sort control button in the column header on the report, the user can change the sort order between ascending and descending.

To set up interactive sorting and visibility toggle

  1. In the development environment, in Object Designer, select the ItemReport report and then choose Design to open it in Report Dataset Designer.

  2. On the View menu, choose Layout. The report opens in Visual Studio.

  3. Select the No Item text box in the first row, first column, open the shortcut menu, and then choose Text Box Properties.

  4. In the Text Box Properties window, choose the Interactive Sorting tab.

  5. Select the Enable interactive sort action for this text box check box.

  6. In the Sort by drop-down list box, select [No_Item] from the list, choose ƒx to open the expression window, and then verify that the Set expression for: SortExpression text box contains the following value: =Fields!No.Item.Value. Choose the OK button.

  7. Choose OK to close the Change interactive sort options for this text box window.

  8. Select the Description_Item text box in the first row, second column, open the shortcut menu, and then choose Text Box Properties.

  9. In the Text Box Properties window, choose the Interactive Sorting tab.

  10. Select the Enable interactive sort action for this text box check box.

  11. In the Sort by drop-down list box, select [Description_Item] from the list, choose ƒx to open the Expression window, and then verify that the Set expression for: SortExpression text contains the following value: =Fields!Description_Item.Value. Choose the OK button.

  12. Choose OK to close the Text Box Properties window.

  13. Open the shortcut menu for the Image field in the second row, third column, and select Image Properties.

  14. In the Image Properties window, on the Visibility tab, select the Display can be toggled by this report item check box, and then, in the field, choose Textbox1.

  15. Choose the OK button.

  16. On the File menu, choose Save Report.rdlc and close Visual Studio.

Resynchronizing and Running the Report

After you have applied the latest changes to the report in Visual Studio, you will load the changes that you made in Microsoft Dynamics NAV to synchronize the two versions of the ItemReport. After the changes have been loaded, you can run the report to see the interactive sorting functionality.

To resynchronize and run the report

  1. Switch to the development environment.

  2. If the ItemReport report is open in Report Dataset Designer, then close it. A message informs you that the .rdlc file for this report has changed and asks if you want to load the changes. Choose Yes to save the changes in the database.

  3. In the Save Changes window, make sure Compile is selected and choose Yes to save the report.

  4. In Object Designer, select the report, and then choose Run.

    Alternatively, you can run the report using the DynamicsNAV:////runreport?report=50000 command from the Windows start menu.

  5. Choose Preview to view the report. You can use interactive sorting for the No Item and Description Item columns. You can also collapse each item to hide the picture.

See Also

Other Resources

Report Design Walkthroughs


Walkthrough: Creating a Link from a Report to a Report

This walkthrough illustrates how to set up a report to include a link from the Customer - Top 10 List report to the Customer - Detail Trial Bal. report. When you run the Customer - Top 10 List report in preview mode and show balance data, you can choose either a value in the Balance (LCY) column or a section of the pie chart to view detailed balance information. By including this functionality, you now have a dynamic report that enables you to drill down into data.

About This Walkthrough

This walkthrough illustrates the following tasks:

  • Enabling hyperlinks on a report.

  • Adding a link from the Balance text box on the report to another report.

  • Formatting the Balance text box to indicate that it is a link.

  • Adding a link from the pie chart to another report.

  • Running the modified report.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 with a developer license.

  • The CRONUS International Ltd. demonstration database.

  • Microsoft Visual Studio installed. For more information about which version of Microsoft Visual Studio you need, see System Requirements for Microsoft Dynamics NAV 2016. This walkthrough assumes that Microsoft Visual Studio 2012 or Microsoft Visual Studio 2013 is used.

Enabling Hyperlinks on a Report

Before you can add a link from a report to another report, you must enable hyperlinks on the report. For more information, see EnableHyperlinks Property.

To enable hyperlinks on a report

  1. In the Microsoft Dynamics NAV 2016 Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report, select report 111, the Customer - Top 10 List report, and then choose Design. The Report Dataset Designer window opens.

  3. In Report Dataset Designer, select an empty row.

  4. On the View menu, choose Properties.

  5. In the Report - Properties window, in the EnableHyperlinks field, set the Value field to Yes.

  6. From the File menu, choose Save, and in the Save dialog box, make sure Compile is selected and choose OK to compile and save the report.

  7. Close the Properties and the Report Dataset Designer windows.

Adding a Link from the Balance Text Box

In the following procedure, you add a link from the balance text box in report 111, the Customer - Top 10 List report to report 104, the Customer Detail Trial Bal. report.

To add a link from the Balance Field

  1. In Object Designer, choose Report, select report 111, the Customer - Top 10 List report, and then choose Design.

  2. On the View menu, choose Layout. Visual Studio opens.

    If you are opening Visual Studio from Microsoft Dynamics NAV for the first time you will choose your development environment. Otherwise, skip the next step.

  3. In the Choose Your Development Default Environment window, select General Settings and choose Start Visual Studio.

  4. In Visual Studio, choose the Report.rldc file to open it, and then in the Body section of the report, locate the BalanceLCY_Customer text box. The value of the text box is =Fields!BalanceLCY_Customer.Value. You can confirm this value by selecting the text box and viewing the Value property in the Visual Studio Properties window.

  5. Select the text box, and then from the shortcut menu, choose Text Box Properties.

  6. In the Text Box Properties window, choose the Action tab.

  7. Select the Go to URL check box and enter the following expression in the Select URL text box below the Go to URL check box:

    Copy Code
    ="dynamicsnav:////runreport?report=104&filter=Customer.%22No.%22:"+Fields!No_Customer.Value

    For more information about creating filters in a URL to run a report, see How to: Run Reports.

  8. Choose OK to close the window.

  9. On the File menu, choose Save Report.rdlc to save the report in Visual Studio.

Formatting the Balance Text Box

After adding the link from the balance text box to report 104, you may want to change the format of the balance text box to indicate that the data in the text box is a link. The following steps illustrate how to format the text box.

To format the Balance text box

  1. In Visual Studio, in the Body section of the report, select the BalanceLCY_Customer text box.

  2. On the View menu, choose Properties Window.

  3. In the Properties window, in the Color field, select Blue. Expand Font and set Text Decoration, to Underline.

  4. Save the report in Visual Studio.

Adding a Link from a Pie Chart

The following steps add a link from the data in the pie chart to report 111.

To add a link from a pie chart

  1. In Visual Studio, select the pie chart, and then, from the shortcut menu, choose Series Properties.

  2. In the Series Properties window, select the Action tab, then select Go to URL and enter the following expression in the Select URL text box below the Go to URL check box:

    Copy Code
    ="dynamicsnav:////runreport?report=104 &filter=Customer.%22No.%22:"+Fields!No_Customer.Value

    For more information about creating filters in a URL to run a report, see How to: Run Reports.

  3. Choose the OK button to close the Series Properties window.

  4. In Visual Studio, on the File menu, choose Save Report.rldc to save and then close the report in Visual Studio.

Running the Modified Report

In the development environment, you must now save the modified report and compile it before it you can run it.

To run the modified report

  1. In the development environment, save the Customer - Top 10 List report.

    A message informs you that the .rdlc file for this report has changed and asks if you want to load the changes. Choose Yes to save the changes in the database.

  2. In the Save window, verify that the Compiled check box is selected, and then choose OK.

  3. In the development environment , select the Customer - Top 10 List report and choose Run. The Edit-Customer- Top 10 List page for report 111 opens in the Microsoft Dynamics NAV Windows client.

  4. Under Options, in the Show drop-down list box, select Balance (LCY) and in the Chart Type drop-down list box, select Pie chart.

  5. Choose Preview to view the report. The report lists the top 10 list of customers. Notice that the Balance (LCY) column is formatted as a hyperlink. If you select the pie chart, you will notice that the chart is also formatted as hyperlink.

  6. Choose a value in a Balance (LCY) column. The Customer - Detail Trial Bal. report for the specified customer opens.

  7. Choose a sector in the pie chart that represents a customer. The Customer - Detail Trial Bal. report for the specified customer opens.

    Alternatively, you can run the report from the Run window.

  8. On the Windows taskbar, choose Start, and then choose Run.

  9. In the Run window, enter the following text: dynamicsnav:////runreport?report=111, and then choose the OK button.

See Also

Tasks

Walkthrough: Creating a Link from a Report to a Page

Other Resources

Report Design Walkthroughs


Walkthrough: Creating a Link from a Report to a Page

You can create reports that provide dynamic data with Visual Studio Report Designer and Microsoft Dynamics NAV 2016. Your reports can include images, graphics, toggles on data columns, interactive sorting, and links to other data in the system. This walkthrough illustrates how to set up a report to include a link to the Customer Card page. When the report is run in preview mode, you can look up any existing customer directly from the report. By including this functionality, you now have a report that is a dynamic list that you can use to drill down into data instead of a report that is a static, printed list.

About This Walkthrough

The walkthrough provides an overview of how to modify the Customer - Order Summary report to include a link to the Customer card. This walkthrough illustrates the following tasks:

  • Enabling hyperlinks on a report.

  • Adding a link to the customer name on the report using Visual Studio.

  • Running the modified report.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 with a developer license.

  • The CRONUS International Ltd. demo data company.

  • Microsoft Visual Studio installed. For more information about which version of Microsoft Visual Studio you need, see System Requirements for Microsoft Dynamics NAV 2016. This walkthrough assumes that Microsoft Visual Studio 2012 or Microsoft Visual Studio 2013 is used.

Enabling Hyperlinks on a Report

Before you can add a link from a report to a page, you must enable hyperlinks on the report. For more information, see EnableHyperlinks Property.

To enable hyperlinks on a report

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report, select report 107, the Customer - Order Summary report, and then choose the Design button.

  3. In Report Dataset Designer, select an empty line.

  4. On the View menu, choose Properties.

  5. In the Properties window, in the EnableHyperlinks field, select Yes.

  6. On the File menu, choose Save In the Save dialog box, make sure Compile is selected and then choose the OK button to compile and save the report.

Adding a Link to Customer Name in Visual Studio

In the following procedure you add a link to the customer name on the report that opens the Customer card for the selected customer.

To add a link to customer name in Visual Studio

  1. In the development environment, with the Customer - Order Summary report open in Report Dataset Designer, on the View menu, choose Layout.

  2. In Visual Studio, in the Body section of the report, locate the First(Name_Cust) text box. The expression for the text box is =First(Fields!Name_Cust.Value).

    Note
    This report has two rows that contain the First(Name_Cust) text box. Only one row is displayed on the report. The row that is displayed depends on whether the user selects the Show Amounts in LCY check box in the request page. You must add the link to both of the text boxes that contain the customer name. This walkthrough only describes adding the link to one text box.

  3. Right-click the text box, and then choose Properties.

  4. In the Properties window, select the Action tab.

  5. Select the Go to URL check box and enter the following line in the Select URL field: ="dynamicsnav://///runpage?page=21&$filter=Customer.'No.'%20IS%20'''%40" + Fields!No_Cust.Value + "*'''"

    This opens page 21, the Customer Card page, and filters on which customer card to open.

  6. In the Text Box Properties window, on the Font tab, under Color, choose ƒx to open the expression window.

  7. Under Set expression for: Color, enter ="#0066dd".

  8. Choose the OK button to close both windows.

  9. Save the Report.rdlc file, and then close Visual Studio.

Running the Modified Report

In the development environment, you must now save the modified report and compile it you run it to see the changes.

To run the modified report

  1. In the development environment, save the Customer - Order Summary report. A message informs you that the .rdlc file for this report has changed and asks if you want to load the changes. Choose Yes to save the changes in the database.

  2. Save and compile the report.

  3. On the Windows taskbar, choose Start, and then choose Run.

  4. In the Run window, enter the following text: dynamicsnav:////runreport?report=107, and then choose OK. For more information about the syntax for running a report from the Run window, see Creating and Running Hyperlinks.

  5. Choose Preview to view the report. The report shows the order detail (the quantity not yet shipped) for each customer in three periods of 30 days each, starting from a selected date. If you select the customer name, then the specific Customer card opens. This makes it possible to drill down into the customer's data.

See Also

Tasks

Walkthrough: Designing a Report with Images, Interactive Sorting, and Visibility Toggle
Walkthrough: Designing a Customer List Report


Walkthrough: Creating a Nonprinting Report

In this walkthrough, you will create a non-printing report. A non-printing report is a report that only does processing without actually outputting or printing a report. This type of processing is usually achieved by using codeunits. You use the ProcessingOnly Property of the report to make the report non-printing without much programming. This functionality also gives you access to the request page and enables the user to filter the data before you run the report. Instead of writing C/AL code to open tables and retrieve records, you only have to define a data item.

About this Walkthrough

This walkthrough shows you how to create a non-printing report that enable a user to adjust the prices in the item table. The user enters the factor by which to adjust the prices on the request page. The user can use the filters on the request page to filter the data and apply the adjustment to only the filtered data.
This walkthrough illustrates the following tasks:

  • Defining a data model.

  • Declaring variables.

  • Adding controls to the request page.

  • Using triggers to process the data.

  • Testing the report.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 installed with a developer license.

  • The CRONUS International Ltd. demonstration database.

Defining the Data Model

When you create a new report, you must define where the data that the report will display should come from. You define the dataset in Microsoft Dynamics NAV Report Dataset Designer.This report has one data item that is based on the Item table (table 27).

To define the data model

  1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report, and then choose the New to open the Report Dataset Designer.

  3. In the first row, in the Data Source field, choose the up arrow to open the Table List window. In the Table List window, select the Item table (table 27), and then choose the OK button.

  4. Verify that the Data Type column is set to DataItem.

  5. On the View menu, choose Field Menu.

  6. In the Field Menu window, select all the fields and then choose the OK button.

    You can select all the fields by selecting the upper-left corner of the window or by holding down the Ctrl key and selecting all the fields.

  7. At the prompt, choose Yes to add the selected fields.

  8. Select the DataItem row, and on the View menu, select Properties.

  9. In the Properties window, select the DataItemTableView property, and in the Value field, choose the AssistEdit button to open the Table View window.

  10. In the Key field, select the No. key and choose the OK button.

  11. In the Order drop-down list, select Ascending. Choose the OK button to close the window.

  12. In the Properties window, select the ReqFilterFields property, and in the Value field, choose the AssistEdit button to open the Field List window.

    You will add filters that will enable users to filter the data based on the No. field or the Inventory Posting Group field or both.

  13. In the first row, choose the up arrow to open the Item-Field List window and select the No. field, and then choose the OK button.

  14. In the second row, choose the up arrow to open the Item-Field List window and select the Inventory Posting Group field, and then choose the OK button.

    You will now set the property that will make the report nonprinting. Later, you will add code to triggers to do the actual processing.

  15. In Report Dataset Designer, select the next empty row. On the View menu, choose Properties to open the Properties window of the report.

  16. In the Properties window, locate the ProcessingOnly property, and in the Value column, choose Yes.

  17. A message that states that the report layout will be deleted appears. Choose Yes to delete the layout. On the File menu, choose Save As.

  18. In the Save As dialog box, in the ID field, enter 50006, and then in the Name text box, enter Nonprinting Report.

  19. Make sure Compile is selected, and then choose the OK button.

Declaring Variables

You will now declare the variables you will be using in the code.

To declare variables

  1. On the View menu, choose C/AL Globals and declare the following variables. You will enter the variable name and the data type in the C/AL Globals window. The subtype and length are not applicable.

    Variable name DataType

    Window

    Dialog

    Adjustment

    Decimal

    NewPrice

    Decimal

Adding Controls to the Request Page

You will now add a text box where the user will enter the adjustment factor. By default, the value of the text box is 0.

To add a text box control

  1. On the View menu, choose Request Page to open the Request Options Page Designer.

  2. In the Request Options Page Designer, on the first row, in the Name column, enter a name, then in the Type column, select Container, and then in the Subtype column, select ContentArea. For example, you can name the container AdjustmentContainer.

  3. On the second row, in the Caption column, enter Enter the adjustment factor, and in the Type column, select Field. In the Source Expr column, choose the AssistEdit button to open the C/AL Symbol Menu window.

  4. In the C/AL Symbol Menu window, select Adjustment, the variable you created earlier, and choose the OK button. This value will be used as the factor by which the unit price will be adjusted.

  5. Verify that the second row is indented one unit to the right and then close the Request Options Page Designer.

Using Triggers to Execute Code

Now that you have defined the data model and designed the request page, you will add C/AL code to the triggers of the Item data item to calculate the actual price adjustment.

To use the triggers to execute code

  1. In Report Dataset Designer, select the DataItem row.

  2. On the View menu, choose C/AL Code to open the C/AL Editor.

  3. In the OnPreDataItem() trigger, enter the following lines of code:

    Copy Code
    Window.OPEN('Processing item #1#########');
If Adjustment = 0 THEN
  CurrReport.QUIT;

    The first statement in the OnPreDataItem trigger opens a progress window that shows the progress of the report as it is run. Because the report is nonprinting, the usual printing progress window is not shown. If the table is large, the report may run for a while. Therefore, it is a good idea to show the user how the process is progressing.

    The second statement ends the report without doing any processing if the adjustment factor is 0 (zero). If the adjustment factor were allowed to be zero, all the prices in the table could be set to zero.

  4. In the OnAfterGetRecord() trigger, enter the following lines of code:

    Copy Code
    Window.UPDATE(1,"No.");
NewPrice := Adjustment * "Unit Price";
VALIDATE("Unit Price", NewPrice);
MODIFY;

    The first statement in the OnAfterGetRecord trigger enters the item number in the window when a new record is retrieved. The second statement uses the value stored in the adjustment variable to adjust the unit price of the items and assigns the adjusted price to the NewPrice variable. The VALIDATE function of the Unit Price field is used to update the price of the items. Any special processing (for example, updating of related fields) in the OnValidate trigger of the table field is performed. Finally, the MODIFY function is used to write the change.

  5. Close the C/AL Editor window and save the report.

Testing the Report

You can now test the report.

To test the report

  1. In Object Designer, select the report you just created and then choose Run. The request page for the report is displayed.

  2. In the Enter the adjustment factor text box, enter an adjustment factor. For example, you can enter 10 and then choose OK. The window opens and displays the items that are being adjusted. In this case, the unit prices for all the items in the table are adjusted. The report is not displayed and is not printed.

    You can run the Items table, look at the unit prices and run to report again using an adjustment factor of 10. If you look at the unit prices in the Item table again, you will notice that the unit prices have increased by a multiple of 10. You can also set the filters to select specific records to modify.

Next Steps

You might consider designing a report that has a layout and can be printed. For more information, see Walkthrough: Designing a Customer List Report.

See Also

Other Resources

Report Design Walkthroughs


Walkthrough: Running a Report Offline

You can view a report and view the dataset and layout on a computer that does not have Microsoft Dynamics NAV installed. To do this, you must have Microsoft Visual Studio installed and you must export the report dataset from Microsoft Dynamics NAV as an .xml file and export the report layout .rdlc file from Visual Studio Report Designer.

Important
The dataset .xml file that you export contains actual data from the report. Do not share this file if you do not want to share actual database data.

About This Walkthrough

This walkthrough illustrates the following tasks:

  • Exporting the report dataset as an .xml file.

  • Copying the report layout .rdlc file.

  • Running the report by using Microsoft Visual Studio.

Prerequisites

To complete this walkthrough, you will need:

  • One computer with the following:

    • Microsoft Dynamics NAV 2016 with a developer license.

    • CRONUS International Ltd. demonstration database.

    • Microsoft Visual Studio installed. For more information about which version of Microsoft Visual Studio you need, see System Requirements for Microsoft Dynamics NAV 2016. This walkthrough assumes that Microsoft Visual Studio 2012 or Microsoft Visual Studio 2013 is used.

  • A second computer with Microsoft Visual Studio.

Story

Viktor is a Microsoft Certified Partner working for CRONUS International. He is working on some enhancements to the Customer - Top 10 List report, but during his development phase, he has encountered some problems. Viktor wants to send the report to Microsoft Support to help him troubleshoot the problems. The Microsoft Support engineer wants to be able to view the report and report data offline instead of on a computer that has Microsoft Dynamics NAV installed. Viktor saves the report dataset and the report layout and sends them to the Microsoft Support engineer, who runs the report on his computer by using Visual Studio.

Saving the report dataset and layout

First, Viktor exports the report dataset to an .xml file.

To export the report dataset to an .xml file

  1. On the computer with Microsoft Dynamics NAV installed, open the Microsoft Dynamics NAV Windows client.

  2. In the Search box, enter Customer - Top 10 List, and then choose the related link.

  3. On the request page for the Customer - Top 10 List report, on the Application menu Application Menu button in menu bar, choose Help, and then choose About This Page to activate the About This Report feature. For more information, see How to: View and Export the Dataset for a Report.

  4. Close the About This Page page.

  5. On the request page for the Customer - Top 10 List report, choose Preview to open the Customer - Top 10 List report in Report Viewer.

  6. On the report preview, on the Application menu Application Menu button in menu bar, choose Help, and then choose About This Report to display the report dataset.

  7. On the About This Report page, choose Export as XML.

  8. In the Export File dialog box, choose Save.

    Export File dialog box. Choose the Save button.

  9. In the Export File dialog box, navigate to your Desktop, enter Dataset for the file name, set the Save as type field to XML (*.xml), and then choose Save.

Next, Viktor must save the report layout as an .rdlc file.

To copy the report layout .rdlc file

  1. In the development environment, choose Tools, and then choose Object Designer.

  2. In Object Designer, choose Report, select report 111, Customer - Top 10 List, and then choose Design.

  3. On the View menu, choose Layout to open the report layout in Visual Studio.

  4. In Visual Studio, in Solution Explorer, select Report.rdlc, and then in the Properties window, note the path where the Report.rdlc file is located.

    Visual Studio 2010 Solution Explorer, Properties
    Tip
    If the Properties window is not visible, then on the View menu, choose Properties.

  5. Copy the Report.rdlc file from the location in the Properties window to your Desktop.

Viktor sends both the Dataset.xml file and the Report.rdlc file to the Microsoft Support engineer who is helping him troubleshoot the report.

Running the Report Offline

The Microsoft Support engineer has received the Dataset.xml file and the Report.rdlc file from Viktor and now runs the report on his computer by using Visual Studio.

Note
If the report references external assemblies, then you must install the assemblies in the global assembly cache on the computer on which you want to run the report. For more information, see EnableExternalAssemblies Property and Extending Microsoft Dynamics NAV Using Microsoft .NET Framework Interoperability,

To run the report by using Visual Studio

  1. Copy the Dataset.xml file and Report.rdlc file from the first computer, which has Microsoft Dynamics NAV installed, to your desktop on the second computer, which does not have Microsoft Dynamics NAV installed.

  2. On the second computer, open Visual Studio.

  3. In Visual Studio, in the File menu, choose New, and then choose Project.

  4. In the New Project window, under Installed Templates, expand Visual C#, choose Windows, and then choose Windows Forms Application.

    Visual Studio 2010, New Visual C# Project
    Tip
    If Visual C# is not listed under Installed Templates, then you must install the Visual C# feature. To do this, in Control Panel, choose Programs, choose Uninstall a program, select your version of Microsoft Visual Studio, and then choose Uninstall/Change. In the setup wizard, follow the instructions to add or remove features, and then choose the Visual C# feature.

  5. In the Name field, enter OfflineReport, and then choose the OK button to create the solution.

  6. In Solution Explorer, right-click the OfflineReport project, choose Add, and then choose Existing Item.

    Visual Studio 2010, Add Existing to project

  7. In the Add Existing Item dialog box, navigate to your Desktop, set the file type to All Files (*.*), select the Dataset.xml file and the Report.rdlc file, and then choose Add.

    Add Existing Item dialog box, file type All Files

  8. In Solution Explorer, under OfflineReport, select Dataset.xml. In the Properties window, in the Copy to Output Directory field, choose Copy Always from the drop-down list.

    Tip
    If the Properties window is not visible, then on the View menu, choose Properties.

  9. In the Toolbox window, under Reporting, drag a new Report Viewer control to Form1.

    Visual Studio 2010, Report Viewer control
    Tip
    If the Toolbox window is not visible, then on the View menu, choose Toolbox.

    Note
    You may need to resize the report viewer control or the form.

  10. Select the report viewer control, and then in the Properties window, under Misc, expand Local Report, and then set the ReportEmbeddedResource property, to OfflineReport.Report.rdlc.

    Visual Studio, ReportEmbeddedResource property
    Note
    If your report includes external images, then in the Properties window of the report viewer control, you must set the EnableExternalImages property to True.

    Note
    If your report includes hyperlinks, then in the Properties window of the report viewer control, you must set the EnableHyperlinks property to True. For examples of creating reports that include hyperlinks, see Walkthrough: Creating a Link from a Report to a Report and Walkthrough: Creating a Link from a Report to a Page.

  11. In Solution Explorer, select the OfflineReport project, and on the shortcut menu, choose Add, and then choose Class.

    Visual Studio 2010, Add a Class to a solution

  12. In the Add New Item window, under Installed Templates, choose Visual C# Items, and then choose Class.

    Visual Studio, Add a Class, select Visual C# class

  13. In the Name field, enter CreateDataSource.cs, and then choose Add.

  14. In the CreateDataSource.cs tab, replace the code with the following.

    Copy Code
    using System.Data;
namespace OfflineReport
{
    public static class CreateDataSource
    {
        public static DataTable CreateTable()
        {
            DataSet dataSet = new DataSet();
            dataSet.ReadXml("Dataset.xml");
            return dataSet.Tables[0];
        }
    }
}

  15. On the File menu, choose Save CreateDataSource.cs.

  16. Choose the Form1.cs [Design] tab, and then on the View menu, choose Code.

  17. In the Form1.cs tab, replace the code with the following.

    Copy Code
    using System;
using System.Windows.Forms;
using Microsoft.Reporting.WinForms;
namespace OfflineReport
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet_Result", CreateDataSource.CreateTable()));
            this.reportViewer1.RefreshReport();
        }
    }
}

  18. On the Build menu, choose Build Solution. The solution builds successfully.

  19. On the Debug menu, choose Start Debugging to view the report in the report viewer control.

    Visual Studio 2010, Debug menu, Start Debugging

  20. To make changes to the report layout, in Solution Explorer, right-click Report.rdlc, and then choose Open.

Tip
Now that you have created the OfflineReport solution, to run other reports from Visual Studio, you only need to replace the Dataset.xml and Report.rdlc files.

See Also

Concepts

Importing and Exporting Objects


Walkthrough: Designing a Report from Multiple Tables

A report object is composed of a report dataset and a visual layout. You design a report by first defining the dataset and then designing the visual layout. You design the dataset for reports in Microsoft Dynamics NAV Report Dataset Designer and design the layout in Visual Studio Report Designer. After you design a report, you can make it available to applications that are running on the Microsoft Dynamics NAV Windows client. A report can be designed from one table or multiple tables. This walkthrough demonstrates how to design a report from multiple tables.

About This Walkthrough

This walkthrough shows you how to design a report by using Report Dataset Designer and Visual Studio Report Designer.

This walkthrough illustrates the following tasks:

  • Defining the dataset for multiple tables.

  • Defining properties for the data items.

  • Adding fields to a data item.

  • Adding labels to a report.

  • Design a client report definition (RDLC) report layout in Visual Studio 2012.

  • Setting filters to hide empty rows and fields in a report.

  • Building and running a report.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 installed with a developer license.

  • The CRONUS International Ltd. demonstration database installed.

  • Microsoft Visual Studio installed. For more information about which version of Microsoft Visual Studio you need, see System Requirements for Microsoft Dynamics NAV 2016. This walkthrough assumes that Microsoft Visual Studio 2012 or Microsoft Visual Studio 2013 is used.

Story

Viktor is a developer who is working for CRONUS International Ltd. Viktor has been asked by his manager to create a report that shows data from the Customer (18), Cust. Ledger Entry (21), Detailed Cust. Ledger Entry (379), and the Sales Header (36) tables. The report should meet the following requirements:

  • The report should display customer information at the top of the report.

  • For each customer, the report should show a list of ledger entries.

  • For each ledger entry, the report should show a list of detailed ledger entries under the ledger entries.

  • The report should display basic sales document headers information for the selected customer.

  • Each section of the data for each customer should begin on a new page.

  • The Amount field from the Cust. Ledger Entry table should be totaled and displayed for each customer.

  • If there are no records to display, the report should not display that data sections. For example, if there are no sales documents for a customer, the sale header section should be skipped.

  • Amount fields must not display zero values.

  • The orientation of the report should be landscape.

    The following illustration shows an example of the second page of the report.

Defining the Dataset

In this task, Viktor will create the dataset that will display customers and their transaction details. The datasets for the data model will come from four tables. Viktor will create a data item for each for table.

To define the dataset

  1. In the Microsoft Dynamics NAV Development Environment, on the main menu, choose Tools, and then choose Object Designer.

  2. In Object Designer, choose Report, and then choose New to open Report Dataset Designer.

  3. In Report Dataset Designer, select the first row, in the Data Type field verify that DataItem is selected. In the Data Source field, choose the up arrow, select the Customer table (18), and then choose the OK button.

  4. On the next row, in the Data Type field, choose DataItem, in the Data Source field choose the AssistEdit button, select Cust. Ledger Entry (21) table from the Table List window, and then choose the OK button. This row is automatically indented under the first row. This means that for each customer record, all the records in the Customer Ledger Entries table will be displayed.

  5. On the next row, in the Data Type field, choose DataItem, in the Data Source field, choose the AssistEdit button, select the Detailed Cust. Ledg. Entry (379) table, and then choose the OK button. Note that this row is automatically indented under the second row.

  6. On the next row, in the Data Type field, select DataItem, in the Data Source field, choose the AssistEdit button, select the Sales Header (36) table, and then choose the OK button.

  7. Use the left arrow to indent the row two times to the left so that the row is at the same level as Cust. Ledger Entry (21) data item.

    The following illustration shows an example of the Report Dataset Designer after you have added the data items.

    The DataItems in Object Designer

Defining Properties for the Data Items

Now that the data set is defined, Viktor will define the properties of data items.

To define properties for the data items

  1. Select the Customer data item, and then on the View menu, choose Properties.

  2. In the Properties window, locate the DataItemTableView Property, and then choose the AssistEdit button in the Value field to open the Table View window.

  3. In the Key field, choose the up arrow, select No. from the Customer-Key List window, choose the OK button, and then in the Table View window, choose the OK button.

  4. Locate the ReqFilterFields Property, choose the AssistEdit from the Value field to open the Fields List window.

  5. In the Field List window, choose the up arrow, choose No. from the Customer - Fields List window, choose the OK button, and then choose the OK button in the Field List window.

  6. Locate the PrintOnlyIfDetail Property and set the Value field to Yes.

    The following illustration shows the properties window for the Customer data item.

    Customer Data Item properties

  7. In Report Dataset Designer, select the Cust. Ledger Entry data item.

  8. In the Properties window, locate the DataItemTableView Property, and then choose the AssistEdit button in the Value field to open the Table View window.

  9. In the Key field, choose the up arrow, select Entry No. from the Cust. Ledger Entry Key List window, choose the OK button, and then in the Table View window, choose the OK button.

  10. Locate the DataItemLink Property (Reports) and choose the AssistEdit button to open the DataItem Link window.

  11. In the first row, in the Field column, choose the up arrow. In the Cust. Ledger Entry-Field List window, select Customer No., and then choose the OK button.

  12. In the Reference Field column, select the up arrow. In the Customer - Field List window, select No., choose the OK button, and then choose the OK button in the DataItemLink window.

    The following illustration shows the Properties window for the Cust. Ledger Entry data item.

    Cust.Ledger Entry Properties

  13. Select the Detailed Cust. Ledg. Entry data item.

  14. In the Properties window, locate the DataItemTableView Property, choose the AssistEdit button in the Value field to open the Table View window.

  15. In the Key field, choose the up arrow, select Entry No. from the Detailed Cust. Ledger Entry Key List window, and then choose the OK button. In the Table View window, choose the OK button.

  16. Locate the DataItemLink Property (Reports) and choose the AssistEdit button to open the DataItem Link window.

  17. In the Field column, choose the up arrow. In the Detailed Cust. Ledg. Entry-Field List window, select Cust. Ledger Entry No., and then choose the OK button.

  18. In the Reference Field column, select the up arrow, in the Cust. Ledger Entry-Field List window, select Entry No., and then choose the OK button.

  19. In the second row, in the Field column, select the up arrow. In the Detailed Cust. Ledg. Entry-Field List window, select Customer No., and then choose the OK button.

  20. In the Reference Field column, select the up arrow. In the Cust. Ledger Entry-Field List window, select Customer No., choose the OK button, and then choose the OK button.

    The following illustration shows the Properties window for the Detailed Cust. Ledg. Entry data item.

    Detailed Cust. Ledger Entry Properties

  21. Select the Sales Header data item.

  22. Locate the DataItemTableView Property and choose the AssistEdit button to open the Table View window.

  23. In the Key field, choose the up arrow, select Document Type,No. from the Sale Header - Key List window, and then choose the OK button. In the Table View window, choose the OK button.

  24. Locate the DataItemLink Property (Reports), choose the AssistEdit button to open the DataItem Link window.

  25. In the Field column, select the up arrow. In the Sales Header-Field List window, select Sell-to-Customer No., and then choose the OK button.

  26. In the Reference Field column, select the up arrow, in the Customer-Field List window, select No., choose OK and then choose the OK button.

    The following illustration shows the Properties window for the Sales Header data item.

    Sales Header Properties window

  27. Close the Properties window.

Adding Fields to the Data Items

Viktor will now add the fields to the data items. For each table, he will add the fields that he wants to display on the report.

To add fields to the data items

  1. In Report Dataset designer, select the Customer data item, on the View menu, choose Field Menu.

  2. In the Field Menu window, select the following fields, and then choose the OK button. The following table shows the fields in Report Dataset Designer.

    Field to select Name

    No.

    No_Customer

    Name

    Name_Customer

    Address

    Address_Customer

    Phone No.

    PhoneNo_Customer

    E-Mail

    EMail_Customer

    Note
    You can hold down the Ctrl key to select multiple fields.

  3. Choose the OK button and then choose Yes at the prompt.

    The following illustration shows the Customer data item with its fields in Object Designer.

    Object Designer with customer fields

  4. Select the Cust. Ledger Entry data item and repeat steps 1 through 3 to add the fields. The following table shows the fields in Report Dataset Designer.

    Field to select Name

    Entry No.

    EntryNo_CustLedgerEntry

    Customer No.

    CustomerNo_CustLedgerEntry

    Posting Date

    PostingDate_CustLedgerEntry

    Document Type

    DocumentType_CustLedgerEntry

    Document No.

    DocumentNo_CustLedgerEntry

    Description

    Description_CustLedgerEntry

    Currency Code

    CurrencyCode_CustLedgerEntry

    Amount

    Amount_CustLedgerEntry

    Original Amt (LCY)

    OriginalAmtLCY_CustLedgerEntry

    Remaining Amt. (LCY)

    EntryType_DetailedCustLedgEntry

  5. Select the Detailed Cust. Ledger Entry data item and repeat steps 1 through 3 to add the fields. The following table shows the fields in Report Dataset Designer.

    Field to select Name

    Entry No.

    EntryNo_DetailedCustLedgEntry

    Entry Type

    EntryType_DetailedCustLedgEntry

    Posting Date

    PostingDate_DetailedCustLedgEntry

    Document Type

    DocumentType_DetailedCustLedgEntry

    Document No.

    DocumentNo_DetailedCustLedgEntry

    Amount (LCY)

    AmountLCY_DetailedCustLedgEntry

    Transaction No.

    TransactionNo_DetailedCustLedgEntry

    Journal Batch Name

    JournalBatchName_DetailedCustLedgEntry

    Debit Amount (LCY)

    DebitAmountLCY_DetailedCustLedgEntry

    Credit Amount (LCY)

    CreditAmountLCY_DetailedCustLedgEntry

  6. Select the Sales Header data item and repeat steps 1 through 3 to add the fields. The following table shows the fields in Report Dataset Designer.

    Field to select Name

    Document Type

    DocumentType_SalesHeader

    No.

    No_SalesHeader

    Posting Date

    PostingDate_SalesHeader

    Prices Including VAT

    PricesIncludingVAT_SalesHeader

    Amount

    Amount_SalesHeader

  7. Select the first field under the Customer data item. On the View menu, choose Properties and then set the IncludeCaption Property of each field to Yes.

  8. Repeat step 7 to set the IncludeCaption Property of each field under each DataItem to Yes. Alternatively, you select the Include Caption check box for all the fields. This check box is located in the right corner in Report Dataset Designer.

Adding Labels to the Report

Viktor will now add labels to the report. The label in Report Dataset Designer stores the label values for the report data set.

To add labels to the report

  1. On the View menu, choose Labels to open Report Label Designer.

  2. In the first row, in the Name field, enter Sales_Document_Caption, and then in the Caption field, enter Sales Documents.

  3. In the second row, in the Name field, enter Total_Caption in the Caption field, and then enter Total. Close Report Label Designer.

    These labels will be used later as captions in the report.

    Viktor will save the report and run it to view how his report looks like at this point.

  4. From the File menu, choose Save to open the Save As window.

  5. In the ID field, enter 50001 . In the Name field, enter Report for Multiple Tables, Make sure that Compile is selected, and then choose the OK button.

  6. In Object Designer, select Report for Multiple Tables (50001), and then choose the Run button to run the report.

    The following illustration shows an example of the request page that is displayed when the report is run.

    If you choose the Preview button on the request page, the report will display a blank page because a layout for the report is not designed yet.

Designing the Visual RDLC Layout for the Report

Next, Viktor will design a RDLC layout for the report by using Visual Studio Report Designer. He will set properties for the report and the report elements, format the report, and then add the data to the report.

To design the RDLC layout for the report

  1. Choose anywhere inside the Report Dataset Designer. On the View menu, choose Layout to open the RDLC report in Microsoft Visual Studio. The body of the report is displayed in Visual Studio.

  2. Right-click anywhere outside the report (in the shaded area) and then choose Add Page Header.

  3. Right-click anywhere outside the report (in the shaded area), and then choose Report Properties.

  4. In the Report Properties window, choose the Page Setup tab. Iin the Paper size section, under Orientation, choose the Landscape, and then choose the OK button.

  5. On the View menu, choose Toolbox to open the Toolbox pane. Select the List control, and then choose the body of the report to add the List control to the report. This control will contain and group all the data.

  6. Move the List control to the top of the report body and resize it to cover the whole report body.

  7. Right-click the middle of the List controls, and then choose Rectangle Properties.

  8. In the Rectangle Properties window, choose the Fill tab, in the Fill Color list color pallet, select Cornflower Blue from the color pallet, and then choose the OK button. You can choose any color.

    Note
    Changing the color of report elements helps you identify elements on the report preview. You can set different color properties for table header, detail rows, text boxes, and so on.

    Viktor will set the properties of the List control to hold the dataset, group the data by Customer No. and set up how the groups should be displayed.

To set the list control properties

  1. Select the List control, right-click the shaded border to the left of the List control, and then choose Tablix Properties.

  2. In the Tablix Properties window, on the General tab, under Dataset name, select DataSet_Result from the drop-down list, and then choose the OK button.

  3. Select the List control, right-click the shaded border to the left of the list control, choose Row Group, and then Group Properties.

  4. In the Group Properties window, on the General tab, under Group expressions:, choose the Add button, and then select [No_Customer] from the Group on: drop-down list. This groups all the data in the List control by customer number.

  5. On the Page Breaks tab, select Between each instance of a group, and then choose the OK button.

    Viktor is now ready to add the customer data. The table will display one customer at a time, therefore Viktor must put all the fields into table header rows. The table data and footer rows will be disabled.

To add customer data

  1. From the Toolbox pane, drag a Table control into the List control and resize the table to about the half the width of the list control. This table will contain the customer data.

    The following illustration shows the list control and the table.

    The list control on the report

    Note that the table contains two table rows, a header row (first row), and a data row (second row). The three parallel lines in the left border of the second row identify the data row.

  2. Select any table row, right-click the shaded border, and then choose Tablix Properties to open the Tablix Properties window.

  3. On the General tab, verify that the Dataset name field is set to DataSet_Result, and then choose the OK button.

    The table has three columns. Viktor will add a fourth column to the table to hold all the customer data.

  4. Right-click the middle column header, choose Insert Column, and then select Right to insert the fourth column into the table.

  5. Select the second table row (the data row), right-click the row, choose Delete Rows to delete the data row, and then choose the OK button in the Delete Rows window to delete the row and its associated groups.

  6. Select the remaining table row, right-click the shaded border on the left, choose Insert Row, and then choose Below to insert another table header row.

  7. Repeat step 6 to insert a third table header row. There should now be three header rows in the table.

  8. Right-click the first cell (row 1, column 1) in the table, and then choose Expression to open the Expression window.

  9. In the Category column, select Parameters, in the Item column, verify that All is selected, and then in the Values column, double-click No_CustomerCaption. Verify that the Set expression for: Value box contains the following value: =Parameters!No_CustomerCaption.Value. This cell will display the customer No. caption in the report.

  10. Modify the expression to =First(Parameters!No_CustomerCaption.Value). Choose the OK button.

    Note
    All caption fields must begin with =First so that the first value for the caption fields in the data set is retrieved and used as caption. If the First function is not used, the report will return the current value for a field. The current value however may be incorrect. For example, the current value could be empty.

  11. Right-click the second cell (row 1, column 2) in the table, and then choose Expression to open the Expression window.

  12. In the Category column, select Field(DataSet_Result), in the Item column verify that All is selected, and then in the Values column double-click No_Customer. Verify that the Set expression for: Value box contains the following value =Fields!No_Customer.Value. Choose the OK button. This cell will display the Customer No..

  13. Repeat steps 8 through 12 to the enter captions and values in the following cells.

    Note
    Columns 1 and 3 will contain the captions and columns 2 and 4 will contain the values.

    Row Column Caption Value

    2

    1

    Name_CustomerCaption

    None

    2

    2

    None

    Name_Customer

    1

    3

    Addreess_CustomerCaption

    None

    1

    4

    None

    Address_Customer

    2

    3

    PhoneNo_CustomerCaption

    None

    2

    4

    None

    PhoneNo_Customer

    3

    3

    Email_CustomerCaption

    None

    3

    4

    None

    Email_Customer

  14. Select all table rows (not the whole table), and then on the View menu, choose Properties Window to open the Properties window in Visual Studio.

  15. In the Properties window, under Fill, set the BackgroundColor property to Plum. You can choose any color.

    The layout that Viktor has designed to this point resembles the following illustration.

    The layout containing the customer data

  16. On the Build menu, choose Build Web site to build the project. Inspect the Output pane and make sure that there are no build errors. Close Visual Studio.

    Note
    It is a good practice to build the project periodically during the report design to make sure that there are no build errors.

    Viktor will run the report and preview what he has done to this point.

  17. In Microsoft Dynamics NAV Development Environment, in Report Dataset Designer, select a data item. In the dialog box that appears that indicates that the layout of the report is changed by another application, choose the Yes button.

  18. On the File menu, choose Save. In the Save window, verify that Compile is selected, and then choose the OK button.

  19. In Object Designer, select your report (50001) and then choose the Run button.

  20. In the request page that is displayed, choose the Preview button to view the report. The first customer is displayed on the first page. If you page through the report, each customer is displayed on a separate page.

Viktor will now add the data for the customer ledger entries and detailed ledger entries. The entries will be put in a different table.

To add the data for ledger entry and detailed ledger entry

  1. Select Report Dataset Designer. On the View menu, choose Layout to open the RDLC report in Microsoft Visual Studio.

  2. From the Toolbox, drag a table control into the list control. Put the table under the table that contains the customer data.

    Note
    You may have to resize the report body and the list controls to make them larger.

  3. Select the table, right-click the shaded border, choose Tablix Properties. On the General tab, verify that the Dataset name field is set to DataSet_Result, and then choose the OK button.

  4. Select the table data row, choose Insert Row and then choose Outside Group - Below. This adds another data row to the table. You now have one header row and two data rows.

  5. Delete the first row (header row) in the table and then insert columns in the table so that the total number of columns is eleven.

  6. Choose the first data row, right-click the shaded border to the left, choose Add Group, and then choose Parent Group.

  7. In the Tablix group window, select Group by, select EntryNo_CustLedgerEntry from the drop-down list. Select Add group header, and then choose the OK button.

  8. Right-click the first row, choose Insert Row, and then choose Inside Group - Above. This header will hold the captions for the Customer Ledger entries.

  9. Right-click the cell in the row1, column 2, and then choose Expression to open the Expression window.

  10. In the Category column, select Parameters and then in the Values column double-click EntryNo_CustLedgerEntryCaption. Note that the Set expression for: Value box contains the following value: =Parameters!EntryNo_CustLedgerEntryCaption.Value

  11. Modify the expression to the following value: =First(Parameters!EntryNo_CustLedgerEntryCaption.Value).

  12. Repeat steps 9 through 11 to add captions for the table cells in the rest of the first row as shown in the following table.

    Column Caption expression

    3

    CustomerNo_CustLedgerEntryCaption

    4

    PostingDate_CustLedgerEntryCaption

    5

    DocumentType_CustLedgerEntryCaption

    6

    DocumentNo_CustLedgerEntryCaption

    7

    Description_CustLedgerEntryCaption

    8

    Skip this cell. You will use this cell later.

    9

    CurrencyCode_CustLedgerEntryCaption

    10

    Amount_CustLedgerEntryCaption

    11

    OriginalAmtLCY_CustLedgerEntryCaption

    12

    RemainingAmtLCY_CustLedgerEntryCaption

  13. Right-click the left-most grouping cell (the cell that contains the EntryNo_CustLedgerEntry field) in the table, select Text Box Properties, in the Text Box Properties window, select the Visibility tab, under the Change display options, select the Hide option.

  14. Select the first row in the table, in the Properties pane, under Fill, set the BackgroundColor property to Dim Grey.

  15. Right-click the cell in the row2, column 2, and then choose Expression to open the Expression window.

  16. In the Category column, select Fields (DataSet_Result), in the Values column, double-click EntryNo_CustLedgerEntry, and then choose the OK button. Note that the Set expression for: Value box contains the following value: =Fields!EntryNo_CustLedgerEntry.Value

  17. Repeat steps 15 and 16 for row 3 to add fields from the ledger entry dataset. Put the fields under the corresponding captions.

  18. Select the row that you just filled and set the BackgroundColor property to Silver.

  19. Build the project, inspect the Output pane, and make sure that there are no build errors.

  20. Select the second table row, right-click the shaded border to the left, choose Insert Row, and then choose Below. The table should now have three group rows, one group data row, and one table footer row. This row will store the captions of Detailed Cust. Ledg. Entry data item.

  21. Add the captions and fields for the Detailed Cust. Ledger Entry table as shown in the following table.

    Third row (Caption) Forth row (Fields)

    EntryNo_DetailedCustLedgEntryCaption

    EntryNo_DetailedCustLedgEntry.Value

    EntryType_DetailedCustLedgEntryCaption

    EntryType_DetailedCustLedgEntry.Value

    PostingDate_DetailedCustLedgEntryCaption.

    PostingDate_DetailedCustLedgEntr.Value

    DocumentType_DetailedCustLedgEntryCaption

    DocumentType_DetailedCustLedgEntry.Value

    DocumentNo_DetailedCustLedgEntryCaption

    DocumentNo_DetailedCustLedgEnt.Value

    TransactionNo_DetailedCustLedgEntryCaption

    TransactionNo_DetailedCustLedgEntry.Value

    JournalBatchName_DetailedCustLedgEntryCaption

    JournalBatchName_DetailedCustLedgEntry.Value

    AmountLCY_DetailedCustLedgEntryCaption

    AmountLCY_DetailedCustLedgEntr.Value

    DebitAmountLCY_DetailedCustLedgEntryCaption

    DebitAmountLCY_DetailedCustLedgEntry.Value

    CreditAmountLCY_DetailedCustLedgEntryCaption

    CreditAmountLCY_DetailedCustLedgEntry.Value

  22. Shrink the column that contains the Customer No. field of the Cust. Ledger Entry to about half of its size.

  23. Right-click the column header that contains the Customer No. field, choose Insert Column, and then choose Right.

  24. Select the cell that contains the Customer No. caption and the empty cell that you just created, and then choose Merge Cells to merge the two cells.

  25. Repeat step 24 to merge the cell that contains the value of the Customer No. field and the empty cell that you created.

  26. Assign the expression from the EntryType caption and field cells of the Detailed Cust. Ledg. Entry to the empty cell that you created to the right. You may have to have to cut the expressions and paste them into the empty cells.

  27. Repeat 26 to move the EntryNo caption and field one cell to the right. This makes sure that the EntryNo and the EntryType data is located directly under the CustomerNo cell.

    The following illustration shows EntryNo and the EntryType cells directly under the CustomerNo cell

  28. Repeat steps through 27 to put the Transaction No. and Journal Batch Name captions and fields under the Description data. This creates a blank cell under the CurrencyCode field.

  29. Select the third row and set the BackgroundColor property to Yellow and then set the BackgroundColor property of the fourth row to Khaki.

    Viktor will now hide all empty cells and add the totals to the footer row. To hide empty cells Viktor will add a filter that selects rows that have [EntryNo] value that are greater than zero.

To hide empty cells and add totals

  1. Select the first row, right-click the shaded border to the left of the row, choose Row Group, and then choose Group Properties.

  2. In the Group Properties window, select the Filters tab, and then choose the Add button.

  3. Set Expression to [EntryNo_CustLedgerEntry], change Text to Integer, set Operator to >, set Value to 0, and then choose the OK button.

    The filter that is set applies to the other rows in the table.

  4. In the Group Properties window, under the Filters tab, verify that the Expression box contains [EntryNo_CustLedgerEntry].

    Viktor will now add the total of the amount field to the footer row of the table, format the cells and hide the total cell if customer ledger entry is not available.

  5. In the last row of the table, right-click the empty cell under the Amount (LCY) field, and then choose Expression.

  6. In the Category column, select Fields (DataSet_Result), in the Values column double-click Amount_CustLedgerEntry, and then change the expression in the Set expression for: Value box to the following value: =Sum(Fields!Amount_CustLedgerEntry.Value). Choose the OK button.

  7. In the Properties window, locate the Format property, choose the drop-down arrow and select Expression.

  8. In the Expression window, enter the following formatting expression in Set expression for: Value box: =Fields!Amount_CustLedgerEntryFormat.Value. Choose the OK button.

    Note
    Alternatively, you set this value by double-clicking Amount_CustLedgerEntryFormat in the Values field of Fields(DataSet) category.

  9. Select the two empty cells to the left of the total cell, right-click the cells, and then choose Merge Cells.

  10. Right-click the merged cell, choose Expression, choose the Parameters category, and then set the caption to Total_Caption

  11. Set the BackgroundColor property of the cells that contain the total and total caption to Red.

    If you run the report now, the total amount cell will be displayed even if there are no ledger entries. Viktor will add an expression to hide the footer row when there are no ledger entries.

  12. Select the last row, in the Properties window, locate the Hidden property, choose the drop-down arrow, and then choose Expression.

  13. In the Expression window, in the Set expression for: Hidden box, enter the following expression to hide the row: =Fields!EntryNo_CustLedgerEntry.Value = 0. Choose the OK button. This hides the row if there are no entry values.

  14. Right-click the left-most cell in the last table row, select Text Box Properties, select the Visibility tab, under Change display options, select the Hide option, and then choose the OK button.

    The next step is to add the data from the Sales Header table.

To add the sales header data

  1. From the Toolbox, drag a Table control to the List control, and then put the table control under the table that contains the Cust. Ledger Entry table

  2. Right-click a column and add columns to create five columns for the table.

  3. Delete the first header row from the table.

  4. Right-click the data row, choose Tablix Properties, verify that the DataSet name is set to DataSet_Result, and then choose the OK button.

  5. Right-click the data row, choose Add Group, and then choose Parent Group to open the Tablix group window.

  6. Select the Group by: option and then choose the fx button to open the Expression window.

  7. In the Category column, select Parameters, and then in the Values, column double-click Sales_Document_Caption. Verify that the Set expression for: Value box contains the following value: =Parameters!Sales_Document_Caption.Value. Choose the OK button.

  8. In the Tablix group window, select Add group header, and then choose the OK button.

  9. Right-click the first row in the table, choose Insert Row, and then choose Inside Group - Above.

  10. Reduce the size of the first column, and then in the Properties window, under Visibility, set the Hidden property to True. This hides the first column.

  11. In the first table row, merge all the cells except the first grouping cell.

  12. Right-click the merged cell, and then choose Expression.

  13. In the Category column, select Parameters, and then in the Values column double-click Sales_Document_Caption. Verify that the Set expression for: Value box contains the following value: =Parameters!Sales_Document_Caption.Value. Choose the OK button.

  14. Modify the expression to =First(Parameters!Sales_Document_Caption.Value).

  15. Right-click the cell in row2, column 2, and then choose Expression to open the Expression window.

  16. In the Category column, select Parameters, and then in the Values column double-click DocumentType_SalesHeader. Verify that the Set expression for: Value box contains the following value: Parameters!DocumentType_SalesHeaderCaption.Value

  17. Modify the expression to the following value: =First(Parameters!DocumentType_SalesHeaderCaption.Value). Choose the OK button.

  18. Right-click the cell that is under the caption that you just created, choose Expression. In the Category column, select Fields (DataSet_Result), and then in the Values column double-click DocumentType_SalesHeader. Choose the OK button. Verify that the Set expression for: Value box contains the following value: =Fields!DocumentType_SalesHeader.Value

  19. Repeat steps 15 through 18 and add the following captions and the corresponding fields.

    Caption Corresponding field

    No_SalesHeaderCaption

    No_SalesHeader

    PostingDate_SalesHeaderCaption

    PostingDate_SalesHeader

    PricesIncludingVAT_SalesHeaderCaption

    PricesIncludingVAT_SalesHeader

    Amount_SalesHeaderCaption

    Amount_SalesHeader

  20. Select the first two rows and in the Properties window, set the BackgroundColor property to Lime.

  21. Select the data row (last row), in the Properties window, set the BackgroundColor property to Turquoise.

    Viktor will now set a filter that hides empty rows.

To set a filter hide empty row

  1. Select any row from this table, right-click the shaded border to the left of the table, and then choose Tablix Properties.

  2. Choose the Filters tab and then choose the Add button.

  3. In the Expression list box, select No_SalesHeader, set Operator to >, set Value to 0, and then choose the OK button.

  4. Save the report.

Building and Running the Report

Before you run the report, you must build and correct all build errors and then run the run report in Object Designer.

To build and run the report

  1. In the main menu, choose Build, and then choose Build Web Site to build the project. Inspect the Output pane and make sure that there are no build errors and then close Visual Studio.

  2. In development environment, in Report Dataset Designer, select a data item, and then in the dialog box that appears that indicates that the layout of the report is changed by another application, choose the Yes button.

  3. On the File menu, choose Save. In the Save window, make sure that Compile is selected, and then choose the OK button.

  4. In Object Designer, select the report (50001), and then choose the Run button to run the report.

  5. On the request page, choose the Preview button to view the report.

  6. Use the paging buttons at the top of the report to move to the next customer.

Next Steps

Viktor can add advanced features to the report. He can add features such as displaying the company name and logo on every page on the report. He might also want to add features that enable users to apply filters on the request page. For more information, see Walkthrough: Adding Company Information, Custom Filters, and Formatting to a Report.

See Also

Tasks

Walkthrough: Adding Company Information, Custom Filters, and Formatting to a Report

Other Resources

Report Design Walkthroughs


Walkthrough: Adding Company Information, Custom Filters, and Formatting to a Report

When you create a report, you can add features such as formatting, custom filters, company logo, and company name to the report. Adding these features make the report readable and improves the visual presentation of the report. You will add these features to the report that you created in Walkthrough: Designing a Report from Multiple Tables.

About This Walkthrough

This walkthrough shows you how to add custom filters, add company information, and format a report.

This walkthrough illustrates the following tasks:

  • Declaring the required variables.

  • Adding a custom filter to the request page. The filter will enable users to display or hide customer details.

  • Adding company information to the report.

  • Hiding or showing customer details.

  • Formatting the data.

  • Formatting the layout of the report.

  • Building and running the report.

Prerequisites

To complete this walkthrough, you will need:

  • To create a report by using Walkthrough: Designing a Report from Multiple Tables. If you have not created this report, you must create it before you start this walkthrough.

  • Microsoft Dynamics NAV 2016 installed with a developer license.

  • The CRONUS International Ltd. demonstration database installed.

  • Microsoft Visual Studio installed. For more information about which version of Microsoft Visual Studio you need, see System Requirements for Microsoft Dynamics NAV 2016. This walkthrough assumes that Microsoft Visual Studio 2012 or Microsoft Visual Studio 2013 is used.

Story

Viktor has created the report that was assigned to him in Walkthrough: Designing a Report from Multiple Tables. Viktor wants to improve the visual presentation of the report by adding the company name and company logo to the report. He will format the data and the layout of the report. The company name and the logo must be displayed on every page. On the request page, Viktor wants to enable users to filter the data by customer number and provide the option to hide or show detailed customer information.

Declaring the Required Variables

First, Viktor will declare the variables that are that are required to create the custom filter and add the company name and logo to the report.

To declare the variables

  1. In the Microsoft Dynamics NAV Development Environment, in Object Designer, select the report that you created by using Walkthrough: Designing a Report from Multiple Tables (Report for Multiple Tables (50001). Choose Design to open Report Dataset Designer.

  2. On the View menu, choose C/AL Globals to open the C/AL Globals window.

  3. On the Variable tab, in the first row, in the Name field, enter ReportFilters. In the DataType field, choose the drop-down arrow, select Text, and then in the Length field enter 250.

  4. In the second row, in the Name field, enter CompanyInfo. In the DataType field, choose the drop-down arrow, and then select Record. In the SubType field, choose the up arrow, and then select the Company Information table (79).

  5. In the third row, in the Name field, enter ShowCustomerDetails. In the DataType field, choose the drop-down arrow, and then select Boolean.

  6. Close the C/AL Globals window.

Adding a Custom Filter to the Request Page

Viktor will add an option control to the request page. The option control will enable users to show or hide detailed information for a customer. If the detailed information is hidden, only the customer’s number and name will be displayed on the report.

To add a custom filter

  1. In Report Dataset Designer, on the View menu, choose C/AL code to open the C/AL Editor.

  2. In the OnPreReport trigger, add the following code: ReportFilters := Customer.GETFILTERS;. Close the C/AL Editor.

  3. In Report Dataset Designer, right-click the Cust. Ledger Entry DataItem, and then choose New to create a new row at the bottom of the Customer DataItem.

  4. In the new row, in the Data Source field, enter the following code: Customer.TABLECAPTION+':' + ReportFilters. In the Name field, enter Cust_ReportFilter.

  5. Repeat step 3 to create a new row at the bottom of the Customer DataItem.

  6. In the new empty row, in the Data Source field, choose the AssistEdit button to open the C/AL Symbol Menu window. In the leftmost window, select ReportFilters, and then choose the OK button. In the Name field, enter ReportFilters.

  7. On the File menu, choose Save to save the report.

  8. In the Save window, make sure that Compile is selected, and then choose the OK button.

  9. On the View menu, choose Layout to open the RDLC layout in Microsoft Visual Studio.

  10. In the body section of the layout, select the List control and move the report down to create space at the top of the report.

  11. On View menu, choose Report Data to display the Report Data pane.

  12. On the DataSource node, under DataSet_Result, drag the Cust_ ReportFilter item to the space you that you created at the top of the body of the Report Designer.

  13. Right-click the Cust_ReportFilter text box, and then choose Expression to open the Expression window.

  14. In the Set expression for: Value box, replace the expression with the following expression: =First(Fields!Cust_ReportFilter.Value). Choose the OK button.

  15. Select the Cust_ReportFilter text box, in the Visual Studio Properties pane, locate the Hidden property, choose the drop-down list, and then choose Expression.

  16. In the Set expression for: Hidden box, replace the expression with the following expression: =iif(First(Fields!ReportFilters.Value=""),true,false). Choose the OK button.

  17. On the Build menu, choose Build Web Site to build the project. Inspect the Output pane and make sure that there are no build errors. Close Visual Studio.

Adding Company Information

Viktor will add the company name and logo to the report.

To add a company name

  1. In Report Dataset Designer, select a DataItem, and then in the dialog box that appears, choose the Yes button. The dialog box contains a message that states that the layout of the report is changed by another application.

  2. In Report Dataset Designer, right-click the Cust. Ledger Entry DataItem, and then choose New to create a new row at the bottom of the Customer DataItem.

  3. In the new row, in the Data Source field, choose the AssistEdit button to open the C/AL Symbol Menu window.

  4. In the leftmost box, select DATABASE. In the middle box, select Functions. In the rightmost box, select COMPANYNAME. Choose the OK button.

  5. In the Name field, enter CompanyName.

  6. Save and compile the report. On the View menu, choose Layout.

  7. In the Report RDLC layout in Visual Studio, on the View menu, choose Report Data.

  8. In the Report Data pane, right-click the DataSource node, choose Refresh, and then verify that the CompanyName report item appears in the list under the DataSource node.

  9. Drag the CompanyName report data item to the Report Header section of the report, build the report, and then close the Visual Studio Designer. The information that is on the header section will be displayed on every page on the report.

To add a company logo

  1. In Report Dataset Designer, select a DataItem. In the dialog box that states that the layout of the report is changed by another application, choose the Yes button.

  2. In Report Dataset Designer, right-click the Cust. Ledger Entry DataItem, and then choose New to create a new row at the bottom of the Customer DataItem.

  3. In the new row, in the Data Source field, choose the AssistEdit button to open the C/AL Symbol Menu window.

  4. In the leftmost box, select CompanyInfo. In the middle box, select FieldName. In the rightmost box, select Picture. Choose the OK button.

  5. In the Name field, enter Picture.

  6. On the View menu, choose C/AL Code.

  7. In the C/AL Editor, in the OnInitReport Trigger, enter the following code.

    Copy Code
    CompanyInfo.GET;
CompanyInfo.CALCFIELDS(Picture);

  8. Close the C/AL Editor, save the report, and then compile the report.

  9. On the View menu, choose Layout.

  10. In Visual Studio, on the View menu, choose Toolbox.

  11. In the Toolbox pane, drag the Image control to the header section of the report. Put the control where you want the company logo to be displayed, and then choose the OK button in the Image Properties window. Resize the image to the desired size.

  12. Select the image control, in the Properties pane, in General node, set the following properties.

    Property Value

    MIMEType

    Image/bmp

    Value

    =First(Fields!Picture.Value, "DataSet_Result")

    Source

    Database

  13. Under Size, set the Sizing property to FitProportional

  14. On the main menu, choose Build, and then choose Build Web Site to build the project. Review the Output pane, make sure that there are no build errors, and then close Visual Studio.

Hiding or Showing Customer Details

In this section, Viktor will define visibility settings for the customer fields (address, telephone number, and email). These fields will be displayed or hidden depending on whether the Show Customer Details check box on the request page is selected. If the check box is not selected, only customer number and name will be displayed on the report.

To hide or show detailed customer information

  1. In Report Dataset Designer, choose Yes in the dialog box that appears.

  2. On the View menu, choose Request Page to open the Request Options Page Designer window.

  3. In the first row, in the Caption field, enter Container, and then accept the defaults for the rest of the fields.

  4. In the second row, in the Type field, choose the drop-down arrow, and then select Group. In SubType field, choose the drop-down arrow, and then select Group. In the Name field, enter Option. Accept the default for the Caption field.

  5. In the next empty row, in the Type field, select Field. In the Name field, enter ShowCustDetails. In the Caption field, enter Show Customer Details.

  6. In the SourceExpr field, choose the AssistEdit button, choose ShowCustomerDetails from the first box, choose the OK button, and then close the Request Options Page Designer window.

  7. In Report Dataset Designer, create a new row at the bottom of the Customer DataItem. In the new row, in the Data Source field, choose the AssistEdit button to open the C/AL Symbol Menu window.

  8. In the leftmost box, select ShowCustomerDetails. Choose the OK button. In the Name field, enter ShowCustomerDetails.

  9. Save and compile the report.

  10. On the View menu, choose Layout to open the RDLC layout in Visual Studio.

  11. In the report layout, in the table that contains the customer data, in the last row, select the first two cells. In the third column, select the cells that contain the customer details data (address, telephone number, and email) values and captions. You can select multiple cells by holding down the Ctrl key and selecting the cells.

    The following illustration shows the selected cells.

    Customer Details cells

  12. In the Properties pane, locate the Hidden property, choose the drop-down list, choose Expression, and then enter the following conditional expression in the Set expression for: Hidden box: =iif(Fields!ShowCustomerDetails.Value,false,true). This expression replaces any expression in the box. Choose the OK button. This expression hides the customer details information unless the Show Customer Details option is selected on the request page.

    Note
    When you select multiple cells, the Properties pane will display properties that are common to the selected cells.

  13. Build the modified report layout, inspect the Output pane and make sure that there are no build errors. Close Microsoft Visual Studio.

  14. In Report Dataset Designer, select a DataItem, in the dialog box that appears, choose the Yes button.

  15. On the File menu, choose Save. In the Save window, make sure that Compile is selected, and then choose the OK button.

  16. In Object Designer, select the report (50001), and then choose the Run button to run the report.

    The following illustration shows the Edit Report for Multiple Tables Request Page with the show details filter.

    Request Page with show details filter

  17. In the Where No. is filter, enter 01445544. Select the Show Customer Details option, and then choose the Preview button. Note that the company name and the company logo are displayed on the report and all customer information is displayed.

    Note
    By default, the Show Customer Details option is not selected.

    The following illustration shows an example of the report with customer details.

    Report with logo and company name

  18. Run the report again. This time, on the Request Page, do not select the Show Customer Details option. Note that only the customer ID and the customer name are displayed on the report.

Formatting the Data

By default, the DateTime fields in the report display the date in the 1/20/2013 12:00 am format, Boolean fields are displayed as true or false, and the amounts fields are displayed without commas. Viktor will format the DateTime values so that they are displayed in the 01/20/2012 (mm/dd/yyyy) format, Boolean values are displayed as Yes or No, and all the amounts are displayed in the #,###.## format. For example, 2,222.00. Later, the cells that display the amount values will be formatted to hide zero decimal values.

To format dates value

  1. In the development environment, select Report Dataset Designer, choose View, and then choose Layout.

  2. In the Visual Studio RDCL layout designer, select the posting date cell from the Cust Ledger Entry item, in the Properties window, locate the Format property, and then set the value to d.

  3. Repeat step 2 to format all the dates in the report, save the changes, and then build the report.

To format a Boolean value

  1. In the development environment, in Report Dataset Designer, select a DataItem, and then choose Yes in the dialog box that appears.

  2. In the last empty row at the bottom of the Sales Header DataItem, in the Data Source field, enter the following expression: FORMAT("Sales Header"."Prices Including VAT"). In the Name field, enter F_Prices_Including_VAT.

  3. Select the Prices Including VAT row, choose View, choose Properties, and then verify that the IncludeCaption Property is set to No. Save and compile the report.

  4. On the View menu, choose Layout.

  5. Right-click the cell that contains the Prices Including VAT value in the Sales Header item, and then choose Expression.

  6. Delete the expression in the Set expression for: Value box.

  7. In the Expression window, in the Category box, select Fields(DataSet_Results), and then in the Values box, double-click F_Prices_Including_VAT.

  8. Verify that the Set expression for: Value box contains the following expression: =Fields!F_Prices_Including_VAT.Value. Choose the OK button.

To format the amount values

  1. In the table that contains the Customer Ledger Entry data, select the cell that contains the Amount field.

  2. In the Properties pane, locate the Format property, select the drop-down list, and then choose Expression to open the Expression window.

  3. In the Category box, select Fields(DataSet_Results), and then in the Values box, double-click Amount_CustLedgerEntryFormat.

  4. Verify that the Set expression for: Value box contains the following expression: =Fields!Amount_CustLedgerEntryFormat.Value. Choose the OK button.

  5. Repeat steps 1 through 4 and format the cells that contain Amount values as show in the following table. Make sure that you double-click the appropriate field in the Values box and verify that the Set expression for: Value box contains the expression for appropriate field.

    Table Field Fields(DataSet_Results) Value to double-click Set expression for: Value box

    Customer Ledger Entry

    Original Amt. (LCY)

    OriginalAmtLCY_CustLedgerEntryFormat

    =Fields!OriginalAmtLCY_CustLedgerEntryFormat.Value

    Customer Ledger Entry

    Remaining Amt.(LCY)

    RemainingAmtLCY_CustLedgerEntryFormat

    =Fields!RemainingAmtLCY_CustLedgerEntryFormat.Value

    Detailed Customer Ledger Entry

    Amount (LCY)

    AmountLCY_DetailedCustLedgEntryFormat

    =Fields!AmountLCY_DetailedCustLedgEntryFormat.Value

    Detailed Customer Ledger Entry

    Debit Amount (LCY)

    DebitAmountLCY_DetailedCustLedgEntryFormat

    =Fields!DebitAmountLCY_DetailedCustLedgEntryFormat.Value

    Detailed Customer Ledger Entry

    Credit Amount (LCY)

    CreditAmountLCY_DetailedCustLedgEntryFormat

    =Fields!CreditAmountLCY_DetailedCustLedgEntryFormat.Value

    Sales Header

    Amount

    Amount_SalesHeaderFormat

    =Fields!Amount_SalesHeaderFormat.Value

    Note
    The field that displays the total amount uses the format of the Amount field in the Customer Ledger Entry table.

To hide zero decimal values

  1. Right-click the cell that displays the amount in the Sales header item, choose Expression, in the Set expression for: Value box, replace the expression with following expression: =Code.BlankZero(Fields!Amount_SalesHeader.Value). The Code.BlankZero() function hides decimal values that are zero.

  2. Repeat step 1 to apply the Code.BlankZero() function to all the amount fields.

Formatting the Report Layout

Viktor will format the report to make it visually appealing and he will resize the cell to make the values readable.

To format the report layout

  1. Select the list control, in the Properties pane, under Fill set the BackgroundColor property to No Color.

  2. Select all the rows in the customer item table and then set the BackgroundColor property to No Color.

  3. Repeat step 2 and set the BackgroundColor property of all rows, for all tables, to No Color.

  4. Ensure that the size of the list control and all tables do not exceed the width of the page.

  5. Resize the table columns and rows so that the values in the fields fit in the table cells.

  6. Drag a text box from the Toolbox to the header section of the report, right-click the text box, and then choose Text Box Properties.

  7. In the Text Box Properties window, choose the General tab. In the Value field, enter a title for the report. For example, you can enter Report From Multiple Tables.

  8. Under Sizing options, verify that the Allow height to increase option is selected, and then choose the OK button.

  9. Select the text box that contains the title that you just created. In the Properties pane, expand Font, set the FontSize property to 14pt, and then set the FontWeight property to Bold.

  10. Select the table that contains the customer data. In the Properties pane, expand the Padding node, and then verify that Left, Right, Top and Bottom properties are set to 0.

  11. Repeat step 10 to set the padding for the tables that contain the Cust. Ledger Entries and Sales Header items.

  12. In the Properties pane, set the properties for the controls and elements, as shown in the following table.

    Control or element BoarderStyle FontFamily FontSize FontWeight

    Row that contains the Cust. Ledger Entry captions

    Bottom - Solid

    Not applicable

    Not applicable

    Not applicable

    All controls on the report

    Not applicable

    Segoe UI

    8pt

    Not applicable

    All caption cells

    Not applicable

    Not applicable

    Not applicable

    Bold

    All data cells

    Not applicable

    Not applicable

    Not applicable

    Normal

  13. Select the page header. In the Properties pane, expand the General node, and then set the Height property to 1.5in or 3.8cm.

  14. In the Properties pane, set the Location properties for the controls as shown in the following table.

    Control Top Left

    Table that contains the Cust. Ledger Entries data.

    0.8in or 1,9cm

    Not applicable

    Table that contains the Sales Header data.

    2.08in or 6cm

    Accept the default

  15. Select an area in the List control, in the Properties pane, expand Size, and then set the Height property to 2.85in or 7.24cm.

  16. Select all the rows except the footer row in the Cust. Ledger Entries, and then set the BackgroundColor property to #f0f0f0.

  17. Repeat step 16 to set the BackgroundColor property for all rows in the table that contain the Sales Header item.

  18. In the table that contains the Cust. Ledger Entries item, select the columns that contain the amount fields, captions, and the total fields. Set the TextAlign property to Right.

  19. Repeat step 18 to set the TextAlign property for the Prices Including VAT column in the Sales Header item.

  20. In the table that contains the Cust. Ledger Entries table, select the merged cells that contain the CustomerNo caption and field value, and then set the TextAlign property to Center.

  21. Repeat step 20 and set the TextAlign property for the merged cell that contains the Description caption and field value.

  22. Select the Total caption and Total Amount cells, expand the Font property, and then set FontWeight to Bold.

  23. Select all cells that contain an amount field, in the General node, make sure that the CanGrow property is set to True.

  24. Select the last row in the Cust. Ledger Entry table, expand the BorderColor property node, and set the Top property to Black.

Building and Running the Report

You will now build and run the report. Note all of the features that Viktor has added to the report.

To build and run the report

  1. On the Build menu, choose Build Web Site to build the project. Review the Output pane, make sure that there are no build errors, and then close Visual Studio.

  2. In the development environment, in Report Dataset Designer, select a DataItem. In.the dialog box that appears that states that the layout of the report is changed by another application, choose the Yes button.

  3. On the File menu, choose Save and in the Save window, make sure that Compile is selected. Choose the OK button.

  4. In Object Designer, select the report that you just formatted (50001), and then choose the Run button to run the report.

  5. On the request page, select the Show Customer Details option, and then choose the Preview button to view the report.

    The following illustration shows an example of the completed and formatted report.

See Also

Tasks

Walkthrough: Designing a Report from Multiple Tables

Other Resources

Report Design Walkthroughs


Running Reports

After you design a report's dataset and layout, you can make it available in Microsoft Dynamics NAV client applications. For example, you can add a report to the Report tab of a page. When you preview a report from a client computer, the report is displayed using Report Viewer.

The following table describes where to find information about how to run reports.

To | See
Learn how to add a report to a client page. | How to: Make a Report Available from a Page
Learn about how to run reports from Object Designer, a client, or at a command prompt. | How to: Run Reports

Report Viewer

The ReportViewer controls included with Visual Studio 2012 and Visual Studio 2013 allow reports to be embedded in Microsoft Dynamics NAV client applications. The ReportViewer controls are installed automatically on the following:

  1. Client computer, for viewing reports from the Microsoft Dynamics NAV client.

  2. Microsoft Dynamics NAV Server, for using the SAVEASEXCEL and SAVEASPDF functions.

  3. Computer running the development environment, for compiling reports.

The ReportViewer controls included with Visual Studio 2012 and Visual Studio 2013 prevent code expressions in hidden items on a report from being evaluated. We recommend that you eliminate code expressions from hidden items on reports.

In Microsoft Dynamics NAV 2009, when you redesigned Classic reports as client report definition (RDLC) reports, in some cases, you may have created hidden text boxes in the body of a report so that in the RDLC layout, you could reference that report item in the header or footer of the report. In Microsoft Dynamics NAV 2016 you do not have to create hidden text boxes in order to reference an item in a header or footer because the RDLC version allows data-bound fields in headers and footers. Additionally, if the hidden text boxes that you added had code expressions, then they may not be evaluated by the ReportViewer controls that are used in Microsoft Dynamics NAV 2016. We recommend that you move these data-bound fields out of the hidden items. For example, you may be able to move the code expression from the hidden text box to the Visibility property of the text box. For more information, see How to: Print Report Header Information on Multiple Pages.

See Also

Concepts

Defining the Report Dataset
Designing Report Layouts from the Microsoft Dynamics NAV Development Environment


How to: Make a Report Available from a Page

After you have created and designed a report, you can add the report to the interface of the page so that users can view the report.

For more information about other ways to run reports, see How to: Run Reports.

The following procedure explains how to make a report available from the Customer List page by adding the report to the promoted actions pane.

To make a report available from a page

  1. In the development environment, open Object Designer, and then choose Page.

  2. Select the page to display the report, such as Page 22, Customer List.

  3. Choose Design to open the page in Page Designer.

  4. Select an empty row in the designer.

  5. On the View menu, choose Page Actions to open Action Designer.

  6. Scroll down to the ActionContainer that has Reports as its subtype.

  7. Right-click the row where you want to add the new action, and then choose New.

  8. On the new row, in the Caption column, enter a name for the action, and in the Type column, select Action.

  9. On the View menu, choose Properties to open the Properties window for the new action.

  10. In the Value field of the RunObject property, choose the drop-down arrow, and then select the new report that you want to run in the Object List window.

  11. Set the Promoted property to Yes, and then set the PromotedCategory property to Report.

  12. Compile and save the page.

  13. Open the Microsoft Dynamics NAV Windows client, in the Search box, enter Customers and then choose the related link to open the Customers page.

    The report is added to the list of promoted actions on the Customers page.

  14. Choose the action to run the report.

See Also

Tasks

Walkthrough: Designing a Customer List Report

Concepts

Designing Reports


How to: Run Reports

You can run reports:

  • From the Microsoft Dynamics NAV Windows client.

  • From the Microsoft Dynamics NAV Web client.

  • From Object Designer.

  • At the command prompt with command-line arguments.

  • From the Run window with command-line arguments.

  • From a web browser window with command-line arguments.

To run a report from the Microsoft Dynamics NAV Windows client

  • Add an action for running the report to a page. For more information, see How to: Make a Report Available from a Page.

To run a report from the Microsoft Dynamics NAV Web client

  • Do one of the following:

    • Open a report directly by using its Internet address. For more information, see Opening a Report in the Microsoft Dynamics NAV Web Client by Using a URL

    • Add an action for running the report to a page. For more information, see How to: Make a Report Available from a Page.

To run a report from Object Designer

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report.

  3. Select the report that you want to run, and then choose Run.

Running Reports Using Command-Line Arguments

To run a report using command-line arguments, you must know the ID of the report. By using command-line arguments, you have various options for opening the RoleTailored client and pages and reports in different modes. For example, you can specify a specific server or specific language, or you can create hyperlinks to specific reports. For more information, see Starting the Windows Client at the Command Prompt and Creating and Running Hyperlinks.

When you run a report using command-line arguments, you can filter the data in the report by adding a filter string to the command. The filter string has the following format:

Copy Code
&filter=<table>.<field>:<value>

To specify the table, you use the Name value of the data item.

To specify the field, use the field name. If the field name contains special characters, then you must enclose it in quotation marks by using the URI escape sequence %22.

The colon operator separates the two parts of the filter string.

To specify the value, you can either use a single value or a comparison operator and a value. The following are valid comparison operators:

  • > (greater than)

  • >= (greater than or equal to)

  • < (less than)

  • <= (less than or equal to)

  • <> (not equal to)

The wildcard character * is permitted in the value.

You can specify multiple filter strings by concatenating them. For example, the following command filters on cities that begin with M and names that begin with A.

Copy Code
DynamicsNAV:////runreport?report=101&filter=Customer.City:G*&filter=Customer.Name:C*

To run a report at the command prompt

  1. At the command prompt, change to the RoleTailored client directory with the following cd command:

    cd "C:\Program Files\Microsoft Dynamics NAV\90\RoleTailored Client"

  2. Type the following command:

    Microsoft.Dynamics.Nav.Client.exe DynamicsNAV:////runreport?report=<ReportID>[&filter=<table>.<field>:<value>]

    Replace <ReportID> with the report ID that you want to run. If you want to filter the data, then replace <table>, <field>, and <value> with the appropriate values.

To run a report from the Run window

  1. In Windows, on the taskbar, choose Start and then choose Run.

  2. In the Run window, enter the following command: DynamicsNAV:////runreport?report=<ReportID>[&filter=<table>.<field>:<value>]

    Replace <ReportID> with the report ID that you want to run. If you want to filter the data, then replace <table>, <field>, and <value> with the appropriate values.

  3. Choose OK to run the report.

To run a report from a web browser window

  1. Open a web browser window.

  2. In the address bar, enter the following command: DynamicsNAV:////runreport?report=<ReportID>[&filter=<table>.<field>:<value>]

    Replace <ReportID> with the report ID that you want to run. If you want to filter the data, then replace <table>, <field>, and <value> with the appropriate values.

See Also

Concepts

Designing Reports


How to: Change Which Layout is Currently Used on a Report

This procedure describes how to change the layout that is used by a report. A report can be set up with more than one report layout, which you can then switch among as needed.

Depending on the layouts that are available for a report, you can choose to use a built-in RDLC report layout, a built-in Word report layout, or a custom layout. For more information about RDLC and Word report layouts, built-in and custom layouts, and more, see About Report Layouts.

To change the layout that is used on a report

  1. In the Search box, enter Report Layout Selection, and then choose the related link.

    The Report Layout Selection window lists all the reports that are available for the company that is specified in the Company field at the top of the window.

    The Selected Layout field specifies the layout that is currently used on the report.

  2. Set the Company field at the top of the window to the company that includes the report.

  3. To change the layout that is used by a report, in the row for the report in the list, set the Selected Layout field to one of the following options:

    Option Description

    RDLC (built-in)

    Uses the built-in RDLC report layout on the report.

    Word (built-in)

    Uses the built-in Word report layout on the report.

    Custom

    Uses a custom layout on the report.

    You can see which custom layouts are available for the report in the Report Layouts Part FactBox. If there are no custom layouts for the report, then you will have to create one first.

    If you choose this option, go to the next procedure to specify the custom layout that you want to use.

    Note
    If you choose RDLC (built-in) or Word (built-in) and you get an error message that the report does not have a layout of the specified type, then you must choose another layout option or create a custom report layout of the type that you want to use.

If you selected a built-in RDLC or Word report layout, then no further action is required and the layout will be used the next time the report is run.

To specify a custom layout on a report

  1. You specify which custom layout to use on the report from the Custom Report Layouts window. If the Custom Report Layouts window is not open, then in the Report Layout Description field, choose the lookup button.

  2. In the Custom Report Layouts window, select the row for custom layout that you want to use, and then choose the OK button.

You return to the Report Layout Selection window. The name of the selected custom layout displays in the Custom Layout Description field. The custom layout will be used the next time that you run the report.

See Also

Managing Report Layouts From the Microsoft Dynamics NAV Clients
How to: Modify a Custom Report Layout
How to: Create a Custom Report Layout

Concepts

Designing Report Layouts from the Microsoft Dynamics NAV Development Environment


Customizing Report Layout Implementation in Codeunit 1

Reports can be run directly from the Microsoft Dynamics NAV client or from C/AL code by calling the RUN, SAVEASWORD, SAVEASPDF, or SAVEASEXCEL functions. When a report is run, the application calls the following functions in codeunit 1 to determine which report layout to use on the report.

  • HasCustomLayout Function

  • MergeDocument Function

  • ReportGetCustomRdlc Function

These functions determine how to handle custom Word and RDLC layouts that are used on the report, which are stored in table 9650 Report Layouts. You can customize the report layout implementation by modifying the C/AL code of these functions in codeunit 1.

Function Call Flow

To use the correct report layout for a report at run time, the report layout functions in codeunit 1 are called according to following flow.

  • Before the OnPreReport Trigger trigger is invoked, the application calls the HasCustomLayout function.

    The HasCustomLayout function determines whether the report is currently set up to use a custom RDLC layout or Word layout, and then calls one of the following functions:

    • If the report is currently set up to use a custom RDLC layout, then the ReportGetCustomRdlc function is called after the OnPreReport Trigger is invoked.

      This function loads the proper RDLC layout and uses the layout to render the report.

    • If the report is currently set up to use a custom Word layout, then the MergeDocument function is called after the OnPostReport Trigger is invoked.

      This function loads the proper Word layout and renders the report based on the action from the report request page, such SaveAsPdf, SaveAsWord, SaveAsExcel, Preview, or Print.

    • If the report is not currently set up to use a custom Word or RDLC layout, then the built-in layout is used for the report.

Modifying the Report Layout Implementation

To modify the report layout implementation, you design the implementation and then add C/AL code to the functions in codeunit 1.

To modify codeunit 1

  1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Codeunit, and then choose codeunit 1 Application Management.

  3. Add a code to the HasCustomLayout, MergeDocument, and ReportGetCustomRdlc functions.

  4. Save and compile codeunit 1.

See Also

Reference

REPORT.RUN Function
SAVEASWORD Function (REPORT)
SAVEASPDF Function (Report)
SAVEASEXCEL Function (Report)

Concepts

Designing RDLC Report Layouts
Designing Word Report Layouts


HasCustomLayout Function

Determines whether a report is currently set up to use a custom Word layout or RDLC layout at run time.

HasCustomLayout(ObjectType : 'Report'; ObjectID : Integer) : Integer

Parameters

ObjectType

Type: Option

The Microsoft Dynamics NAV object type that is run. Currently only the Report value is supported.

ObjectID

Type: Integer

The ID of the Microsoft Dynamics NAV report object.

Return Value

Type: Integer

The following values are available.

Value Description

0

The report is not currently set up to use a custom RDLC or Word layout.

1

The report is currently set up to use a custom RDLC layout.

2

The report is currently set up to use a custom Word layout.

Applies To

Report layout implementation in codeunit 1 ApplicationManagement.

Remarks

This function is executed when a report is run from the Microsoft Dynamics NAV client or by a call to the Run, SaveAsWord, SaveAsPdf, and SaveAsExcel functions. The HasCustomLayout function is executed at run time before the OnPreReport Trigger.

Example

The following example shows the default implementation on the function in codeunit 1. This example uses a variable ReportLayout that has the data type Record and subtype Report Layout.

Copy Code
IF ObjectType <> ObjectType::Report THEN
    ERROR(NotSupportedErr);
IF ReportLayout.GetActiveReportLayout(ObjectID,ReportLayout.Type::RDLC) THEN
    EXIT(1);
IF ReportLayout.GetActiveReportLayout(ObjectID,ReportLayout.Type::Word) THEN
    EXIT(2);
EXIT(0);

See Also

Reference

REPORT.RUN Function
SAVEASWORD Function (REPORT)
SAVEASPDF Function (Report)
SAVEASEXCEL Function (Report)

Concepts

Customizing Report Layout Implementation in Codeunit 1


MergeDocument Function

Loads the custom Word layout that is currently set up to use on the report and renders it in the targeted format, such as Word or PDF.

MergeDocument(ObjectType : 'Report'; ObjectID : Integer;ReportAction : 'SaveAsPdf,SaveAsWord,SaveAsExcel,Preview,Print'; XmlData : Instream; FileName : Text)

Parameters

ObjectType

Type: Option

The Microsoft Dynamics NAV object type that is run. Currently only Report is supported.

ObjectID

Type: Integer

The ID of the Microsoft Dynamics NAV object.

ReportAction

Type: Option

The action that runs a report the request page or function call. The parameter has the following values: SaveAsPdf, SaveAsWord, SaveAsExcel, Preview, or Print.

XmlData

Type: Instream

The report data as structured XML.

Note
The delivered XML is in the same format as the XML that is produced by calling the SAVEASXML Function (Reports).

FileName

Type: Text

The path and the name of the report file that is returned by the report request page action or function calls SaveAsWord, SaveAsPdf, or SaveAsExcel. The parameter is empty for Preview and Print actions.

Applies To

Report layout implementation in codeunit 1 ApplicationManagement.

Remarks

At report run time, this function is called if the HasCustomLayout Function determines that the report is currently set up to use a custom Word layout. The MergerDocument function is called after the OnPostReport Trigger is invoked.

Example

The following example shows the default implementation on the function in codeunit 1. This example uses a variable DocumentReportMgt that has the data type Codeunit and subtype Document Report Mgt..

Copy Code
IF ObjectType <> ObjectType::Report THEN
    ERROR(NotSupportedErr);
DocumentReportMgt.MergeWordLayout(ObjectID,ReportAction,XmlData,FileName);

See Also

Reference

REPORT.RUN Function
SAVEASWORD Function (REPORT)
SAVEASPDF Function (Report)
SAVEASEXCEL Function (Report)

Concepts

Customizing Report Layout Implementation in Codeunit 1


ReportGetCustomRdlc Function

Loads the proper custom RDLC layout for a report at run time and uses the layout to render the report.

ReportGetCustomRdlc(ReportID : Integer) : Text

Parameters

ObjectType

Type: Option

The Microsoft Dynamics NAV object type that is running. Currently only the Report value is supported.

ReportID

Type: Integer

The ID of the Microsoft Dynamics NAV report object that is run.

Return Value

Type: Text

The RDLC layout as text string.

Applies To

Report layout implementation in codeunit 1 ApplicationManagement.

Remarks

At report run time, this function is called if the HasCustomLayout Function determines that the report is currently set up to use a custom RDLC layout. The ReportGetCustomRdlc function is called after the OnPreReport Trigger is invoked.

Example

The following example shows the default implementation on the function in codeunit 1. This example uses a variable ReportLayout that has the data type Record and subtype Report Layout.

Copy Code
EXIT(ReportLayout.GetCustomRdlc(ReportId));

See Also

Reference

REPORT.RUN Function
SAVEASWORD Function (REPORT)
SAVEASPDF Function (Report)
SAVEASEXCEL Function (Report)

Concepts

Customizing Report Layout Implementation in Codeunit 1


Printing Reports

You can specify page settings and page orientation for a printed report from the following UI locations:

  • The Report Properties dialog box on the client report definition (RDLC) report layout in Visual Studio.

  • The Properties dialog box for the printer.

  • The Print dialog box that is displayed immediately before you print.

  • The Page Setup dialog box from the Print Preview page in the Microsoft Dynamics NAV Windows client.

The page settings that are used for the printed report depend on the mode in which you print the report.

You can use the following modes to print a report:

  • Run a report that has the UseRequestPage Property set to No, and therefore, does not display a request page.

  • Print a report from the request page without previewing the report.

  • Print a report from the Print Preview page.

    Note
    The printer that you use determines what to do if the actual paper size in the printer differs from the page size that is specified.

With Microsoft Dynamics NAV Web client, from the print preview, you can only print to a local printer. To print from the print preview, you must the install a client-side component. For more information, see Printing Reports from ReportViewer.

Specifying Page Settings and Orientation

The following table describes how you access each of the dialog boxes in which you can specify page settings and orientation.

Print mode | To access the Report Properties dialog box | To access the Properties dialog box for the printer | To access the Print dialog box | To access the Page Setup dialog box
Run a report that does not have a request page | When you design the report layout in Visual Studio, on the Report menu, choose Report Properties. | In Control Panel, double-click Printers. Right-click the selected printer, and then choose Properties. | Cannot access | Cannot access
Print a report from the request page without previewing | When you design the report layout in Visual Studio, on the Report menu, choose Report Properties. | In Control Panel, double-click Printers. Right-click the selected printer, and then choose Properties. | From the client, on the request page, choose Print. | Cannot access
View a preview of a report | When you design the report layout in Visual Studio, on the Report menu, choose Report Properties. | In Control Panel, double-click Printers. Right-click the selected printer, and then choose Properties. | In the Print Preview window, choose the Print icon. | In the client, in the Print Preview window, choose the Page Setup icon.

How Printed Report Settings Are Determined

Because there are several locations in the UI where you can specify page settings and orientation, you should know how the settings are determined for a printed report. How the settings are determined depends on the mode that you use to print the report.

Printing a Report Without a Request Page

The following table describes the page settings and orientation that are used if you print a report that does not have a request page.

If | Then the printed report paper size and margins are determined by | And the printed report orientation is determined by
The settings in the Report Properties dialog box on the layout of the report specify a standard paper size. | The settings in the Report Properties dialog box on the RDLC layout. | The settings in the Report Properties dialog box on the RDLC layout.
The settings in the Report Properties dialog box on the layout of the report specify a custom paper size. | The settings in the Properties dialog box for the printer. | The settings in the Properties dialog box for the printer.

Printing a Report From the Request Page

The following table describes the page settings and orientation that are used if you print a report from the request page without previewing the report.

If | Then the printed report paper size and margins are determined by | And the printed report orientation is determined by
The settings in the Report Properties dialog box on the layout of the report specify a standard paper size. | The settings in the Report Properties dialog box on the RDLC layout but is overridden if you change the settings in the Print dialog box. | The settings in the Report Properties dialog box on the RDLC layout but is overridden if you change the settings in the Print dialog box.
The settings in the Report Properties dialog box on the layout of the report specify a custom paper size. | The settings in the Properties dialog box for the printer but is overridden if you change the settings in the Print dialog box. | The settings in the Report Properties dialog box on the RDLC layout but is overridden if you change the settings in the Print dialog box.
Note
The values in the Print dialog box are initially set to the values from the Report Properties dialog box on the RDLC report layout.

Printing a Report From the Print Preview Page

The following table describes the page settings and orientation that are used if you print a report from the Print Preview page.

If | Then the printed report paper size and margins are determined by | And the printed report orientation is determined by
The settings in the Report Properties dialog box on the layout of the report specify a standard paper size | The settings in the Report Properties dialog box on the RDLC layout but is overridden if you change the settings in the Page Setup dialog box. | The paper size settings in the Report Properties dialog box on the RDLC layout but is overridden if you change the settings in the Page Setup dialog box.
The settings in the Report Properties dialog box on the layout of the report specify a custom paper size | The settings in the Report Properties dialog box on the RDLC layout but is overridden if you change the settings in the Page Setup dialog box. | The paper size settings in the Report Properties dialog box on the RDLC layout but is overridden if you change the settings in the Page Setup dialog box.
Note
The values in the Page Setup dialog box are initially set to the values from the Report Properties dialog box on the RDLC report layout.

See Also

Tasks

How to: Specify Printer Selection for Reports
How to: Verify the Paper Size

Concepts

Printing Reports from a Background Session


How to: Add GetPaperTrayForReport Procedure in Codeunit 1

You can print a report that uses different paper trays to print different letterheads. You can programmatically achieve this by adding the GetPaperTrayForReport procedure in codeunit 1 Application Management to set the paper tray from C/AL code. This is a procedure that you must add yourself if you need it. This gives you runtime control over paper tray selection for first, last, and default pages in all reports. When a report is run, the GetPaperTrayForReport procedure is called automatically to determine which paper trays should be used. If the GetPaperTrayForReport procedure is absent, then the report uses the PaperSourceFirstPage, PaperSourceDefaultPage,and PaperSourceLastPage properties that are set on the report.

To add the GetPaperTrayForReport procedure in codeunit 1

  1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Codeunit, and then choose codeunit 1 Application Management.

  3. Add a new procedure, which has ID 75 in codeunit 1. The following code example shows how the GetPaperTrayForReport procedure can be used to set paper tray in report 110.

    Copy Code
    PROCEDURE GetPaperTrayForReport@75(ReportID@1000 : Integer; VAR FirstPage@1001 : Integer; VAR DefaultPage@1002 : Integer; VAR LastPage@1003 : Integer)
BEGIN
    IF ReportID = 110 THEN BEGIN
        FirstPage := 1;
        DefaultPage := 2;
        LastPage := 3;
    END;
END;

  4. The following table describes the procedure parameters.

    Parameter Description

    ReportID

    The ID of the report that is currently running.

    FirstPage

    A reference value that returns the integer value of the paper tray used on the first page. If the value returns 0, then the printer uses the paper tray that is defined in the printer settings.

    DefaultPage

    A reference value that returns the integer value of the paper tray used on the default page. If the value returns 0, then the printer uses the paper tray that is defined in the printer settings.

    LastPage

    A reference value that returns the integer value of the paper tray used on the last page. If the value returns 0, then the printer uses the paper tray that is defined in the printer settings.

  5. Save and compile codeunit 1.

See Also

Reference

PaperSourceDefaultPage Property
PaperSourceFirstPage Property
PaperSourceLastPage Property


How to: Verify the Paper Size

Before you print or preview a report, the client checks the page width and page height to verify that the paper size is supported by the printer. After you create an RDLC report layout, to ensure that you can print and preview the report, you must verify that the page width and page height properties are valid.

To verify the page height and page width properties

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Report, select a report that you want to modify, and then choose the Design button.

  3. On the View menu, choose Layout.

  4. In Microsoft Visual Studio, in the Report.rdlc file, on the Report menu, choose Report Properties.

  5. In the Report Properties window, on the Page Setup tab, verify that the values in the Width and Height fields are valid.

    The following table shows valid paper size dimensions.

    Paper size Width Height

    A4

    21 cm

    29.7 cm

    Letter

    8.5 inches

    11 inches

See Also

Concepts

Printing Reports
Designing Reports


How to: Specify Printer Selection for Reports

You can set up reports so that they must be printed on a specific printer from the Microsoft Dynamics NAV Windows client. The following are some uses of printer selection:

  • You can print reports on special company letterhead.

  • You can print reports on different paper sizes.

  • You can print reports on the default printer of a specified employee.

  • When you start a session by using the STARTSESSION Function (Sessions), which does not have a UI, you can print reports from the server.

You can set different values to obtain different output. If you set a specific printer selection, then it takes precedence over a more general printer selection. For example, you can set a printer selection that has values in the User ID, Report ID, and Printer Name fields. This printer selection takes precedence over a printer selection that has blank entries in the User ID or Report ID fields.

The following table describes the combination of values to specify when you set up printer selections for a report.

To | Set the following values
Print a report to a specific printer for all users | Specify values in the Report ID and Printer Name fields and leave the User ID field blank.
Print all reports to a specific printer for a specific user | Specify values in the User ID and Printer Name fields and leave the Report ID field blank.
Set the default printer for all reports | Specify a value in the Printer Name field and leave the User ID and Report ID fields blank.
Print a specific report to the user’s default printer | Specify a value in the Report ID field and leave the Printer Name and User ID fields blank.
Print a specific report to a specific printer for a specific user | Specify values in all three fields.

To set up printer selections for a report

  1. In the Microsoft Dynamics NAV Windows client, in the navigation pane, choose Departments, choose Administration, choose IT Administration, choose General, and then choose Printer Selections.

  2. On the Home tab, in the New group, choose New to add a printer selection for a specific report.

  3. In the User ID field, select whether the printer selection applies to a specific user.

  4. In the Report ID field, select the ID of the report to print. The Report Name field is automatically populated with the report name.

  5. In the Printer Name field, select from the list of available printers. The list of available printers is generated from the printers that are currently installed. Different users on different computers may see different options.

  6. Choose the OK button to close the page.

The specified report is now set up to print to the selected printer. You can always change the printer selection in the Print dialog box.

See Also

Concepts

Printing Reports


Printing Reports from a Background Session

If you print a report from a background session that you started by using the STARTSESSION Function (Sessions), or if you print a report from a NAS services session, then you must know which printer prints the report.

Printer Selection Rules

If the UseSystemPrinter Property for the report that you want to print is true, then the rules in the following table apply, regardless of what is set on the Printer Selections page.

A default printer is set on the computer on which the Microsoft Dynamics NAV Server instance is installed. | Result
Yes | Report is printed on the default printer.
No | You receive an error in the event log on the computer on which the Microsoft Dynamics NAV Server instance is installed.

If the UseSystemPrinter property for the report that you want to print is false, then the printer on which the report is printed depends on what is set on the Printer Selections page. The rules in the following table apply.

Report ID condition | User ID in the Printer Selections page entry matches the User ID that started the background session | User ID in the Printer Selections page entry matches the account under which the NAS services session is running | User ID in the Printer Selections page entry is blank | User ID in the Printer Selections page entry does not match the User ID that started the background session
Report ID in the Printer Selections page entry matches the report ID that you run from the background session | Report is printed on the printer that is specified in the Printer Selections page entry. | Report is printed on the printer that is specified in the Printer Selections page entry. | Report is printed on the printer that is specified in the Printer Selections page entry. | Report is printed to the default printer of the computer on which the Microsoft Dynamics NAV Server instance is installed.
Report ID in the Printer Selections page entry is blank | Report is printed on the printer that is specified in the Printer Selections page entry. | Report is printed on the printer that is specified in the Printer Selections page entry. | Report is printed on the printer that is specified in the Printer Selections page entry. | Report is printed to the default printer of the computer on which the Microsoft Dynamics NAV Server instance is installed.
Report ID in the Printer Selections page entry does not match the report ID that you run from the background session | Report is printed to the default printer of the computer on which the Microsoft Dynamics NAV Server instance is installed. | Report is printed to the default printer of the computer on which the Microsoft Dynamics NAV Server instance is installed. | Report is printed to the default printer of the computer on which the Microsoft Dynamics NAV Server instance is installed. | Report is printed to the default printer of the computer on which the Microsoft Dynamics NAV Server instance is installed.

Be aware of the following:

  • If the printer that is specified on the Printer Selections page is not installed on the computer on which the Microsoft Dynamics NAV Server instance is installed, then you receive an error in the event log on the computer on which the Microsoft Dynamics NAV Server instance is installed.

  • If the selected printer is a not an actual printer but a driver, such as the Microsoft XPS Document Writer or One Note, then the report is not printed and the background session is blocked.

  • If the selected printer displays a dialog box, such as a request for credentials or a warning about low printer ink, then the report is not printed and the background session is blocked.

  • The user account must have access to print to the specified printer. By default, Microsoft Dynamics NAV Server instances run under the Network Service account, which does not have access to print to network printers or most local printers. If the user account does not have access to print to the specified printer, then one of the following occurs:

    • If there is a default printer installed for the user account, then the user account attempts to print to that default printer.

    • If there is not a default printer installed for the user account, then you receive an error in the event log on the server on which the Microsoft Dynamics NAV Server instance is installed and the background session exits.

  • If the report should be printed on the printer that is specified in the Printer Selections page entry but the Printer Name field is blank for the entry, then the report is printed to the default printer of the computer on which the Microsoft Dynamics NAV Server instance is installed.

See Also

Tasks

How to: Specify Printer Selection for Reports

Concepts

Printing Reports
Configuring NAS Services
Managing Microsoft Dynamics NAV Server Instances


Upgrading Reports from Earlier Versions

If you want to use reports from earlier versions of Microsoft Dynamics NAV, you must upgrade the reports before you can run or modify them. The report formats that were supported in Microsoft Dynamics NAV 2013 were client report definition (RDLC) 2008. In Microsoft Dynamics NAV 2013 R2, the report formats were replaced with client report definition (RDLC) 2010. This format is also used in Microsoft Dynamics NAV 2016.

Typically, upgrading reports is part of upgrading the Microsoft Dynamics NAV application. However, you can also import reports from .txt files or .fob files.

Important
You cannot import reports from versions earlier than Microsoft Dynamics NAV 2013 into Microsoft Dynamics NAV 2016. If you want to import a Microsoft Dynamics NAV 2009 report, you must first upgrade the report to Microsoft Dynamics NAV 2013, and then import it into Microsoft Dynamics NAV 2016. For more information, see How to: Upgrade Reports in the MSDN Library for Microsoft Dynamics NAV 2013.

This topic provides an overview of suggested options to upgrade reports from Microsoft Dynamics NAV 2013 to Microsoft Dynamics NAV 2016.

Importing RDLC 2008 Reports

If you import reports that have RDLC 2008 format from Microsoft Dynamics NAV 2013, then you must upgrade the reports to Microsoft Dynamics NAV 2016.

Upgrading reports is part of the Upgrading the Application Code section of the upgrade process.

The following illustration shows the upgrade process for the reports.

Upgrade Process for RDLC 2008 Reports

When you import the report, Microsoft Dynamics NAV automatically upgrades it to RDLC 2010. SQL Server Report Builder first validates that the reports have the correct RDLC 2008 format and then upgrades them to RDLC 2010 format.

In Object Designer, when the upgrade is complete, the Modified flag is set to Yes. All other properties for the report are not changed.

After the upgrade, you can open the layout in Visual Studio. For more information, see How to: Integrate Report Dataset Designer and Visual Studio Report Designer. You must compile the imported report before you can run it.

Importing RDLC 2010 Reports

You can import reports that have RDLC 2010 format to Microsoft Dynamics NAV 2016. Upgrading the reports is an automated process. SQL Server Report Builder first validates that the reports have the correct RDLC 2010 format and then imports them.

In Object Designer, no properties for the report are changed.

See Also

Tasks

How to: Integrate Report Dataset Designer and Visual Studio Report Designer
How to: Export Objects

Concepts

Designing Reports

Other Resources

Upgrading to Microsoft Dynamics NAV 2016


Queries

A query is a new object in Microsoft Dynamics NAV 2016 that you use to specify a set of data from the Microsoft Dynamics NAV database. You can query the database to retrieve fields from a single table or multiple tables. You can specify how to join tables in the query. You can filter the result data. You can specify totaling methods on fields, such as sums and averages.

The following section describes how to locate Microsoft Dynamics NAV 2016 documentation about designing queries in Microsoft Dynamics NAV.

Creating Queries

This section explains how to design queries to specify datasets.

To | See
Learn how to create a basic query in Query Designer. | How to: Create Queries
Learn the supported ways to join tables in Query Designer. | Understanding Data Item Links
Learn how to add totaling methods to columns in a query. | Understanding Query Totals and Grouping
Learn how to filter the results of a query. | Understanding Query Filters
Learn how to run queries from C/AL code | Working with Queries in C/AL
Learn how to create complex queries by walking through examples that use the CRONUS International Ltd. demonstration database. | Walkthrough: Creating a Query to Link Two Tables Walkthrough: Creating a Query That Uses a Totaling Method and Sorting Walkthrough: Creating a Query to Link Three Tables
Note
You cannot run a query that gets data from both the application database and the business data database. This also applies to single-tenant deployments so that you do not have to rewrite queries if you decide to export the application. For a description of which tables are considered part of the application database, see Separating Application Data from Business Data.

Using Queries

The following examples show how you can use queries in your Microsoft Dynamics NAV application.

  • Creating charts that are based on a query instead of a table. For more information, see How to: Create Generic Charts in the Application Help for Microsoft Dynamics NAV 2016.

  • Saving a query as an .xml or .csv file. You can use the SAVEASXML Function to create an .xml file that contains the resulting dataset of a query. You can use the .xml file to integrate with external applications.

  • Exposing data as an OData web service. You can register and publish a query as a web service in the same way that you can register and publish pages or codeunits as web services. You use the Web Services page to register and publish pages, codeunits, or queries. After you expose a query as a web service, you can import it into other applications. For example, you can import Microsoft Dynamics NAV data into Microsoft Excel using Microsoft PowerPivot for Excel, which is a data analysis add-in. You can then create PivotTables in Excel that use the Microsoft Dynamics NAV data from your query. For an example , see Walkthrough: Combining Data from Microsoft Dynamics NAV Queries and Pages with Data from Azure DataMarket (OData)


How to: Create Queries

A query describes a dataset of Microsoft Dynamics NAV data. Queries retrieve records from one or more tables and combine the records into rows and columns in a single dataset. You create queries in the development environment using Query Designer. To create a query, you define data items and columns. A data item specifies the table to retrieve records from. A column specifies a field of the table to include in the resulting dataset of a query. After you have added the data items and columns, you create links between the data items. A data item link determines which records to include in the dataset based on a common field between two data items. For more information, see Understanding Data Item Links.

To create a query and add data items and columns

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Query, and then choose New.

  3. In Query Designer, on the first line, in the Type column, choose DataItem from the drop-down list.

    Note
    The first line in Query Designer must be a DataItem and not a Column.

  4. In the Data Source column, enter the name of the table from which you want to add fields. To select the table from the Table List window, choose the up arrow.

  5. In the Name column, verify the default name or enter a Common Language Specification (CLS)-compliant name for the data item. The first character must be a letter. Subsequent characters can be any combination of letters, integers, and underscores.

    For more information, see the "Naming" section in Common Language Specification in the MSDN Library.

    Warning
    All DataItem and Column rows must have unique names.

  6. In Query Designer, on the next line, in the Type column, choose Column from the drop-down list.

  7. In the Data Source column, enter a field that you want to include in the query dataset. To select one or more fields from the Field List window, choose the up arrow.

    Note
    Fields are indented one level from the parent data item.

  8. In the Name column, enter a CLS-compliant name for the field.

  9. In the user interface for the query results, such as in a chart, the name of the underlying table field is displayed for the query column. If you want to display a different name for the column, then change the Caption Property or CaptionML Property.

    Note
    When you run the query from Object Designer, the About This Query window that opens in the RoleTailored client displays the name that is defined by the Name property of the column, not the Caption property or CaptionML property.

  10. Continue to enter DataItems and Columns in Query Designer until it contains all fields from all tables that you want to include in the query.

    Note
    You must have at least one Column in the query. You are not required to have one Column for each DataItem.

To link data items

  1. In Query Designer, choose the lower data item.

    A data item must be linked to the data item or data items above it. You create the link from the lower data item in Query Designer.

  2. On the View menu, choose Properties.

  3. In the Properties window, in the Value column of DataItemLink property, choose the AssistEdit button.

    The Data Item Link window opens. You will use the Data Item Link window to create a reference link between a field in the table of the lower data item and a field in the table of the upper data item.

  4. In the Field column of the first line, choose the up arrow.

    The Field List window opens to display all the fields in the table of the lower data item.

  5. In the Field List window, choose the field from the table of the lower data item, and then choose OK to close the Field List window.

  6. In the Reference DataItem column of the same line of the DataItem List window, choose the up arrow.

    The Field List window opens to display all the fields in the table of the upper data item.

  7. In the Field List window, choose the field from the table of the upper data item that is common to the field of the lower data item, and then choose OK to close the Field List window.

  8. Choose OK to return to the Properties window.

  9. In the Value column of the DataItemLinkType property, choose one of the values described in the following table.

    Value Description

    Use Default Values If No Match

    The resulting dataset will include all the records from the upper data item, even if a record does not have a matching value in the linked field of lower data item as specified by the DataItemLink property. When a record does not have a matching record in the lower data item, the columns from the lower data item include the default value for the data type of the table field that specifies the column. For example, if the field has an integer data type, then the default value is 0.

    Exclude Row If No Match

    The resulting dataset will include only records from data item tables that have matching values for the fields that are linked by the DataItemLink property.

    SQL Advanced Options

    Provides alternatives to Use Default Values If No Match and Exclude Row If No Match for generating a dataset that corresponds to joins in SQL SELECT statements. When you set the property to SQL Advanced Options, the SQLJoinType property appears so that you can select the SQL join type.

  10. If you set the DataItemLinkType property to SQL Advanced Options, then set the SQLJoinType property. For more information, see SQL Advanced Options for Data Item Link Types.

  11. Close the Properties window.

To save the query

  1. On the File menu, choose Save.

  2. In the Save As window, in the ID field, enter an ID for the query object. The ID must be in a valid range for your solution. In the Name field, enter a name for the query, verify that the Compiled check box is selected, and then choose the OK button.

See Also

Tasks

Walkthrough: Creating a Query to Link Two Tables
Walkthrough: Creating a Query That Uses a Totaling Method and Sorting

Reference

SQLJoinType Property

Concepts

Understanding Data Item Links


Understanding Data Item Links

With Microsoft Dynamics NAV queries, you can retrieve records from one or more tables and combine the records into rows in a single dataset. In Query Designer, tables are specified by data items. You combine tables by linking the data items in Query Designer. In most cases, the tables are combined based on a relationship between certain fields in the tables. Microsoft Dynamics NAV includes different types of data item links that you can use to limit the records that are included in the resulting dataset by how the fields in data item tables are related to each other.

Sample Tables and Query

This topic uses the following sample tables and query to demonstrate data item links.

Salesperson/Purchaser Table

The Salesperson/Purchaser table contains a list of salespersons. Each salesperson is identified by a unique code

Code | Name
AA | Annette
BB | Bart
DD | Debra
JJ | John

Sales Header Table

The Sales Header table contains a list of sales orders. Each sales order has a unique number, includes the name of the customer to sell to, and is assigned to a salesperson by the Salesperson_Code column.

No | Sell_to_Customer_Name | Salesperson_Code
1000 | Autohaus | AA
2000 | Blanemark | DD
3000 | Candoxy | JJ
4000 | New Concepts |

Sample Query

The following illustration shows the Query Designer for a query that links the Sale Header table with the Salesperson/Purchaser table on the Salesperson_Code and Code columns, as specified by the DataItemLink property. In the illustration, the DataItemLinkType property is set to Exclude Row If No Match. You can set the property to Always Include to change the resulting dataset as described in this topic.

Query Designer inner join

How Data Item Links Work in Query Designer

When you add data items in Query Designer, they are arranged in a hierarchy, where the DataSource column of each data item is indented to one level from the data item above to indicate a link between with the data items above it. The order of the data items determines the sequence in which data items are linked. In SQL SELECT statements, this hierarchy corresponds to designating tables as left and right, where the upper data item would be on the left and the lower data item would be on the right.

To create a link between two data items in Query Designer, you set the DataItemLink property and the DataItemLinkType property on the lower data item in Query Designer.

  • The DataItemLink property links one or more columns of the lower data item table to the upper data item table.

  • The DataItemLinkType property determines which records to include in the results based on the columns that are linked by the DataItemLink property.

Note
By default, the DataItemLinkType property is set to Use Default Values If No Match.

For example, the following illustration shows the Query Designer and Properties window for linking the Sales Header table to the Salesperson/Purchaser table. You set the DataItemLink property and the DataItemLinkType property on the Sales Header data item because it is the lower data item in Query Designer.

Query Designer showing link between 2 data items

Linking More Than Two Data Items

A query links data items in the order that they appear in Query Designer, starting from the top and then working downward. When you have more than two data items, subsequent data items are linked to the resulting dataset of the linked data items above it. For example, when you link the first two data items, the query generates a dataset. When you add another data item, the data item is linked to the dataset of the first linked pair of data items, where it applies the conditions that are specified by its DataItemLink property and DataItemLinkType property. The following illustration shows an example with three data items.

Query Designer showing 3 data item links

This pattern continues for each additional data item.

Setting the DataItemLink Property

The DataItemLink property sets up a reference between one or more columns of the data item tables for combining records. In a query, two data item tables typically will have columns that have values that are common to both tables. For example, the Salesperson table and Sales Header table have the Code column and Salesperson_Code column in common. To create a link between these two tables, you could add the following value in the DataItemLink property of the Sales Header data item.

Field | Reference DataItem | Reference Field
Salesperson code | Salesperson_Purchaser | Code

The DataItemLink property sets up "equal to" (=) comparison condition between two columns of the data items. When the query is run, the query compares each row of the two data items to find records that having matching values for the columns. Records that have matching column values are combined into a row in the resulting dataset. In some cases, there will be records that do not have matching values. You use the DataItemLinkType property to include records that do not have matching column values.

Setting Up the DataItemLinkType Property

You use the data item link type to limit the records that are included in the resulting dataset based on the conditions of the DataItemLink property. You have the following options from which to choose:

  • Exclude Row If No Match

  • Use Default Values If No Match

  • SQL Advanced Options

    The SQL Advanced Options provide alternatives to Always Include and Include Matches Only that correspond to joins in SQL SELECT statements. For more information, see SQL Advanced Options for Data Item Link Types.

Exclude Row If No Match

The resulting dataset of the Exclude Row If No Match link type contains only records from both data item tables that have matching values for the columns that are linked by the DataItemLink property. The query finds the records from each data item that have matching column values, and then, for each pair of records, a row is added to the dataset that includes the columns from the two data items.

For example, the following table shows the resulting dataset of the sample query when the DataItemLinkType property is set to Exclude Row If No Match.

Name | No | Sell_to_Customer_Name
Annette | 1000 | Autohaus
Debra | 2000 | Blanemark
John | 3000 | Candoxy

The records for Bart in the Salesperson table and New Concepts in the Sales Header table do not have matching records in the opposing table, so they are excluded from the resulting dataset.

Use Default Values If No Match

The resulting dataset of the Use Default Values If No Match link type contains all the records from the upper data item or data items; even if a record does not have a matching value in the linked column of lower data item as specified by the DataItemLink property. For each record in the upper data item, the query adds a row in the dataset that combines columns from the upper and lower data item. When a record does not have a matching record in the lower data item, the columns from the lower data item include the default value for the data type of the table field that specifies the column. For example, if the field has an integer data type, then the default value is 0.

For example, the following table shows the resulting dataset of the sample query when the DataItemLinkType property is set to Use Default Values If No Match.

Name | No | Sell_to_Customer_Name
Annette | 1000 | Autohaus
Bart | null | null
Debra | 2000 | Blanemark
John | 3000 | Candoxy

The record for Bart in the Salesperson table does not have a matching record in the Sales Header table, so a row is included but the columns from the Sale Header table are given a null value. The record in the Sale Header table for New Concepts is not included in the resulting dataset because it does not have a matching column in the Salesperson table.

See Also

Tasks

How to: Create Queries
Walkthrough: Creating a Query to Link Two Tables
Walkthrough: Creating a Query That Uses a Totaling Method and Sorting
Walkthrough: Creating a Query to Link Three Tables


SQL Advanced Options for Data Item Link Types

With queries, you can link data items together to combine records from two or more tables into a single dataset. In Query Designer, tables are defined by data items. To create a link between data items, you set the DataItemLinkType Property of a data item in Query Designer. The DataItemLinkType property controls which records to include or exclude from resulting dataset based on the conditions of the DataItemLink Property (Reports). The DataItemLinkType property includes the SQL Advanced Options value that you can use create links that correspond to joins in SQL select statements. For more general information about linking data items, see Understanding Data Item Links.

Left and Right Table Designation

In SQL join statements, tables are designated as either left or right. In Query Designer, data items are arranged vertically, starting from the top. When linking data items in Query Designer, the left table in SQL corresponds to the first or upper data item in Query Designer and the right table in SQL corresponds to the second or lower table in Query Designer.

Accessing the SQL Advanced Options

When setting up a data item link between two data items, you always set up the link on the lower data item in Query Designer. To access the SQL advanced options, you open the properties of a data item, and then set the DataItemLinkType Property to SQL Advanced Options. The SQLJoinType property appears in the Properties window for the data item. The SQLJoinType property has the following values:

  • Inner Join

  • Left Outer Join

  • Right Outer Join

  • Full Outer Join

  • Cross Join

Sample Tables and Query

This topic uses the following sample tables and query to demonstrate the SQL Advanced Options for data item links.

Salesperson/Purchaser Table

The Salesperson/Purchaser table contains a list of salespersons. Each salesperson is identified by a unique code.

Code | Name
AA | Annette
BB | Bart
DD | Debra
JJ | John

Sales Header Table

The Sales Header table contains a list of sales orders. The Sales Header table contains a list of sales orders. Each sales order has a unique number, includes the name of the customer to sell to, and is assigned to a salesperson by the Salesperson_Code column.

No | Sell_to_Customer_Name | Salesperson_Code
1000 | Autohaus | AA
2000 | Blanemark | DD
3000 | Candoxy | JJ
4000 | New Concepts |

Sample Query

The following illustration shows the Query Designer for a query that links the Sale Header table with the Salesperson/Purchaser table on the Salesperson_code and Code columns, as specified by the DataItemLink property. In the illustration, the SQL Advanced Options property is set to Inner Join. For each of the data item links types discussed in the following sections, you change the SQL Advanced Options property to the appropriate type.

Query Designer for an SQL Inner link type

Inner Join

Inner Join creates a dataset by combining records from data item tables where a match is found between the columns that are linked by the DataItemLink property of the lower data item. Inner Join uses an "equal to" comparison operator to match rows from the lower data item table with rows from the upper data item table that is based on the values of the linked columns.

  • Each pair of matching records is combined into a row in the dataset.

  • Records from the upper and lower data item tables that do not have a matching column in the lower data item table are excluded from the resulting dataset.

The following illustration shows an Inner Join type between tables A and B. The shaded area indicates the records that are included in the resulting dataset.

Visualization of SQL inner join between two tables

Dataset Example

The following table shows the resulting dataset for an Inner Join between the Sales Header table and Salesperson/Purchaser table in sample query.

Name | Sell_to_Customer_No | Sell_to_Customer_Name
Annette | 1000 | Autohaus
Debra | 2000 | Blanemark
John | 3000 | Candoxy

The records for Bart in the Salesperson table and New Concepts in the Sales Header table do not have matching records in the opposing table, so they are excluded from the resulting dataset.

SQL SELECT Statement for Inner Join

To specify an inner join with an SQL statement, you can do either of the following:

  • Use a WHERE clause.

  • Use the INNER JOIN condition with an ON clause.

The following two examples show how to create an inner join on the Salesperson/Purchaser and Sales Header tables with SQL statements. These two statements result in the same dataset.

Copy Code
SELECT "Salesperson/Purchaser".Name, "Sales Header"."No.", "Sales Header"."Sell-to Customer Name"
FROM "Salesperson/Purchaser" INNER JOIN "Sales Header"
  ON "Salesperson/Purchaser".Code = "Sales Header"."Salesperson Code"
Copy Code
SELECT "Salesperson/Purchaser".Name, "Sales Header"."No.", "Sales Header"."Sell-to Customer Name"
FROM "Salesperson/Purchaser", "Sales Header"
WHERE "Salesperson/Purchaser".Code = "Sales Header"."Salesperson Code"

Left Outer Join

A left outer join resembles the inner join except that the resulting dataset set contains every record from the upper data item table, even if a record does not have a matching value in the lower data item for columns that are linked by the DataItemLink property.

  • For each record in the upper data item, a row is added in the dataset that combines columns from the upper and lower data item.

  • When a record in the upper data item table has no matching record in the lower data item table, columns coming from the lower data item table have null values.

The following illustration shows a Left Outer Join type between tables A and B. The shaded area indicates the records that are included in the resulting dataset. In the sample query, the Salesperson/Purchaser table is considered the left table.

Visualization of SQL left outer join

Dataset Example

The following table shows the resulting dataset for a Left Outer Join between the Sales Header table and Salesperson/Purchaser table in sample query.

Name | No | Sell_to_Customer_Name
Annette | 1000 | Autohaus
Bart | null | null
Debra | 2000 | Blanemark
John | 3000 | Candoxy

The record for Bart in the Salesperson/Purchaser table does not have a matching record in the Sales Header table, so a row is included but the columns from the Sale Header table are given null values. The record for New Concepts in the Sale Header table is not included in the resulting dataset because it does not have a matching column in the Salesperson/Purchaser table.

SQL SELECT Statement for Left Outer Join

To specify a left outer join with an SQL statement, you use the LEFT OUTER JOIN condition.

The following example shows how to create a left outer join on the Salesperson/Purchaser and Sales Header tables by using a SQL statement.

Copy Code
SELECT "Salesperson/Purchaser".Name, "Sales Header"."No.", "Sales Header"."Sell-to Customer Name"
FROM "Salesperson/Purchaser" LEFT OUTER JOIN "Sales Header"
  ON "Salesperson/Purchaser".Code = "Sales Header"."Salesperson Code"

Right Outer Join

A Right Outer join resembles the inner join except that the resulting dataset set contains every record from the lower data item table, even if a record does not have a matching value in the upper data item for columns that are linked by the DataItemLink property.

  • For each record in the lower data item, a row is added in the dataset that combines columns from the lower and upper data item tables.

  • When a record in the lower data item table has no matching record in the upper data item table, columns coming from the upper data item table have null values.

The following illustration shows a Right Outer Join type between tables A and B. The shaded area indicates the records that are included in the resulting dataset.

Visualization of SQL right outer join

Dataset Example

The following table shows the resulting dataset for a Right Outer Join between the Salesperson/Purchaser table and Sales Header table in the sample query. The Sales Header table is considered the right table.

Name | No | Sell_to_Customer_Name
Annette | 1000 | Autohaus
Debra | 2000 | Blanemark
John | 3000 | Candoxy
null | 4000 | New Concept

The record for New Concepts in the Sales Header table does not have a matching record in the Salesperson/Purchaser table, so a row is included but the columns from the Salesperson/Purchaser table are given null values. The record for Bart in the Salesperson/Purchaser table is not included in the resulting dataset because it does not have a matching column in the Sales Header table.

SQL SELECT Statement for Right Outer Join

To specify a left outer join with an SQL statement, you use the RIGHT OUTER JOIN condition.

The following example shows how to create a right outer join on the Salesperson/Purchaser and Sales Header tables by using a SQL statement.

Copy Code
SELECT "Salesperson/Purchaser".Name, "Sales Header"."No.", "Sales Header"."Sell-to Customer Name"
FROM "Salesperson/Purchaser" RIGHT OUTER JOIN "Sales Header"
  ON "Salesperson/Purchaser".Code = "Sales Header"."Salesperson Code"

Full Outer Join

A Full Outer join contains all the records from the upper data item table, and all records from the lower data item, including records that do not have a matching value for columns that are linked by the DataItemLink property.

  • Each pair of records from the data items that have matching column values are combined into a row in the dataset.

  • Records from the upper data item table that do have a matching column are included in a row, where the columns from lower data item table have null values.

  • Records from the lower data item table that do have a matching column are included in a row, where the columns from upper data item table have null values.

The following illustration shows a Full Outer Join type between tables A and B. The shaded area indicates the records that are included in the resulting dataset.

Visualization of an SQL full outer join

Dataset Example

The following table shows the resulting dataset for a Full Outer Join between the Sales Header table and Salesperson/Purchaser table in sample query.

Name | No | Sell_to_Customer_Name
Annette | 1000 | Autohaus
Bart | null | null
Debra | 2000 | Blanemark
John | 3000 | Candoxy
null | 4000 | New Concept

The records for Bart in the Salesperson/Purchaser table and New Concepts in the Sales Header table are included in a row, even though they not have matching values for columns.

SQL SELECT Statement for Full Outer Join

To specify a left outer join with an SQL statement, you use the FULL OUTER JOIN condition.

The following example shows how to create a full outer join on the Salesperson/Purchaser and Sales Header tables by using a SQL statement.

Copy Code
SELECT "Salesperson/Purchaser".Name, "Sales Header"."No.", "Sales Header"."Sell-to Customer Name"
FROM "Salesperson/Purchaser" FULL OUTER JOIN "Sales Header"
  ON "Salesperson/Purchaser".Code = "Sales Header"."Salesperson Code"

Cross Join

A cross join contains rows that combine each row from the upper data item table with each row from a lower data item table. Cross joins are also called Cartesian products. A cross join does not apply any comparisons between columns of data items, so the DataItemLink property is left blank.

Dataset Example

The following table shows the resulting dataset for a Cross Join between the Sales Header table and Salesperson/Purchaser table in sample query.

Name | No | Sell_to_Customer_Name
Annette | 1000 | Autohaus
Annette | 2000 | Blanemark
Annette | 3000 | Candoxy
Annette | 4000 | New Concept
Bart | 1000 | Autohaus
Bart | 2000 | Blanemark
Bart | 3000 | Candoxy
Bart | 4000 | New Concept
Debra | 1000 | Autohaus
Debra | 2000 | Blanemark
Debra | 3000 | Candoxy
Debra | 4000 | New Concept
John | 1000 | Autohaus
John | 2000 | Blanemark
John | 3000 | Candoxy
John | 4000 | New Concept

SQL SELECT Statement for Cross Join

To specify a cross join with a SQL statement, you can do either of the following:

  • Use the CROSS JOIN condition

  • Create an implicit join, which has no join condition, without using a WHERE clause

The following examples shows how to create a cross join of the Salesperson/Purchaser and Sales Header tables by using a SQL statement.

Copy Code
SELECT "Salesperson/Purchaser".Name, "Sales Header"."No.", "Sales Header"."Sell-to Customer Name"
FROM "Salesperson/Purchaser" CROSS JOIN "Sales Header"
Copy Code
SELECT "Salesperson/Purchaser".Name, "Sales Header"."No.", "Sales Header"."Sell-to Customer Name"
FROM "Salesperson/Purchaser", "Sales Header"


Understanding Query Totals and Grouping

In a query, you use a totals method to perform a calculation on the fields of a column and return the calculated value in the dataset. For example, you can sum all the fields in a column or find the average value. The following table shows the available totals methods.

Value Description

Sum

Calculates the sum of the values of the field in the designated column for all records that are selected as part of the grouped set.

Average

Calculates the average value of the field in the designated column for all records that are selected as part of the grouped set.

When averaging fields that have an integer data type (such as Integer or BigInteger), integer division is used. This means that result is not rounded, and the remainder is discarded. For example, 5÷2=2 instead of 2.5 (or 2 1/2).

Min

Retrieves the lowest value of the field in the designated column for all records that are selected as part of the grouped set.

Max

Retrieves the highest value of the field in the designated column for all records that are selected as part of the grouped set.

Count

Returns the number of records that are selected as part of the grouped set.

Working with Totals and Grouping in Query Designer

To specify a totals method in Query Designer, you set the Method Type column to Totals, and then select the totals method in Method column. By default, retrieved records are automatically grouped by the other columns in the query, as indicated by a check mark in the Group By column in Query Designer. When grouped by a column, records that have similar values for the column are grouped together and the totals method is applied against the records in the group. A summary value is calculated and returned in a single row for the group in the dataset.

Note
Except for the Count method, you can only use a totals method (Sum, Average, Min, and Max) on a field that has a numeric data type of Decimal, Integer, BigInteger, or Duration.

The following illustration shows how to use Query Designer to create a query that links the Customer table and the Sales Line table and retrieves the total number of items for each customer. The query is grouped by the No. and Name columns.

Query with Sum column

The totals methods and grouping correspond to using aggregate functions and the GROUP BY clause, respectively, in SQL SELECT statements. For more information, see Creating Queries with Totals in SQL.

The grouping concept is further explained in the examples for each totals method in the following sections.

Sample Query

The sample query retrieves the quantity of items and customer for each open sales order from the CRONUS International Ltd. demonstration database. The query links table 18 Customer with table 37 Sales Line. The following illustration shows the query setup in Query Designer.

Query Designer for Customer Sales query

The following table represents a simplified version of the resulting dataset for the sample query.

Customer number | Customer name | Quantity
20000 | Selangorian Ltd. | 200
30000 | Blanemark Hifi | 150
20000 | Selangorian Ltd. | 300
40000 | Deerfield Graphics | 250
20000 | Selangorian Ltd. | 400
30000 | Blanemark Hifi | 350

In its current state, the query does not implement a totals method. The following sections explain how you can modify the query to implement the different totals methods.

Sum

The Sum method adds the values of all fields for the specified column within a group. To set up a Sum method on the Quantity column of the sample query, set the MethodType property to Totals and the Method property to Sum. The name of the Quantity column automatically changes to Sum_Quantity and the query is automatically grouped by the No. and Name columns. The following illustration shows the query in Query Designer.

Query with Sum column

The following table illustrates the resulting dataset for the query.

Customer number | Customer name | Quantity
20000 | Selangorian Ltd. | 900
30000 | Blanemark Hifi | 500
40000 | Deerfield Graphics | 250

For step-by-step instructions about how to create this query, see Walkthrough: Creating a Query That Uses a Totaling Method and Sorting.

Average

The Average method calculates the average value of the fields in the column within a group. To set up an Average method on the Quantity column of the sample query, set the MethodType property to Totals and the Method property to Sum. The name of the Quantity column automatically changes to Ave_Quantity and the query is automatically grouped by the No. and Name columns.

The following table illustrates the resulting dataset for the query.

Customer number | Customer name | Quantity
20000 | Selangorian Ltd. | 300
30000 | Blanemark Hifi | 250
40000 | Deerfield Graphics | 250

Min

The Min method retrieves the lowest value of fields in the column within a group. To set up a Min method on the Quantity column of the sample query, set the MethodType property to Totals and the Method property to Min. The name of the Quantity column automatically changes to Min_Quantity and the query is automatically grouped by the No. and Name columns.

The following table illustrates the resulting dataset for the query.

Customer number | Customer name | Quantity
20000 | Selangorian Ltd. | 200
30000 | Blanemark Hifi | 150
40000 | Deerfield Graphics | 250

Max

The Min method retrieves the highest value of fields in the column within a group. To set up a Min method on the Quantity column of the sample query, set the MethodType property to Totals and the Method property to Max. The name of the Quantity column automatically changes to Max_Quantity and the query is automatically grouped by the No. and Name columns.

The following table illustrates the resulting dataset for the query.

Customer number | Customer name | Quantity
20000 | Selangorian Ltd. | 400
30000 | Blanemark Hifi | 350
40000 | Deerfield Graphics | 250

Count

The Count method returns the number of records from the data item table that comprise a group in the dataset. Unlike the other totals methods, the Count method is not associated with a specific column. Records are identified and counted based on the primary key of the data item table. Referring to the sample query, you can use a Count method to get the number of open sales orders per customer. To set up a Count method in the sample query, do the following:

  1. Delete the Quantity column because the Count method is not associated with a specific column.

    Note
    When using the Count method, the DataSource Property must be blank.

  2. On a blank line under the data item for Sales Lines, set the MethodType property to Totals and the Method property to Count. The name of the new column automatically changes to Count_ and the query is automatically grouped by the No. and Name columns.

    Query Designer will look similar to the following illustration.

    Query Designer for counting Customer Sales

The following table illustrates the resulting dataset for the query.

Customer number | Customer name | Count
20000 | Selangorian Ltd. | 3
30000 | Blanemark Hifi | 2
40000 | Deerfield Graphics | 1

In SQL SELECT statements, the Count method corresponds to a COUNT(*) or COUNT(field) clause.

Creating Queries with Totals in SQL

If you are familiar with SQL, then it is helpful to know how the totaling methods in Microsoft Dynamics NAV relate to SQL statements. To specify a totaling method in an SQL statement, you add the method to the SELECT statement and then add a GROUP BY clause. To group results on columns, you add the GROUPED BY statement.

The following example shows how to use an SQL statement to create an inner join of the Customer table and the Sales Line table and a sum of items for each customer. The result is grouped by the No. and Name columns.

Copy Code
SELECT Customer."No.", Customer.Name, SUM("Sales Line".Quantity)
FROM Customer INNER JOIN "Sales Line"
  ON Customer."No." = "Sales Line"."Sell-to Customer No."
GROUP BY Customer."No.", Customer.Name

See Also

Tasks

Walkthrough: Creating a Query That Uses a Totaling Method and Sorting

Reference

Method Property


Understanding Query Filters

You can specify filters in a query to restrict the data in the resulting dataset. A filter applies conditions on fields in a table that is associated with the query. For a field to be included in the resulting dataset, a field must meet the conditions of the filter.

Different Ways to Filter a Query Dataset

You can set up filters on a field from Query Designer or from C/AL code by using any of the methods that are outlined in the following table.

Method | Filter | Description
From Query Designer | Filter on a Data item | You can set the DataItemTableFilter property of a data item to filter on a field in the table of the data item. You can apply the filter to any field in the table, not just fields that are defined as columns in the resulting dataset. A data item filter cannot be overwritten from C/AL code.
 | Filter on a Column | You can set the ColumnFilter property of a column to filter on the source field of the column. A filter on a column can be overwritten by the SETFILTER and SETRANGE functions from C/AL code.
 | Filter on a Filter row | A filter row lets you add a filter on a field that will not be included in the resulting dataset, but can be changed from C/AL code. To set up a filter row in Query Designer, you add a row of the type Filter that is set to the field thaaat you want to filter, and then set its ColumnFilter property.. A filter row is like a data item filter except a filter on a filter row can be overwritten by the SETFILTER and SETRANGE functions from C/AL code.
From C/AL | SETFILTER function | You can call the SETFILTER function from C/AL code to set a filter on a field that is exposed through a column or filter row. The filter that is set by the SETFILTER function will overwrite any filter that is applied to a column or filter row on the same field by the ColumnFilter property.
 | SETRANGE function | You can SETRANGE function from C/AL code to set a filter on a field that is exposed through a column or filter row. The filter that is set by the SETRANGE function will overwrite any filter that is applied to column or filter row on the same field.

Filtering From Query Designer

You can set up filters from Query Designer on data items, columns, and filter rows. You can set up multiple filters on the same field in addition to different fields.

Filtering with Data Items in Query Designer

To specify filters on a data item in Query Designer, you set the DataItemTableFilter Property of a data item. You can apply a filter on any field in a table, not just those fields that are represented by a column in the query.

The following illustration shows Query Designer for a query that links table 18 Customer and table 37 Sales Line. The illustration includes the Properties window for the Sales Line data item that sets a filter to include only sales lines that have a quantity greater than 10.

Query inner join, filters on a field

The following illustration shows the resulting dataset for the query.

Result of a query that filters on a field

A data item filter is static which means that it cannot be overwritten by a filter on a column or filter row in Query Designer or by the SETFILTER or SETRANGE functions in C/AL code. If one of these filter types is applied to the same field as the data item filter, then the filters are combined. In logical terms, this combination corresponds to an "AND" operation. For example, if the data item filter applies a filter on a field to include values greater than 10 (>10) and a column filter applies a filter on the same field to include values less than fifty (<50), then the resultant filter includes values that are greater than 10 and less than fifty (10< value <50).

The DataItemTableFilter property corresponds to a WHERE clause in an SQL SELECT statement. For more information, see Equivalent SQL SELECT Statements for Query Filters .

Filtering with Columns and Filter Rows From Query Designer

Unlike data item filters, filters on a column or filter row are dynamic and can be overwritten from C/AL code at runtime from a call to the SETFILTER or SETRANGE function that sets a filter on the same field.

You use filters on a column to filter on fields that are included in the dataset. To apply a filter on a column, you set the ColumnFilter Property of the column. You can apply a filter on any column, including aggregated columns that are applied a totals method by the Method Property.

You use filters on a filter row to filter on fields that you do not want included in the dataset. To set up a filter row, you add a row of the type Filter in Query Designer that specifies a field, and then set its ColumnFilter property. For more information about how to set up filter rows, see How to: Set Up Filter Rows in Query Designer.

The following illustration shows Query Designer for a query that links the Customer table and the Sales Line table and retrieves the total quantity of items ordered for each customer. The query includes the following filters, as shown by the Properties windows in the illustration.

  • A filter on the Sum_Quantity column to include only records from the Sales Line table where the total quantity is less than 50.

  • A filter on filter row for the Location Code field of the Sales Line table that includes only records where the location code is WHITE.

Query example showing column filters

The following illustration shows the resulting dataset for the query.

Shows the rendered dataset of a filtered query

In an SQL SELECT statement, filters on a column or filter row that do not apply a totals method, as with the Location Code filter row in the example, would correspond to a WHERE clause. Filters on a columns or filter rows that do apply a totals method, as with the Quantity column in the example, would correspond to a HAVING clause. For more information, see Equivalent SQL SELECT Statements for Query Filters .

Equivalent SQL SELECT Statements for Query Filters

If you are familiar with SQL, then it is helpful to know how filtering in Microsoft Dynamics NAV queries relates to SQL statements. To specify filters in an SQL statement, you use WHERE and HAVING clauses. The WHERE clause filters on fields. The HAVING clause filters on the results that have aggregated values as applied by of a totals method.

The following example shows the corresponding SQL SELECT statement for the previous data item filter example that links the Customer and Sales Line tables and filters on the Quantity field.

Copy Code
SELECT Customer."No.", Customer.Name, "Sales Line".Quantity
FROM Customer LEFT OUTER JOIN "Sales Line"
ON Customer."No." = "Sales Line".Sell-to Customer No.
WHERE "Sales Line"."Quantity" > 10

The following example shows the corresponding SQL SELECT statement for the previous column and filter row example that links the Customer and Sales Line tables and filters on the Location Code field and the total sum of the Quantity field.

Copy Code
SELECT Customer."No.", Customer.Name, SUM("Sales Line".Quantity) as Sum_Quantity
FROM Customer LEFT OUTER JOIN "Sales Line"
  ON Customer."No." = "Sales Line".Sell-to Customer No.
WHERE “Sales Line”.”Location Code” = WHITE
GROUP BY Customer."No."
HAVING Sum_Quantity  50

Filtering From C/AL Code

C/AL code includes the SETFILTER and SETRANGE functions that you can use to apply a filter on a field that is represented as a column or filter row in a query. The SETFILTER and SETRANGE functions enable you to set filters programmatically on a query at runtime. You use the SETRANGE function to filter on a range of values in a column or filter row. The SETFILTER function is more versatile than the SETRANGE function and enables you to filter a field based on a filter expression.

The SETFILTER and SETRANGE functions will overwrite any filter on the same field that is set on a column or filter row by the ColumnFilter property in Query Designer. If a SETFILTER or SETRANGE function filters on the same field as a filter on a data item, as specified by the DataItemTableFilter property, then the function filter and DataItemTableFilter property filter are combined.

Calling the SETFILTER and SETRANGE Functions

You can call the SETFILTER and SETRANGE function from the C/AL code of the Microsoft Dynamics NAV object that runs the query object or from the OnBeforeOpen Trigger of the query object.

To call the SETFILTER function, you use the following code.

Copy Code
Query.SETFILTER(Column, String)
  • Query is a variable of the Query type that specifies the query object.

  • Column is the name of the column or filter row as defined by its Name property.

  • String is the filter expression.

To call the SETRANGE function, you use the following code.

Copy Code
Query.SETRANGE(Column, FromValue, ToValue)
  • Query is a variable of the Query type that specifies the query object.

  • Column is the name of the column or filter row as defined by its Name property.

  • FromValue is the lower value of the range.

  • ToValue is the higher value of the range.

For more information, see SETFILTER Function (Query) and SETRANGE Function (Query).

Example

Referring to the query example in the previous section, you can add the following code to the OnBeforeOpen trigger of the query object to change the filters on the Quantity column and the Location_Code filter row to include quantities of less than 50 and a location code of RED.

Copy Code
currQuery.SETFILTER(Sum_Quantity, '<50');
currQuery.SETFILTER(Location_Code, '=RED');

See Also

Tasks

How to: Create Queries
How to: Set Up Filter Rows in Query Designer

Reference

SETFILTER Function (Query)
SETRANGE Function (Query)

Concepts

Understanding Data Item Links
Understanding Query Totals and Grouping
Working with Queries in C/AL


How to: Set Up Filter Rows in Query Designer

You use a Filter row in Query Designer when you want to filter the query on a field, but you do not want to include the field in the dataset. For example, you might want to filter a date field on a specific date, but you do not want to include the date in the dataset. To specify the filter for the Filter row, you set its ColumnFilter Property.

Note
The filter on a Filter row is similar to a filter on a data item, except that the filter of a Filter row can be programmatically overwritten by calling the SETFILTER and SETRANGE functions from C/AL code. For more information, see Understanding Query Filters.

To add a Filter row in a query

  1. To open the query for editing in the development environment, on the Tools menu, choose Object Designer, choose Query, select the query you want to update, and then choose Design.

  2. In Query Designer, under the data item that defines the table that contains the field on which you want to filter, choose a blank row or insert a new one.

  3. In the blank row, set the Type column to Filter.

  4. In the Data Source, enter the name of the field to filter or choose the up arrow, choose the field, and then choose the OK button.

To set up a filter on the Filter row

  1. In Query Designer, choose the Filter row.

  2. On the View menu, choose Properties.

  3. In the Properties windows, in the Value field of the ColumnFilter property, choose the AssistEdit button.

  4. In the Column Filter window, in the row that contains the field, set the Type column to CONST if you want to filter on constant value or FILTER if you want to set filter based on an expression.

  5. In the Value column of the row, do one of the following:

    1. If you set the Type column to CONST, then enter the value that you want to filter on.

    2. If you set the Type column to FILTER, then enter the filter expression. For more information, see Entering Criteria in Filters.

  6. Choose the OK button to return to the Properties window.

  7. Close the Properties window and save the query.

See Also

Tasks

How to: Create Queries

Reference

ColumnFilter Property

Concepts

Understanding Query Filters


Entering Criteria in Filters

When you enter criteria, you can use all the numbers and letters that you can normally use in the field. In addition, you can use some special symbols or mathematical expressions. Here are the available formats:

Symbol | Meaning | Sample Expression | Records Displayed
= | Equal to | 377 | Number 377
 |  | BLUE | Those with the BLUE code, for example, the BLUE warehouse code
 |  | 22 | A datetime: from 22-current month-current year 0:00:00 to 22-current month-current year 22:59:59
 |  | 22 10 | An exact datetime: 22-01-01 10:00:00
.. | Interval | 1100..2100 | Numbers 1100 through 2100
 |  | ..2500 | Up to and including 2500
 |  | ..12 31 00 | Dates up to and including 12 31 00
 |  | P8.. | Information for accounting period 8 and thereafter
 |  | ..23 | From the beginning of time until 23-current month-current year 23:59:59
 |  | 23.. | From 23-current month-current year 0:00:00 until the end of time
 |  | 22..23 | From 22-current month-current year 0:00:00 until 23-current month-current year 23:59:59
| | Either/or | 1200|1300 | Those with number 1200 or 1300
& | And | <2000&>1000 | Numbers that are less than 2000 and greater than 1000. The & sign cannot be used by itself with numbers because no record can have two numbers.
<> | Not equal to | <>0 | All numbers except 0
> | Greater than | >1200 | Numbers greater than 1200
>= | Greater than or equal to | >=1200 | Numbers greater than or equal to 1200
< | Less than | <1200 | Numbers less than 1200
<= | Less than or equal to | <=1200 | Numbers less than or equal to 1200
* | An indefinite number of unknown characters | *Co* | Texts that contain "Co"
 |  | *Co | Texts that end with "Co"
 |  | Co* | Texts that begin with "Co"
? | One unknown character | Hans?n | Texts such as Hansen or Hanson
 | Calculate before rest | 30|(>=10&<=20) | Those with number 30 or with a number from 10 through 20 (the result of the calculation within the parentheses)
@ | Ignore case (either uppercase or lowercase allowed) | @location | Texts such as LOCATION, location or Location

You can also combine the various format expressions:

5999|8100..8490 | Include any records with the number 5999 or a number from the interval 8100 through 8490.
..1299|1400.. | Include records with a number less than or equal to 1299 or a number equal to 1400 or greater (all numbers except 1300 through 1399).
>50&<100 | Include records with numbers that are greater than 50 and less than 100 (numbers 51 through 99).
*C*&*D* | Texts containing both C and D.
@*co?* | Texts containing co, CO, Co, cO, such as cot, cope and incorporated. CO, cO, Co or co must be present, followed by at least one character, but there can be an indefinite number of characters before and after these, and case is unimportant.
Note
It is important that you enter only meaningful filters. For example, it is possible to specify an interval that does not exist, and the program cannot check this for you. In order to enter meaningful filters, you must know the sorting rules followed by this program.

See Also

Concepts

Understanding Query Filters


How to: Sort a Query Dataset in Ascending or Descending Order

By default, the rows in the resulting dataset of query are not necessarily arranged in any specific order. You can sort the rows in the dataset in ascending or descending order by one or more selected columns in the query. For example, if the query retrieves the quantity of items in sales orders for each customer, then you could sort the results in alphabetical order by the customer name, or you could sort the results by the quantity of items from the highest value to the lowest value. To sort query results, you modify the OrderBy Property of the query object.

Note
If you are familiar with SQL select statement syntax, the OrderBy property corresponds to the ORDERBY clause.

To sort query results by a column

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Queries, select the query that you want to modify, and then choose Design.

  3. Select the first blank line after the last data item or column in the list.

  4. On the View menu, choose Properties.

  5. In the Properties window, in the Value column of the OrderBy property, choose the AssistEdit button.

  6. In the Order By window, in the Column field of the first row, choose the AssistEdit button to open the Column List - Table window.

    The Column List - Table window includes all the columns that are defined in the query.

  7. Select the column that you want, and then choose the OK button.

  8. In the Order By window, set the Direction field for the column to Ascending or Descending.

    • Ascending sorts the column from lowest value to the highest value (A to Z, 0 to 9).

    • Descending sorts the column from highest value to the lowest value (Z to A, 9 to 0).

  9. Repeat the previous step to sort by additional columns.

    When you sort by multiple columns, the sort order is determined by the column’s position in the Order By window, where the query sorts the results by the first listed column, then the second column, and so on.

Example

This section includes a simple example of how you can set the OrderBy property to sort the resulting dataset of a query. For a detailed step-by-step example of sorting a query dataset, see Walkthrough: Creating a Query to Link Two Tables.

This following table shows the results of a query that retrieves the quantity of items in every open sales order for each customer.

Customer | Quantity
The Cannon Group | 50
New Concepts | 15
New Concepts | 30
Selangerian Ltd. | 20
Selangerian Ltd. | 60

To sort the Customer column in ascending order and the Quantity column in descending order, you add the following entries to the Order By window of the OrderBy property of the query.

Column | Direction
Name | Ascending
Quantity | Descending

In the Properties window, the OrderBy property is set to Name=Ascending,Quantity=Descending.

The following table shows the query results after sorting.

Customer | Quantity
New Concepts | 30
New Concepts | 15
Selangerian Ltd. | 60
Selangerian Ltd. | 20
The Cannon Group | 50

The following code is the ORDERBY clause of an SQL select statement that corresponds to the OrderBy property in this example.

Copy Code
OrderBy Name,Quantity

See Also

Tasks

Walkthrough: Creating a Query to Link Two Tables


Using the Date Method to Retrieve Day, Month, and Year Data

When you have fields in a table that contain dates, you can use a date method to retrieve only the year, month, or day instead of including the date in the resulting dataset of a query.

Setting Up a Date Method on a Query Column

To set up a date method on a query column, you can do one of the following from Query Designer:

  • In the row that specifies the column, set the Method Type to Date and the Method to Day, Month, and Year.

  • Open the properties of the column, and then set the MethodType Property to Date and Method Property to Day, Month, and Year.

For more information about how to set up query columns and properties, see How to: Create Queries.

Important
You can only use a date method on fields that have a Date or DateTime data type. For additional information about how to use a date method on a field that has the DateTime data type, see Working with DateTime Data Types.

Sample Table and Query

This topic uses the following sample table and query to demonstrate the different date methods.

Sample Sales Header Table

The following table contains data about sales orders for customers. The Order Date field has the data type of Date and the format DD-MM-YYYY, where DD is the day, MM is the month, and YYYY is the year.

Note
This is a simplified subset of the data that is found in table 36 Sales Header of the CRONUS International Ltd. demonstration database.

No. | Bill-to Name | Order Date
1000 | Autohaus Meilberg KG | 18-01-2013
5000 | Autohaus Meilberg KG | 21-05-2013
4000 | Beef House | 30-09-2011
3000 | Deerfield Graphics Company | 05-04-2012
3000 | Deerfield Graphics Company | 29-04-2012

Sample Query

The following illustration shows Query Designer for a query that retrieves data from the sample Sales Header table. The query includes a totals method that counts the total the number of records from the table included in the dataset.

Query Designer showing a date method
Note
A column that applies a date function is still part of the group unlike columns that apply a totals method.

Day Method

The Day method retrieves the day from the date expression of a field value in the query column. The day is returned as an integer, in the range of 1 to 31, which represents the day of the month. If the day in the date expression is 0, then 1 is returned.

Example

The following table displays the resulting dataset for the sample query with the Method property of the Order Date column set to Day.

Bill_to_Name | Day_Order_Date | Count_
Autohaus Meilberg KG | 18 | 1
Autohaus Meilberg KG | 21 | 1
Beef House | 30 | 1
Deerfield Graphics Company | 5 | 1
Deerfield Graphics Company | 29 | 1

Month Method

The Month method retrieves the month from the date expression of a field value in the query column. The month is returned as an integer, in the range of 1 to 12, where 1 represents January and 12 represents December. If the month in the date expression is 0, then 1 is returned.

Example

The following table displays the resulting dataset for the sample query with the Method property of the Order Date column set to Month.

Bill_to_Name | Month_Order_Date | Count_
Autohaus Meilberg KG | 1 | 1
Autohaus Meilberg KG | 5 | 1
Beef House | 9 | 1
Deerfield Graphics Company | 4 | 2

Year Method

The Year method gets the year from the date expression of a field value in the query column. The year is returned as an integer. If the year in the date expression is 0, then 1900 is returned.

Example

The following table displays the resulting dataset for the sample query with the Method property of the Order Date column set to Year.

Customer Name | Year_Order_Date | Count_
Autohaus Meilberg KG | 2013 | 2
Beef House | 2011 | 1
Deerfield Graphics Company | 2012 | 2

Working with DateTime Data Types

On the SQL server, date and time values are processed using Coordinated Universal Time (UTC). If your Microsoft Dynamics NAV solution uses a time zone other than UTC and the field on which you apply the date method has a data type of DateTime, then there might be a difference between the date value that is returned in the dataset for the field and the actual day, month, or year for the field in the table. This occurs when the corresponding UTC date for a field falls on the next day or previous day because of the time of day and the time zone of Microsoft Dynamics NAV solution. The following table includes examples of DateTime values for two time zones that will return days, months, and years in a dataset that differ from the values in the table.

Time Zone | Date and Time in Microsoft Dynamics NAV | Day returned by Day method | Month returned by Month method | Year returned by Year method
Pacific Time (UTC -8:00:00) | 12-31-2011 17:00:00 | 31 | 12 | 2011
Middle European Time (UTC +1:00:00) | 01-01-2012 00:59:00 | 1 | 1 | 2012

The differences in day, month, or year occur because when a date and time value is retrieved from the Microsoft Dynamics NAV database table, it is converted from the regional settings of the Microsoft Dynamics NAV solution to the UTC date and time. The day, month, or year is calculated on the SQL server, and then returned to the query dataset as an integer, which does not consider the regional settings of the Microsoft Dynamics NAV solution.

To avoid this condition, you should use the date method on fields that have a Date data type instead of a DateTime data type whenever possible. You can also return the DateTime value and implement post processing for the day, month, and year as needed.

See Also

Tasks

How to: Create Queries

Reference

MethodType Property
Method Property

Concepts

Understanding Query Totals and Grouping


Configuring User Permissions to Queries

You can control which users have permission to run a query object and access its resulting dataset. Similar to other Microsoft Dynamics NAV objects, you grant permission to a query in a permission set that you assign to the user's Windows account.

The following permissions are required as a minimum:

  • Read permission on the Query object.

  • Read permission on each table that is specified as a data item in the query.

  • Read permission on any objects that are called from the query's ONBEFOREOPEN trigger.

Granting Users Permission to a Query

To grant a user permission to query, you can either change an existing permission set or create a new permission set and then assign it to the user. You create and modify a permission set using the RoleTailored client.

To grant users permission to a query

  1. Start the RoleTailored client.

  2. In the Search box, enter Permission Sets, and then choose the related link.

    The Permission Sets page opens.

  3. Open an existing permission set for editing or create a new permission set.

    For more information about how to create and editing permissions sets, see How to: Create or Modify Permission Sets.

  4. Add the following permissions to the permission set:

    • Include a Query object type permission that specifies the query, and set the Read Permission to Yes. Additional permissions are not relevant.

    • For each data item in the query, include a Table Data object type permission that specifies the underlying table of the data item, and set the Read Permission to Yes or Indirect.

      If you choose Indirect, you must also set the Permissions property of the query object to specify the table with at least Read permission. For more information, see Permissions Property.

      Set additional permissions are needed.

    • If the query will be executed from the C/AL code of another object, such as a codeunit, then for each data item add a Table object type permission that specifies the underlying table. Set the Read Permission to Yes. Set additional permissions as needed.

    • If there are any objects that are called from the query's ONBEFOREOPEN trigger, then include a permission entry for each object, and set the Read Permission set to Yes. Set additional permissions as required.

  5. When the permission set is complete, choose the OK button to close the Edit - Permissions page.

  6. Assign the permission set to users who require access to the query.

    For more information, see How to: Define Permissions for Users.

Query Permissions Example

The following table illustrates a permission set for query 50001 Customer_SalesQuantity that retrieves data from table 18 Customer and table 37 Sales Lines. The query will be executed from the C/AL code of codeunit. The user only requires access to the Sales Line table through the query, so you grant indirect access to this table, which you set up in the permission set and query's Permission property. This permission set configures the minimum permissions that are required for a user to run the query and access the resulting dataset.

Object type | Object ID | Object name | Read permission | Insert permission | Modify permission | Delete permission | Execute permission | Security Filter
Table Data | 18 | Customer | Yes |  |  |  |  |
Table Data | 37 | Sales Line | Indirect |  |  |  |  |
Query | 50001 | Customer_SalesQuantity | Yes |  |  |  |  |

To give indirect permission to table 37 Sales Line from the query, set the Permissions property of the query object to the following value

TableData Sales Line=r

Note
For step-by-step instructions about how to create the query discussed in this example, see Walkthrough: Creating a Query to Link Two Tables.

See Also

Tasks

How to: Create or Modify Permission Sets
How to: Create Queries

Reference

Permissions Property

Other Resources

Managing Permissions and Permission Sets


Working with Queries in C/AL

After you create a query, you can use C/AL code to run the query and retrieve data from the resulting dataset. There are several functions that you can call on the query to filter the dataset, read rows, access columns, and save the dataset to a file in XML or CSV format.

Query Functions

The following table contains the C/AL functions available for running queries and accessing the resulting dataset.

Function | Description
SETFILTER Function (Query) | Sets a filter on a field of a specified data column or filter row in the query.
SETRANGE Function (Query) | Sets a simple range filter on a field of a specified data column or filter row in the query.
TOPNUMBEROFROWS Function | Sets the maximum number of rows to include in the resulting dataset.
OPEN Function (Query) | Runs a query object and generates a dataset so that it can be read.
READ Function (Query) | Retrieves a row from the resulting dataset of a query.
QueryVariable.ColumnName | Retrieves the value of a column in the dataset row that is currently being read. QueryVariable is a variable of the Query data type that specifies the query object. ColumnName is the name of the column in the query. For more information, see Accessing Columns of a Query Dataset.
GETFILTER Function (Query) | Returns the filters on a specified column in the query.
GETFILTERS Function (Query) | Returns the filters on all columns in the query.
CLEAR Function | Clears the instance of the query, including all filters.
CLOSE Function (Query) | Closes a query dataset and returns it to the initialized state. Any filters that are set by the SETFILTER or SETRANGE functions are still valid.
SAVEASCSV Function | Saves a query data set as a comma separated values file.
SAVEASXML Function | Saves a query dataset as an .xml file.

Query Triggers

Queries include an OnBeforeOpen trigger in C/AL that executes before the query is opened and the dataset is generated. For more information, see OnBeforeOpen Trigger.

Query State Diagram

The following figure illustrates the state of a query object for each of the query function calls in C/AL.

State diagram for query function calls

Note
  • The Read function can only be called when the query is in the opened state after a call to the OPEN function.

  • query. ColumnName can only be called when the query is in reading state after a call to the READ function.

  • The SAVEASCSV and SAVEASXML functions can be called from any state. If the dataset is currently open, then it will be closed. These functions implicitly call the OPEN, READ, and CLOSE functions, which pass the query through the Opened, Reading, and End Of Result Set states.


Using Queries Instead of Record Variables

In scenarios where you want to read records from multiple table, it can be a good idea to use a query instead of implementing code with record variables. Using a query can improve performance and also simplify the C/AL code that is required to perform the operation.

Code Example Using Record Variables

The following C/AL code shows an example of using record variables to retrieve and handle records from two tables. You could potentially use this code to track item movement. The code uses two record variables, Item and ItemLedgerEntry, to retrieve the first five records from table 27 Item and table 32 Item Ledger Entry where the Entry Type field equals Sale. The retrieved records are passed to and handled by the OutputData function.

Copy Code
count := 0;
IF Item.FINDSET THEN
  REPEAT
    PrevDate := 0D;
    TotalQty := 0;
    ItemLedgerEntry.SETCURRENTKEY("Item No.","Posting Date");
    ItemLedgerEntry.SETRANGE("Item No.",Item."No.");
    ItemLedgerEntry.SETRANGE("Entry Type",
      ItemLedgerEntry."Entry Type"::Sale);
    IF ItemLedgerEntry.FINDSET THEN
      REPEAT
        IF (ItemLedgerEntry."Posting Date" <> PrevDate) AND (PrevDate <> 0D) THEN BEGIN
          OutputData(1, Item."No.",Item.Description,PrevDate,-TotalQty);
          TotalQty := 0;
          count := count + 1;
        END;
        PrevDate := ItemLedgerEntry."Posting Date";
        TotalQty := TotalQty + ItemLedgerEntry.Quantity;
      UNTIL (ItemLedgerEntry.NEXT = 0) OR (count >= 4);
      IF PrevDate <> 0D THEN BEGIN
        OutputData(1, Item."No.",Item.Description,PrevDate,-TotalQty);
        count := count +1;
      END;
  UNTIL (Item.NEXT = 0) OR (count >= 4);

Corresponding Query Implementation

To get the same results with a query instead of record variables, you create a query and add C/AL code to an object to run the query as follows:

  1. In Query Designer, create a query that has the following characteristics:

    • Include a data item for table 27 Item with columns for the No. and Description fields of the table.

      This corresponds to the Item record variable in the record variable example.

    • Include a data item for table 32 ItemLedgerEntry with a filter row for the Entry Type field and columns for the Posting Date and Quantity fields.

      This corresponds to the ItemLedgerEntry record variable in the record variable example.

      Note
      The field of a filter row is not included in the resulting dataset. For more information, see Understanding Query Filters and How to: Set Up Filter Rows in Query Designer.

    • Link the data items on the No. field of table 27 Item and Item No. field of table 32 ItemLedgerEntry by setting DataItemLink property. Set the DataItemLinkType property to Exclude If No Matches.

      This corresponds to the ItemLedgerEntry.SETRANGE("Item No.",Item."No."); statement in the record variable example.

    • Set a SUM method on the Quantity column for calculating the total number of items.

      This corresponds to the TotalQty := TotalQty + ItemLedgerEntry.Quantity; statement in the record variable example.

    The following illustration shows the query in Query Designer.

    Query that links Item and Item Legder Entry tables
  2. Add the following code to a codeunit that will run the query.

Copy Code
ItemMovements.TOPNUMBEROFROWS(5);
ItemMovements.SETRANGE(Entry_Type,ItemMovements.Entry_Type::Sale);
ItemMovements.OPEN;
WHILE ItemMovements.READ DO
  OutputData(2, ItemMovements.Item_No,ItemMovements.Description,ItemMovements.Posting_Date,ItemMovements.Sum_Quantity);

The ItemMovements.TOPNUMBEROFROWS(5); statement will include only the first 5 records in the resulting dataset and corresponds to implementing the count variable in the record-based code example.

The OutputData function performs the same operations as the OutputData function in the record variable example.

See Also

Tasks

How to: Create Queries

Reference

SETRANGE Function (Query)
OPEN Function (Query)
TOPNUMBEROFROWS Function

Concepts

Queries
Working with Queries in C/AL
Understanding Query Filters


Walkthrough: Creating a Query to Link Two Tables

This walkthrough demonstrates how to create a query that links two tables.

About This Walkthrough

This walkthrough illustrates the following tasks:

  • Creating a query that links the Customer table and the Sales Line table.

  • Running the query to view the data that this query describes.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 with a developer license.

  • CRONUS International Ltd. demonstration database.

Story

Viktor is a Microsoft Certified Partner working for CRONUS International Ltd. He has been asked to create a query that will get the quantity of items in every sales order for each customer. Viktor knows how to do this in SQL, but he wants to use a Microsoft Dynamics NAV query.

The SQL query for the dataset that Viktor wants is the following:

Copy Code
SELECT C.Name, C.'No.' SL.AmountFROM Customer AS C, 'Sales Line' AS SL WHERE C.'No.' = SL.'Sell-to Customer No.'

Creating a Query That Links Two Tables

Viktor wants to create a dataset that contains the quantity of items and the customer name for every sales order. The customer name is stored in the Customer table. Sales order quantities are stored in the Sales Line table. To create this dataset, Viktor will use Query Designer to create a query and do the following:

  1. Include data items and columns for the Customer and Sales Lines tables and their fields.

    A data item defines a table to retrieve data from. Viktor will add one data item for the Customer table and another data item for the Sales Line table. A column specifies a field from a table to be displayed in the resulting dataset. Viktor will add columns for the No. and Name fields from the Customer table, and a column for the Quantity field from the Sales Line table.

  2. Link the Customer table and Sales Line table.

    To generate a dataset from the Customer table and Sales Line table, Viktor must link the two tables. A link specifies a condition between two fields of the tables that must be met for a record to be included in the dataset. To link the two tables, Viktor must first identify a field that is common in both tables. He determines that the No. field in the Customer table is the same as the Sell-to Customer No. field in the Sales Line table. For a record to be included in the resulting dataset, the value of the No. field in the Customer table must equal the Sell-to Customer No. field in the Sales Line table.

To create this dataset in a Microsoft Dynamics NAV query, Viktor creates a query in Object Designer.

To create a query that includes columns from the Customer table and the Sales Line table

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Query, and then choose the New button.

  3. In Query Designer, add five rows as described in the following table. Choose the drop-down arrow to select tables and fields from the drop-down list box.

    Line No. Type Data Source Name

    Line 1

    DataItem

    Customer

    C

    Line 2

    Column

    No.

    <No>

    Line 3

    Column

    Name

    <Name>

    Line 4

    DataItem

    Sales Line

    SL

    Line 5

    Column

    Quantity

    <Quantity>

Tip
The Name column in Query Designer is equivalent to using the AS keyword in an SQL statement. It defines an alias for the data item. Type a value in this column when you want to replace the default value with an alias.

To link the Customer table and the Sales Line table

  1. In Query Designer, select the SL data item.

    Important
    When you create a link between two data items, you set up the link on the lower of the two data items in Query Designer.

  2. On the View menu, choose Properties. The SL - Properties window opens

  3. In the Value field of the DataItemLink property, choose the AssistEdit button.

    The DataItem Link window opens. You use this window to create a reference link between the Sell-to Customer No. field of the Sales Line table and the No. field of the Customer table.

  4. In the DataItem Link window, in the Field column, choose the up arrow.

    Note
    DataItem Link is like a WHERE clause in an SQL statement.

  5. In the Sales Line - Field List window, select Sell-to Customer No., and then choose the OK button.

  6. In the Reference DataItem column, choose the up arrow.

    The DataItem List - Table window opens. You use this window to create a link to the Customer table.

  7. In the DataItem List window. select the C data item row, and then choose the OK button.

  8. In the Reference Field column, choose the up arrow.

  9. In the Customer - Field List window, select No., and then choose the OK button.

  10. Choose the OK button to close the DataItem Link window.

  11. In the SL Properties window, in the Value field of the DataItemLinkType property, choose Exclude If No Match from the drop-down list.

    Note
    Exclude If No Match only includes rows where the linked fields from both data items are equal.

The following figure shows Query Designer and Properties window.

Query Join SalespersonPurchaser and SalesHeader

Saving and Running the Query

Viktor wants to verify that the query describes the dataset that he wants. He saves the query, and then runs it from Object Designer. The call to run the query runs on Microsoft Dynamics NAV Server and opens a view of the dataset in the Microsoft Dynamics NAV Windows client.

To save and run a query

  1. On the File menu, choose Save.

  2. In the Save As window, in the ID field, enter 50001. In the Name field, enter Customer_SalesQuantity. Verify that the Compiled check box is selected, and then choose the OK button.

    Note
    If 50001 is already being used by another query, you will get an error when you try to save the query. If so, use another ID.

  3. In Object Designer, select query 50001, and then choose the Run button. When you run a query, you can view the data in the dataset.

    The result of running Customer_SalesQuantity query

Next Steps

Viktor’s next steps are to create more complex queries. For more information, see Walkthrough: Creating a Query That Uses a Totaling Method and Sorting and Walkthrough: Creating a Query to Link Three Tables.

See Also

Concepts

Queries


Walkthrough: Creating a Query That Uses a Totaling Method and Sorting

This walkthrough demonstrates how to modify an existing query, which links two tables, so that the query includes a totaling method on a field in one of the tables.

About This Walkthrough

This walkthrough illustrates the following tasks:

  • Modifying a query to get the total sum of items in open sales orders per customer.

  • Sorting the resulting dataset by quantity of items.

  • Running the query to view the data that this query describes.

Prerequisites

This walkthrough builds on the steps that are described in Walkthrough: Creating a Query to Link Two Tables.

Story

Viktor is a Microsoft Certified Partner working for CRONUS International Ltd. He wants to create a dataset that contains the total number of items in open sales orders for each customer. Viktor has already created a query that contains the quantity of items of every open sales order for each customer. He can modify that query so that it displays the sum of quantity of items for each customer.

The SQL query for this dataset that Viktor wants is the following:

Copy Code
SELECT C.Name, C.'No.', SUM(SL.Quantity)
FROM Customer AS C, "Sales Line" AS SL
WHERE C.'No.' = SL.'Sell-to Customer No.'
GROUP BY C.Name, C.'No.'
ORDER BY Quantity

Adding a Totaling Method to a Query

Viktor examines the query that he created earlier. To calculate the total number of items in open sales orders for each customer, he adds the Quantity column from the Sales Line table to the query, and then implements a sum method on the column by changing the Method Property.

To add a totaling method to a query

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Query, select query 50001, Customer_SalesQuantity, and then choose the Design button.

  3. In Query Designer, under the Sales Line (SL) data item, select the row for the Quantity column.

  4. In the Method Type column, choose Totals from the drop-down list box.

  5. In the Method column, choose Sum from the drop-down list box.

    Note
    The query is automatically set to group the dataset by the No. and Name fields as indicated by the check marks in the Group By column. This creates a single row for each customer in the dataset that shows the total quantity of sales for the customer. For more information about grouping, see Understanding Query Totals and Grouping.

    The following figure shows the Query Designer for this query.

    Query with Sum column

    Note
    When you set the Method column to Totals, the name of the column is automatically changed from Quantity to <Sum_Quantity>. The column name is specified by its Name Property. The OrderBy property identifies a column by the Name property.

Sorting the Query Results

Viktor wants the resulting dataset to display records according to the item quantity in descending order from highest value to lowest value. To achieve this, he will set the OrderBy Property on the query object.

To sort query results by item quantity

  1. In Query Designer, select the first blank line.

  2. On the View menu, choose Properties.

  3. In the Query - Properties window, in the Value field of the OrderBy property, choose the AssistEdit button.

  4. In the Order By window, in the Column field of the first row, choose the AssistEdit button to open the Column List - Table window.

    The Column List - Table window includes all the columns that are defined in the query.

  5. In the Column List - Table window, select the Sum_Quantity row, and then choose the OK button.

  6. In the Order By window, set the Direction field for the Sum_Quantity column to Descending.

    This sorts the column from highest to lowest value (9 to 0).

  7. Choose the OK button, close the Query - Properties window, and return to Query Designer.

Saving and Running the Query

Viktor wants to verify that the resulting dataset what he wants. He saves the query and then runs it from Object Designer. The call to run the query runs on Microsoft Dynamics NAV Server and opens a view of the dataset in the Microsoft Dynamics NAV Windows client.

To save and run a query

  1. On the File menu, choose Save As.

  2. In the Save As window, in the ID field, enter 50002. In the Name field, enter Customer_SumSalesQuantity. Verify that the Compiled check box is selected, and then choose the OK button.

  3. In Object Designer, select query 50002, and then choose the Run button. When you run a query, you can see the data in the dataset.

    The result of running Customer_SumQuantity query

Next Steps

Viktor’s next step is to create a more complex query. For more information, see Walkthrough: Creating a Query to Link Three Tables.

See Also

Concepts

Understanding Query Totals and Grouping


Walkthrough: Creating a Query to Link Three Tables

This walkthrough demonstrates how to create a query that links three tables. It also includes the SQL query that this query object represents.

About This Walkthrough

This walkthrough illustrates the following tasks:

  • Creating a query that uses three tables and includes fields from those tables.

  • Setting up a totals method on a query column.

  • Specifying how to link the tables.

  • Specifying filters to limit the resulting dataset.

  • Running the query to view the data that this query describes.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 with a developer license.

  • CRONUS International Ltd. demonstration database.

Story

Viktor is a Microsoft Certified Partner working for CRONUS International Ltd. He has been asked to create a query that displays the total number of items in each sales order for each salesperson. Viktor knows how to do this in SQL, but he wants to create a Microsoft Dynamics NAV query.

The SQL query for this dataset that Viktor wants is the following:

Copy Code
SELECT SP.Name, SUM(SL.Quantity)
FROM "Salesperson/Purchaser" AS SP INNER JOIN "Sales Header" AS SH
  ON SP.Code = SH."Salesperson Code" INNER JOIN "Sales Line" AS SL
  ON SL."Document No." = SH."No."
WHERE SL."Document Type" = 'Order' AND SL.Type = 'Item'
GROUP BY SP.Name

Creating the Query with Three Tables

Viktor must create a query with Query Designer. The salesperson name is stored in the Salesperson/Purchaser table. The salesperson code for sales orders is stored in the Sales Header table. The quantity of items in sales orders is stored in the Sales Line table. To create this query, Viktor must do the following:

  • Add tables and fields by specifying data items and columns.

  • Set up a Totals method on the Quantity of the Sales Line table to return the total number of items in each sales order for each salesperson.

  • Link the Salesperson/Purchase table and the Sales Header table on the condition that the salesperson code matches, and then link the resulting dataset with the Sales Line table to find all sales lines for each sales header.

To add tables and fields to the query

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Query, and then choose the New button.

  3. In Query Designer, add four rows as described in the following table. Choose the drop-down arrow to select tables and fields from the drop-down list box.

    Line No. Type Data Source Name

    Line 1

    DataItem

    Salesperson/Purchaser

    SP

    Line 2

    Column

    Name

    <Name>

    Line 3

    DataItem

    Sales Header

    SH

    Line 4

    DataItem

    Sales Line

    SL

Tip
The Name column in Query Designer is equivalent to using the AS keyword in an SQL statement. It defines an alias for the data item. Type a value in this column when you want to replace the default value with an alias.

Note
The Sales Header data item is indented. This indicates that this data item, which is the Sales Header table, is linked to the upper data item, which is the Salesperson/Purchaser table.

Note
The Sales Line data item is indented. This indicates that this data item, which is the Sales Line table, is joined to the parent data item, which is the result of the previous join.

To set up a totals method on the Quantity column

  1. In Query Designer, on the next line after the Sales Line data item, in the Type column, choose Column from the drop-down list box.

  2. In the Data Source column, select Quantity from Sales Line - Field List window, and then choose the OK button.

  3. In the Method Type column, choose Totals from the drop-down list box.

    Note
    You want the query results to group by the Name field of the Salesperson/Purchaser table. This is automatically done for you. The query groups all fields that are not totals fields. In Query Designer, grouped fields are indicated by a check mark in the Group By column. In this example, the only column that is grouped is the Name field under the Salesperson/Purchaser data item.

  4. In the Method column, choose Sum from the drop-down list box.

The following figure shows the Query Designer for this example.

Query joins three tables

Specifying the Data Item Links

Viktor has added the data items and columns to the query, but he must specify how to link the data items to display the information he wants and eliminate unwanted records. For this query, Viktor wants the following:

  • Only salespersons who have sales orders.

    The Salesperson/Purchase table and the Sales Header table have a field for the sales person's code in common. Viktor will link the Salesperson/Purchase table and the Sales Header table on the condition that the code for the salesperson in the two tables matches. This will exclude any salesperson who is not assigned a sales order.

  • Only sales headers that have sales lines.

    The Sales Header table and the Sales Lines table have a field for the document number in common. Viktor will link the Sales Header table and Sales Line table on the condition that the document number in the two tables matches. This will exclude any sales headers that do not have sales lines.

To link the Salesperson/Purchase table and the Sales Header table

  1. In Query Designer, select the SH data item row.

  2. On the View menu, choose Properties. The SH - Properties window opens.

  3. In the Value field of the DataItemLink property, choose the AssistEdit button.

    The DataItem Link window opens. You use this window to create a reference link between the Salesperson Code field of the Sales Header table and the Code field of the Salesperson/Purchaser table.

  4. In the DataItem Link window, in the Field column, choose the up arrow.

  5. In the Sales Header - Field List window, select Salesperson Code, and then choose the OK button.

  6. In the Reference DataItem field, choose the up arrow.

    The DataItem List - Table window opens. You use this window to create a link to the Salesperson/Purchaser table.

  7. In the DataItem List - Table window, select the SP data item, and then choose the OK button.

  8. In the Reference Field, choose the up arrow.

  9. In the Salesperson/Purchaser - Field List window, select Code, and then choose the OK button.

  10. Choose the OK button to close the DataItem Link window.

  11. In the SH Properties window, in the Value field of the DataItemLinkType property, choose Exclude Row If No Match from the drop-down list box.

    The following figure shows the SH Properties window and Query Designer.

    Query that joins three tables

  12. Close the SH Properties window, and then link the Sales Line table and the Sales Header table.

To link the Sales Line table and the Sales Header table

  1. In Query Designer, select the SL data item row.

  2. On the View menu, choose Properties. The SL - Properties window opens.

  3. In the Value field of the DataItemLink property, choose the AssistEdit button.

    The DataItem Link window opens. You use this window to create a reference link between the Document No. field of the Sales Line table and the No. field of the Sales Header table.

  4. In the DataItem Link window, in the Field column, choose the up arrow.

  5. In the Sales Line - Field List window, select Document No., and then choose the OK button.

  6. In the Reference DataItem column, choose the up arrow.

    The DataItem List - Table window opens. You use this window to create a link to the Sales Header table.

  7. In the DataItem List - Table window, select the SH data item, and then choose the OK button.

  8. In the DataItem Link window, in the Reference Field column, choose the up arrow.

  9. In the Sales Header - Field List window, select No., and then choose the OK button.

  10. Choose the OK button to close the DataItem Link window.

  11. In the SL - Properties window, in the Value field of the DataItemLinkType property, choose Exclude Row If No Match from the drop-down list box.

Specifying Filters

Viktor wants to limit the records in the dataset to include only sales lines in which the Document Type is Order and the Type is Item. To achieve this, he will set up a filter on the Sales Line data item of the query.

To specify filters

  1. In the SL - Properties window, in the Value field of DataItemTableFilter property, choose the AssistEdit button.

  2. In the Table Filter window, in the Field column, choose the up arrow.

    The Sales Line - Field List opens. You use this window to select a field from the Sales Line table on which to filter.

  3. In the Sales Line - Field List window, select Document Type, and then choose the OK button.

  4. In the Table Filter window, set the Type column to CONST.

  5. In the Value column of the Document Type entry, enter Order.

  6. On the next line in the Table Filter window, in the Field column, choose the up arrow, select Type from the Sales Line - Field List window, and then choose the OK button.

  7. In the Table Filter window, set the Type column to CONST.

  8. In the Value column of the Type entry, enter Item, and then choose the OK button.

    Tip
    Specifying a filter in the DataItemTableFilter property is equivalent to using a WHERE clause in an SQL statement.

    Query that joins three tables

  9. Close the Sales_Line - Properties window,

Saving and Running the Query

Viktor has finished designing his query. He saves the query and then runs it to verify that the resulting dataset is what he wants. He runs the query from Object Designer. The call to run the query runs on Microsoft Dynamics NAV Server and opens a view of the dataset in the Microsoft Dynamics NAV Windows client.

To save and run the query

  1. On the File menu, choose Save.

  2. In the Save As window, in the ID field, enter 50003. In the Name field, enter SumSalesQty_PerSalesperson. Verify that the Compiled check box is selected, and then choose the OK button.

  3. In Object Designer, select query 50003, and then choose the Run button. When you run a query, you can see the data in the dataset.

    Result of query that joins three tables

See Also

Concepts

Queries
Understanding Data Item Links
Understanding Query Filters
Understanding Query Totals and Grouping


XMLports

XMLports are used to export or import data between an external source and a Microsoft Dynamics NAV database. Sharing data between different computer systems is seamless when it is shared in XML format. Working with XML files can be tedious so the details of how the XML file is handled are encapsulated in XMLports.

To use an XMLport to import or export data, you first design the XMLport in the XMLport Designer window and set some properties. You can run the XMLport from Object Designer or create a codeunit to run the XMLport. For more information about how to run XMLports in a codeunit, see How to: Create Codeunits to Run XMLports. For information about how to run XMLports in Object Designer, see How to: Run an XMLport from Object Designer.

If you are upgrading from an earlier version of Microsoft Dynamics NAV and used Dataports in the earlier version, then you should analyze the functionality of each Dataport and re-create that functionality in Microsoft Dynamics NAV 2016 using XMLports.

Introducing XMLports

The following table lists topics that provide detailed information about how to use XMLports.

To See

Read about the XMLport Designer window.

XMLport Designer

Read about triggers available for XMLports and XMLport elements.

XMLport Triggers

Learn how to design an XMLport for import or export.

  • Designing XMLports

  • How to: Create XMLports

Learn how to create codeunits to run XMLports.

How to: Create Codeunits to Run XMLports

Learn about designing request pages for XMLports

Request Pages (XMLPorts)

Learn how to run XMLports from Object Designer.

How to: Run an XMLport from Object Designer

Read about XMLport data types and functions.

XMLport Data Type

XMLports Walkthroughs

The following table lists topics that provide information about how to use XMLports to create scenario based applications.

To | See
Learn how to export data from a Microsoft Dynamics NAV table into an XML document. | Walkthrough: Exporting Data from Tables to XML Documents
Learn how to import data from an XML document to multiple tables in a Microsoft Dynamics NAV database. The XML document contains data that belongs in two different tables in the database. | Walkthrough: Inserting Data from XML Documents to Multiple Tables
Learn how to export data from tables to CSV (comma separated value) files. | Walkthrough: Exporting Data from Tables to CSV Files
Learn how to import data from text files. | Walkthrough: Importing Data from Text Files to Tables

See Also

Concepts

Designing XMLports


Request Pages (XMLPorts)

A request page is a dialog box that appears when an XMLport is run from Object Designer. It enables the user to set a filter on the data, sort the data, and choose whether the XMLport imports or exports the data. For more information about how to run XMLports from Object Designer, see How to: Run an XMLport from Object Designer.

The filters are located on the Options FastTab. You design the Options FastTab of a request page by using Request Options Page Designer in the development environment. To access Request Options Page Designer, open XMLport Designer, choose View, and then choose Request Page.

You design the filters on request pages by using the following properties:

  • ReqFilterHeading Property

  • ReqFilterHeadingML Property

  • ReqFilterFields Property

  • Direction Property

  • UseRequestPage Property

The following illustration shows the request page for an XMLport that imports and exports from the Customer table. The No. and Name fields have been set as filters.

XMLport Request page

Filtering on Request Pages

The fields that you define as ReqFilterFields are shown on the request page. In addition, a user can add more fields on which to filter.

Note
We recommend that you add fields that users of the XMLport will frequently set filters on.

By default, for every data item in the XMLport, a FastTab for defining filters and sorting is created on the request page. To remove a FastTab from a request page, do not define any ReqFilterFields property for the data item and set the SourceTableView property (XMLports) property to define sorting. In this case, the request page is displayed but there is no tab for this data item.

If you set the UseRequestPage property to No, then the request page will not be presented to the user.

In a complex XMLport that uses data from several tables, the functionality may depend on a specific key and sort order. Design your XMLports so that users cannot change the sort order in a way that affects the functionality of the XMLport.

Exporting and Importing Data

If the Format Property (XMLports) of the XMLport is set to Both, the XMLport can be used to import or export data. In that case, from the request page, users can choose whether to import or export the data from the Direction list. By default, Import is selected. If Import is selected and you choose the OK button, the Import window, where you can select the file to import opens. If you select Export and you choose the OK button, the Export File dialog box is displayed. On the dialog box, you can open the file or save it to your computer.

If the Format Property (XMLports) is set to either Import or Export, then the Direction list box is not displayed on the request page.

See Also

Tasks

How to: Run an XMLport from Object Designer

Concepts

Designing XMLports

Other Resources

XMLport Walkthroughs


Designing XMLports

XMLports are used to export data from or import data to a Microsoft Dynamics NAV database. The import or export is between the database and an external file. XMLports enable seamless exchange of data between different computer systems. XMLports are used to import and export data to and from text files, CSV, and XML files. You can use XMLports to export or import data from multiple tables in the database. Although you can design an XMLport for both import and export, XMLports are typically designed for either import or export. To use an XMLport, you first design it in XMLport Designer and set properties for the XMLport. For more information about the XMLport Designer window, see XMLport Designer. After the XMLport is designed, you create a codeunit to run the XMLport or run it from Object Designer.

Designing an XMLport

To create an XMLport that exports or imports data, you first specify the root of the file that you want to import or export and then specify the data items and the fields. For example, to create an XMLport that exports data from a Microsoft Dynamics NAV database to an XML document, you first specify the root of the XML document by using the <Root></Root> element, specify all the XML node names, and then choose the type for each node to indicate whether it represents an element or an attribute. You then map these node names to corresponding data structures, such as tables, text, or fields. For more information, see How to: Create XMLports.

At run time, when an XMLport object is called from a codeunit to import or export an XML document, the XMLport first reads the XML document into a data stream before the import or export. For example, when you design an XMLport for export and use codeunit to call the XMLport at run time, the XMLport object reads the specified data from the database, adds the necessary XML nodes to form the XML document, and then writes the document to a data stream. The data stream saves the XML file in to a location that you specify in the codeunit. For more information, see How to: Create Codeunits to Run XMLports.

Important
When you design in the XMLport Designer window, child elements must be indented one time to add them under the parent element. Otherwise it causes a compile error.

Spaces are not allowed in the names of the XML nodes that you enter in the Node Name column of the XMLport Designer.

You must set the Direction Property for the XMLport to indicate whether the XMLport is used to import, export, or both. You must also set the Format Property (XMLports) to indicate the type of file format that you want to work with.

Note
Although XMLports can be designed for both export and import, we recommend designing for either export or import.

XMLports do not handle the following XML documents:

  • Documents that find and delete data in the database.

  • Documents that query the database for data, such as item catalog information.

If you must work with an incoming document of one of these types, you can use C/AL code to work with the database to achieve the result that you want.

Note
Do not use a semicolon in a quoted argument as a field value when you import a file through an XMLport. Even in a quoted argument, the semicolon is interpreted as a record separator.

Namespaces With XMLports

The external system that provides or consumes Microsoft Dynamics NAV data as XML might require that the XML documents include namespaces. Namespaces are used to avoid element name conflicts. In these cases, you must add namespaces on the XMLport to make it compatible with the XML schema that is used by the external system. For more information, see Using Namespaces with XMLports.

Request Pages are not Supported by Microsoft Dynamics NAV Web client

Microsoft Dynamics NAV Web client does not support request pages with XMLports. A request page is a dialog box that appears when an XMLport is run that enables the user to set a filter on the transferred data and choose whether the XMLPort imports or exports the data.

If the XMLport will be displayed in the Microsoft Dynamics NAV Web client, you should not set up the XMLport to use a request page because an error will occur when the XMLport is run. By default, XMLports are set up to use a request page. To specify not to use a request page, you can either change the UseRequestPage Property in XMLPort Designer or if the XMLPort is run from C/AL code by calling the RUN Function (XMLport), you can set the ReqWindow parameter of the Run function.

Running XMLports

After you have designed and saved the XMLport, you can create a code unit that uses the XMLport to perform the import or export. You can run the XMLport from Object Designer. For information about how to run XMLports from Object Designer, see How to: Run an XMLport from Object Designer. To create a codeunit to run the XMLport, first you define the location of the document you want to import from or export to. Whether the XMLport is importing or exporting, the data is read into a data stream and the XMLport uses the stream to insert the data into the table or export it into the file. For more information about how to create the condeunit, see How to: Create Codeunits to Run XMLports.

For information about how to design XMLports, see How to: Create XMLports. For information about how to export data from a Microsoft Dynamics NAV database, see Walkthrough: Exporting Data from Tables to XML Documents.

Handling XML Documents That Use Data in Different Scopes

XML documents have a tree structure that can include many levels. A database table, however, can only store data in a flat structure, which is the field level. An XML document can contain data in different scopes, although the data belongs in the same scope in the database. For example, the <BillTo> node of an XML sales order document could contain a <PaymentTerms> child element. The value of the <PaymentTerms> node sometimes must be assigned to all sales items, and sometimes to only one of them. If you declare the <PaymentTerms> value node as the Element node type and the Text source type, the XMLport can store the value and therefore when it starts to process the sales item information, you can specify which records the value is to be assigned to.

To avoid writing data to a table, you can apply a style sheet to the XML document to make sure that the XML node names are transferred in the correct order. Alternatively, you could design an XMLport to write the data to a temporary table. You could then write code that inserts the data into the relevant table using the correct order.

The following example shows an XML sales order document that contains two items. One item contains a <DocumentNo> node that must be written to the Sales Header table in the database.

Copy Code
<Items>
  <Item PartNum="LS-75">
    <ProductName>Loudspeaker, Cherry, 75W</ProductName>
      <Quantity>10</Quantity>
<UnitPrice>79</UnitPrice>
<Comment>Confirm the voltage is 75W</Comment>
   </Item>
   <Item PartNum="1908-8">
     <ProductName>LONDON Swivel Chair, blue</ProductName>
       <Quantity>12</Quantity>
 <UnitPrice>190,926</UnitPrice>
 <ShipDate>12-05-04</ShipDate>
 <DocumentNo>9999</DocumentNo>
   </Item>
</Items>

Before the <DocumentNo>9999</DocumentNo> node can be written to the database, the value must be checked to make sure that it is valid. However, the XMLport design will not work because the position of the <DocumentNo> node violates the validation order of the Sales Lines table.

To prevent this, you could assign the XML node names that were mapped to the Sales Lines table to a temporary table. You could then write code that assigns the value of the <DocumentNo> node to the correct table, and in the correct validation order, after the value has been assigned to a temporary table record. This means that the <DocumentNo> value must be copied from the temporary record to the real record before any of the other fields are copied to the Sales Lines table. By using temporary tables, you will be able to solve most of the cases where you can see that an incoming XML document contains nodes in a sequence that would violate the database validation order.

Assigning a Value from an XML Node to Multiple Records.

In a relational database, certain information must be repeated in various tables for data linking purposes. For example, a Sales Order XML document might contain an attribute that specifies Order as the document type as shown in the following code snippet:

<Items Type="Order">

To write the Type=”Order” information to the relevant table in the Sales Lines table, you declare the type attribute as text source type to cache the Order value and write code to assign the value to each record in the table. The code is typically written in the Import::OnAfterInitRecord trigger for the <Item> node. The code that assigns the value resembles the following code snippet:

L.Document Type := Type;

XMLport Functions and Properties

XMLport objects include functions and properties that can be used to work with the object. For more information, see XMLport Data Type.

See Also

Reference

XMLport Designer

Concepts

XMLports

Other Resources

XMLport Walkthroughs


Using Namespaces with XMLports

When using the XMLport to import or export an XML document, you can set up multiple namespaces on the XMLport to make it compatible with the XML schema that is used system that provides or consumes Microsoft Dynamics NAV data. Namespaces are used to avoid XML element name conflicts. You can define multiple namespaces.

For example, the following code is a portion of a simple XML document for transferring sales order information. The XML includes namespaces for mapping fields from the Sales Header table.

Copy Code
<?xml version="1.0" encoding="UTF-16"?>
<Root xmlns="urn:nav:schema:all" xmlns:navField="urn:nav:schema:field" xmlns:navTable="urn:nav:schema:table">
  <navTable:SalesHeader>
    <navField:DocType>Order</navField:DocType>
    <navField:DocNo>101005</navField:DocNo>
    <navField:SellToCustNo>30000</navField:SellToCustNo>
    <navField:SellToCustName>John Haddock Insurance Co.</navField:SellToCustName>
    <navField:BillToCustNo>30000</navField:BillToCustNo>
    <navField:BillToCustName>John Haddock Insurance Co.</navField:BillToCustName>
  </navTable:SalesHeader>
...
</Root>

The <root> element contains the namespace declarations. Each namespace has the syntax xmlns:prefix="namespacename".

  • The namespacename is a string of characters, often referred to as a Uniform Resource Identifier (URI), which uniquely identifies an Internet resource. This is typically a Uniform Resource Locator (URL) or Universal Resource Name (URN).

  • The prefix is a short string of characters that acts as an alias for the namespacename. The prefix is applied to specific elements in the XML document. The example includes the prefixes navField and navTable.

  • A namespace that does not include a prefix declares the default namespace. In the example, the default namespace is urn:nav:schema:all. The default prefix is applied to all elements that do not include a prefix.

To set up namespaces on an XMLport, you can use the properties Namespaces, Namespaceprefix, DefaultNamespace, and UseDefaultNamespace as described in the following sections.

Adding Namespaces on an XMLport

To set up namespaces on an XMLport, do the following:

  1. Define the namespaces in the Namespaces property of the XMLport.

    For each namespace, you specify a prefix and a namespace name. For more information, see Namespaces Property.

  2. Apply the prefixes to the XMLport elements of by setting the NamespacePrefix property.

    You can only apply a prefix on Element node types, not Attribute node types.

    For more information, see NamespacePrefix Property.

For detailed steps about how to set these properties, see How to: Create XMLports.

Adding a Default Namespace to an XMLport

A default namespace is a namespace that does not include a prefix. When you set up a default namespace, any elements that are note applied a prefix are assumed to belong to the default namespace. You can set up a default namespace one of the following ways:

  • In the Namespace property, add a namespace that has no prefix.

  • Specify the namespace in the DefaultNamespace property, and set the UseDefaultNamespace property to Yes.

    For more information, see DefaultNamespace Property and UseDefaultNamespace Property.

Note
There can only be on default namespace. Therefore, if you specify the default namespace in the Namespace property, you must set the UseDefaultNamespace property to No. If you want to use the default namespace that is defined in the DefaultNamespace property, you cannot define a default namespace in the Namespace property.

XMLport Example

The following example creates an XMLport that supports the XML document example in the introduction of this topic. Copy the code into a text editor, such as Notepad, save the file as .txt type file, and then import the file in the Microsoft Dynamics NAV Development Environment.

Copy Code
OBJECT XMLport 90010 Sales Document Sample
{
  OBJECT-PROPERTIES
  {
    Date=;
    Time=;
    Modified=Yes;
    Version List=;
  }
  PROPERTIES
  {
    Namespaces=[=urn:nav:schemaall;
        navTable=urn:nav:schema:table;
        navField=urn:nav:schema:field];
  }
  ELEMENTS
  {
    { [{9827B702-7694-48F4-A925-97849E2766B7}];  ;Root                ;Element ;Text     }
    { [{AF69A186-5A31-4A60-B594-5DF633965504}];1 ;SalesHeader         ;Element ;Table   ;
                                                  SourceTable=Table36;
                                                  NamespacePrefix=navTable }
    { [{B1DA8310-AAFB-47B9-827B-4936589DAC7C}];2 ;DocType             ;Element ;Field   ;
                                                  DataType=Option;
                                                  SourceField=Sales Header::Document Type;
                                                  NamespacePrefix=navField }
    { [{8715B36A-82B8-40B5-A67E-184F6DDA7998}];2 ;DocNo               ;Element ;Field   ;
                                                  DataType=Code;
                                                  SourceField=Sales Header::No.;
                                                  NamespacePrefix=navField }
    { [{80B0F630-EDDC-4A0F-87CD-4B8739A8AD81}];2 ;SellToCustNo        ;Element ;Field   ;
                                                  DataType=Code;
                                                  SourceField=Sales Header::Sell-to Customer No.;
                                                  NamespacePrefix=navField }
    { [{FCE5D19F-BD09-41FF-9FF1-EDB8A29BCFB8}];2 ;SellToCustName      ;Element ;Field   ;
                                                  DataType=Text;
                                                  SourceField=Sales Header::Sell-to Customer Name;
                                                  NamespacePrefix=navField }
    { [{B3F85EB5-64BB-42B0-A39B-35778443BCFE}];2 ;BillToCustNo        ;Element ;Field   ;
                                                  DataType=Code;
                                                  SourceField=Sales Header::Bill-to Customer No.;
                                                  NamespacePrefix=navField }
    { [{AC807456-23F0-42DB-9628-210196C14AD1}];2 ;BillToCustName      ;Element ;Field   ;
                                                  DataType=Text;
                                                  SourceField=Sales Header::Bill-to Name;
                                                  NamespacePrefix=navField }
  }
  EVENTS
  {
  }
  REQUESTPAGE
  {
    PROPERTIES
    {
    }
    CONTROLS
    {
    }
  }
  CODE
  {
    BEGIN
    END.
  }
}

See Also

Concepts

Designing XMLports


How to: Create XMLports

You design XMLports to export data from Microsoft Dynamics NAV tables or import data to a Microsoft Dynamic NAV tables. You can design XMLports to import or export XML documents, variable text files, or fixed-width text files.

To design an XMLport

  1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose XMLport, and then choose the New button to open XMLport Designer.

  3. On the View menu, choose Properties to open the XMLport-Properties window.

  4. In the XML-Properties window, set the Direction Property. If you want to export data, set the property to Export. If you want to import data, set the property to Import.

  5. Set the Format Property (XMLports) to the format of the document you want to import or export. You can set the format property to Xml, Variable Text or Fixed Text. By default the format property is set to Xml.

  6. If you set the format property to variable text, then do the following:

    1. Set the following properties. By default these properties are set as shown in the table but you change the values.

      Property Value

      TextEncoding Property (XMLports)

      <MSDOS>

      FieldDelimiter Property

      “

      FieldSeparator Property

      ,

      RecordSeparator Property

      <NewLine>

      TableSeparator Property

      <NewLine><NewLine>

    Note
    If you are importing a text file, you must examine the text file to determine the appropriate values for these properties.

  7. If you set the file format to fixed text, then do the following:

    1. Set the following properties. By default, these properties are set as shown in the following table but you can change the values.

      Property Value

      TextEncoding Property (XMLports)

      <MSDOS>

      RecordSeparator Property

      <NewLine>

      TableSeparator Property

      <NewLine><NewLine>

    Note
    If you are importing a text file, you must examine the text file to determine the appropriate values for these properties.

  8. If you set the file format to XML, then you can set up namespaces by setting the following properties as required:

    • Namespaces Property

    • DefaultNamespace Property

    • UseDefaultNamespace Property

    For more information, see Using Namespaces with XMLports.

  9. In XMLport Designer, in the first row, in the Node Name column, enter a name

    Note
    If the document that you want to import or export is an XML file, then you must enter Root in the Node Name column. Root indicates the beginning of XML documents.

  10. In the Node Type column, select Element.

  11. In the Source Type column, select Text.

    This element represents the start of the document you want to import or export.

  12. In the Data Source column, verify that the value is the same as the name of the node.

  13. In the second row, in the Node Name column, enter a name for the table you want to export or import.

  14. In the Node Type column, select Element.

  15. In the Source Type column, select Table.

  16. In the Data Source column, choose the arrow to open the Table List.

  17. From the Table List, select the table you want to export from or import to.

  18. Choose the right arrow to indent the row one time to make the row a subset of the top row.

  19. If you want to specify a namespace prefix on the element, do the following:

    1. Select the element, and then on the View menu, choose Properties.

    2. In the Properties window, set the NamespacePrefix property to the prefix that you want to use.

  20. In the next row, in the Node Type column, choose Element.

  21. In the Source Type column, select Field

  22. In the Data Source column select the field you want from the Field Lookup window.

  23. In the Node Name column, enter a name for the field. For consistency you can enter the same name as the field you selected.

  24. If you want to specify a namespace prefix on the element, do the following:

    1. Select the element, and then on the View menu, choose Properties.

    2. In the Properties window, set the NamespacePrefix property to the prefix that you want to use.

  25. Indent the field row one time to make it a subset of the table row.

  26. Repeat steps 20 through 25 to select all the fields you want to export or import.

  27. If the format of the file is fixed text, then for each field, set the Width property to an appropriate value.

    Note
    If the value of the Width property is less the width of a field, the data in the field will be truncated.

  28. From the File menu, choose the Save As button.

  29. In the Save As window, enter an ID and a name for the XMLport, and verify that Compile is selected, and then choose the OK button to save the XMLport.

See Also

Concepts

Designing XMLports
Using Namespaces with XMLports

Other Resources

XMLport Walkthroughs


How to: Create Codeunits to Run XMLports

After creating an XMLport, you can create a codeunit to run the XMLport or run it from Object Designer. For more information about how to run XMLports from Object Designer, see How to: Run an XMLport from Object Designer. This topic shows you how to create codeunits to run XMLports. Before you create a codeunit, you must first design and save the XMLport. For more information about how to design an XMLport, see How to: Create XMLports.

The basic steps for creating codeunits for export or import are similar. However, the specific code that you write is slightly different.

To create a codeunit, you:

  • Define the location where the XML document will be exported to or imported from.

  • Create the data stream to output or input the data.

  • Use the appropriate XMLport function to call the XMLport.

  • Close the XML document after the export or import is completed.

To create a codeunit to run XMLports

  1. In Object Designer, select Codeunit, and then choose the New button to open the C/AL Editor.

    You declare variables to represent the XML document that you want to work with, which is the data file that XMLport will use.

  2. Open the C/AL Globals window and declare a variable that represents the XML document. Set the DataType to File.

  3. Declare a second variable that represents the data stream that will be exported or imported.

  4. If the data stream is for exporting data, set the DataType to OutStream, otherwise set it to InStream.

  5. In the C/AL Editor, in the OnRun trigger, add the following lines of code if the XMLport is for exporting data.

    Copy Code
    varXmlFile.CREATE(“FilePath\myXmlfile.xml”);
varXmlFile.CREATEOUTSTREAM(varOutputStream);
XMLPORT.EXPORT(XMLPORT::XMLportName, varOutputStream);
varXmlFile.CLOSE;

    The CREATE Function (File) creates the XML file that will contain the exported data. The CREATEOUTSTREAM Function (File) creates the output stream for the XML file. The EXPORT Function (XMLport) uses the output stream and the name of the specified XMLport to export the data to the XML file.

    If the XMLport is designed for importing data, add the following lines of code.

    Copy Code
    varXmlFile.OPEN(“FilePath\myXmlfile.xml”);
varXmlFile.CREATEINSTREAM(varInputStream);
XMLPORT.IMPORT(XMLPORT::XMLportName, varInputStream);
varXmlFile.CLOSE;

    The OPEN Function (File) opens the XML file that contains the data that you want to import. The CREATEINSTREAM Function (File) creates the input stream for the XML file. The IMPORT Function (XMLport) uses the input stream and the name of the specified XMLport to import the data from the XML file to the Microsoft Dynamics NAV database.

    The following table shows the variables that are used in the code.

    Variable Description

    varXmlFile

    Represents the XML file to create for export or open for import.

    MyXmlfile

    The name of the XML file that the exported data will be saved as or the name of the XML file to open for export.

    FilePath

    The path or the location of the XML file that you want to work with, for example, C:\Myfolder\MyXmlfile.xml.

    When exporting data, the code will save the XML file to this location. When importing data, the code will look for the XML file to import from this location.

    varOutputStream

    The output stream that the XMLport uses when exporting data.

    varInputStream

    The input stream that the XMLport uses when importing data.

    XMLportName

    The name of the XMLport to use.

  6. Close the C/AL Editor. In the Save As dialog box, in the ID textbox, enter an ID for the codeunit. In the Name text box, enter a name for the codeunit. Verify that the Compile check box is selected and then choose the OK button.

See Also

Tasks

How to: Create XMLports
Walkthrough: Exporting Data from Tables to XML Documents


How to: Run an XMLport from Object Designer

After designing an XMLport, you can either create a codeunit to run the XMLport or run it from Object Designer. XMLports can be designed to export or import data. XMLports can also be designed for both export and import. This topic shows you how to run XMLports from Object Designer. For information about how to design an XMLport, see How to: Create XMLports. For information about how to run an XMLport from codeunit, see How to: Create Codeunits to Run XMLports.

To run an XMLport from Object Designer

  1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose XMLport, choose the XMLport you want to run, and then choose the Run button. The Edit-<XMLport Name> request page opens in Microsoft Dynamics NAV.

  3. If the XMLport you want to run is designed to both import and export data, then do the following:

    1. On the Edit-<XMLport Name> request page, in the Direction drop-down list, select the direction you want and then choose the OK button. The direction drop-down list box is located at the bottom of the page. You can specify how you want to sort the data and the filtering criteria on the Edit-<XMLport Name> request page.

      For information about the XMLport request page, see Request Pages (XMLPorts).

    2. If you select Export, then do the following:

      1. In the Export File dialog box, choose the Save button to open the Export window.

      2. In the Export window, browse to the location on your computer where you want to save the file that you are exporting.

      3. In the File name text box, enter a name for the file. By default, the name of the XMLport is used as the name of the file.

      4. In the Save as type drop-down list box, choose the file format you want, and then choose the Save button to export the data from the database. Instead of saving the file, you can choose the Open button from the Export File dialog box to view the file.

        Note
        If you save the file and you do not specify a name, the file will be saved in the format that is specified in the Format Property (XMLports).

    3. If you select Import, then do the following:

      1. In the Import window, browse to the location on your computer where the file that you want to import is located.

      2. Choose the file and then choose the Open button to import the file to the database.

    Note
    For XMLports that are designed to both import and export data, the Edit-<XMLport Name> page that is displayed differs from the Edit-<XMLport Name> page that is displayed for either import or export.

  4. If the XMLport only exports data, do the following:

    1. On the Edit-<XMLport Name> page, choose the OK button. The Export File dialog box is displayed.

    2. In the Export File dialog box, choose the Save button to open the Export window.

    3. In the Export window, browse to the location on your computer where you want to save the file that you are exporting.

    4. In the File name text box, enter a name for the file. By default, the name of the XMLport is used as the name of the file.

    5. In the Save as type drop-down list box, choose the file format you want, and then choose the Save button to export the data from the database. Instead of saving the file, you can choose the Open button from the Export File dialog box to view the file.

      Note
      If you save the file and you do not specify a name, the file will be saved in the format that is specified in the Format Property (XMLports).

  5. If the XMLport only imports data, do the following:

    1. On the Edit-XMLport Name page, choose the OK button. The Import window is displayed.

    2. In the Import window, browse to the location on your computer where the file that you want to import is located.

    3. Choose the file and then choose the Open button to import the file to the database.

See Also

Concepts

Designing XMLports

Other Resources

XMLport Walkthroughs


XMLport Walkthroughs

This topic provides end-to-end scenario based walkthrough topics about XMLports. You can use these topics to learn how to create and use XMLports.

In This Section

Documentation | Description
Walkthrough: Exporting Data from Tables to XML Documents | Describes how to export data from a Microsoft Dynamics NAV database table to an XML file.
Walkthrough: Inserting Data from XML Documents to Multiple Tables | Describes how to export data from an XML file and insert the data into multiple tables in a Microsoft Dynamics NAV database.
Walkthrough: Exporting Data from Tables to CSV Files | Describes how to export data from a Microsoft Dynamics NAV database to a CSV file.
Walkthrough: Importing Data from Text Files to Tables | Describes how to import data from a fixed-width text file and update existing records in a Microsoft Dynamics NAV table.
Walkthrough: Uploading a File from a Client to Microsoft Dynamics NAV Server | Describes how to use file functions to send a file from a client to the server, use stream functions to read the file, and use an XMLport to load values into the database.

Reference

XMLport Data Type

Related Sections

Designing XMLports

XMLports


Walkthrough: Exporting Data from Tables to XML Documents

XMLports are used to export data from a Microsoft Dynamics NAV database to XML format or import data from an XML file to Microsoft Dynamics NAV database. Exporting data from your Microsoft Dynamics NAV database into XML format enables seamless exchange of information between different computer systems. You only need a basic knowledge of XML to design and work with XMLports.

XMLports are called and run from codeunits or run from Object Designer. In this walkthrough, you will call the XMLport from a codeunit. You define the output stream that will export the data and location where the XML document should be saved in the codeunit.

About This Walkthrough

This walkthrough shows you how to export data from a Microsoft Dynamics NAV table into an XML document. This walkthrough illustrates the following tasks:

  • Creating an XMLport.

  • Compiling and saving the XMLport.

  • Creating the codeunit that will run the XMLport.

  • Running the XMLport.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 installed with a developer license.

  • The CRONUS International Ltd. demonstration database.

Story

Simon is a Microsoft Certified Partner working for CRONUS International Ltd. He has been asked to export records from the Customer table to an XML document. The records will include only the No., Name, Address, City, and Contacts fields. The information will be shared with another colleague who works on a different computer system. Simon knows that he can use XMLports to convert the records in the table to XML format that can easily be shared with the colleague.

Creating the XMLport

You create the XMLport by designing it in XMLport Designer and setting the properties for the XMLport. You define the table and fields that you want to export in XMLport Designer. You then compile and save the XMLport.

To create the XMLport

  1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose XMLport, and then choose New to open XMLport Designer.

  3. Select an empty row in the designer. On the View menu, choose Properties to open the XMLport-Properties window.

  4. In the XMLport-Properties window, locate the Direction Property, choose the drop-down arrow in the Value column and then set it to Export.

  5. In the XMLport-Properties window, locate the Format Property (XMLports), verify that the Value column is set to XML and then close the XMLport-Properties window.

  6. In XMLport Designer, in the first row, in the Node Name column, enter Root.

  7. In the Node Type column, verify that Element is selected.

  8. In the Source Type column, verify that Text is selected. This node represents the beginning of the XML document.

  9. In the second row, in the Node Name column, enter Customer.

  10. In the Node Type column, select Element.

  11. In the Source Type column, select Table. This node represents a customer record in the XML document.

  12. In the Data Source column, select the Customer table (18) from the Table List window. The data will be exported from the Customer table.

  13. Select the Customer row and use the right arrow button to indent the row one time to make it a subset of the Root element.

    The next step is to select the fields that you want to export.

  14. In the next empty row under the Customer row, in the Node Type column, select Element.

  15. In the Source Type column, select Field.

  16. In the Data Source column, select the No. field from the Field Lookup window, and then choose the OK button.

  17. In the Node Name column, enter a name for the field. For example, you can enter No. This node represents the fields in the record. You can enter any name, but because of consistency you might want to enter the name of field that you select.

    Note
    The name that you enter in the Node Name column cannot contain spaces. White space in the name will result in a compile error.

  18. Select the No. row and use the right arrow button to indent the field one time to make it a subset of the Customer element.

  19. Repeat these steps to select additional fields that you want to export. For this walkthrough you can select the following fields.

    Node Name Node Type Source Type Data Source

    No.

    Element

    Field

    Customer::No.

    Name

    Element

    Field

    Customer::Name

    Address

    Element

    Field

    Customer::Address

    City

    Element

    Field

    Customer::City

    Contact

    Element

    Field

    Customer::Contact

  20. On the File menu, choose Save As.

  21. In the Save As window, enter 50001 in the ID text box.

  22. In the Name text box, enter CustomerXMLport, verify that the Compiled check box is selected, and then choose the OK button. You will use the name of the XMLport later in the codeunit.

  23. Close XMLport Designer.

Creating the Codeunit to Export the Data

After you have created the XMLport, you create the codeunit that will run the XMLport and save the data. In this walkthrough, you will save the XML document on the client computer. To do this, you create the file in a temporary folder, and then download it to the client after the export is completed. In the codeunit, you will specify the path of the temporary file and the path where the XML document will be saved on the client.

To create the codeunit

  1. In Object Designer, select Codeunit, and then choose New to open the C/AL Editor.

    You will declare variables that you will use in the code. You will create variables for the XML file, the output stream that exports the data, and the return value for the EXPORT Function (XMLport). You will also create variables for the file that will be downloaded from the server and the file that will be saved on the client.

  2. In the C/AL Editor, place the cursor in the OnRun function, and then, on the View menu, choose C/AL Locals to open the C/AL Locals window.

  3. On the Variables tab, in the Name column, enter CustXmlFile.

  4. In the DataType column, choose the drop-down arrow and select File. This variable represents the XML file.

  5. Repeat steps 3 and 4 to create the following additional variables.

    Variable name DataType

    CustXmlFile

    File

    XmlStream

    OutStream

    IsExported

    Boolean

    FromFile

    Text

    ToFile

    Text

  6. You will create the text constants that will store messages that are displayed in the message boxes.

    In the C/AL Locals window, choose the Text Constants tab.

  7. In the Name field, enter Text000 and then in the ConstValue field, choose the EditAssist button to open the Multilanguage Editor.

  8. In the Multilanguage Editor, in the Language field, select ENU from the Windows Language List window and then choose the OK button.

  9. In the Value field, enter the following text: The Customer table export to XML is completed.

  10. Create another text constant that is named Text001 with value The Export Failed.

    Note
    The text constants are optional. However they enable messages to be translated into different languages.

  11. Close the C/AL Locals window.

  12. In the C/AL Editor, in the OnRun trigger, add the following code.

    Copy Code
    CustXmlFile.CREATE(TEMPORARYPATH + 'Customer.xml');
CustXmlFile.CREATEOUTSTREAM(XmlStream);
IsExported := XMLPORT.EXPORT(XMLPORT::CustomerXMLport, XmlStream);
FromFile := CustXmlFile.NAME;
ToFile := 'CustomerClient.xml';
CustXmlFile.CLOSE;
IF IsExported THEN
BEGIN
  DOWNLOAD(FromFile,'Download file','C:\Temp','Xml file(*.xml)|*.xml',ToFile);
  ERASE(FromFile);
  MESSAGE(Text000);
END
ELSE
  MESSAGE(Text001);

    The code uses the CREATE Function (File) to create an XML file that is named CustXmlFile in a temporary folder on the server. The TEMPORARYPATH Function gets the path of the temporary folder. The CREATEOUTSTREAM Function (File) opens a data stream to output the data from the table to the XML file. The EXPORT Function (XMLport) uses the XMLport and the stream to export the data. If the export succeeds, the DOWNLOAD Function (File) downloads the file from the temporary folder on the computer that is running Microsoft Dynamics NAV Server to the client. The default path of the file on the client computer is set to ‘C:\Temp’ but you can change it in the download dialog box. A message is displayed at the end of the export to indicate that the export is completed. Otherwise, an error message is displayed. This message is not required but it lets the user know that something actually occurred. The temporary file is deleted after the download is completed.

  13. Close the C/AL Editor and choose the Yes button at the prompt.

  14. In the Save As dialog box, in the ID text box, enter 50000.

  15. In the Name text box, enter ExportCode.

  16. Verify that the Compiled check box is selected and then choose the OK button.

Running the XMLport

After the XMLport is created and the codeunit is written, you run the codeunit to export the data.

To run the XMLport

  1. In Object Designer, select the ExportCode codeunit (50000), and then choose the Run button. The Microsoft Dynamics NAV Windows client opens and the Export File dialog box is displayed. You can choose the Open button to open and view the file or choose the SAVE button to save it. In this walkthrough, you will save the file.

  2. Choose the SAVE button to open the download window.

  3. In the Download file window, choose the SAVE button. You can change the default name of the file and location where it will be saved.

  4. After the export is complete, browse to the location where the XML document was saved and open it. Notice that all the records in the table are now in XML format. The <Customer></Customer> element represents a record and each record contains the fields that you selected in the XMLport Designer.

    The XML file that is exported resembles the XML file in the following illustration. The XML file contains data for only the first four customers.

    Exported XML file

    XML file that was exported from the Customer table

Next Steps

You can also use XMLport to import data from an XML document to a Microsoft Dynamics NAV database. For more information, see Walkthrough: Inserting Data from XML Documents to Multiple Tables.

See Also

Tasks

Walkthrough: Importing Data from Text Files to Tables

Concepts

Designing XMLports

Other Resources

XMLport Walkthroughs


Walkthrough: Inserting Data from XML Documents to Multiple Tables

XMLports are used to export data from a Microsoft Dynamics NAV database to an XML document or import data from an XML document to a Microsoft Dynamics NAV database. The data can be exported from or imported to multiple tables in the database. Exporting data from a Microsoft Dynamics NAV database into XML format enables seamless exchange of information between different computer systems. You only need a basic knowledge of XML to design and work with XMLports.

XMLports can be called and run from codeunits or run from Object Designer. In this walkthrough, you will create a codeunit to call and run the XMLport. When you create a codeunit, you define the InStream object that will import the data and the location where the XML document should be saved.

About this Walkthrough

This walkthrough shows you how to import data from a Sales Order XML document to a Microsoft Dynamics NAV database. The Sales Order XML document contains data that belongs in two different tables in the database because the tables have a header-line relationship. The data is inserted into the appropriate tables. This walkthrough illustrates the following tasks:

  • Creating an XMLport.

  • Creating the codeunit to insert the XML data.

  • Running the XMLport.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 installed with a developer license.

  • The CRONUS International Ltd. demonstration database.

Story

Simon is a Microsoft Certified Partner working for CRONUS International Ltd. A colleague in the Sales Department has shared Sales Order records with Simon. Simon has been asked to import the Sales Order records from an XML document into the appropriate tables in the database. When Simon examined the data in the XML document, he realized that the data in the Sales Order document belongs in two different tables, the Sale Header table and the Sales Line table. The tables have a header-lines relationship. Simon’s task is to insert the Sales Header records from the XML document into the Sales Header table and insert the Line records into the Sales Line table. Simon knows that he can create an XMLport to import the data into the database and he also knows that he can design the XMLport to insert the Header data into the Sales Header table and the Line data into data into the Sales Line table.

Setting Up the Sample Data

In this walkthrough, you import an XML document and insert it into the database. The document contains Sales Order information, which is made up of sales header and sales lines information. The customer named “The Cannon Group PLC” has new sales order information in the sales order document. The sales header information is in the <Header></Header> element and the sales line information is in the <Line></Line> elements. You create an XMLport that inserts the header data into the Sales Header table and the sales line data into the Sales Line table.

To create the XML document

  1. On the c: drive on your computer, create a folder named Multiple.

  2. Copy and paste the following XML document into a text file and save it as NewSalesOrder.xml in the folder that you just created. Later, you will create a codeunit that looks for this XML file in this folder.

Copy Code
<Root>
 <Header>
    <DocumentType>Order</DocumentType>
    <SellToCustomerNo>10000</SellToCustomerNo>
    <No>1015</No>
    <BillToName>The Cannon Group PLC</BillToName>
    <BillToAddress>192 Market Square</BillToAddress>
    <BillToCity>Birmingham</BillToCity>
    <BillToContact>Mr. Andy Teal</BillToContact>
    <BillToCountryRegion />
    <BillToPostCode>B27 4KT</BillToPostCode>
    <Line>
      <DocumentType>Order</DocumentType>
      <Type>Item</Type>
      <ItemNo>LS-2</ItemNo>
      <DocumentNo>1015</DocumentNo>
      <LineNo>20000</LineNo>
      <Description>Cables for Loudspeakers</Description>
      <UnitOfMeasure>BOX</UnitOfMeasure>
      <Quantity>100</Quantity>
      <UnitPrice>21.00</UnitPrice>
    </Line>
  </Header>
</Root>

Creating the XMLport

You create the XMLport by designing it in XMLport Designer and setting the properties for the XMLport. You define the nodes of the XML document and specify the tables and fields into which you want to insert the data.

To create the XMLport

  1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose XMLport, and then choose New.

  3. In XMLport Designer, choose an empty row in the designer, and on the View menu, choose Properties.

  4. In the XMLport-Properties window, locate the Direction Property, choose the drop-down arrow in the Value column, and then set it to Import.

  5. In the XMLport-Properties window, locate the Format Property (XMLports), verify that the Value column is set to Xml, and then close the XMLport-Properties window.

  6. In XMLport Designer, in the first row, in the Node Name column, enter Root. In the Node Type column, verify that Element is selected. In the Source Type column, verify that Text is selected. This node represents the beginning of the XML document.

  7. In the second row, in the Node Name column, enter Header. In the Node Type column, choose Element. In the Source Type column, choose the drop-down arrow, and then choose Table. This node represents a Sales Header record in the XML document.

  8. In the second row, in the Data Source column, choose the up arrow, choose the SalesHeader table (36) from the Table List window, and then choose the OK button. The data will be imported into the Sales Header table.

  9. Choose the Header row and use the right arrow to indent the row once to place it under the Root element.

    The next step is to map the nodes in the XML document to fields in the Sales Header table.

  10. In the next empty row under the Header row, in the Node Type column, choose Element, and in the Source Type column, choose Field.

  11. In the Data Source column, choose the up arrow, choose the Document Type field from the Field Lookup window, and then choose the OK button.

  12. In the Node Name column, enter a name for the field. For example, you can enter DocumentType. You can enter any name but because of consistency you might want to enter the name of field you choose.

    Note
    The name that you enter in the Node Name column cannot contain spaces. White space in the name results in a compile error.

  13. Choose the DocumentType row and use the right arrow to indent the field once to make it a subset of the Header element.

  14. Repeat steps 10 through 13 to map the fields you want to import. For this walkthrough choose the following fields.

    Node Name Node Type Source Type Data Source

    DocumentType

    Element

    Field

    Sales Header::Document Type

    SellToCustomerNo

    Element

    Field

    Sales Header::Sell-to Customer No.

    No

    Element

    Field

    Sales Header::No.

    BillToName

    Element

    Field

    Sales Header::Bill-to Name

    BillToAddress

    Element

    Field

    Sales Header::Bill-to Address

    BillToCity

    Element

    Field

    Sales Header::Bill-to City

    BillToContact

    Element

    Field

    Sales Header::Bill-to Contact

    BillToCountryRegion

    Element

    Field

    Sales Header::Bill-to Country/Region Code

    BillToPostCode

    Element

    Field

    Sales Header::Bill-to Post Code

    You have mapped the nodes in the Header element in the XML document to the fields in the Sales Header table. Next, you map the Line node in the XML document to the Sales Line table.

  15. In the next empty row, in the Node Name column, enter Line, and in the Node Type column, choose Element, and then in the Source Type column, choose the drop-down arrow and then choose Table. This node represents a Sales Line record in the XML document.

  16. In the Data Source column, choose the up arrow, choose the Sales Line table (37) from the Table List window, and then choose the OK button.

    The next step is to map the nodes that you want to import.

  17. In the next empty row under the Line row, in the Node Type column, choose Element, and in the Source Type column, choose Field.

  18. In the Data Source column, choose the up arrow, choose <Sales Line>(Sales Line) from the first column in the Field Lookup window, choose the Document Type field from the second column of the Field Lookup window, and then choose the OK button.

  19. In the Node Name column, enter a name for the field. For example, you can enter DocumentType.

  20. Choose the DocumentType row and use the right arrow to indent the field once to make it a subset of the Line element.

  21. Repeat steps 17 through 20 to map the nodes that you want to import. For this walkthrough map the following fields.

    Node Name Node Type Source Type Data Source

    DocumentType

    Element

    Field

    Sales Line::Document Type

    Type

    Element

    Field

    Sales Line::Type

    ItemNo

    Element

    Field

    Sales Line::No.

    DocumentNo

    Element

    Field

    Sales Line::Document No.

    LineNo

    Element

    Field

    Sales Line::Line No.

    Description

    Element

    Field

    Sales Line::Description

    UnitOfMeasure

    Element

    Field

    Sales Line::Unit of Measure

    Quantity

    Element

    Field

    Sales Line::Quantity

    UnitPrice

    Element

    Field

    Sales Line::Unit Price

    The design of the XMLport shows that the data in the XML document has been mapped to database tables that have a header-line relation. The XMLport must insert the header information before inserting the line information. You must set the properties to achieve this.

  22. From XMLport Designer, choose the Line row, and from the View menu, choose Properties.

  23. In the Line-Properties window, locate the LinkTableForceInsert Property and set its value to Yes.

  24. Locate the LinkTable Property, in the Value column choose the up arrow to open the Table List window, and then choose Sales Header.

  25. Locate the LinkFields Property and choose the AssistEdit button in the Value column to open the DataItem Link window.

  26. In the DataItem Link window, in the Field column, choose the up arrow to open the Sales Line - Field List window, choose Document No., and then choose the OK button.

  27. In the DataItem Link window, in the Reference Field column, choose the up arrow to open the Sales Header - Field List window, choose No., and then choose the OK button. Choose the OK button to close the DataItem Link window.

  28. From the File menu, choose Save As.

  29. In the Save As window, enter 50002 in the ID text box and enter MultipleTables in the Name text box. Verify that Compile is selected, and then choose the OK button.

    Note
    You use the name of the XMLport later in the codeunit.

  30. Close XMLport Designer.

Creating the Codeunit to Insert the XML Data

After you have created the XMLport, you create the codeunit that imports the data.

To create the codeunit

  1. In Object Designer, choose Codeunit, and then choose New to open the C/AL Editor.

  2. On the View menu, choose C/AL Globals.

  3. On the Variables tab, in the Name column, enter SalesOrderXmlFile and in the DataType column, choose the drop-down arrow, and then choose Text. This variable represents the XML file that you will import.

  4. In the second row, in the Name column, enter XmlStream and in the DataType column, choose the drop-down arrow, and then choose InStream. This variable represents the data stream from the XML document to the table.

  5. In the third row, in the Name column, enter IsImported and in the DataType column, choose the drop-down arrow, and then choose Boolean. This variable indicates whether the import succeeded. Close the C/AL Globals window.

  6. In the C/AL Editor, in the OnRun trigger, add the following code.

    Copy Code
    SalesOrderXmlFile := 'C:\Multiple\NewSalesOrder.xml';
UPLOADINTOSTREAM('Import','',' Xml Files (*.xml)|*.xml',SalesOrderXmlFile,XmlStream);
IsImported := XMLPORT.IMPORT(XMLPORT::MultipleTables, XmlStream);
IF (IsImported = TRUE) THEN
  MESSAGE('The import from XML is complete.')
ELSE
  MESSAGE(GETLASTERRORTEXT);

    The code uses the UPLOADINTOSTREAM Function (File) to send a file from the client to the server. The file is an XML file named NewSalesOrder.xml, which is located in a folder named Multiple on the C: drive. The IMPORT Function (XMLport) imports the data by using the specified XMLport. A message is displayed at the end of the export to indicate that the import is complete. If the import fails, then an error message is displayed. This message is not required but it lets the user know that something actually happened.

  7. Close the C/AL Editor and choose Yes at the prompt. In the Save AS dialog box, in the ID text box, enter 50003, in the name text box enter ImportMultiple, make sure Compile is selected, and then choose the OK button.

Running the XMLport

After the XMLport is created and the codeunit is written, run the codeunit to import the data.

To Run the XMLport

  1. In Object Designer, choose the ImportMultiple codeunit (50003), which is the codeunit that you just created, and then choose Run. The client opens and a message indicating that the export is complete is displayed.

  2. After the export is complete, in Object Designer, choose Table, select the Sales Header table, and then choose the Run button. Verify that the new record is included in the table.

  3. Similarly, run the Sales Line table and verify that the new record is included in the table.

See Also

Other Resources

XMLport Walkthroughs


Walkthrough: Exporting Data from Tables to CSV Files

XMLports are used to export data from a Microsoft Dynamics NAV database to a file or import data from a file to a Microsoft Dynamics NAV database. The file format can be an XML file, text file, or a comma separated value (CSV) file. Exporting data from your Microsoft Dynamics NAV database into one of these file formats enables seamless exchange of information between different computer systems. In this walkthrough, you will export data from a Microsoft Dynamics NAV database to a CSV file. For information about how to export data to XML file format, see Walkthrough: Exporting Data from Tables to XML Documents.

XMLports can be called and run from codeunits or run from Object Designer. In this walkthrough, you will run the XMLport in Object Designer. For information about how to run XMLports from codeunit, see Walkthrough: Exporting Data from Tables to XML Documents.

About This Walkthrough

This walkthrough shows you how to export data from a Microsoft Dynamics NAV table to a CSV file. This walkthrough illustrates the following tasks:

  • Designing an XMLport that exports data from a database to a CSV file.

  • Compiling and saving the XMLport.

  • Running the XMLport in Object Designer.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV installed with a developer license.

  • The CRONUS International Ltd. demonstration database installed.

Story

Viktor is a Microsoft Certified Partner working for CRONUS International Ltd.. He has been asked to export records from the Item table to a CSV file. The records will include only the No., Description, Shelf Number, and Unit price fields. The information will be shared with other colleagues who work on a different computer system. The CSV file can be used by any computer system in the company. Viktor knows that he can use XMLports to convert the records in the table to a CSV file format that can easily be shared with colleagues.

Designing the XMLport

You create an XMLport by designing it in XMLport Designer and setting the properties. You define the table and fields that you want to export in XMLport Designer. You then compile and save the XMLport.

To create the XMLport

  1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose XMLport, and then choose New to open a new XMLport Designer.

  3. In XMLport Designer, select an empty row.

  4. On the View menu, choose Properties to open the XMLport-Properties window.

  5. In the XMLport-Properties window, locate the Direction Property, choose the arrow in the value column, and then set the Value column to Export.

  6. In the XMLport-Properties window, locate the Format Property (XMLports) property, and then set the Value column to Variable Text.

    Warning
    When you export variable text files, the text in the fields will use as much space as needed to hold the all of the text.

  7. Verify that the FieldDelimiter Property is set to a quotation mark (“). This character marks the start and the end of each field. This is the default field delimiter.

  8. Verify that the FieldSeparator Property is set to a comma (,). This is the default field separator.

  9. Accept the default value for the RecordSeparator Property. The default is a new line separator.

    You can change the default values of the properties that you have just set to any character. However, for this walkthrough accept the default values.

  10. Close the XMLport-Properties window.

  11. In XMLport Designer, in the first row, in the Node Name column, enter ItemsFile.

  12. In the Node Type column, verify that Element is selected.

  13. In the Source Type column, verify that Text is selected. This node represents the start of the text file.

  14. In the second row, in the Node Name column, enter Item.

  15. In the Node Type column, verify that Element is selected.

  16. In the Source Type column, choose the drop-down arrow, and then select Table. This node represents a record in the Item table.

  17. In the Data Source column, choose the drop-down arrow, select the Item table (27) from the Table List window, and then choose the OK button. The data will be exported from the Item table.

  18. Select the Item row and then use the right arrow to indent the row one time to make it a subset of the ItemsFile element.

    The next step is to select the fields that you want to export.

  19. In the next empty row below the Item row, in the Node Type column, select Element.

  20. In the Source Type column, select Field.

  21. In the Data Source column, choose the up arrow, select the No. field from the Field Lookup window, and then choose the OK button.

  22. In the Node Name column, enter a name for the field. For example, you can enter No. This column represents the fields in the record. You can enter any name but because of consistency you might want to enter the name of field that you select.

    Note
    The name that you enter in the Node Name column cannot contain spaces. White space in the name will create a compile error.

  23. Select the No. row and use the right arrow to indent the field one time to make it a subset of the Item element.

  24. Repeat steps 19 through 23 to select additional fields that you want to export. For this walkthrough you can select the following fields.

    Node Name Node Type Source Type Data Source

    No.

    Element

    Field

    Item::No.

    Description

    Element

    Field

    Item::Description

    ShelfNumber

    Element

    Field

    Item::Shelf No.

    UnitPrice

    Element

    Field

    Item::Unit Price

  25. On the File menu, choose Save As.

  26. In the Save As window, enter 50003 in the ID text box, and then enter ItemsXMLport in the Name text box. By default, this name will be used as the name of the file.

  27. Verify that Compiled is selected and then choose the OK button.

  28. Close XMLport Designer.

Running the XMLport

After the XMLport is created you run it in Object Designer

To run the XMLport from Object Designer

  1. In Object Designer, select the XMLport that you just created (50003), and then choose the RUN button. The Edit-ItemsXMLport page is displayed.

  2. On the Edit-ItemsXMLport page, choose the OK button. The Export File dialog box is displayed.

  3. In the Export File dialog box, choose the Save button. The Export window opens.

  4. In the Export window, browse to the location on your computer where you want to save the file.

  5. Verify that the File name text box is set to the name of your XMLport and then verify that in the Save as type drop-down box, Text Files (*.txt,*.csv) is selected.

  6. Choose the Save button to export and save the file.

    Note
    On the Edit-ItemsXMLport request page, you can set filters to select specific records that you want to export.

  7. After the export is complete, browse to the location where you saved the file and open it. Note that all the records in the table are separated by a new line and each field in the record is delimited by using quotation marks ( “) and separated by a comma (,). Depending on the regional setting of the Microsoft Dynamics NAV Server, the data in the unit price field may contain a comma. If you delimit the data in the fields, the data is easier to identify and read. You can change the field separator.

    The following CSV file shows and example of the file that is exported from the Item table.

    Copy Code
    "1000","Bicycle","F4","4,000.00"
"1001","Touring Bicycle","F5","4,000.00"
"1100","Front Wheel","F6","1,000.00"
"1110","Rim","F1","0.00"
"1120","Spokes","A1","0.00"
"1150","Front Hub","F7","500.00"
"1151","Axle Front Wheel","A2","0.00"
"1155","Socket Front","A3","0.00"
"1160","Tire","A4","0.00"
"1170","Tube","A5","0.00"
"1200","Back Wheel","F9","1,200.00"
"1250","Back Hub","F10","1,100.00"
"1251","Axle Back Wheel","A6","0.00"

Next Steps

You might want to try importing a CSV file into the Item table. For information about how to import data into a database, see Walkthrough: Inserting Data from XML Documents to Multiple Tables.

See Also

Other Resources

XMLport Walkthroughs


Walkthrough: Importing Data from Text Files to Tables

XMLports are used to export data from a Microsoft Dynamics NAV database to a file or import data from a file to a Microsoft Dynamics NAV database. The file format can be an XML document, fixed width text file, or CSV (Comma Separated Value) file. Exporting or importing data by using these file formats enables seamless exchange of data between different computer systems. When importing files to a Microsoft Dynamics NAV database, you can replace an entire record or update specific fields in records that already exist in the database. You can also automatically save the data you are importing or you can manipulate the data in code before you save it.

In this walkthrough, you will import data from a fixed width text file to a Microsoft Dynamics NAV database. The text file contains data will be used to update specific fields in an existing record. The data in text file will be automatically saved into the database. For information about how to export data to XML file format, see Walkthrough: Exporting Data from Tables to XML Documents. For information about how to export CSV files, see Walkthrough: Exporting Data from Tables to CSV Files.

XMLports can be called and run from codeunits or run from Object Designer. In this walkthrough, you will run the XMLport from Object Designer. For information about how to run XMLports from codeunits, see Walkthrough: Exporting Data from Tables to XML Documents.

About This Walkthrough

This walkthrough shows you how to import data from a fixed width text file and update existing records in a Microsoft Dynamics NAV table. The walkthrough illustrates the following tasks:

  • Designing an XMLport that imports data from a fixed width text file to a Microsoft Dynamics NAV table.

  • Setting properties to update existing records.

  • Compiling and saving the XMLport.

  • Running the XMLport in Object Designer.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 installed with a developer license.

  • The CRONUS International Ltd. demonstration database.

Story

Viktor is a Microsoft Certified Partner working for CRONUS International Ltd. Viktor’s manager has informed him that the marketing department has changed the unit price of the loud speakers in their inventory and requesting that the current unit prices in the database should be replaced with the new prices. The loud speaker information is located in the Item table. The marketing department provided the new prices in a text file. The file contains only item number values for the No. field, which is the primary key, and the new unit prices. The text file is in a fixed width text file format. Viktor’s task is to import the data in the text file into the Item table and update the unit price field. Viktor knows that he can accomplish the task by designing an XMLport that can import the data from the text file and set properties to update the existing record in the table.

The text file that the marking department provided resembles the following. You will use this file in the walkthrough.

Copy Code
LS-100      30.00
LS-120      88.88
LS-150      130.00
LS-75       80.00
LS-81       89.89
LS-10PC     59.59

The first column is the data in the No. field, and the second column is the data that will be used to update the Unit Price field. You can view and confirm the current prices for the loud speakers in the Item table before the records are updated. For information about how to view table data, see How to: View and Sort Table Data.

Designing the XMLport

You create an XMLport by designing it in XMLport Designer and setting properties. You define the table and fields that you want to import data to in XMLport Designer. You then compile and save the XMLport.

To create the XMLport

  1. Copy and paste the text file into a text editor such as Notepad, give it a name, and save it on your computer.

  2. In the development environment, on the Tools menu, choose Object Designer.

  3. In Object Designer, choose XMLport, and then choose the New button.

  4. In XMLport Designer, in the first row, in the Node Name column, enter a name. You can enter any name but for this walkthrough you can enter ItemPrices.

  5. In the Node Type column, verify that Element is selected.

  6. In the Source Type column, verify that Text is selected. This node represents the start of the text file.

  7. In the second row, in the Node Name column, enter ItemRecord.

  8. In the Node Type column, verify that Element is selected.

  9. In the Source Type column, select Table from the drop-down list. This node represents a record in the Item table.

  10. In the Data Source column, choose the up arrow, select the Item table (27) from the Table List window and then choose the OK button. The data will be imported to the Item table.

  11. Select the ItemRecord row and use the right arrow button to indent the row one time to make it a subset of ItemsPrice element.

    The next step is to select the fields that you want to import and update. The text file contains only data that belongs in the No. field and the Unit Price field, so you will select those two fields.

  12. In the next empty row under the ItemRecord row, in the Node Type column, select Element.

  13. In the Source Type column, select Field.

  14. In the Data Source column, choose the up arrow, select the No. field from the Field Lookup window, and then choose the OK button.

  15. In the Node Name column, enter a name for the field. For example, you can enter No.. This column represents the No. field in the record. You can enter any name but because of consistency you might want to enter the name of field that you select.

    Note
    The name that you enter in the Node Name column cannot contain spaces. White space in the name will result in a compile error.

  16. Select the No. row and use the right arrow button to indent the field one time to make it a subset of the Item element.

  17. In the next empty row under the Item row, in the Node Type column, select Element.

  18. In the Source Type column, select Field.

  19. In the Data Source column, choose the arrow, select the Unit Price. field from the Field Lookup window, and then choose the OK button.

  20. In the Node Name column, enter a name for the field. For example, you can enter UnitPrice.

  21. Verify that the UnitPrice row is indented one time to make it a subset of the Item element.

Setting Properties to Import and Update Data

The next step is to set properties for the XMLport and fields you want to update.

To set properties

  1. In Object Designer, select an empty row, and on the View menu, choose Properties to open the XMLport-Properties window.

  2. In the XMLport-Properties window, locate the Direction Property, choose the arrow in the Value column and then set value to Import. This defines the XMLport to import.

  3. In the XMLport-Properties window, locate the Format Property (XMLports) property, and then set the Value column to Fixed Text. Data in fixed width text files use a specified amount of space.

  4. Select the ItemRecord row, and on the View menu, choose Properties.

  5. In the ItemRecord - Properties window, locate the AutoSave Property, and then verify that the Value column is set to Yes. This allows the data to be automatically saved to the table.to the table.

  6. Locate the AutoUpdate Property, and then set the Value column to Yes. This allows the data in the unit price field to be updated.

  7. Select the No. row, and then on the View menu, choose Properties.

  8. In the No. - Properties window, locate the Width Property (XMLport), and then set the Value column to 8. This defines the width of the No. field in the file.

  9. Select the UnitPrice row, and on the View menu, choose Properties.

  10. In the Unit Price - Properties window, locate the Width Property (XMLport), and then set the Value column to 10. This defines the width of the data in the file.

    Note
    The width that you enter must be equal or greater than the width of the data with most characters in the column. If the width of the data in the column is less than the width you specified, then the extra space is ignored.

Compiling and Saving the XMLport

After designing an XMLport, you must compile it, give it a name and ID, and then save it.

To compile and save the XMLport

  1. On the File menu, choose Save As.

  2. In the Save As window, enter 50004 in the ID text box and then enter a name for the XMLport. For example, you can enter NewItemPrice in the Name text box.

  3. Verify that the Compiled check box is selected and then choose the OK button.

Running the XMLport

In this walkthrough, you will run the XMLport from Object Designer and select the file you want to import from your computer.

To run the XMLport from Object Designer

  1. In Object Designer, select the XMLport you just created (50003), and then choose the Run button. The Edit-NewItemPrice page is displayed.

  2. On the Edit - NewItemPrice page, choose the OK button. The Import window is displayed.

  3. From the Import window, browse to the location on your computer where the file that you want to import is located.

  4. Choose the file and then choose the Open button to import the file to the database.

  5. Verify that the Unit Price fields in the records have been updated.

    Note
    You can write code in the OnBeforeModifyRecord Trigger in the C/AL code editor to indicate that the records have been updated.

Next Steps

You might want to try importing a CSV file or exporting a fixed width text file. For information about how to import CSV files, see Walkthrough: Exporting Data from Tables to CSV Files.

See Also

Concepts

Designing XMLports

Other Resources

XMLport Walkthroughs


MenuSuites

MenuSuites contain menus that enable users to navigate and perform actions in the Microsoft Dynamics NAV Windows client. MenuSuites display menus on the Departments page in the Microsoft Dynamics NAV Windows client. Microsoft Dynamics NAV provides a basic MenuSuite that can be modified. You can also create your own MenusSuites. You create MenuSuites in Object Designer and modify them in Navigation Pane Designer. For information about Navigation Pane Designer, see Navigation Pane Designer.

Note
MenuSuites are not supported by Microsoft Dynamics NAV Web client. They are used only to build the Department page in the Microsoft Dynamics NAV Windows client.

A MenuSuite has the following characteristics:

  • Consists of a set of menus.

  • Contains a menu node that can be either a menu group or a menu item.

  • Has a GUID (Globally Unique Identifier).

  • Contains a collection of menu nodes in a menu group.

  • A menu item is the lowest level in the tree. When you select a menu item, its associated object such as a report, a batch job, or a codeunit, is run.

MenuSuite Topics

The following table lists topics that provide information about MenuSuites.

To | See
Learn about how to design MenuSuites. | Designing MenuSuites
Learn about how to create a new MenuSuite. | Walkthrough: Creating MenuSuites for the Microsoft Dynamics NAV Windows Client
Learn about how create a menu for a department. | How to: Create a Menu for a Department in a MenuSuite
Learn about how to make changes to a menu that opens a department. | How to: Modify a Department Menu in a MenuSuite
Learn about how to make changes to menu items. | How to: Modify Menu Items in a MenuSuite

See Also

Concepts

Designing MenuSuites


Designing MenuSuites

In Microsoft Dynamics NAV 2016, you can create MenuSuites that contain menu content that is displayed in the Microsoft Dynamics NAV Windows client. The MenuSuite that is provided in Microsoft Dynamics NAV is a generic MenuSuite that you can modify. You can also create a new MenuSuite from the basic MenuSuite. Each menu in the basic MenuSuite represents a department such as Financial Management, Human Resources, and Manufacturing. Each department contains menu items that are specific for that department area. A department menu contains menu items that can link to the following objects:

  • Codeunits

  • Pages

  • Queries

  • Reports

  • Tables

  • XMLports

The links to these objects are displayed on the department page in the Microsoft Dynamics NAV Windows client. When the link is selected in the Microsoft Dynamics NAV Windows client, the object that it links to is run. MenuSuites are designed in Navigation Pane Designer but they are run in the Microsoft Dynamics NAV Windows client.

Note
MenuSuites cannot be run directly from Object Designer in the Microsoft Dynamics NAV Development Environment.

A menu links to a department and a menu item links to a specific object in the department. You can create a group that contains related menu items. When you design menu items and groups in Navigation Pane Designer, you can organize them to display on the Microsoft Dynamics NAV Windows client by department or by category. Menu items are displayed as links that users can use to open objects such as reports and pages.

Design Permissions Levels

For each MenuSuite that you create, you choose a design level. Design levels are permissions that allow different roles to create MenuSuites for specific functions. The design level that you are allowed to work in depends on your active license. In other words, you can only access or create MenuSuites as allowed by your active license and permissions. For example, if your active license allows you to localize and you design an application that will be localized, your design level will be at the Country or Region level. These levels enable localization for specific countries or regions. If you are a developer working at a Microsoft Certified Partner organization, you might design a MenuSuite at the Partner level. The following table describes the design levels.

MenuSuite Design Level | Description
Dept - MBS | The base design level that is provided in Microsoft Dynamics NAV. Any MenuSuite you create inherits from this base design level or a design level that inherited from this base design level.
Dept - Region | The design level that is used for region specific MenuSuites. This level is typically used for localization. Only one region specific design level MenuSuite can be created in a given application.
Dept - Country | The design level that is used for country specific MenuSuite. This level is typically used for localization and other items such as taxes that are country specific. Only one country specific design level MenuSuite can be created in a given application.
Dept - Add-on | The design level that a developer or Microsoft Dynamics NAV partner can use for customization. Up to ten Add-on design level MenuSuites can be created in a given application.
Dept - Partner | The design level that Microsoft Dynamics NAV partners use to customize MenuSuites. Only one partner design level MenuSuite can be created in a given application.
Dept - Company | The design level that is used to design for a specific company. Only one company specific design level MenuSuite can be created in a given application.

The following illustration shows the design permission levels that are available in Microsoft Dynamics NAV.

Microsoft Dynamics NAV MenuSuite Design Level

When you create a MenuSuite, it inherits from the design level that is above the level you selected. The most basic design level is the Dept - MBS level and the highest design level is the Dept - Company level. Only one MenuSuite can be created for each level in an application except the Add-on level, which can have a maximum of ten instances of MenuSuites.

At design time, the header area of Navigation Pane Designer displays the design level of the MenuSuite you are working with.

Creating a New MenuSuite

You create new MenuSuites in Object Designer and modify them in Navigation Pane Designer. When you create a new MenusSuite, Microsoft Dynamics NAV gives the MenuSuite a unique name and ID in Object Designer. The ID identifies the design level that the MenuSuite was designed at. The following table lists the IDs and the MenuSuites that is associated with the ID.

MenuSuite ID | MenuSuite name
1010 | Dept - MBS
1020 | Dept - Region
1030 | Dept - Country
1051...1060 | Dept.- Add-on 1….Dept. - Add-on 10
1080 | Dept - Partner
1090 | Dept - Company

Every new MenuSuite that you create is designed at one of the design levels and run on the Department page in the Microsoft Dynamics NAV Windows client. As such, the full names of the menus are prefixed with “Dept.”, followed by the design level, and then followed by the name of the menu. For example, if you create a new MenuSuite at the Partner level and you create a menu for a department that is named My New Department, the full name of the menu will be Dept-Partner: My New Department. This name is displayed in the header of the Navigation Pane Designer. The following screenshot shows the Navigation Pane Designer header section and group of menu items.

Navigation Pane Designer Header

After creating a new MenuSuite, you can do the following:

  • Create new menus

  • Delete menus

  • Rename menus

  • Change the location of menus

  • Hide or show menus

  • Disable menus

  • Modify menu items

For information about how to create a MenuSuite, see Walkthrough: Creating MenuSuites for the Microsoft Dynamics NAV Windows Client. For information about how to modify a MenuSuite, see How to: Modify Menu Items in a MenuSuite.

Inheriting MenuSuite Content

When you create a new MenuSuite, it inherits all its content from the 1010 Dept - MBS, the base MenuSuite that is provided in Microsoft Dynamics NAV. For example, when you create a MenuSuite and you select the Region design permission level, the MenuSuite that you created at the Region level inherits from 1010 Dept - MBS. The 1020 Dept - Region MenuSuite then becomes the highest design level MenuSuite in Object Designer. If you create another MenuSuite, it inherits from the 1020 Dept - Region MenuSuite and so on.

A MenuSuite cannot inherit from a MenuSuite that is created at a lower design level. For example, if you create a MenuSuite at the Dept - Partner level and then you create a second MenuSuite at the Dept - Country level, although the Partner level MenuSuite was created first, the Dept - Country level MenuSuite cannot inherit from the Partner level MenuSuite because the Dept - Partner is at a higher level than the Dept - Country level MenuSuite. Instead, the Dept - Country level object will inherit from the Dept - Region level. If a MenuSuite has not been created at the Region level, it will inherit from the Dept - MBS level MenuSuite.

Changes that you make in the new MenuSuite are merged into the inherited MenuSuite and saved as the difference between the new and the original MenuSuites. For example, if you make a change in the Dept - MBS MenuSuite, the change is also made in the Dept - Region MenuSuite. If you import the inherited MenuSuite to a text file, the file will contain only the difference between the two MenuSuites.

Menus in a MenuSuite that are inherited are identified by the symbol >> on the menu button. This symbol precedes the name of the menu. The following screenshot shows the departments menus in the Navigation Pane Designer.

Navigation Pane Designer Departments

These menus, except the My New Department menu, were inherited; therefore, My New Department does not have the symbol >> on the menu button.

Modifying a MenuSuite

To modify a MenuSuite in the Navigation Pane Designer, select the MenuSuite in Object Designer, apply the changes you want, compile, and save the MenuSuite. You can change the properties of menu items and departments in the Properties windows. For information about how to modify MenuSuites, see How to: Modify a Department Menu in a MenuSuite.

In addition to all the actions you can perform after you modify a MenuSuite, you can modify menu items and group folders as follows:

  • Add departments, items, and groups folders

  • Delete departments, items, and group folders

  • Rename departments’ items, and groups folders

  • Change bitmaps that are associated with departments

  • Hide departments

The menu items can be added directly on the department page or can be added to a submenu on the department page. You can change the bitmap images that are associated with the departments in the Menu Properties window. Valid bitmap numbers are from 0 to 15, inclusive. The menu items that you create in the Navigation Pane Designer are run in Microsoft Dynamics NAV Windows client. For more information about how to create MenuSuites, see Walkthrough: Creating MenuSuites for the Microsoft Dynamics NAV Windows Client.

Designing for Multiple Languages

By default, Microsoft Dynamics NAV display menus in the language that is set on your computer. The language code is shown in the CaptionML field in the Menu Properties window. If you create a menu that will be used in multiple languages, you must give the menu a name in each language in the Multilanguage Editor window. To open the Multilanguage Editor window, choose the EditAssist button in the CaptionML Property field. For more information, see How to: Enter Text in the Multilanguage Editor.

See Also

Tasks

Walkthrough: Creating MenuSuites for the Microsoft Dynamics NAV Windows Client
How to: Create a Menu for a Department in a MenuSuite
How to: Modify Menu Items in a MenuSuite

Concepts

MenuSuites


How to: Create a Menu for a Department in a MenuSuite

Microsoft Dynamics NAV 2016 provides a basic MenuSuite that you can modify, or you can create a new MenuSuite from the basic MenuSuite. You modify a MenuSuite by designing it in Navigation Pane Designer. In Navigation Pane Designer, you can modify an existing menu for a department or create a new menu. Creating a new menu creates a new department in the MenuSuite. This procedure describes how to create a menu for a department in a MenuSuite. For more information about how to modify a department menu, see How to: Modify a Department Menu in a MenuSuite. For information about how to modify a menu item in a MenuSuite, see How to: Modify Menu Items in a MenuSuite.

To create a Menu for a department

  1. In the Microsoft Dynamics NAV Development Environment, choose Tools and then choose Object Designer.

  2. In Object Designer, choose MenuSuite.

  3. Select the MenuSuite that you want to add the department menu to, and then choose Design to open Navigation Pane Designer.

  4. In Navigation Pane Designer, select the department tabs section, and from the shortcut menu, choose Create Menu.

  5. In the Create Menu window, in the Caption text box, enter a name for the menu.

  6. You can enter a value for CaptionML so that the menus are displayed in multiple languages. For information about how to enter a value for CaptionML, see How to: Enter Text in the Multilanguage Editor.

    Note
    By default, the language setting on your computer is used for CaptionML. However, you can change the language setting in the Multilanguage Editor window.

  7. In the Bitmap text box, enter the number of the bitmap you want to display on the department menu and then choose the OK button. Valid bitmap numbers are 0-15.

  8. In Navigation Pane Designer, from the shortcut menu, choose Close Navigation Pane Designer.

  9. In the Save Changes dialog box, make sure Compile is selected and then choose Yes to save the MenuSuite.

    After you have created a menu for a new department, add menu items to make the department menu functional. For information about how to add menu items to the department menu, see How to: Modify Menu Items in a MenuSuite.

See Also

Concepts

Designing MenuSuites
MenuSuites


How to: Insert Items in a MenuSuite

You can modify a MenuSuite by inserting existing items. If an item already exists in a menu, instead of recreating the item in another menu, you can just insert the existing item. For information about how to modify menu items, see How to: Modify Menu Items in a MenuSuite.

To insert a menu item

  1. In the Microsoft Dynamics NAV Development Environment, choose Tools, and then choose Object Designer to open the Object Designer window.

  2. In Object Designer, choose MenuSuite.

  3. Choose the MenuSuite that you want to modify, and then choose Design to open Navigation Pane Designer.

  4. In Navigation Pane Designer, choose the company you want to insert the item into.

  5. Right-click the location in Navigation Pane Designer where you want to insert the item and then choose Insert Items.

  6. In the Insert Items window, select Insert for each item that you want to insert, and then choose the OK button. This window lists all items that have already been created in Navigation Pane Designer.

    Note
    Make sure that the Insert check box is selected for all the items that you want to insert.

See Also

Tasks

Walkthrough: Creating MenuSuites for the Microsoft Dynamics NAV Windows Client


How to: Modify a Department Menu in a MenuSuite

Microsoft Dynamics NAV 2016 provides a basic MenuSuite that you can modify, or you can create a new MenuSuite from the basic MenuSuite. You modify an existing MenuSuite by designing it in Navigation Pane Designer. You can modify the shortcut menus, which typically represent a department area. You can modify the department menu either directly from the shortcut menu or in the Menu Properties window. This procedure describes how to modify a department menu in a MenuSuite. For more information about how to modify a menu item, see How to: Modify Menu Items in a MenuSuite. For information about how to create a new MenuSuite, see Walkthrough: Creating MenuSuites for the Microsoft Dynamics NAV Windows Client.

To modify a department menu in a MenuSuite

  1. In the Microsoft Dynamics NAV Development Environment, choose Tools and then choose Object Designer.

  2. In Object Designer, choose MenuSuite.

  3. Choose the MenuSuite that you want to modify, and then choose Design to open Navigation Pane Designer.

  4. In Navigation Pane Designer, select the department you want to modify, and open the shortcut menu. From here, you can make the following modifications:

    • Delete the department menu.

    • Rename the department menu.

    • Move the department menu to a different location.

    • Hide or show the department menu.

    • Disable or enable the department menu.

    • Change the properties (Caption, CaptionML and Bitmap) of the department menu in the Menu Properties window. Changing the caption in the Menu Properties window is the same as renaming the department.

    Tip
    The department tabs are located at the bottom half of Navigation Pane Designer. The design level and the name of the department that you selected are shown at the top of Navigation Pane Designer.

See Also

Tasks

Walkthrough: Creating MenuSuites for the Microsoft Dynamics NAV Windows Client
How to: Modify Menu Items in a MenuSuite
How to: Change Department Icons in the Windows Client

Reference

Bitmap Property
Menu Properties

Concepts

Designing MenuSuites


How to: Modify Menu Items in a MenuSuite

Microsoft Dynamics NAV 2016 provides a basic MenuSuite that you can modify, or you can create a new MenuSuite from the basic MenuSuite. You modify an existing MenuSuite by designing it in Navigation Pane Designer. You can modify the shortcut menus, which typically represent a department area or the menu items that are in the department menus. This procedure describes how to modify menu items in a MenuSuite. For more information about how to modify a department menu, see How to: Modify a Department Menu in a MenuSuite. For information about how to create a new MenuSuite, see Walkthrough: Creating MenuSuites for the Microsoft Dynamics NAV Windows Client.

To modify menu items in a MenuSuite

  1. In the Microsoft Dynamics NAV Development Environment, choose Tools and then choose Object Designer to open the Object Designer window.

  2. In Object Designer, choose MenuSuite.

  3. Choose the MenuSuite that you want to modify, and then choose Design to open Navigation Pane Designer.

  4. In Navigation Pane Designer, choose the department that contains the menu items that you want to modify.

    The department tabs are located at the bottom half of Navigation Pane Designer. The design level and the name of the department you selected are shown in the header section of Navigation Pane Designer. The menus for each department are displayed in the top half of Navigation Pane Designer, under the header section of Navigation Pane Designer.

  5. Select the menu item or group that you want to modify, and from the shortcut menu, choose an action from the list.

    You can modify a menu by creating new items, inserting existing items, creating new groups, deleting or renaming items or groups.

    Note
    For information about how to insert items, see How to: Insert Items in a MenuSuite.

  6. If you are creating a new menu item, do the following:

    1. Right-click the folder that you want to create new item in and then choose Create Item to open the Create Item window.

    2. From the Object Type drop-down list box, select the object type that you want to create the menu item for.

    3. In the Object ID box, choose the AssistButton and choose an object from the <Object> List window.

    4. In the Caption text box, enter a caption for the menu item, and then accept the default for CaptionML.

    5. In the Department list box, select the sub menu in the department where you want the menu item to appear in the Microsoft Dynamics NAV Windows client and then choose OK.

  7. Right-click Navigation Pane Designer, and then choose Close Navigation Pane Designer.

  8. In the Save Changes dialog box, make sure Compile is selected and then choose Yes to save the MenuSuite.

See Also

Concepts

Designing MenuSuites


Walkthrough: Creating MenuSuites for the Microsoft Dynamics NAV Windows Client

MenuSuites display menus on the Departments page in the Microsoft Dynamics NAV Windows client. MenuSuites contain links that enable you to browse application or objects, and make the applications or objects easier to access in the Microsoft Dynamics NAV Windows client. A MenuSuite contains a set of menus that enable you to access reports, pages, codeunits, and so on, from the Microsoft Dynamics NAV Windows client.

Microsoft Dynamics NAV 2016 provides a basic MenuSuite that you can modify, or you can create new MenuSuites from the basic MenuSuite. You create MenuSuites in Object Designer and modify them in Navigation Pane Designer. This walkthrough demonstrates how to create a MenuSuite from the basic Menusuite for the Microsoft Dynamics NAV Windows client. For information about how to modify MenuSuites, see How to: Modify Menu Items in a MenuSuite.

About This Walkthrough

This walkthrough shows you how to create a MenuSuite and modify department menus and menu items. This walkthrough illustrates the following tasks:

  • Creating a MenuSuite.

  • Adding a new department to the Departments page.

  • Modifying a department menu.

  • Modifying menu items in a department.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 installed with a developer license.

  • The CRONUS International Ltd. demonstration database.

Story

Simon is a Microsoft Certified Partner working for CRONUS International Ltd. The company has recently reorganized. The Financial Management department has been converted to Accounting department and some of the menu items in the department will no longer be needed in the new Accounting department. The Human Resources department is no longer needed because the functions of that department have been contracted out to an agency. The functions of the Services department have been suspended because the department will closed until further notice. A new Customer Support department has been created at CRONUS International Ltd.. This new department will contain customer and vendor support information, including pages and reports.

Simon has been asked to perform the following tasks and create a MenuSuite that meets the following requirements:

  • Create a new department named Customer Support. This department should contain customer and vendor information such as a Customer Card page, Vendor List page, and Customer-Order Summary report. The information will be grouped under vendor and customer submenus. The List page should be accessed from the Lists category and the card page should be accessed from the Tasks subcategory.

  • Add customer reports to the Reports and Analysis submenu The MenuSuite should contain the Customer-Order Summary report, which should be accessed from the Reports and Analysis subcategory in the Customer Support department.

  • Remove departments and menu items that are no longer needed.

  • Modify the MenuSuite to reflect all the changes at have been made at CRONUS International Ltd.

Simon knows that he can create a MenuSuite in Object Designer and make the changes in Navigation Pane Designer to accomplish his task.

Creating the MenuSuite

You create MenuSuites from the basic MenuSuite that is provided in Microsoft Dynamics NAV and design it in Navigation Pane Designer. To create a new MenuSuite, choose a design level that your license allows. For this walkthrough, you will design the MenuSuite at the Dept-Partner design level. For more information about design permission levels, see Designing MenuSuites.

To create the MenuSuite

  1. In the Microsoft Dynamics NAV Development Environment, choose Tools and then choose Object Designer.

  2. In Object Designer, choose MenuSuite and then choose New. The Design Level window is displayed.

    The following image shows the MenuSuite design levels that are available in Microsoft Dynamics NAV.

    Microsoft Dynamics NAV MenuSuite Design Level

  3. In the Design Level window, choose Dept - Partner and then choose OK to open Navigation Pane Designer.

    The design level that you selected is shown in the header section of Navigation Pane Designer.

  4. Right-click the Navigation Pane Designer header and then choose Close Navigation Pane Designer.

  5. In the Save Changes dialog box, verify that Compile is selected and then choose Yes.

    The MenuSuite that you created has an ID 1080, which is the ID for MenuSuites that are designed at the Partner level.

Adding a New Department

The next step is to create a menu for the new Customer Support department. You will make changes to the department menu and add menu items later.

To add a department

  1. In Object Designer, choose the MenuSuite that you just created and then choose Design.

  2. In Navigation Pane Designer, right-click the department tabs section and then choose Create Menu.

  3. In the Create Menu window, in the Caption text box, enter Customer Support. This is name of the new department.

  4. In the CaptionML text box, choose the EditAssist button to open the Multilanguage Editor.

    Note
    By default, the language setting on your computer is used for CaptionML, so clicking the text box automatically enters the defaults values.

  5. In the Multilanguage Editor window, verify that Language is set to English (United States) and Value is set to Customer Support, and then choose the OK button. You can change the language in the Windows Language List window by choosing the up arrow in the Language column.

  6. In the Bitmap text box, enter 10 and then choose OK. The Customer Support department menu is added to the MenuSuite. Valid bitmap numbers are 0-15. This is the bitmap that is displayed on the department menu in Navigation pane. However, the icons that are displayed on the departments on the Microsoft Dynamics NAV Windows client are different.

Modifying the Department Menus

Next, you will make the changes that were requested in the department menus. First, you will change the Financial Management menu to Accounting. You will also make changes to the menu items in the departments. You will delete the Human Resources department and hide the Services department. Simon knows that he may need the Services department in the future so he will hide it for now.

To modify the department menus

  1. In Navigation Pane Designer, select the Financial Management menu, from the shortcut menu, choose Properties.

  2. In the Menu Properties window, in the Caption text box, change the text to Accounting and then choose the OK button.

  3. Select the Human Resources menu, and from the shortcut menu, choose Delete.

  4. In the dialog box that opens, choose Yes. This removes this department from the MenuSuite.

  5. Select the Services department menu. From the shortcut menu, choose Hide in Designer. This removes it from the list but is not deleted.

  6. Select the Customer Support department menu. From the shortcut menu, choose Move Up. Move Customer Support below Accounting.

Modifying the Menu Items in a Department

You will now modify the menu items in the Accounting department and add menu items to the Customer Support department.

To modify the menu items

  1. Select the Accounting department and notice the menu items that appear in the top half of Navigation Pane Designer.

  2. Select the Periodic Activities group folder. From the shortcut menu, choose Properties to open the Group Properties window.

  3. Clear the Department Page check box and then choose OK. This removes the Periodic Activities group folder from the department page in the Microsoft Dynamics NAV Windows client.

  4. Select the Cash Management group folder. From the shortcut menu, choose Delete. This removes the folder and all menu items that are in it.

  5. Select the Customer Support department you created earlier. Notice that it does not contain any menu items or group folders.

  6. Right-click the menu items section, choose Create Group, and then name the folder Customers. You will add pages that are related to customers in this group.

  7. Expand the Customer folder node, right-click [Empty Group], and then choose Create Item to open the Create Item window.

  8. In the Object Type list, choose the drop-down arrow, and then select Page.

  9. In the Object ID text box, choose the up arrow to open the Page List window and then choose Customer Card (21) and then choose OK.

  10. Accept the defaults values for the Caption and CaptionML text boxes.

  11. In the Department list box, select Tasks and then choose the OK button. This puts this menu item in the Tasks sub menu.

  12. In the Create Item window, choose the OK button.

  13. Right-click the Customer Card menu item that you just created and then choose Create Item to open the Create Item window.

  14. Repeat steps 8 through 12 and set the following values in the Create Item window to add the Customer List (22) Page.

    Object Type

    Page.

    Object ID

    Customer List.

    Caption

    Customer List.

    CaptionML

    ENU=Customer List.

    Department

    Lists.

    This puts this menu item in the Lists sub category.

  15. Right-click the menu items section, choose Create Group and then name the folder Vendors. You will add pages that are relate to vendors in this group.

  16. Expand the Vendors group folder node, right-click [Empty Group], and choose Create Item to open the Create Item window.

  17. Repeat steps 8 through 12 and set the following values in the Create Item window to add the Vendor Card (26) page.

    Object Type

    Page.

    Object ID

    Vendor Card.

    Caption

    Vendor Card.

    CaptionML

    ENU=Vendor Card.

    Department

    Tasks.

    This puts this menu item in the Tasks sub category.

  18. Right-click the Vendor Card menu item you just added and then choose Create Item… to open the Create Item window.

  19. Repeat steps 8 through 12 and set the following values in the Create Item window to add the Vendor List (27) pages.

    Object Type

    Page.

    Object ID

    Vendor List.

    Caption

    Vendor List.

    CaptionML

    ENU=Vendor List.

    Department

    Lists.

    This puts this menu item in the Lists sub category.

  20. Right-click Vendors and then choose Create Item… to open the Create Item window.

  21. Repeat steps 8 through 12 and set the following values in the Create Item window to add the Customer-Order Summary (107) report.

    Object Type

    Report.

    Object ID

    Customer-Order Summary.

    Caption

    Customer-Order Summary.

    CaptionML

    ENU=Customer-Order Summary.

    Department

    Reports and Analysis.

    This puts this menu item in the Reports and Analysis sub category.

    If the item you want to create already exists, instead of creating a new one you can just insert the existing item. For information about how to insert an item, see How to: Insert Items in a MenuSuite.

    You have made all the changes that were requested. You will now save the MenuSuite and run it.

    The following image shows the departments and menu items in the Customer Support department in Navigation Pane Designer. The MenuSuite you have created in Navigation Pane Designer is similar to this image.

    MenuSuite Navigation Pane Designer

  22. Right-click the Navigation Pane Designer header and choose Close Navigation Pane Designer to save the MenuSuite. Notice the ID and the name of the MenuSuite you are saving. The ID and the name are given by Microsoft Dynamics NAV.

  23. In the Save Changes dialog box, verify that Compile is selected and then choose the OK button.

Running and Testing the MenuSuite

MenuSuites cannot be run directly in the development environment. You run MenuSuites in the Microsoft Dynamics NAV Windows client. In the Microsoft Dynamics NAV Windows client, menus are located under Departments and the submenus under the departments. Menus can be selected by department or by category.

To run and test the MenuSuite

  1. Open the Microsoft Dynamics NAV Windows client.

    Note
    If the Microsoft Dynamics NAV Windows client is already open, you must close it and reopen it. Otherwise, the MenuSuite that you created will be displayed.

  2. In the leftmost pane, choose Departments.

  3. Verify that the Customer Support department and all the changes that you made appear in the Microsoft Dynamics NAV Windows client.

Next Steps

You might want to create another MenuSuite at the Dept - Company level. This MenuSuite will inherit from the MenuSuite that you just created in this walkthrough.

See Also

Tasks

How to: Modify a Department Menu in a MenuSuite

Reference

Bitmap Property
Menu Properties

Concepts

MenuSuites
Designing MenuSuites


Compiling Objects

Before you can run a Microsoft Dynamics NAV object, you must compile the object. To compile an object, do one of the following:

  • In Object Designer, choose Tools, and then choose Compile. Any syntax errors are displayed in a dialog box. Any errors or warnings about obsolete constructs in a three-tier environment are displayed in the Error List window.

  • Run finsql.exe with the CompileObjects command. Any errors or warnings are added to the log file. For more information, see CompileObjects.

Note
To compile an object, you must have a developer license.

Syntax Errors

Syntax errors are detected by the C/AL compiler when you try to compile C/AL code, either in a codeunit or as code in another object, such as a table, page, report, query, or XMLport. If you open an object in the designer and then compile the object, then if the compiler detects a syntax error, when you press ENTER and acknowledge the error message, the C/AL editor opens with the cursor in front of the expression that has the error. If you compile an object directly from Object Designer and if the compiler detects a syntax error, then the C/AL editor does not open to show where the error occurred.

The compiler will not compile code that contains a syntax error.

Obsolete Construct Errors

The following types of obsolete construct errors and warnings are displayed:

  • Unsupported data type warnings for Binary and XMLport types.

  • Unsupported function calls.

Note
Unsupported function calls for reports are not reported in the Error List window.

If you select an error in the Error List window and choose Design, then the C/AL Editor opens for the object to which the error or warning relates.

Multilanguage Captions

When you compile application objects, Microsoft Dynamics NAV stores the objects in Unicode encoding. If the application objects contain multilanguage captions, Microsoft Dynamics NAV uses the code page that is relevant for the languages that you have specified. For more information, see Developing Multilanguage-Enabled Applications.

See Also

Concepts

Compiling Tables
Objects
Programming in C/AL


Troubleshooting: "You cannot enter table 'Table Name' in TableNo" error when compling an object

If C/AL code references a table whose name starts with a number, followed by a space and then text, you will get the following error when you compile the object:

You cannot enter table '[Number][ ][Text]' in TableNo.

For example, if a table has the name 340 Declaration Line, then the C/AL code MESSAGE(FORMAT(DATABASE::"340 Declaration Line")); would result in the following error when the object is compiled:

You cannot enter table '304 Declaration Line' in TableNo.

Resolution

To resolve this issue, do one of the following.

  • Reference the table by its ID instead of its name.

    If the table in the previous example has an ID of 5000, then you could change the code to MESSAGE(FORMAT(DATABASE::"5000"));.

    The ID is specified by the table's ID Property.

    This is the recommended resolution.

  • Rename the table by either removing the number or the space between the number and the rest of the name. The name is specified by the table's Name Property.

See Also

Tasks

How to: Create a Table
How to: Save a New Table


Importing and Exporting Objects

You can import objects into Microsoft Dynamics NAV and export objects from Microsoft Dynamics NAV in the development environment or by using development environment commands. The following table describes when you can use each method.

Method | Recommended uses | For more information
Import and Export from the File menu in the development environment. | To move, copy, or share objects from Object Designer. | How to: Import Objects How to: Export Objects Import Worksheet
ImportObjects and ExportObjects commands. | To move, copy, or share objects at a command prompt. Use the commands if you want to automate the import or export. | Development Environment Commands How to: Import Objects How to: Export Objects

When you export an object, you export the design object, but not the data, from the database.

Warning
When you import objects to Microsoft Dynamics NAV from a .txt file, and the file contains syntax errors, the objects are not imported. You must correct the error and import the .txt file again.

To translate strings for customized objects in a multilanguage environment, you can import and export text strings. For more information, see How to: Add Translated Strings By Importing and Exporting Multilanguage Files. Alternatively, you can export your application objects into text files and then use Windows PowerShell cmdlets to export and import languages. For more information, see Working with Application Objects as Text Files.

To view or troubleshoot a report on a computer that does not have Microsoft Dynamics NAV installed, you can export the dataset of a report as an .xml file. This exports the structure of the dataset and the data from the report. For more information, see Walkthrough: Running a Report Offline.

See Also

Tasks

How to: Import Objects
How to: Export Objects
How to: Add Translated Strings By Importing and Exporting Multilanguage Files

Reference

ImportObjects
Import Worksheet

Concepts

Objects
Working with Application Objects as Text Files


How to: Export Objects

You can export one or more application objects to one of the following formats:

  • Microsoft Dynamics NAV Object format (.fob)

  • Text format (.txt)

You can export objects either by using the development environment UI or by running finsql.exe with the ExportObjects command.

Note
To export objects to .txt format, you must have a developer license. To export objects to .fob format, you can have either an end-user license or a developer license.

To export objects by using the development environment UI

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, select the object type that you want to export, or select All if you want to export different types of objects to the same file.

  3. Select one or more objects that you want to export. To select multiple objects, hold down the Ctrl key when you select objects.

  4. On the File menu, choose Export.

  5. In the Export Objects window, locate the folder where you want to create the exported objects file, enter a file name, select the file type, and then choose the Save button.

To export objects by running finsql.exe with the ExportObjects command

  1. At a command prompt, move to the location of finsql.exe. By default, finsql.exe is located at C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored client\.

  2. Run finsql.exe with the parameter "command=exportobjects". You must specify the following parameters:

    • file

    • servername

    • database

    All other parameters are optional.

    For more information about the ExportObjects command, see ExportObjects.

See Also

Concepts

Importing and Exporting Objects


How to: Import Objects

You can import application objects into the database from a file. The file must be one of the following formats:

  • Microsoft Dynamics NAV Object format (.fob)

  • Text format (.txt)

You can import objects either by using the development environment UI or by running finsql.exe with the ImportObjects command.

Note
To import objects from .txt format, you must have a developer license. To import objects from .fob format, you can have either an end-user license or a developer license.

To import objects by using the development environment UI

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. On the File menu, choose Import.

  3. In the Import Objects window, locate the folder where the import file is located, select the file, and then choose Open.

    If you import objects from a .txt file, then the objects in the file overwrite any objects that are already in the database. If you import objects from a .fob file and one or more objects in the file has the same ID as an object that are already in the database, then you receive a warning. You can choose to either cancel the import or open the Import Worksheet to resolve the conflicts.

  4. Use the Import Worksheet to specify how to resolve conflicts between objects in the import file and objects in the database. For more information, see Import Worksheet.

To import objects by running finsql.exe with the ImportObjects command

  1. At a command prompt, move to the location of finsql.exe. By default, finsql.exe is located at C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored client\.

  2. Run finsql.exe with the parameter "command=importobjects". You must specify the following parameters:

    • file

    • servername

    • database

    All other parameters are optional.

    For more information about the ImportObjects command, see ImportObjects.

See Also

Concepts

Importing and Exporting Objects


Import Worksheet

When you import objects from a binary file (.fob), if there are conflicts with objects that exist in the database with the same ID, then you use the Import Worksheet to resolve the conflicts. If the import file contains only objects that are new, then the objects are imported.

If you import objects from a .txt file, then the objects in the file overwrite any existing objects in the database.

You use the Import Worksheet when you import objects by using the UI in the development environment. For more information about how to import objects, see How to: Import Objects.

Default Actions in the Import File

The value of the Action column for each object in the Import Worksheet can be saved in the .fob file with the objects by choosing the Save As button in the Import Worksheet. When you import a .fob file, in the dialog box, you can choose the Yes button to import all objects and use the actions that are saved in the .fob file, or choose the No button to open the Import Worksheet and revise the action for any object in the file.

The Import Worksheet

Each line in the Import Worksheet displays information about one object. You decide how to handle the conflict by choosing an action in the Action column. The following table shows the information that is displayed about each object in the import file.

Object Description

Type

The type of this object. The type is one of the following:

  • TableData

  • Table

  • Report

  • Codeunit

  • XMLport

  • MenuSuite

  • Page

  • Query

  • System

  • FieldNumber

No.

The ID of the object.

Name

The name of the object.

New Object

Specifies if the object to import is a new object that does not exist already in the database.

New Object Changed

Specifies if the new object to import has been marked as changed.

Existing Object Changed

Specifies if the object to import is an existing object that has been changed, for example, the Modified field is set or the Version List is changed.

Warning

Specifies if there is a conflict that must be resolved before this object can be imported.

Action

Specifies how the conflict will be resolved. This is the only field that you can change The options are the following:

Create | The new object will be added to the database. This option is only valid if no such object already exists.
Replace | The existing object will be replaced by the new object.
Delete | The existing object will be deleted and no new object created. This option is only valid if the new object has size 0. The intended use is to remove obsolete objects from the database.
Skip | This object will not be imported.
Merge: Existing<-New | Only valid for tables. All fields in the existing table will remain and any additional fields from the new object will be added.
Merge: New<-Existing | Only valid for tables. All fields in the new table will be imported and any additional fields in the existing table will be added to the new table.

Existing Object Modified

Specifies if the existing object has the Modified field set.

Existing Object Version List

The version of the existing object.

New Object Modified

Specifies if the new object has the Modified field set.

New Object Version List

The version of the new object.

In addition, the Name, Modified, Version list, Size, Date, and Time fields are displayed in the window for the object that is selected.

Using the Import Worksheet

For each object, you can choose an action, given the constraints outlined in the preceding table. You can apply these actions by choosing the appropriate buttons.

Action | Definition
OK | Perform the import according to the current settings in the worksheet.
Cancel | Cancel the import.
Replace All | Set Action for all objects in the worksheet to Replace.
Save As | Save the current settings in the worksheet in the import file, together with the objects.
Help | Display the Help topic.

See Also

Reference

Options for Merging Objects

Concepts

Importing and Exporting Objects


Options for Merging Objects

The following sequence of events shows when objects are merged:

  1. The old object is decompiled.

  2. The new object is decompiled.

  3. The objects are merged.

  4. The resulting object is compiled.

If any one of these steps fail, the merge will be discontinued.

There are two options for merging:

  • Existing <- New

  • New <- Existing

Existing <- New

When you use Existing <- New, the following items from the existing object are always used:

  • Table properties.

  • Local C/AL functions on the table, including local variables.

  • Global variables.

The following items are merged into the existing object from the new object:

  • New fields.

  • Field properties that are different in the objects.

  • Trigger code on field level, including local variables.

Fields are merged based on the field number. The following scenarios are possible:

  • The field is located in the old object, but not in the new. The field will remain as it was.

  • The field is located in the new object, but not in the old. The field will be added.

  • The field is located in both objects. If the properties are different in the new object, these new properties will be used.

This could lead to problems that have to be resolved manually. For example, consider a new object that differs from an old object by introducing code in a field trigger and this code uses a global variable that is not in the old object. The merge will fail because the global variables are taken from the old object, and the merged object needs the global variable in order to compile.

A workaround would be to declare the global variable in the old object before merging the objects.

New <- Existing

When you use New <- Existing option, this reverses the scenario.

The following items from the new object are always used:

  • Table properties.

  • Local C/AL functions on the table, including local variables.

  • Global variables.

The following items are merged into the new object from the existing object:

  • New fields.

  • Field properties that are different in the objects.

  • Trigger code on field level, including local variables.


Working with Application Objects as Text Files

You can export application objects to text files and modify them in external tools such as comparing and merging objects using Windows PowerShell cmdlets. Optionally, you can store the files in external source control systems for better maintainability.

Objects in Text Files

The input to and output from the application merge utilities, for example, are text files that have been exported from a Microsoft Dynamics NAV database. You can also use other tools to bulk edit the files, such as if you want to set a version number. You can export all objects into a single file, or you can export objects into separate files per object. Microsoft Dynamics NAV includes Windows PowerShell cmdlets that can split a large text file into separate files per object, and join separate files into a single text file.

For example, you can update the VersionList, Modified, Date, and Time properties for all or some of the application objects by using the Set-NAVApplicationObjectProperty cmdlet. This can be useful when you are applying the latest cumulative update to your solution, for example, and you want to set the date and time for all modified objects at the end of the process.

The following Windows PowerShell command sets all object properties on all text files in the RESULTS folder.

Copy Code
Set-NAVApplicationObjectProperty -TargetPath .\RESULT\*.txt -VersionListProperty "MySolutionV2" -ModifiedProperty Yes -DateTimeProperty (Get-Date -Format g)

The example sets the following properties: VersionList is set to MySolutionV2, Modified to Yes, and Date and Time are set to the current date and time. In the example, you update the text files that are the result of running the Merge-NAVApplicationObject cmdlet. For more information, see Comparing and Merging Application Object Source Files.

External Source Control

When you export your application objects as text files, you can choose to store the files in external source control systems for source control and version control. Using a version control system such as Visual Studio Team Foundation Server for your application source text files is always highly recommended, and it makes it simpler to compare and merge objects using the Windows PowerShell cmdlets.

Adding and Removing Languages

When your application objects are in text format, you can also export captions into text files. You can use Windows PowerShell cmdlets to export one or more languages from the specified application objects, and you can import new languages, for example. This supplements the support for importing and exporting languages using the development environment and the development environment commands that are based on the application objects in a Microsoft Dynamics NAV database. But if your application objects are stored externally as text files, you can use Windows PowerShell cmdlets such as Export-NAVApplicationObjectLanguage, Import-NAVApplicationObjectLanguage, and Remove-NAVApplicationObjectLanguage instead. You can use other cmdlets to test that all objects have captions in a specific language, for example, and to join and split application language files.

The following Windows PowerShell command exports the German captions from the objects in the TARGET folder to a single text file.

Copy Code
Export-NAVApplicationObjectLanguage -Source .\TARGET\*.TXT -Destination .\RESULT\ALL-DEU.TXT -LanguageId "DEU"

The example exports the DEU captions for all application objects into an application language file, ALL-DEU.txt. Optionally, you can use the Split-NAVApplicationObjectLanguageFile cmdlet to the split that text file into separate text files with captions for each object. However, in most cases you probably prefer to work with a single application language file.

When you export a language by using the Export-NAVApplicationObjectLanguage cmdlet, and an object is missing a caption in that language, the exported text file will not have an entry in that language for that object. However, if the language that you are exporting is the base development language, then the entry is generated based on the name of the object. The default base development language is ENU.

For example, you exported table 50000 to a text file, TAB50000.txt. In the development environment, you did not specify a caption for field number 1, so the following example shows how that field is defined in TAB50000.txt:

Copy Code
{ 1   ;   ;Code                ;Code10        }

If you then run the Export-NAVApplicationObjectLanguage cmdlet for ENU , the cmdlet will generate an entry for this field with the language code for ENU as shown in the following example:

Copy Code
T50080-F1-P8629-A1033-L999:Code

If your Windows PowerShell script exported other languages, the corresponding entries for this field will be blank as shown in the following example for DAN:

Copy Code
T50080-F1-P8629-A1030-L999:

Similarly, the Remove-NAVApplicationObjectLanguage cmdlet will remove the captions in the languages that you specify. However, you can also use the cmdlet to remove all captions. If you do not set the LanguageId parameter, all available languages are removed from the objects except the development language.

See Also

Tasks

How to: Export Objects

Concepts

Comparing and Merging Application Object Source Files
Importing and Exporting Objects


Running Objects from the Development Environment

In Object Designer in the Microsoft Dynamics NAV Development Environment, you can run any object. The object is run on the computer that is running Microsoft Dynamics NAV Server, not on a client computer.

To run an object from Object Designer, you must first open a company. If you do not have a company open, then you are prompted to open a company or to create a company if no companies exist.

You can also run objects from hyperlinks. For more information, see Creating and Running Hyperlinks.

The instance of Microsoft Dynamics NAV Server on which the object is run is specified in the Database Information window and in the Options window. For more information about how to change the server instance, see How to: Change the Microsoft Dynamics NAV Server Instance.

If there is only one Microsoft Dynamics NAV Server instance configured for the currently open database, then this instance is automatically used to run the object.

See Also

Concepts

Objects
Compiling Objects


Using About This Page and About This Report

To see more information about a page, use the About This Page feature to view all the fields that make up the current page. These fields are the fields for the current record in the table on which the page is based. For example, if you open a sales order page, choose the Help button, and then choose About This Page, the About This Page: Sales Order window opens. The About This Page window shows the following FastTabs:

  • Page Information

  • Table Fields, sorted first by key fields, then alphabetically

  • Source Expressions

  • FlowFilter Fields

  • Filters

  • URLs that open the page in the Microsoft Dynamics NAV Windows client, the Microsoft Dynamics NAV Web client, and in SOAP and OData web services.

The following illustration shows a Sales Order page and the About This Page.

About This Page window that shows all fields
Note
To see more information about a subpage, such as a Factbox or a Line page, you must use the shortcut for About This Page, CTRL+ALT+F1.

To see more information about a report, use the About This Report feature to view the dataset on which the report is based. For example, if you view the report preview of the Inventory Cost and Price List report, then the first time that you choose the Help button and then choose About This Report, you activate the About This Report feature. After the feature is activated, if you view the report preview, choose the Help button, and then choose About This Report, then the About this Report: Inventory Cost and Price List page opens. The following illustration shows the Inventory Cost and Price List report and the About This Report page.

About This Report page that shows the dataset
Note
The About This Report feature remains active during the client session. When the feature is active, the size of the data that is sent to the client when you run a report is about twice the size of the data when the feature is not active. To deactivate the feature, restart the client.

URLs for the Page or Report

The About This Page window includes a FastTab where you can see the URLs for opening the page. For example, if you want to save the hyperlink to open a page in the Microsoft Dynamics NAV Web client, you can copy the URL from the About This Page window. Similarly, you can get the URL for a report from the request page for the report. For more information, see How to: Copy the URL to Open a Page or Report.

The URLs are generated based on the current Microsoft Dynamics NAV Server configuration.

Troubleshooting with About This Page and About This Report

You can use the About This Page and About This Report features to help you troubleshoot and debug issues. For example, if you create a new page and need to troubleshoot the data that is displayed on the page, then you can use the About This Page feature to view all the fields for the current record, including filters that were set by the user and FlowFilter fields.

Exporting About This Page Information

You can export the About This Page information to the following formats:

  • HTML attachment in a new e-mail message

  • Microsoft Word document

  • Microsoft Excel spreadsheet

You can also print the About This Page information directly from the About This Page window.

See Also

Tasks

How to: View All Table Fields for a Record
How to: View and Export the Dataset for a Report
How to: Copy the URL to Open a Page or Report


How to: View All Table Fields for a Record

You can use the About This Page feature to view all fields for the current record that are in the table on which the page is based.

To view field values

  1. In the client, open the page for which you want to view table field values.

  2. On the menu bar, on the Application menu Application Menu button in menu bar, choose Help, and then choose About This Page.

    The About This Page window displays every field that is in the table on which the selected page is based. It displays both visible and invisible fields. It also displays the value of each field for the selected record.

  3. (optional) To view the fields in the table on which a subpage is based, place the cursor on the subpage and then press Ctrl+Alt+F1.

To export field values

  1. In the client, open the page for which you want to view table field values.

  2. On the menu bar, on the Application menu Application Menu button in menu bar, choose Help, and then choose About This Page.

  3. On the About This Page page, on the Actions tab, in the Send To group, choose one of the following options to send the field data to another format:

    • Recipient as Attachment (HTML format)

    • Microsoft Word

    • Microsoft Excel

  4. (optional) On the About This Page page, on the Actions tab, in the General group, choose Print Page to open the Print window and send the information to a printer.

See Also

Tasks

How to: View and Export the Dataset for a Report


How to: View and Export the Dataset for a Report

You use the About This Report feature to view the dataset on which the report is based. Before viewing the dataset for the first time, you must activate the About This Report feature. To deactivate the feature, restart the client.

Note
The About This Report feature remains active during the client session. When the About This Report feature is active, the size of the data that is sent to the client when you run a report is about twice the size of the data when the feature is not active.

To activate the About This Report feature

  1. In the client, open the report for which you want to view the dataset.

  2. To activate the feature, do one of the following steps:

    • In the request page for the report, on the Application menu Application Menu button in menu bar, choose Help, and then choose About This Page.

    • In the request page for the report, choose Preview. On the Print Preview page, on the Application menu Application Menu button in menu bar, choose Help, and then choose About This Report. If the About This Report feature was not previously active, then the About This Report window will display the following message:

      “The About This Report feature is now active. Run your report again to view the dataset.”

To view the dataset from the preview page

  1. Activate the About This Report feature.

  2. In the client, open the report for which you want to view the dataset.

  3. In the request page for the report, set any filters on the report data, and then choose Preview.

  4. On the Print Preview page, on the Application menu Application Menu button in menu bar, choose Help, and then choose About This Report.

    Note
    The data in the About This Report page will be filtered based the filters that you set in the request page.

To export the dataset from the preview page

  1. Activate the About This Report feature.

  2. In the client, open the report for which you want to export the dataset.

  3. In the request page for the report, set any filters on the report data, and then choose Preview.

  4. On the Print Preview page, on the Application menu Application Menu button in menu bar, choose Help, and then choose About This Report.

    Note
    The data in the About This Report page will be filtered based the filters that you set in the request page.

  5. On the About This Report page, on the Actions tab, choose one of the following options to send the field data to another format:

    • Recipient as Attachment

    • Microsoft Word

    • Microsoft Excel

    • Export to XML

  6. (optional) On the About This Report page, on the Actions tab, choose Print Page to open the Print window and send the About This Report information to a printer.

See Also

Tasks

How to: View All Table Fields for a Record
Walkthrough: Running a Report Offline

Concepts

Using About This Page and About This Report


How to: Assign Permission to Use About This Page

The supplemental permission sets that are provided for the RoleTailored client do not include permissions to run About This Report and do not include permissions to view all information for About This Page. To add permissions to run About This Report and to view all information for About This Page, you add the Zoom permission to a permission set and assign users to that permission set.

Adding the Zoom Permission

To add the Zoom permission to a permission set

  1. Edit the permission set to which you want to add the Zoom permission. For more information, see How to: Create or Modify Permission Sets. Follow the steps in the procedure to edit a permission set.

  2. Scroll to the end of the list and position the pointer on a new line to add an additional object to the permission set definition.

  3. In the Object Type field, select System.

  4. In the Object ID field, enter 5330.

    The Object Name field is filled in automatically with Tools, Zoom.

  5. In the Execute Permission field of the line for the Tools, Zoom permission, choose Yes.

  6. Close the Permissions window and the Permission Sets window.

Next Steps

After you add the Zoom permission to a permission set, you must assign users to that permission set. For more information, see How to: Define Permissions for Users.

See Also

Concepts

Managing Users

Other Resources

Managing Permissions and Permission Sets


How to: Copy the URL to Open a Page or Report

Microsoft Dynamics NAV generates URLs for opening pages and report request pages from the Microsoft Dynamics NAV Windows client, the Microsoft Dynamics NAV Web client, and SOAP and OData web services. You can copy these URLS from the About This Page window and save them as shortcuts for your own use, or you can send them to other people as hyperlinks, for example.

The URLs are generated based on the GETURL function that you can also use in your code. For more information, see GETURL Function.

Note
You can only view the URLs in the Microsoft Dynamics NAV Windows client.

To view URLS for a Page

  1. In the Microsoft Dynamics NAV Windows client, in the relevant page, in the Application menu, point to Help, and then choose About This Page.

  2. On the URLs FastTab, copy the link that you want to use.

    The following table shows the syntax for the URLs.

    Field URL

    Microsoft Dynamics NAV Windows client

    DynamicsNAV://server/instance/company

    Microsoft Dynamics NAV Web client

    https://server:port/instance/WebClient?company='MyCompany'/

    OData client

    https://server:port/instance/OData/Company('MyCompany')/

    SOAP client

    https://server:port/instance/WS/MyCompany

To view URLS for a Report

  1. In the Microsoft Dynamics NAV Windows client, in the relevant report request page, in the Application menu, point to Help, and then choose About This Page.

  2. On the URLs FastTab, copy the link that you want to use.

    The following table shows the syntax for the URLs.

    Field URL

    Microsoft Dynamics NAV Windows client

    DynamicsNAV://server/instance/company

    Microsoft Dynamics NAV Web client

    https://server:port/instance/WebClient?company='MyCompany'/

See Also

Reference

GETURL Function

Concepts

Using About This Page and About This Report
Creating and Running Hyperlinks


Viewing the Definition of a Function or Object by Using Go To Definition

You can view the definition of a function or object by selecting the item in the C/AL Editor and then choosing Go To Definition. You can also view the definition of a function by selecting it in the C/AL Globals window and then choosing Go To Definition.

To go to the definition of a function or object, select or place the cursor anywhere in the function name or object variable name, and then do one of the following:

  • On the View menu, choose Go To Definition.

  • Right-click the function name or object variable name, and then choose Go To Definition.

  • Press Shift+F12.

The following table describes how you can go to the definition of a function or object.

Starting location Result

User-Defined Function from the C/AL Globals Window

The C/AL Editor goes to the C/AL code that defines the selected function.

User-Defined Function from the C/AL Editor

The C/AL Editor goes to the C/AL code that defines the selected function.

User-Defined Function from the C/AL Editor for an Object Variable

  • The object is opened in the corresponding designer.

  • A new C/AL Editor window opens to the C/AL code that defines the selected function.

System Function from the C/AL Editor

If the system function is called on an object variable, such as a record, codeunit, or report, then the object is opened in the corresponding designer. If the system function is not called on an object variable, then nothing occurs.

Object Variable from the C/AL Editor:

  • Record

  • Page

  • Report

  • Codeunit

  • XMLport

  • Query

The object is opened in the corresponding designer or editor:

  • Table Designer

  • Page Designer

  • Report Dataset Designer

  • C/AL Editor

  • XMLport Designer

  • Query Designer

Note
If you select a variable that is a fundamental data type, such as Integer or Decimal, then information about the variable is displayed in the status bar.

Examples

This section shows examples of using the Go To Definition shortcut menu item.

User-Defined Function from the C/AL Globals Window

From the C/AL Globals window, right-click a user-defined function, and then choose Go To Definition.

Go To Definition of a user-defined function

The result is that the C/AL Editor jumps to the C/AL code that defines the selected function.

Go To Definition of a user-defined function

User-Defined Function from the C/AL Editor

From the C/AL Editor, right-click a user-defined function, and then choose Go To Definition.

Go To Definition from user function in C/AL Editor

The result is that the C/AL Editor jumps to the C/AL code that defines the selected function.

Go To Definition from user function in C/AL Editor

User-Defined Function from the C/AL Editor for an Object Variable

From the C/AL Editor, right-click a user-defined function that is called on an object variable, and then choose Go To Definition.

Go To Definition from user function in C/AL Editor

The result is that the object on which the function is called is opened in the corresponding designer and a new C/AL Editor window opens to the C/AL code that defines the selected function.

Go To Definition from user function in C/AL Editor

System Function from the C/AL Editor

From the C/AL Editor, right-click a system function that is called on an object variable, and then choose Go To Definition.

Go To Definition from a system function

If the system function is called on a record variable, then the table that the record is from is opened in Table Designer.

Go To Definition from system function

If the system function is the <codeunit>.RUN function, then the codeunit is opened in a new C/AL Editor window.

Go To Definition from codeunit.RUN function

If the system function is called on any other object type variable, then the object is opened in the corresponding designer. For any other system function that is not called on an object variable, nothing occurs.

Object Variable from the C/AL Editor

From the C/AL Editor, right-click a variable that is one of the following object types, and then choose Go To Definition:

  • Record

  • Page

  • Report

  • Codeunit

  • XMLport

  • Query

Go To Definition from Record variable

The object is opened in the corresponding designer:

  • Table Designer

  • Page Designer

  • Report Dataset Designer

  • C/AL Editor

  • XMLport Designer

  • Query Designer

Go To Definition from Record variable

Permissions

To go to a definition, you must have the correct permissions. If you do not have permission to view the definition of an object by selecting the object in Object Designer and then choosing Design, then you cannot view it with the Go To Definition option.


Locking and Unlocking Objects

You can lock an object in Object Designer so that other developers cannot save design changes to the object. After you lock an object, the Locked field in Object Designer is selected, and the Locked By column shows the user who locked the object.

When an object is locked, another user can still do the following:

  • Open the object in the designer, make changes, and compile the object. However, another user cannot save the object. The locked object is marked as Read Only when another user opens it in the designer.

  • Run the object. For example, a user can run a table and can add or delete records in the table even if it is locked for design changes.

When you finish making design changes to an object, you can unlock it in Object Designer. The Locked and Locked By fields are cleared, and other users can now lock the object or save changes to the object.

You can select one object or multiple objects at the same time to lock or unlock. You can also set the Auto-Lock on Design option to automatically lock all objects that you open for designing.

Object Table

The information in the Locked and Locked By columns is stored in table 2000000001, the Object table. The Object table is a system table that stores information about objects in the application.

Concurrency Considerations

Even though you can lock objects, it is still possible for developers to have concurrency issues, as shown in the following examples.

  • A developer opens an object in the designer but does not lock it. The developer makes several changes to the object and saves the changes periodically. At the same time, a second developer locks the object, and the first developer cannot save design changes to the object. The first developer gets an error message that the object is locked by the second developer.

  • A developer locks an object. A second developer opens the locked object in read-only mode, and then the first developer unlocks the object. The second developer still cannot save design changes to the object even though the object is now unlocked because it is open in read-only mode.

See Also

Tasks

How to: Lock an Object
How to: Unlock an Object


How to: Lock an Object

You can lock objects so that other developers cannot save changes to the objects. You can either lock objects manually, or you can set an option so that all objects that you open for design are locked.

To manually lock an object

  1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, select one or more objects that are not already locked, and then do one of the following steps:

    • Right-click the object or objects, and then choose Lock.

    • On the File menu, choose Lock.

    • Press Ctrl+Alt+L.

To automatically lock all objects that you open for design

  1. In the development environment, on the Tools menu, choose Options.

  2. In the Options window, in the Auto-Lock on Design field, enter Yes, and then choose OK.

    Tip
    You cannot automatically unlock objects that you have locked. However, you can filter for locked objects, select all objects that you have locked, and then unlock these objects. For more information, see How to: Unlock an Object.

    Note
    If you go to the definition of an object, then the object is opened in design mode. Therefore, if you set the Auto-Lock on Design field and then go to the definition of an object, then the object is locked. For more information, see Viewing the Definition of a Function or Object by Using Go To Definition.

See Also

Tasks

How to: Unlock an Object

Concepts

Locking and Unlocking Objects


How to: Unlock an Object

You can lock and unlock objects to prevent other developers from making changes while you work with those objects. If you lock an object, then only you can save changes to the object. After you save your changes, you unlock the object so that other developers can make changes to that object.

In some cases, a system administrator may need to force unlock an object. For example, if a user locks an object and then cannot unlock the object because of a holiday or other absence, then the system administrator can force unlock the object. To force unlock an object, the system administrator must have the SUPER user permission set.

In some cases, you may want to unlock all objects that you have locked. To do this, you can filter on locked objects, select all objects that you have locked, and then unlock these objects.

To unlock an object

  1. In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, select one or more objects that you have locked, and then do one of the following steps:

    • Right-click the object or objects, and then choose Unlock.

    • On the File menu, choose Unlock.

    • Press Ctrl+Alt+U.

To force unlock an object

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, select one or more objects that you want to force unlock, and then do one of the following steps:

    • Right-click the object or objects, and then choose Force Unlock.

    • On the File menu, choose Force Unlock.

  3. Confirm that you want to force unlock the object.

    Note
    You must have the SUPER user permission set to force unlock an object.

To unlock all objects that you have locked

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose All.

  3. On the View menu, choose Table Filter.

  4. In the Table Filter window, enter Locked By in the Field field, enter your user name in the Filter field, and then choose OK.

  5. On the Edit menu, choose Select All, and then do one of the following steps:

    • Right-click the object or objects, and then choose Unlock.

    • On the File menu, choose Unlock.

    • Press Ctrl+Alt+U.

See Also

Tasks

How to: Lock an Object

Concepts

Locking and Unlocking Objects


Object Specifications and Limitations

This topic describes the specifications and limitations for the database and application objects.

Specifications for the database

Feature | Characteristic
Maximum number of physical disk files | 16
Database file size | 256 GB
Maximum number of objects in a database | 1,000,000,000
Maximum number of characters in application object names | 30
Maximum number of characters in a Database Authentication password | 80

Specifications for Tables

Feature | Characteristic
Range for table object ID numbers | 1 - 999,999,999 1
Maximum number of characters in a table name | 30
Maximum table size | Depends on available storage
Maximum number of records in a table | Depends on available storage
Maximum record size | 8000 bytes
Maximum number of fields in a record | 500
Range for field numbers | 1 - 999,999,999
Maximum number of keys for a table | 40
Maximum size of a Microsoft Dynamics NAV key | 900 bytes
Maximum number of distinct fields per key | 16
Maximum size of an index | 900 bytes
Maximum number of SumIndexFields per key | 20
Maximum number of characters in a text or code field | 250
Maximum size of a BLOB field | 2 GB
Maximum number of characters in a field name | 30

Specifications for Pages and Reports

Feature | Characteristic
Range for page or report object ID numbers | 1 - 999,999,999 1
Maximum number of characters in a caption | 1024
Maximum bitmap size in bitmap property | 32500 bytes

Specifications for Codeunits

Feature | Characteristic
Range for table object ID numbers | 1 - 999,999,999 1
Maximum number of characters in variable names | 30
Maximum number of dimensions in array variables | 10
Maximum number of elements in an array variable | 1,000,000
Maximum physical size of a codeunit | 2 GB
Lower bound of index in an array | 1

1All application objects are identified by an ID number. There are restrictions, however, on the numbers you can use when you create your own application objects. Review your Partner License Agreement for more information.

See Also

Reference

Field Data Types

Concepts

Objects

Other Resources

Maximum Capacity Specifications for SQL Server


Displaying Charts Using the Chart Control Add-in

In Microsoft Dynamics NAV, you can graphically represent data in charts that you can display in the Microsoft Dynamics NAV Windows client. Microsoft Dynamics NAV supports several chart types, such a line charts, bar charts, and pie charts. With the basic chart feature of Microsoft Dynamics NAV, you can retrieve data from a table or using query and render the data in a single chart type, such as a line or bar graph. There might be scenarios for which you want to display data that does not fit the model of the basic chart feature. For example, you might want to display data that is calculated on a page, or you might want to render data different measures using different chart types. For these cases, Microsoft Dynamics NAV includes the Business Chart control add-in. With the Microsoft Dynamics NAV, you can create custom charts for displaying complex data on a Microsoft Dynamics NAV Windows client page.

For an example of a chart that uses the Business Chart control add-in, see Cash Flow Chart Example.

Business Chart Design Concept and Components

Business Chart Control Add-in Assembly

The Business Chart control add-in is provided by the Microsoft.Dynamics.Nav.Client.BusinessChart.dll assembly. The Business Chart control add-in is a Microsoft .NET Framework object that creates the user interface of a chart on page and populates the chart with data from C/AL code.

The assembly is installed on the computer running the Microsoft Dynamics NAV Windows client. By default the assembly is located in the C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client\Add-ins\BusinessChart folder.

The Business Chart control add-in assembly includes an API that you can use to call methods and properties from C/AL code to build your chart.

Business Chart Buffer Table

Table 485 Business Chart Buffer is a default table that is available with the Microsoft Dynamics NAV demo database. The purpose of the Business Chart Buffer table is to separate the chart data from the page. The Business Chart Buffer table temporarily holds the data for building a chart, such as the chart type, measures, and labels. The table uses Microsoft .NET Framework interoperability to reference types in the System.Data assembly for building a data table that contains the chart data. To generate a chart, the page that contains the Business Chart control add-in retrieves data from the Business Chart Buffer table and passes the data to the Business Data Chart control add-in.


Cash Flow Chart Example

This code example demonstrates how to use the Business Data Chart control add-in to create a chart that displays a cash flow forecast as shown in the following figure:

Shows a cash flow chart

The cash flow forecast chart combines the current bank balances with the outstanding receivables and payables, and displays the data for the next six days, including the current day. The chart displays data for four measures: Accounts Receivable, Accounts Payable, Forecasted Balance, and Credit Limit in Banks. The data for the measures is displayed using the following chart types: stacked column, line, and step line.

The chart is interactive. When you choose a data point, a list appears that shows overdue customer ledger entries, vendor ledger entries, or bank accounts.

Cash Flow Chart Design

The chart is designed around enhanced performance, testability, and code reuse. The chart design separates the business logic and data handling from the chart rendition on the page. This improves performance because you can run the business logic on the computer running the Microsoft Dynamics NAV Server instead of the Microsoft Dynamics NAV Windows client and limit the data calls between the client and server. The cash flow chart uses Microsoft .NET Interoperability to call Microsoft .NET Framework types from Microsoft Dynamics NAV objects to build the chart and populate it with data.

The following figure illustrates the Microsoft Dynamics NAV objects that are used to create the cash flow chart.

Cash Flow chart design

Page 50000 Demo Cash Flow Chart contains the Business Data Chart control add-in that renders the chart user-interface on the page. The Business Data control add-in is defined by the Microsoft.Dynamics.Nav.Client.BusinessChart assembly that is available by default in the Microsoft Dynamics NAV installation.

Table 485 Business Chart Buffer temporarily holds the data for building the cash flow chart, such as the chart type, measures, and labels. The data is retrieved by page 50000 and passed to the Business Data Chart control add-in. Table 485 is a default table that is available with the Microsoft Dynamics NAV demo database. The table uses Microsoft .NET Framework interoperability to reference types in the System.Data assembly for building a data table that contains the chart data. You can use this table with other charts that are built on the Business Data control add-in.

Codeunit 50000 Demo Cash Flow Chart Mgt. contains the business logic for the cash flow chart and generates the data that is displayed in the chart.

Creating the Page for Displaying the Chart

The following code creates a CardPart type page that includes the Business Data Chart control add-in and the C/AL for displaying data. To create the page, copy the code to a text file, and then, in the Microsoft Dynamics NAV development environment, import the text file. After you create the page, you can use it in the Microsoft Dynamics NAV Windows client. For example, you can add it in a part on the Role Center page.

Copy Code
OBJECT Page 50000 Demo Cash Flow Chart
{
  OBJECT-PROPERTIES
  {
    Date=18-04-12;
    Time=15:57:04;
    Modified=Yes;
    Version List=;
  }
  PROPERTIES
  {
  }
  CONTROLS
  {
    { 1   ;    ;Container ;
                Name=Content;
                ContainerType=ContentArea }
    { 2   ;1   ;Field     ;
                Name=Chart;

ControlAddIn=[Microsoft.Dynamics.Nav.Client.BusinessChart;PublicKeyToken=31bf3856ad364e35] }
  }
  CODE
  {
    VAR
      BusinessChartBuffer@1000 : Record 485;
      DemoCashFlowChartMgt@1001 : Codeunit 50000;
    LOCAL PROCEDURE UpdateChart@2();
    BEGIN
      DemoCashFlowChartMgt.GenerateData(BusinessChartBuffer);
      BusinessChartBuffer.Update(CurrPage.Chart);
    END;
    EVENT Chart@-2::DataPointClicked@12(point@1000 : DotNet "'Microsoft.Dynamics.Nav.Client.BusinessChart.Model, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.Microsoft.Dynamics.Nav.Client.BusinessChart.BusinessChartDataPoint");
    BEGIN
      BusinessChartBuffer.SetDrillDownIndexes(point);
      DemoCashFlowChartMgt.OnDataPointClicked(BusinessChartBuffer);
    END;
    EVENT Chart@-2::DataPointDoubleClicked@13(point@1000 : DotNet "'Microsoft.Dynamics.Nav.Client.BusinessChart.Model, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.Microsoft.Dynamics.Nav.Client.BusinessChart.BusinessChartDataPoint");
    BEGIN
    END;
    EVENT Chart@-2::AddInReady@14();
    BEGIN
      UpdateChart;
    END;
    BEGIN
    END.
  }
}

Understanding the Page Code

The following list explains some of the page’s C/AL code:

  • The page includes a single field that has its ControlAddin Property set to the Microsoft.Dynamics.Nav.Client.BusinessChart assembly, which defines the Business Data Chart control add-in.

  • The Update function populates the chart with data from the Business Chart Buffer table. The Chart - AddinReady trigger calls the Update function when the Business Chart control add-in is loaded and ready on the page. Depending on your scenario, you could also call the Update function on the OnAfterGetRecord trigger, OnFind trigger, or on an action.

  • The business logic has been isolated in codeunit 50000 Demo Cash Flow Chart Mgt. The page includes the Business Chart Buffer record variable that references table 485 Business Chart Buffer. The Business Chart Buffer record variable holds the chart data and updates the control add-in when it is passed into the function Update. Note that we pass on CurrPage.Chart, for example, the chart add-in to the function. The Microsoft.Dynamics.Nav.Client.BusinessChartData object is defined by a DotNet variable. The DotNet variable for the BusinessChartData object is configured to instantiate on the computer running the Microsoft Dynamics NAV Server. This populates the object with data and properties without having the server calling the client. After the chart data has been generated, it is delivered to the Business Data chart control add-in in a single call. The data that is transferred between the Microsoft Dynamics NAV Server and the Microsoft Dynamics NAV Windows client is automatically serialized. For more information, see Serializing .NET Framework Types.

  • The OnDataPointClicked trigger is called when you choose a data point or column in the cash flow chart. Depending on the data point or column that you choose, a list page appears that shows overdue customer ledger entries, vendor ledger entries or bank accounts. To improve code testability, the drill-down logic for the OnDataPointClicked trigger is called from codeunit 50000 Demo Cash Flow Chart Mgt. This construction allows you to test the data generation and drill-down from code by calling functions on the codeunit.

Creating the Codeunit for Handling Data

The following code creates codeunit 50000 Demo Cash Flow Chart Mgt. To create the codeunit, copy the code to a text file, and then, in the development environment, import the text file.

Copy Code
OBJECT Codeunit 50000 Demo Cash Flow Chart Mgt.
{
  OBJECT-PROPERTIES
  {
    Date=18-04-12;
    Time=16:11:09;
    Modified=Yes;
    Version List=Charts;
  }
  PROPERTIES
  {
    OnRun=BEGIN
          END;
  }
  CODE
  {
    VAR
      TextCust@1000 : TextConst 'ENU=Accounts Receivable';
      TextVend@1001 : TextConst 'ENU=Accounts Payable';
      TextBank@1002 : TextConst 'ENU=Bank Balances';
      TextTotal@1003 : TextConst 'ENU=Forecasted Balance';
      TextCredit@1004 : TextConst 'ENU=Credit Limit in Banks';
      TextDate@1005 : TextConst 'ENU=Date';
    PROCEDURE OnInitPage@6(VAR BusChartBuf@1000 : Record 485);
    BEGIN
    END;
    PROCEDURE GenerateData@3(VAR BusChartBuf@1000 : Record 485);
    VAR
      i@1007 : Integer;
      BankBalance@1006 : Decimal;
      CustNetChange@1005 : Decimal;
      VendNetChange@1004 : Decimal;
      TotalBalance@1003 : Decimal;
      BalanceDate@1002 : Date;
      BankCreditLimit@1001 : Decimal;
    BEGIN
      WITH BusChartBuf DO BEGIN
        Initialize;
        AddMeasure(TextCust,1,"Data Type"::Decimal,"Chart Type"::StackedColumn);
        AddMeasure(TextVend,2,"Data Type"::Decimal,"Chart Type"::StackedColumn);
        AddMeasure(TextTotal,3,"Data Type"::Decimal,"Chart Type"::Line);
        AddMeasure(TextCredit,4,"Data Type"::Decimal,"Chart Type"::StepLine);
        SetXAxis(TextDate,"Data Type"::DateTime);
        BalanceDate := WORKDATE - 1; // demo. Should be TODAY.
        CalcBankBalance(BalanceDate,TotalBalance,BankCreditLimit);
        FOR i := 1 TO 6  DO BEGIN  //  Generate 6 columns
          CustNetChange := CalcCustNetChange(BalanceDate,BalanceDate);
          VendNetChange := CalcVendNetChange(BalanceDate,BalanceDate);
          TotalBalance := TotalBalance + CustNetChange + VendNetChange;
          AddPeriodColumn(BalanceDate);  // X-Axis value
          SetValueByIndex(1 - 1,i - 1,CustNetChange); // zero indexed.
          SetValueByIndex(2 - 1,i - 1,VendNetChange);
          SetValueByIndex(3 - 1,i - 1,TotalBalance);
          SetValueByIndex(4 - 1,i - 1,BankCreditLimit);
          BalanceDate := BalanceDate + 1;
        END;
      END;
    END;
    PROCEDURE OnDataPointClicked@5(VAR BusChartBuf@1000 : Record 485);
    VAR
      VendLedgEntry@1001 : Record 25;
      DrillDownDate@1000000001 : Date;
    BEGIN
      DrillDownDate := WORKDATE + BusChartBuf."Drill-Down X Index" + 1; // ref. first balance date in GenerateData function
      CASE BusChartBuf."Drill-Down Measure Index" + 1 OF
        1 : // Customer
          DrillDownCust(DrillDownDate);
        2 : // Vendor
          DrillDownVend(DrillDownDate);
        4 : // Bank Credit limits
          DrillDownBank;
      END;
    END;
    LOCAL PROCEDURE CalcCustNetChange@1(FromDate@1000 : Date;ToDate@1001 : Date) : Decimal;
    VAR
      CustLedgEntry@1002 : Record 21;
      TotalRemainingAmount@1003 : Decimal;
    BEGIN
      WITH CustLedgEntry DO BEGIN
        SETCURRENTKEY(Open,"Due Date");
        SETRANGE(Open,TRUE);
        SETRANGE("Due Date",FromDate,ToDate);
        IF FIND('-') THEN
          REPEAT
            CALCFIELDS("Remaining Amt. (LCY)");
            TotalRemainingAmount := TotalRemainingAmount + "Remaining Amt. (LCY)";
          UNTIL NEXT = 0;
      END;
      EXIT(TotalRemainingAmount);
    END;
    LOCAL PROCEDURE CalcVendNetChange@4(FromDate@1000 : Date;ToDate@1001 : Date) : Decimal;
    VAR
      VendLedgEntry@1002 : Record 25;
      TotalRemainingAmount@1003 : Decimal;
    BEGIN
      WITH VendLedgEntry DO BEGIN
        SETCURRENTKEY(Open,"Due Date");
        SETRANGE(Open,TRUE);
        SETRANGE("Due Date",FromDate,ToDate);
        IF FIND('-') THEN
          REPEAT
            CALCFIELDS("Remaining Amt. (LCY)");
            TotalRemainingAmount := TotalRemainingAmount + "Remaining Amt. (LCY)";
          UNTIL NEXT = 0;
      END;
      EXIT(TotalRemainingAmount);
    END;
    LOCAL PROCEDURE CalcBankBalance@7(EndDate@1000 : Date;VAR TotalBalance@1003 : Decimal;VAR BankCreditLimit@1002 : Decimal);
    VAR
      BankAcc@1001 : Record 270;
    BEGIN
      WITH BankAcc DO BEGIN
        SETFILTER("Date Filter",'..%1',EndDate);
        IF FIND('-') THEN
          REPEAT
            CALCFIELDS("Balance at Date (LCY)");
            TotalBalance := TotalBalance + "Balance at Date (LCY)";
            BankCreditLimit := BankCreditLimit + BankAcc."Min. Balance";
          UNTIL NEXT = 0;
      END;
    END;
    LOCAL PROCEDURE DrillDownCust@1000000002(DrillDownDate@1000000000 : Date);
    VAR
      CustLedgEntry@1000000001 : Record 21;
    BEGIN
      CustLedgEntry.SETRANGE(Open,TRUE);
      CustLedgEntry.SETRANGE("Due Date",DrillDownDate,DrillDownDate);
      PAGE.RUNMODAL(PAGE::"Customer Ledger Entries",CustLedgEntry);
    END;
    LOCAL PROCEDURE DrillDownVend@1000000004(DrillDownDate@1000000000 : Date);
    VAR
      VendLedgEntry@1000000001 : Record 25;
    BEGIN
      VendLedgEntry.SETRANGE(Open,TRUE);
      VendLedgEntry.SETRANGE("Due Date",DrillDownDate,DrillDownDate);
      PAGE.RUNMODAL(PAGE::"Vendor Ledger Entries",VendLedgEntry);
    END;
    LOCAL PROCEDURE DrillDownBank@1000000005();
    BEGIN
      PAGE.RUNMODAL(PAGE::"Bank Account List");
    END;
    BEGIN
    END.
  }
}

Understanding the GenerateData Function

Codeunit 50000 accesses data in the Cust. Ledger Entry table, the Vender Ledger Entry table, and the Bank Account table. The GenerateData function generates the data for the cash flow chart. The following figure shows the C/AL code for the GenerateData function and how it maps to the cash flow chart user interface.

Shows the C/AL for the Flow Chart codeunit

The C/AL code sets the characteristics of the cash flow chart, including measure labels, chart types, and more. The functions that are called in GenerateData function are defined in table 485 Business Chart Buffer. The following table describes the functions of the Business Chart Buffer table that you can use for defining the chart.

Function | Description | Example
AddMeasure(Caption,ValueIndex,ValueType,ChartType) | Sets the label and type for the measure. | AddMeasure('Acc. Receivables',1,"Data Type"::Decimal,"Chart Type"::StackedColumn);
SetXAxis(Caption,Type) | Sets the x-axis caption and value. | SetXAxis('Date',"Data Type"::DateTime);
SetXAxisCaption(Caption) | Sets the x-axis name. | SetXAxisCaption('Due Date');
SetValueByIndex(MeasureIndex0,Xindex0,Value) | Sets the data point value in the chart. 0-based indexing. | SetValueByIndex(0,0,CustNetChange);
SetDrillDownIndexes(point) | DataPointClicked | SetDrillDownIndexes(point);

Understanding the Drill-down Logic of the OnDataPointClicked Function

When you choose a data point or column in the cash flow chart, a list page appears that shows due customer ledger entries, vendor ledger entries, or bank accounts. To accomplish this, the OnDataPointClicked event trigger on page 50000 Demo Cash Flow Chart is passed to the point object as a parameter. The point can then be passed on to the SetDrillDownIndexes(point) function that updates the Drill-Down X Index and Drill-Down Measure Index fields on the record. You use the Drill-Down X Index and Drill-Down Measure Index fields to retrieve the x-axis value and measure value for filtering the list that you want to display. The following figure shows the C/AL code on the OnDataPointClicked function.

Shows the C/AL code on OnDataPointClicked function

The OnDataPointClicked function calls the DrillDownCust function, DrillDownVend function, and DrillDownBank function, which are shown in the following figure.

Shows the drill-down functions used by chart

See Also

Concepts

Displaying Charts Using the Chart Control Add-in


How to: Specify the Start ID Offset of Elements on Objects

You can specify a start ID for new objects so that elements on these new objects have IDs that are offset by the number that you specified. For example, you can specify a start ID of 1000 and then create a new page. The first element that you create on the page, for example, a Container control, has ID 1000. The next element that you create on the page, for example, a Group control, has ID 1001. The ID of each element on the page is incremented by 1, starting with the offset that you specified. If you create variables or text constants on the page, then the first variable or text constant has ID 1000. The ID of each variable or text constant that you create is incremented by 1, starting with the offset that you specified. If you create functions on the page, then they start with ID 1000. Parameters, return value, local variables, and local text constants of a function start with ID 1000.

Note
In earlier versions of Microsoft Dynamics NAV, you specified the start ID offset by using the GetUidOffset function in codeunit 1.

You can use the start ID to identify a set of elements in your application, for example, to identify the elements in a country/region-specific version. When you merge changes from different country/region-specific versions, having different start IDs lets you easily identify the country/region-specific version for each element.

If you do not specify a start ID, then the IDs are determined by your license.

To specify the start ID

  1. In the development environment, on the File menu, choose Database, and then choose Alter.

  2. In the Alter Database window, select the Advanced tab.

  3. On the Advanced tab, under Designer, in the Start ID (UidOffset) text box, enter an integer, and then choose the OK button.

    Important
    We recommend that you specify a start ID that is greater than or equal to 1000. If you specify a start ID that is less than 1000, then variables and text constants on the object have a starting offset of 1000, not the value that you specified. Other elements on the object have the starting offset that you specified.

  4. Create a new table, page, report, codeunit, query, or XMLport. The IDs of the elements on that object are offset by the number that you specified.

    Note
    To view the ID of an element, select the element in the designer, and then on the View menu, choose Properties.

See Also

Concepts

Altering Databases - Advanced Tab


Web Services

The following sections provide an overview of the documentation for web services in Microsoft Dynamics NAV 2016.

Overview of Microsoft Dynamics NAV Web Services

This section provides overview material and information that is relevant to both SOAP and OData web services.

To | See
Compare the features and constraints of SOAP and OData web services. | Web Service Alternatives: SOAP and OData
Create and publish a web service. | How to: Publish a Web Service
Avoid issues that may occur when Microsoft Dynamics NAV pages expect user interaction. | Handling UI Interaction When Working with Web Services
Coordinate web service applications across multiple time zones. | Managing Time Zones with Web Services
Avoid data loss that can be caused by out-of-date proxies. | Preserving Data When Working with a Statically Generated Proxy
Implement policies to make your web services easier to understand and maintain. | Web Services Best Practices

SOAP Web Services

The topics in this section describe how to create and maintain SOAP web services.

To | See
Review the different options for creating URIs to interact with SOAP web services. | SOAP Web Service URIs
Review the operations that are available when a page is exposed as a web service. | Basic Page Operations
Learn how to write code that provides a list of existing companies in a Microsoft Dynamics NAV database. | How to: Use SystemService to Find Companies
Ensure that field values are actually updated from web services. | Using Properties with Visual Studio to Indicate the Presence of a Value in a Field

OData Web Services

The topics in this section describe how to create and maintain OData web services.

To | See
Use OData to obtain an AtomPub document. | How to: Use OData to Return/Obtain an AtomPub Document
Use OData to obtain a service metadata (EDMX) document. | How to: Use OData to Return/Obtain a Service Metadata (EDMX) Document
Use OData to obtain a JavaScript Object Notation (JSON) document. | How to: Use OData to Return/Obtain a JSON Document
Write to the database through an OData web service that exposes a writable page | Using OData Web Services to Modify Data
Use filter expressions in OData URIs. | Using Filter Expressions in OData URIs
Use FlowFilters in OData URIs. | How to: Use FlowFilters in OData URIs
Use server-driven paging in OData URIs. | Server-Driven Paging in OData Web Services

Web Services Walkthroughs

The topics in this section demonstrate how to implement Microsoft Dynamics NAV web services.

To | See
Create an extension codeunit for an existing page, expose the page, and then write code that calls the page. | Walkthrough: Creating a Web Service using Extension Codeunits (SOAP)
Create and consume a simple codeunit web service. | Walkthrough: Creating and Using a Codeunit Web Service (SOAP)
Create and consume a page as a SOAP web service. | Walkthrough: Registering and Using a Page Web Service (SOAP)
Create and consume a page as an OData web service. | Walkthrough: Creating and Interacting with a Page Web Service (OData)
View and analyze Microsoft Dynamics NAV page data in Microsoft Excel using Microsoft PowerPivot for Excel, which is a data analysis add-in. | Walkthrough: Viewing Page Data in Excel Using PowerPivot (OData)
Make web service communication more secure. | Walkthrough: Configuring Web Services to Use SSL (SOAP and OData)
Combine data from Microsoft Dynamics NAV 2016 with data from Microsoft Azure Marketplace. | Walkthrough: Combining Data from Microsoft Dynamics NAV Queries and Pages with Data from Azure DataMarket (OData)


Web Service Alternatives: SOAP and OData

Microsoft Dynamics NAV supports OData web services in addition to the SOAP web services that have been available since Microsoft Dynamics NAV 2009. Developers planning to create Microsoft Dynamics NAV web services may need to decide which type of web service is better suited to their needs. First, there are some absolute limitations:

  • It is not currently possible to access Microsoft Dynamics NAV query objects with SOAP web services. See Queries for information about Microsoft Dynamics NAV queries.

  • It is not currently possible to access codeunits with OData web services.

SOAP Web Services

SOAP web services allow full flexibility for building operation-centric services. They provide industry standard interoperability. Windows Communication Framework (WCF) has supported SOAP services since its initial release in .NET Framework 3.0, and later releases of the .NET Framework have added additional support and default bindings to make it easier to build SOAP services using WCF.

The most common type of messaging pattern in SOAP is the Remote Procedure Call (RPC), where one network node (the client) sends a request message to another node (the server), and the server sends a response message to the client.

OData Web Services

The OData standard is well suited for web service applications that require a uniform, flexible, general purpose interface for exposing create retrieve update delete (CRUD) operations on a tabular data model to clients. OData is less suited for applications that are primarily RPC-oriented or in which data operations are constrained to certain prescribed patterns. OData supports Representational State Transfer (REST)-based data services, which enable resources, identified using Uniform Resource Identifiers (URIs), and defined in an abstract data model (EDM), to be published and edited by web clients within corporate networks and across the Internet using simple Hypertext Transfer Protocol (HTTP) messages. OData services are lightweight, with functionality often referenced directly in the URI.

Whereas SOAP web services expose a WSDL document, OData web services expose an EDMX document containing metadata for all published web services.

OData is supported in PowerPivot, a data-analysis add-in to Microsoft Excel that provides enhanced Business Intelligence capabilities. PowerPivot supports sharing and collaboration on user-generated business intelligence solutions in a Microsoft SharePoint Server environment. For more information about PowerPivot, see http://www.powerpivot.com/.

The extensions to the Atom Publishing Protocol defined in the AtomPub extensions to the OData protocol documentation (which you can download here) describe how REST-based data services can enable resources, identified using URIs and defined in an abstract data model (EDM), to be published and edited by web clients within corporate networks and across the Internet using simple HTTP messages.

In addition to the AtomPub format, the OData implementation in Microsoft Dynamics NAV 2016 also supports the JSON format, a somewhat less verbose format that may perform better in low-bandwidth environments.

See Also

Concepts

Microsoft Dynamics NAV Web Services Overview
OData Web Services
SOAP Web Services

© 2015 Microsoft. All rights reserved.

Build Date:

2015-08-27


How to: Publish a Web Service

Web services are a lightweight way to make application functionality available to a variety of external systems and users. In Microsoft Dynamics NAV, you can expose pages, codeunits, and queries as web services. When you publish Microsoft Dynamics NAV objects as web services, they are immediately available on the network.

You can set up a web service in the Microsoft Dynamics NAV Windows client or the Microsoft Dynamics NAV Web client. You must then publish the web service so that it is available to service requests over the network. Users can discover web services by pointing a browser at the computer that is running Microsoft Dynamics NAV Server and requesting a list of available services. When you publish a web service, it is immediately available over the network for authenticated users. All authorized users can access metadata for Microsoft Dynamics NAV web services, but only users who have sufficient Microsoft Dynamics NAV permissions can access actual data.

Creating and Publishing a Web Service

The following steps explain how to create and publish a web service.

To create and publish a web service

  1. Open the Microsoft Dynamics NAV Windows client or the Microsoft Dynamics NAV Web client.

  2. In the Microsoft Dynamics NAV Windows client, in the Search box, enter Web Services, and then choose the related link.

    In the Microsoft Dynamics NAV Web client, choose the Search for Page or Report button, enter Web Services, and then choose the related link.

  3. In the Web Services page, choose New.

  4. In the Object Type column, select Codeunit, Page, or Query.

    Note
    Codeunit and Page are valid types for SOAP web services. Page and Query are valid types for OData web services.

  5. In the Object ID column, select the object ID of the object that you want to expose. For example, to expose the customer card as a web service, enter 21.

    If the database contains multiple companies, you can choose an object ID that is specific to one of the companies.

  6. In the Service Name field, assign a name to the web service. For example, if you expose the customer card as a web service, enter Customers.

    Note
    The service name is visible to consumers of your web service and is the basis for identifying and distinguishing web services, so you should make the name meaningful. If you are setting up integration with Microsoft Outlook using codeunit 5313, then you must use DynamicsNAVsynchOutlook as the service name.

  7. Select the check box in the Published column.

    When you publish the web service, in the OData URL and SOAP URL fields, you can see the URLs that are generated for the web service. You can test the web service immediately by choosing the links in the OData URL and SOAP URL fields. Optionally, you can copy the value of the field and save it for later use.

After you publish a web service, it is available on the Microsoft Dynamics NAV Server computer that you were connected to when you published. The web service is available across all Microsoft Dynamics NAV Server instances running on the server computer.

You can verify the availability of that web service by using a browser, or you can choose the link in the OData URL and SOAP URL fields in the Web Services window. The following procedure illustrates how you can verify the availability of the web service for later use.

To verify the availability of a web service

  1. In your browser, enter the relevant URL. The following table illustrates the types of URLs that you can enter. For SOAP web services, use the following format for your URI.

    Web service type Syntax Example

    SOAP

    https://Server:SOAPWebServicePort/ServerInstance/WS/CompanyName/services/

    https://localhost:7047/DynamicsNAV90/WS/CRONUS International Ltd./services/

    OData

    https://Server:ODataWebServicePort/ServerInstance/OData/Company('CompanyName')

    https://localhost:7048/DynamicsNAV90/OData/Company('CRONUS International Ltd.')

    The company name is case-sensitive.

  2. Review the information that is displayed in the browser. Verify that you can see the name of the web service that you have created.

When you access a web service, and you want to write data back to Microsoft Dynamics NAV, you must specify the company name. You can specify the company as part of the URI as shown in the examples, or you can specify the company as part of the query parameters. For example, the following URIs point to the same OData web service and are both valid URIs.

Copy Code
https://localhost:7048/DynamicsNAV90/OData/Company('CRONUS International Ltd.')/Customer
Copy Code
https://localhost:7048/DynamicsNAV90/OData/Customer?company='CRONUS International Ltd.'

See Also

Web Services

Concepts

Web Service Walkthroughs


Handling UI Interaction When Working with Web Services

Whether you are publishing or consuming web services, exceptions and dialog boxes that may be displayed while code runs must be handled correctly. Exceptions must be handled to prevent the system from ending the web service client execution. You can handle exceptions in the following ways:

  • Writing conditional code inside Microsoft Dynamics NAV.

  • Writing the code in the web service client application.

The most robust solution is to use both methods.

Publishing Web Services

When publishing a web service, you must make sure that the code that you are publishing does not assume the ability to interact with a user through the UI. You can use the GUIALLOWED Function to suppress the UI. For example, you can use this function to determine whether a codeunit is being called from the RoleTailored client or from a web service client. You must make sure to suppress errors when a codeunit is called from a web service client.

When implementing a conditional code check in Microsoft Dynamics NAV, you should implement the check only around code that could cause an error. You should not encapsulate the whole business logic.

Note
The server returns the following exception when trying to invoke a dialog UI through a web service: Microsoft.Dynamics.Nav.Types.Exceptions.NavNCLCallbackNotAllowedException: Callback functions are not allowed.

C/AL Keywords That Can Cause Faults or Exceptions

Variables of the Dialog Data Type or any of the functions listed as dialog functions can cause callback not allowed exceptions when they are called from a web service application. The MESSAGE Function (Dialog) is the only function in this category that does not cause an exception.

Other keywords that you should not use are:

  • PAGE.RUN

  • PAGE.RUNMODAL

  • ACTIVATE

  • REPORT.RUN

  • REPORT.RUNMODAL

  • HYPERLINK

  • FILE.UPLOAD

  • FILE.DOWNLOAD

You should also avoid operations on client-side Automation and .NET Framework interoperability objects.

Consuming Web Services

You must handle exceptions in client code that calls a Microsoft Dynamics NAV web service. Appropriate exception capturing code should be included around any call to a Microsoft Dynamics NAV web service.

See Also

Tasks

How to: Publish a Web Service

Concepts

Microsoft Dynamics NAV Web Services Overview


Managing Time Zones with Web Services

Microsoft Dynamics NAV Server provides a Services Default Time Zone setting for defining the time zone in which web service calls run. This setting affects both SOAP and OData web services, in addition to NAS Services.

Time Zone Configuration

You can configure the Services Default Time Zone using the Microsoft Dynamics NAV Server Administration Tool, Microsoft Dynamics NAV Windows PowerShell Cmdlets, or by directly editing CustomSettings.config, the configuration file for the relevant Microsoft Dynamics NAV Server instance. The following table describes the possible values for the Services Default Time Zone setting.

Value | Description
UTC | Specifies that all business logic for services on the server instance runs in Coordinated Universal Time (UTC). This is the default value. This is how web services business logic was handled in Microsoft Dynamics NAV 2009 SP1 and Microsoft Dynamics NAV 2009.
Server Time Zone | Specifies that services use the time zone of the computer that is running Microsoft Dynamics NAV Server.
ID of any Windows time zone | Specifies that services use a Windows time zone as defined in the system registry under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones. For example, Romance Standard Time is a valid Windows time zone value.

When a web service writes data back to Microsoft Dynamics NAV, dates and times are based on the setting of the Services Default Time Zone setting. However, the web service consumer can override the setting and specify a different time zone.

Note
Microsoft Dynamics NAV Server stores dates and times as UTC. When a web service receives data from Microsoft Dynamics NAV Server, the time zone is UTC even if the Services Default Time Zone setting is set to a different time zone.

For example, if the Services Default Time Zone setting is set to UTC+3, the following table describes two scenarios where a web service consumer modifies Microsoft Dynamics NAV data and sends this back to Microsoft Dynamics NAV Server.

Web service changes the DateTime field to | Microsoft Dynamics NAV Server interprets the DateTime value as | Microsoft Dynamics NAV Server saves the DateTime value as
01/01/2014 17:00 UTC+1 | 01/01/2014 17:00 UTC+1 | 01/01/2014 16:00 UTC
01/01/2014 17:00 | 01/01/2014 17:00 UTC+3 | 01/01/2014 14:00 UTC

See Also

Concepts

Communicating with Microsoft Dynamics NAV Clients in Different Time Zones
Microsoft Dynamics NAV Server Administration Tool
Microsoft Dynamics NAV Windows PowerShell Cmdlets


Preserving Data When Working with a Statically Generated Proxy

You can lose data if you develop a web service client that interacts with a statically generated proxy. Similarly, a client web service cannot detect if a field has been added to or removed from a page since a proxy was last generated. This topic describes an approach for avoiding this pitfall.

Avoiding Data Loss by Building the Proxy with Your Client Application

To avoid data loss due to a statically generated proxy, automatically generate your proxy whenever you build your client.

Assume you have published page 21, Customer Card, as a SOAP web service with Customer as the Service Name value. Add a service reference to this web service from a C# console application and insert the following code in the Main method:

C# Copy Code
static void Main(string[] args)
{
  CustomerService.Customer_Service svc
      = new CustomerService.Customer_Service();
  svc.UseDefaultCredentials = true;
  Customer c = svc.Read("01121212");
  Console.WriteLine(c.Name);
  Console.ReadKey();
}

When you run the application, you will see the following output (assuming the CRONUS International Ltd. demonstration database):

Copy Code
Spotsmeyer's Furnishings

Then go back to page 21 and set the Name property for the control that is bound to the Name field to CustomerName, and save the page.

Finally, switch back to the console application without updating the web reference and run the code. Instead of getting an error message that indicates that the web request does not match the web service description, you do not get an error message, and Console.WriteLine shows an empty line.

See Also

Concepts

Microsoft Dynamics NAV Web Services Overview


Web Services Best Practices

This topic provides recommendations that you can implement to make your web services applications easier to understand and maintain.

Recommendation | Example
Use the HTTPS protocol to send data between Microsoft Dynamics NAV and the web service consumer. The examples in this section use the HTTP protocol to illustrate the setup, but we recommend that your solution uses transport-level security. | In the application that consumes the Microsoft Dynamics NAV web service, require that URIs are accessed by using HTTPS. For example, a more secure URI for the OData web services on your local computer is https://localhost:7048/DynamicsNAV/OData/.
Use singular forms of names. This provides meaningful singular entity names in the generated proxy classes. | When publishing page 21, Customer Card, use Customer as the service name instead of Customers or CustomerCard.
Avoid using spaces and other characters because they are transformed to underscores or other characters that may not be displayed as you want and could lead to ambiguity. | When publishing page 42, Sales Order, remove the space and use SalesOrder as the service name.
Use Pascal casing when you combine words. Pascal casing capitalizes the first character of each word, including acronyms and initialisms that are more than two letters long. | Use SalesOrder or ContactPerson as the service name.


Web Services Authentication

When users send a request for a web service, they are authenticated according to the credential type that is configured for Microsoft Dynamics NAV Server. To access a web service, users must provide valid credentials for the credential type being used. If Microsoft Dynamics NAV is configured for Windows credential type, then users are automatically authenticated against the Windows account that their computer is running under, and they are not prompted for their credentials. For other credential types, users are prompted to enter a user name and password.

If your solution uses NavUserPassword or AccessControlService as the credential type, users can access data through SOAP and OData web services if they specify a password or a web service access key. You set up the user accounts in the User Card window based on how they will access Microsoft Dynamics NAV data. For example, if you set up a user account that will allow an external application to read Microsoft Dynamics NAV data through a web service, you can generate a web service access key and specify that in the User Card window for the relevant user accounts. Then, you add the access key to the configuration of the application that consumes the web service. In contrast, when users access Microsoft Dynamics NAV data through a web service in Microsoft Excel, for example, they specify a password instead of a web service access key.

Microsoft Dynamics NAV also supports OAuth authentication on OData and SOAP endpoints. OAuth is an open standard for authentication that provides client applications with secure delegated access to server resources. OAuth enables you to extend single sign-on with Office 365 to Microsoft Dynamics NAV web services.

To | See
Learn about how to create users and configure the credential type for Microsoft Dynamics NAV Server. | Users and Credential Types
Learn about how to use a web access key to authenticate SOAP and OData web services. | How to: Use an Access Key for SOAP and OData Web Service Authentication
Learn about OAuth authentication on Microsoft Dynamics NAV web services. | Using OAuth to Authenticate Microsoft Dynamics NAV Web Services (Odata and SOAP)
Important
If the Microsoft Dynamics NAV Server is configured to use NavUserPassword or AccessControlService authentication, then the username, password, and access key can be exposed if the SOAP or OData data traffic is intercepted and the connection string is decoded. To avoid this condition, configure SOAP and OData web services to use Secure Socket Layer (SSL). For more information, see Walkthrough: Configuring Web Services to Use SSL (SOAP and OData)

When Microsoft Dynamics NAV data is consumed by a web service, users cannot be authenticated if their user name or password contains Unicode characters. This is a limitation in the basic authentication mechanism that is defined in the HTTP/1.1 specification.

The same limitation applies to exposing Microsoft Dynamics NAV data in external products such as a browser or a Microsoft .NET Framework assembly.

See Also

Concepts

Web Services Authentication
Microsoft Dynamics NAV Web Services Overview
SOAP Web Services
OData Web Services
Users and Credential Types


How to: Use an Access Key for SOAP and OData Web Service Authentication

If your solution is configured for NavUserPassword or AccessControlService authentication, then you can configure Microsoft Dynamics NAV user accounts to include an access key that can be used instead of a password to authenticate SOAP and OData web service requests. A web service access key is a random 44 character string that is associated with the user account. Because it can only be used for SOAP and OData web services, it does not require the same level of protection as a password.

Generating a Web Service Access Key

To generate a web service access key for a Microsoft Dynamics NAV user

  1. In the RoleTailored client in the Search box, enter Users, and then choose the Users link in the Results list.

    The Users page opens.

    Note
    For more information about how to create a user, see How to: Create Microsoft Dynamics NAV Users.

  2. Select a user and choose Edit in the ribbon.

  3. In the Web Service Access section, choose the AssistEdit button that is next the Web Service Access Key field.

  4. In the Set the Web Service Access Key window, if you do not want the key to expire, select the Key Never Expires check box. If you want the key to expire, set the Key Expiration Date field to the date.

  5. Choose the OK button.

    The access key is automatically generated and appears in the Web Service Access Key field.

Implementing the Web Service Access Key

Typically, you would create a user account strictly for web services, and then use the account's credentials, which include the user name and access key, in a web service application. For example, if you develop your own web service application, then you can design your application to programmatically pass the credentials to the web service. Some applications, such as Microsoft Excel PowerPivot, let you provide the connection credentials through a user interface. The key tasks for implementing the web service access key are as follows.

To implement a web service access key

  1. Create a user specifically for web services.

    For more information, see How to: Create Microsoft Dynamics NAV Users.

  2. Generate a web service access key in the user account.

  3. Use the access key in the web service application.

    To See

    Learn how to use the web access key in Excel PowerPivot

    Walkthrough: Viewing Page Data in Excel Using PowerPivot (OData)

    Learn how to use code to pass the user name and web access key to a web service

    Passing Credentials for Authentication to Web Services

See Also

Tasks

How to: Create Microsoft Dynamics NAV Users

Concepts

Web Services Authentication
Microsoft Dynamics NAV Web Services Overview
SOAP Web Services
OData Web Services


SOAP Web Services

SOAP web services enable full flexibility for building operation-centric services. They provide industry-standard interoperability and channel and host pluggability.

You can use SOAP to interact with page or codeunit web services in Microsoft Dynamics NAV 2016.

To | See
Review the different options for creating URIs to interact with SOAP web services. | SOAP Web Service URIs
Review the set of operations that are available when a page is exposed as a web service. | Basic Page Operations
Learn how to write code that provides a list of existing companies in a Microsoft Dynamics NAV database. | How to: Use SystemService to Find Companies
Ensure that field values are updated from web services. | Using Properties with Visual Studio to Indicate the Presence of a Value in a Field


SOAP Web Service URIs

Web service users can discover published web services by pointing a browser or a tool such as the Web Services Discovery Tool at the computer running Microsoft Dynamics NAV Server and getting a list of available services. For SOAP web services, you typically enter a URI in a browser to view a list of available Microsoft Dynamics NAV web services or to view a schema for a particular web service.

URIs for SOAP Web Services

To display all published SOAP web services that are exposed by a Microsoft Dynamics NAV Server instance, use a URI of the following type:

Copy Code
http://<Server>:<Port>/<ServerInstance>/WS/<CompanyName>/services

The following example displays all published SOAP web services that are exposed for the CRONUS International Ltd. demonstration database.

Copy Code
http://localhost:7047/DynamicsNAV/WS/CRONUS%20International%20Ltd/services

To view the schema for a particular service, use a URI of the following type:

Copy Code
http://<Server>:<Port>/<ServerInstance>/WS/<CompanyName>/Page/<servicename>

The following example displays the schema for the Customer service for the CRONUS International Ltd. demonstration database.

Copy Code
http://localhost:7047/DynamicsNAV/WS/CRONUS%20International%20Ltd/Page/Customer

You can also use a URI for a codeunit web service, as shown in the following example:

Copy Code
http://localhost:7047/DynamicsNAV/WS/CRONUS%20International%20Ltd/Codeunit/Letters

See Also

Concepts

Web Service Walkthroughs


Basic Page Operations

When you publish a page as a SOAP web service, it has a set of default operations that are exposed to consumers of the web service.

These operations match the actions a user can perform by interacting with a page using the RoleTailored client. The same page- and table-based business logic is executed.

The following table lists the operations and provides links to reference pages.

Pages that are backed by virtual tables are not editable through web services. When such pages are published as SOAP web services, the only operations that are available are Read, ReadMultiple, and IsUpdated.

The term entity that is used in the operation signatures describes the data type that is used. The actual entity is defined by the page that is exposed because it contains all controls that are defined on the page. The controls are normally bound to the page's source table. The entity also contains a key that is a special string that uniquely identifies the source table record with a timestamp. This key is used as an argument in many page operations.

All basic page operations are atomic, which means that either all relevant records are affected or no records are affected, even if there was a faulty condition in only one record.

Operation | Description and signature
Create Operation | Creates a single record. void Create(ref Entity entity)
CreateMultiple Operation | Creates a set of records. void CreateMultiple(ref Entity[] entity)
Delete Operation | Deletes a single record. bool Delete(string key)
Delete_<part> Operation | Deletes a subpage of the current page. bool Delete_<part>(string key)
GetRecIdFromKey | Converts a key, which is always part of the page result, to a record ID. string GetRecIdFromKey(string key)
IsUpdated Operation | Checks if an object has been updated since the key was obtained. bool IsUpdated(string key)
Read Operation | Reads a single record. Entity Read(string no)
ReadByRecId Operation | Reads the record that is identified by RecId. You can use GetRecIdFromKey to obtain a record ID. If the record is not found, then the operation returns null. Entity ReadByRecId(string formattedRecId)
ReadMultiple Operation | Reads a filtered set of records, paged. Entity [] ReadMultiple(Entity_Filter[] filterArray, string bookmarkKey, int setSize)
Update Operation | Updates a single record. void Update(ref Entity entity)
UpdateMultiple Operation | Updates a set of records. void UpdateMultiple(ref Entity[] entity)

See Also

Tasks

Walkthrough: Registering and Using a Page Web Service (SOAP)
Walkthrough: Creating a Web Service using Extension Codeunits (SOAP)


Create Operation

Creates a single record. The supplied record object is overwritten with the version that is created by the page.

Method Signature

void Create(ref Entity entity)

Parameters

Parameter | Description
entity | Type: Entity A variable of a specific object type that represents the page.

Results

Result name | Description
entity | Type: Entity A variable of a specific object type that represents the page. Contains the latest values that are present on the page after the record has been inserted into the table.

Faults

SOAP fault message | Description
The [record name] already exists. Identification fields and values: [field]=[value] | Indicates that the record insertion would violate key constraints.

Other faults are possible if they are generated by the C/AL code.

Usage Example

For a detailed code example, see Walkthrough: Registering and Using a Page Web Service (SOAP).

C# Copy Code
Customer cust = new Customer();
cust.Name = "Customer Name";
service.Create(ref cust);

See Also

Concepts

Basic Page Operations


CreateMultiple Operation

Creates a set of records. The supplied record object is overwritten with the version that is created by the page.

Method Signature

void CreateMultiple(ref Entity[] entity)

Parameters

Parameter | Description
entity[] | Type: An array of Entities An array of a specific object type that represents the page.

Results

Result name | Description
entity[] | Type: An array of Entities An array of a specific object type that represents the page. Contains the latest values that are present on the page after the records have been inserted into the table.

Faults

SOAP fault message | Description
The [record name] already exists. Identification fields and values: [field]=[value] | Indicates that the insertion of at least one of the records would violate key constraints.

Other faults are possible if they are generated by the C/AL code.

The CreateMultiple operation is executed as a single transaction unless the C/AL code explicitly commits the transaction. Either all or none of the records are inserted unless the application code does not explicitly call COMMIT.

Usage Example

C# Copy Code
Customer[] custArray = new Customer[3];
for (int i = 0; i < custArray.Length; i++)
{
  custArray[i] = new Customer();
  custArray[i].Name = "Customer Name " + i.ToString();
}
service.CreateMultiple(ref custArray);

See Also

Concepts

Basic Page Operations


Delete Operation

Deletes a single record.

Executing the Delete operation in a web service first executes the OnDeleteRecord Trigger on the designated page. If application code in the OnDeleteRecord trigger for the page returns true, then the OnDelete Trigger for the corresponding table is executed. If no fault occurs, then the record is deleted from the database.

If the application code in the trigger returns false, then the OnDelete trigger is not executed. This does not necessarily mean that the record has not been deleted because it may have been deleted explicitly by the application code for the page's OnDeleteRecord trigger.

The return value from the Delete operation is the return value from the page's OnDeleteRecord trigger.

If Delete returns true, then the record has been deleted. If Delete has thrown a fault, then the record has not been deleted. But when Delete returns false, then this indicates that there was application logic involved, and the record may or may not have been deleted.

Method Signature

bool Delete(string key)

Parameters

Parameter | Description
key | Type: String The bookmark of the record, including both primary key and concurrency information.

Results

Result name | Description
Delete_Result | Type: Boolean The value that is returned by the OnDeleteRecord page trigger.

Faults

SOAP fault message | Description
Other user has modified [record name]. | Indicates that another user or process has modified the record after it has been retrieved for this delete operation.
[record name] [field] [value] does not exist. | Indicates that the record has been deleted by another user or process after it has been retrieved for this delete operation.

Other faults are possible if they are generated by the C/AL code.

Usage Example

C# Copy Code
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication
{
    // Imports newly generated web service proxy.
    using WebService;

    class Program
    {
        static void Main(string[] args)
        {
            // Creates instance of service and sets credentials.
            Customer_Service service = new Customer_Service();
            service.UseDefaultCredentials = true;
            Customer cust = new Customer();
            cust.Name = "Customer Name";
            service.Create(ref cust);
            cust = service.Read(cust.No);
            service.Delete(cust.Key);
        }
    }
}

See Also

Concepts

Basic Page Operations


Delete_<part> Operation

Deletes records on a subpage of the current page.

This operation is exposed only by pages that have subpages, which are pages that have parts of type Page. For example, the Sales Order page has a part with the name SalesLines, which has PartType equal to Page and PagePartID equal to “Sales Order Subform.” The name of the operation that is exposed by the Sales Order page is Delete_SalesLines.

When you call this operation, you delete a record of the subpage. When you call Read on a page that has a subpage, you get the records of the top-level page and the corresponding records of the subpage. To modify them or add to them, you must modify the whole top-level record.

Executing the Delete_<part> operation in a web service first executes the OnDeleteRecord Trigger on the designated record of the subpage. If application code in the OnDeleteRecord trigger for the record of the subpage returns true, then the OnDelete Trigger for the corresponding table is executed. If no fault occurs, then the record of the subpage is deleted from the database.

If the application code in the trigger returns false, then the OnDelete trigger is not executed. This does not necessarily mean that the record of the subpage has not been deleted because it may have been deleted explicitly by the application code for the page's OnDeleteRecord trigger.

The return value from the Delete_<part> operation is the return value from the page's OnDeleteRecord trigger.

If Delete returns true, then the record of the subpage has been deleted. If Delete has thrown a fault, then the record of the subpage has not been deleted. When Delete returns false, there was application logic involved, and the record of the subpage may or may not have been deleted.

Method Signature

bool Delete_<part>(string key)

Parameters

Parameter | Description
key | Type: String The bookmark of the record of the subpage, including both primary key and concurrency information.

Results

Result name | Description
Delete_Result | Type: Boolean The value that is returned by the OnDeleteRecord page trigger.

Faults

SOAP fault message | Description
Other user has modified [record name]. | Indicates that another user or process has modified the record of the subpage after it has been retrieved for this delete operation.
[record name] [field] [value] does not exist. | Indicates that the record of the subpage has been deleted by another user or process after it has been retrieved for this delete operation.

Other faults are possible if they are generated by the C/AL code.

Usage Example

This example presents a console application that is created in Visual Studio after registering and publishing the Sales Order page. For details on how to register and publish a page, see Walkthrough: Registering and Using a Page Web Service (SOAP). After you publish the page as a web service, you must also add a web reference to it. This task is also described in the walkthrough.

C# Copy Code
using Delete_SalesLinesSample.DynamicsNAVService;
namespace Delete_SalesLinesSample
{
    class Program
    {
        static void Main(string[] args)
        {
            DynamicsNAVService.SalesOrder_Binding so = new SalesOrder_Binding();
            so.UseDefaultCredentials = true;
            SalesOrder salesOrder = so.Read("2001");
            Sales_Order_Line[] salesLines = salesOrder.SalesLines;
            if (salesLines.Length > 0)
            {
                string key = salesLines[0].Key;
                so.Delete_SalesLines(key);
            }
        }
    }
}

See Also

Concepts

Basic Page Operations


GetRecIdFromKey

Converts a key to a record ID. The key is always part of the page result.

Method Signature

string GetRecIdFromKey(string key)

Parameters

Parameter | Description
key | Type: String The bookmark of the record that includes both primary key and concurrency information.

Results

Result name | Description
String | Type: String The record ID that was obtained from the key.

Faults

SOAP fault message | Description
[record name] [field] [value] does not exist. | Indicates that the record has been deleted by another user or process after it has been retrieved for this operation.

Usage Example

C# Copy Code
Customer_Service service = new Customer_Service();
Customer cust = new Customer();
service.UseDefaultCredentials = true;
string id = service.GetRecIdFromKey(cust.No);
cust = service.ReadByRecId(id.ToUpper());

See Also

Concepts

Basic Page Operations


IsUpdated Operation

Checks if an object has been updated since the key was obtained. This operation returns true if the object has been updated by any user; otherwise, false. Concurrency management prevents a record being changed if it has been subsequently updated. This check proactively prevents that failure.

Method Signature

bool IsUpdated(string key)

Parameters

Parameter | Description
key | Type: String The bookmark of the record, including both primary key and concurrency information.

Results

Result name | Description
IsUpdated_Result | Type: Boolean Returns true if and only if another user has modified the record.

Faults

SOAP fault message | Description
[record name] [field] [value] does not exist. | Indicates that the record has been deleted by another user or process after it has been retrieved for this operation.

Usage Example

C# Copy Code
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication
{
    // Imports newly generated web service proxy.
    using WebService;

    class Program
    {
       static void Main(string[] args)
           {
              // Creates instance of service and sets credentials.
              Customer_Service service = new Customer_Service();
              service.UseDefaultCredentials = true;
              Customer cust = new Customer();
              cust.Name = "Customer Name";
              service.Create(ref cust);
              cust = service.Read(cust.No);
              if (!service.IsUpdated(cust.Key))
           {
              // Add code here to modify record.
           }
        }
    }
}

See Also

Concepts

Basic Page Operations


Read Operation

Reads a single record.

Note
The signature of an operation changes if the page contains one or more unbound fields in the root content area. If there are unbound fields, then the names from the SourceExpr property for the unbound fields are added as the first parameters to the operation. They are added according to the tab order of the page. For an example, see the Item Journal.

Method Signature

Entity Read(string no)

Parameters

Parameter Description

no

Type: String

The primary key of the requested record.

This argument is a filter on the primary key and returns the first record that matches the filter. When special characters, such as an apostrophe, equal sign, or ampersand, are part of the key, you must enclose the argument with quotation marks.

For example, when you write C# code, you should use standard quotation marks for strings and also use additional single quotation marks around a value, such as "'A&B'".

Results

Result name Description

entity

Type: Entity

A variable of a specific object type that represents the page. Contains the latest values that are present on the page.

If the record with the given primary key does not exist, then no value is returned. In the .NET Framework, a null reference is returned.

Faults

This operation does not return a fault when a matching record is not present. Instead, it returns no value. In C#, you should test whether the result is a null reference. Otherwise, you may get a NullReferenceException exception.

Faults are possible if they are generated by the C/AL code.

Usage Example

C# Copy Code
Customer customer = new Customer();
customer.Name = "Customer Name";
service.Create(ref customer);
customer = service.Read(customer.No);

See Also

Concepts

Basic Page Operations


ReadByRecId Operation

Reads the record that is identified by the record ID.

Method Signature

Entity ReadByRecId(string formattedRecId)

Parameters

Parameter | Description
formattedRecId | Type: String The RecId that is used to read the record.

Results

Result name | Description
entity | Type: Entity A variable of a specific object type that represents the page. Contains the latest values that are present on the page. If the record is not found, then the operation returns null.

Faults

This operation does not return a fault when a matching record is not present. Instead, it returns null. In C#, you should test whether the result is a null reference. Otherwise, you may get a NullReferenceException exception.Faults are possible if they are generated by the C/AL code.

Usage Example

C# Copy Code
public void ReadById(String id)
{
  Customer_Service service = new Customer_Service();
  Customer cust = new Customer();
  service.UseDefaultCredentials = true;
  cust = service.ReadByRecId(id.ToUpper());
}

See Also

Concepts

Basic Page Operations


ReadMultiple Operation

Reads a filtered set of records. This operation returns an array of entities. The ReadMultiple operation allows the consumer of a web service to specify the number of records to be returned at one time. This can reduce load on the server.

Note
Records on a page that were inserted after the page was retrieved are not read. Records on a page may be incorrectly included in the retrieved dataset if they were deleted after the page was retrieved.

Method Signature

Entity [] ReadMultiple(Entity_Filter[] filterArray, string bookmarkKey, int setSize)

Parameters

Parameter | Description
filterArray | Type: Entity_Filter[] An array of record filters.
bookmarkKey | Type: String The last record bookmark of the page that was previously read. To return the first page of results, set bookmarkKey to NULL.
setSize | Type: Integer The size of the set to be returned. To return the complete set of results, set setSize to zero. To reverse the order of the results, set setSize to negative.

Results

Result name Description

entity[]

Type: An array of Entities

An array of a specific object type that represents the page. Contains the latest values that are present on the page.

The server will return at most setSize records. If all records have been already returned, then subsequent calls will return no records (a 0-element array in C#). You should keep calling the ReadMultiple function until no records are returned.

entity.Key

Type: String

The key of the last record read. In C#, you can access it with Entity[Entity.Length-1].Key. Pass this as bookmarkKey for the next ReadMultiple call.

Faults

This operation does not throw faults when no matching records are present. Instead, it returns an empty record list.

Faults are possible if they are generated by the C/AL code.

Remarks

Retrieving Last Page

To retrieve the last record of a page, set setSize to -1. Using negative numbers in setSize sorts the records in descending order.

Entity_Filter

You use the Entity_Filter parameter with the ReadMultiple operation. It describes a filter that can be applied on a specific field in a record. The Entity_Filter parameter contains two members: Field and Criteria.

  • Field contains the name of the field that the filter is applied to. This name comes from the Entity_Fields enum.

  • Criteria is of type string and can contain any valid Microsoft Dynamics NAV style filter that is specified in a standard Microsoft Dynamics NAV filter format.

Usage Examples

The following example returns the first 100 customer names that start with an S. For a detailed code example, see Walkthrough: Registering and Using a Page Web Service (SOAP).

C# Copy Code
List<Customer_Filter> filterArray = new List<Customer_Filter>();
Customer_Filter nameFilter = new Customer_Filter();
nameFilter.Field = Customer_Fields.Name;
nameFilter.Criteria = "S*";
filterArray.Add(nameFilter);
Customer[] custList = service.ReadMultiple(filterArray.ToArray(), null, 100);

This example uses the bookmarkKey argument to read customer records in batches of 10:

C# Copy Code
Customer_Service service = new Customer_Service();
service.UseDefaultCredentials = true;
const int fetchSize = 10;
string bookmarkKey = null;
List<Customer> customerList = new List<Customer>();
// Reads customer data in pages of 10.
Customer[] results = service.ReadMultiple(new Customer_Filter[] { }, bookmarkKey, fetchSize);
while (results.Length > 0)
{
    bookmarkKey = results.Last().Key;
    customerList.AddRange(results);
    results = service.ReadMultiple(new Customer_Filter[] { }, bookmarkKey, fetchSize);
}
// Prints the collected data.
foreach (Customer customer in customerList)
{
    Console.WriteLine(customer.Name);
}

See Also

Concepts

Basic Page Operations


Update Operation

Updates a single record. The updated record is passed as a reference and is updated with the latest version.

Method Signature

void Update(ref Entity entity)

Parameters

Parameter | Description
entity | Type: Entity A variable of a specific object type that represents the page.

Results

Result name | Description
entity | Type: Entity A variable of a specific object type that represents the page. Contains the latest values that are present on the page after the record has been updated by the business logic or another concurrent process.

Faults

SOAP fault message | Description
Other user has modified [record name]. | Indicates that another user or process has modified the record after it has been retrieved for this update operation.
[record name] [field] [value] does not exist. | Indicates that the record has been deleted by another user or process after it has been retrieved for this update operation.
The [record name] already exists. Identification fields and values: [field]=[value] | Indicates that the renaming of the record would violate key constraints.

Other faults are possible if they are generated by the C/AL code.

Usage Example

For a detailed code example, see Walkthrough: Registering and Using a Page Web Service (SOAP).

C# Copy Code
Customer cust = new Customer();
cust.Name = "Customer Name ";
service.Create(ref cust);
cust.Name = cust.Name + "Updated";
service.Update(ref cust);

See Also

Concepts

Basic Page Operations


UpdateMultiple Operation

Updates a set of records. The updated array of records is passed as a reference and is updated with the latest version.

Note
The UpdateMultiple operation attempts to update one field at a time. This can cause errors if the updated value in one field prevents another field's value from being valid. You can resolve this by deleting and inserting lines instead of updating fields.

Method Signature

void UpdateMultiple(ref Entity[] entity)

Parameters

Parameter | Description
entity[] | Type: An array of Entities. An array of a specific object type that represents the page.

Results

Result name | Description
entity[] | Type: An array of Entities An array of a specific object type that represents the page. Contains the latest values that are present on the page after the records have been updated by the business logic or another concurrent process.

Faults

SOAP fault message | Description
Other user has modified [record name]. | Indicates that another user or process has modified the record after it has been retrieved for this update operation.
[record name] [field] [value] does not exist. | Indicates that the record has been deleted by another user or process after it has been retrieved for this update operation.
The [record name] already exists. Identification fields and values: [field]=[value] | Indicates that the renaming of the record would violate key constraints.

Other faults are possible if they are generated by the C/AL code.

The UpdateMultiple operation is executed as a single transaction unless the C/AL code explicitly commits the transaction. Either all or none of the records are updated provided that the application code does not explicitly call COMMIT.

Usage Example

The following example adds the string "Updated" to the name of the first 100 customer names that start with S.

C# Copy Code
List<Customer_Filter> filterArray = new List<Customer_Filter>();
Customer_Filter nameFilter = new Customer_Filter();
nameFilter.Field = Customer_Fields.Name;
nameFilter.Criteria = "S*";
filterArray.Add(nameFilter);
Customer[] custList = service.ReadMultiple(filterArray.ToArray(), null, 100);
for (int i = 0; i < custList.Length; i++)
{
  custList [i].Name = custList [i].Name + " Updated";
}
service.Update(ref custList)

See Also

Concepts

Basic Page Operations


How to: Use SystemService to Find Companies

You can use the SystemService service in a SOAP web service application to retrieve a list of companies available in a specific database. A company name is typically part of the URI when you access a Microsoft Dynamics NAV web service, and the system service lets you retrieve names of available companies. If you do not specify a company name in a URI, then the default company is used.

In this procedure, you use the SystemService service to retrieve and print a list of companies. You must use Visual Studio 2012 or Visual Studio 2010.

To use the SystemService service to find companies

  1. In Visual Studio, on the File menu, point to New, and then choose Project.

  2. Expand the Visual C# node, select Windows, and then select Console Application.

    Caution
    Do not double-click or otherwise dismiss the New Project dialog box.

  3. Enter FindingCompanies as the Name for the application, and then choose OK.

  4. In Solution Explorer, right-click the References node in the project, and then choose Add Service Reference.

  5. In the Add Service Reference dialog box, choose the Advanced button, choose the Add Web Reference button, type or paste the URL that you used when checking the WSDL, such as http://localhost:7047/DynamicsNAV/WS/Services, and then choose the green arrow to visit the URL.

  6. When the SystemService service is displayed, choose View Service, wait for the service to be displayed, and then choose Add Reference. Rename the Web reference name from localhost to NavSOAPService.

  7. On the Program.cs tab, replace the stub code with the following.

    C# Copy Code
    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FindingCompanies
{
    using System;
    using NavSOAPService;
    public class Program
    {
        static void Main(string[] args)
        {
            // Creates instance of service and set credentials.
            var systemService = new SystemService
            {
                UseDefaultCredentials = true
            };
            // Loads all companies into an array.
            var companies = systemService.Companies();
            // Runs through and print all companies.
            // Also prints company name in encoded form.
            foreach (string company in companies)
            {
                Console.WriteLine(company);
                Console.WriteLine((Uri.EscapeDataString(company)));
            }
            Console.ReadLine();
        }
    }
}

  8. Save (press Ctrl+F6) and compile (press F6) the FindingCompanies application.

  9. Press F5 to run the application in debug mode.

    A list of all companies in the current database is presented in a command session.

See Also

Tasks

Walkthrough: Creating a Web Service using Extension Codeunits (SOAP)
Walkthrough: Creating and Using a Codeunit Web Service (SOAP)
Walkthrough: Registering and Using a Page Web Service (SOAP)

Concepts

SOAP Web Services


Using Properties with Visual Studio to Indicate the Presence of a Value in a Field

When you set a field to a value in the code for a web service client and then send the value back to the web service, such as when you use the Create Operationor the Update Operation, the field value is not actually updated to anything other than its default value. This issue can occur if you are using proxies that are generated by Visual Studio or the tools in the .NET Framework SDK. This topic describes the issue and shows how to avoid the problem.

Using Properties to Indicate the Presence of Values

The problem occurs because of the way proxies are autogenerated and the way the .NET Framework handles values in XML documents that are exchanged between the web service and the client. The issue is not specific to Microsoft Dynamics NAV.

For example, the following code shows the schema for the two fields on this Customer Card web service:

Copy Code
<xsd:element minOccurs="0" maxOccurs="1" name="Credit_Limit_LCY" type="xsd:decimal" />
<xsd:element minOccurs="0" maxOccurs="1" name="Salesperson_Code" type="xsd:string" />

Both fields are optional, which means that they do not have to be present in the XML document. One field is declared as a Decimal data type in Microsoft Dynamics NAV. The other field is a string because it is declared as a Text data type in Microsoft Dynamics NAV.

If both values are present, then the XML document should contain the following elements:

Copy Code
<Credit_Limit_LCY>1000</Credit_Limit_LCY>
<Salesperson_Code>JR</Salesperson_Code>

But if there is no information about the credit limit, then the document should contain the following element:

Copy Code
<Salesperson_Code>JR</Salesperson_Code>

If the credit limit is zero, then the document should contain the following line:

Copy Code
<Credit_Limit_LCY>0</Credit_Limit_LCY>

For the decimal type and all .NET Framework value types, you can handle this state in the proxy objects by using a Boolean *Specified property:

Copy Code
if (salesOrder.Credit_Limit_LCYSpecified)
    there is a value present in salesOrder.Credit_Limit_LCY
else
    there is no useful value in salesOrder.Credit_Limit_LCY

If you assign a non-default value in the value type, then you should confirm this by setting the accompanying Boolean *Specified property to true:

Copy Code
salesOrder.Credit_Limit_LCY = 1000;
salesOrder.Credit_Limit_LCYSpecified = true;

To specify that there is no meaningful value in the salesOrder.Credit_Limit_LCY value type, set the accompanying Boolean *Specified property to false:

Copy Code
salesOrder.Credit_Limit_LCYSpecified = false;

The value in the salesOrder.Credit_Limit_LCY value type will now be disregarded.

.NET Framework reference types, such as the String class, are handled differently because .NET Framework declarations that are based on those types can be null, which means that they can have an explicit expression of no value present:

Copy Code
if (salesOrder.Salesperson_Code != null)
    there is a value present in salesOrder.Salesperson_Code
else
    there is no value in salesOrder.Salesperson_Code

If you assign a value, then you implicitly also define it as present:

Copy Code
salesOrder.Salesperson_Code = "JR";

To specify that there is no useful value in salesOrder.Salesperson_Code, you should set it to null:

Copy Code
salesOrder.Salesperson_Code = null;

Example

Copy Code
SalesOrder salesOrder = new SalesOrder();
salesOrder.Order_Date = DateTime.Today;
salesOrder.Order_DateSpecified = true;
salesOrder.Currency_Code = "SEK";
salesOrderService.Create(ref salesOrder);


OData Web Services

The Open Data Protocol (OData) is a web protocol that is designed for querying tabular data and provides you with an alternative to SOAP-based web services. OData builds on web technologies such as HTTP, the Atom Publishing Protocol (AtomPub), and JavaScript Object Notation (JSON) to provide access to information from different applications, services, and stores. OData uses URIs for resource identification and commits to an HTTP-based, uniform interface for interacting with resources. This commitment to core Web principles allows for OData to enable a new level of data integration and interoperability across a broad range of clients, servers, services, and tools.

You can use OData web services to show Microsoft Dynamics NAV data, and you can update data in a Microsoft Dynamics NAV database using OData web services.

OData can be found in other Microsoft products and technologies, including the following:

  • Microsoft Excel implements OData for its PowerPivot add-in.

  • Microsoft SharePoint can expose its list-oriented data with OData.

  • Microsoft Azure Table Services are based on OData.

The topics in this section describe the key concepts and techniques for accessing Microsoft Dynamics NAV data from OData applications that are supported by Microsoft Dynamics NAV.

To | See
Use OData to obtain an AtomPub document. | How to: Use OData to Return/Obtain an AtomPub Document
Use OData to obtain a service metadata (EDMX) document. | How to: Use OData to Return/Obtain a Service Metadata (EDMX) Document
Use OData to obtain a JavaScript Object Notation (JSON) document. | How to: Use OData to Return/Obtain a JSON Document
Use filter expressions in OData URIs. | Using Filter Expressions in OData URIs
Use FlowFilters in OData URIs. | How to: Use FlowFilters in OData URIs
Use server-driven paging in OData URIs. | Server-Driven Paging in OData Web Services
Navigate in an OData web service application by using resource properties. | Using Containments and Associations
Write to the database through an OData web service that exposes a writable page. | Using OData Web Services to Modify Data

Known Limitations

You can specify filters in OData web services in general that are not supported in Microsoft Dynamics NAV, such as using an OR operator to filter on two different fields. In those cases, you will see the following error:

Copy Code
An error occurred while processing this request.
 The 'OR' operator is not supported on distinct fields on an OData filter.

See Also

Concepts

SOAP Web Services
Web Service Alternatives: SOAP and OData
Web Service Walkthroughs


How to: Use OData to Return/Obtain an AtomPub Document

When you register an OData web service, you expose an OData service that can be accessed from a uniform resource identifier (URI) by using a web browser or any other HTTP client. OData clients can use Atom Publishing Protocol (AtomPub) documents to interact with Microsoft Dynamics NAV data. AtomPub is a simple HTTP-based protocol for creating and updating web resources. It is related to the Atom Syndication Format, which is XML for web feeds. In these procedures, you obtain different kinds of AtomPub documents or feeds from a Microsoft Dynamics NAV OData web service. AtomPub documents and feeds are XML.

Note
To use the URIs in this topic, you must have access to the CRONUS International Ltd. demonstration database.

Obtaining an AtomPub Document or Feed

Depending on how you construct your URI, you can return an AtomPub document or an AtomPub feed. A feed is a request for data that can change over time. For example, this can be news content or other kinds of information. In the case of Microsoft Dynamics NAV, the information is database content.

To obtain an AtomPub document or feed

  1. Register and publish a page web service by using the RoleTailored client. For more information, see Walkthrough: Creating and Interacting with a Page Web Service (OData).

    The AtomPub documents that are shown in the walkthrough are based on the page 21, the Customer Card page, with Customer as the service name. The concepts and steps are the same for any RoleTailored client page that you register and publish as a web service.

    Note
    You can also register and publish a Microsoft Dynamics NAV query as a web service.

  2. Start Windows Internet Explorer. In the Address field, enter a URI in this format:

    Copy Code
    http://<Server>:<WebServicePort>/<ServerInstance>/OData

    If Microsoft Dynamics NAV Server is running on the local computer with the default Microsoft Dynamics NAV Server instance and OData port, then the address is:

    Copy Code
    http://localhost:7048/DynamicsNAV90/OData

    The browser should now show the web service that you have published in the format of an AtomPub document:

    Basic AtomPub document for a page

  3. If you have multiple companies, then you can modify your URI to return a feed that enumerates all available companies:

    Copy Code
    http://localhost:7048/DynamicsNAV90/OData/Company
    Important
    You must modify your Internet Explorer settings to display the actual XML for a feed instead of the feed content that has changed. Choose Internet Options, choose Content, choose Feeds and Web Slices, and then clear the Turn on feed reading view check box. Restart Internet Explorer to enable the new setting.

Obtaining a Keyed Service Entry

With a keyed service entry, you specify content from a particular row in a Microsoft Dynamics NAV table. The AtomPub document will contain information that is specific to that row. This procedure assumes that you have registered and published a page web service in the previous procedure.

To obtain a keyed service entry

  1. Start Windows Internet Explorer. In the Address field, enter a URI in the following format to get the entry for the CRONUS International Ltd. company:

    Copy Code
    http://localhost:7048/DynamicsNAV90/OData/Company('CRONUS%20International%20Ltd.')

  2. To get the data feed for the Customer table in the CRONUS International Ltd. company database, enter a URI in the following format:

    Copy Code
    http://localhost:7048/DynamicsNAV90/OData/Company('CRONUS%20International%20Ltd.')/Customer

  3. To additionally constrain data to a specific keyed customer in the Customer table, enter a URI in the following format, using the customer no. for the record you want. The example uses customer no. 01121212:

    Copy Code
    http://localhost:7048/DynamicsNAV90/OData/Company('CRONUS%20International%20Ltd.')/Customer('01121212')

Obtaining a Filtered Data Feed

With a filtered data feed, you use special syntax in the URI to define a query on the available data. For details on the specific filters available for Microsoft Dynamics NAV OData web service applications and the syntax for using them, see Using Filter Expressions in OData URIs.

To obtain a filtered service data feed

  1. Start Windows Internet Explorer. In the Address field, enter a URI in the following format to get the entry for the CRONUS International Ltd. company:

    Copy Code
    http://localhost:7048/DynamicsNAV90/OData/Company('CRONUS%20International%20Ltd.')/Customer?$filter=City%20eq%20'Birmingham'

See Also

Concepts

OData Web Services


How to: Use OData to Return/Obtain a Service Metadata (EDMX) Document

The Entity Data Model (EDM) is a specification for defining the data that is used by applications that are built on the Entity Framework. EDMX is an XML-based file format that is the packaging format for the service metadata of a data service. When you interact with an OData service that is published from Microsoft Dynamics NAV, you can request EDM-based proxies and then use tools such as LINQ to create data access logic. LINQ is a programming model that developers can use to query data from a variety of data sources, including OData. For more information, see LINQ (Language-Integrated Query)

The Microsoft Dynamics NAV implementation of EDM follows the .NET 4.0 WCF Data Service Framework implementation.

The following guidelines have been implemented for EDM.

  • Microsoft Dynamics NAV field names are mapped to EDMX property names by replacing spaces with underscores.

  • Primary key fields in tables are automatically defined as properties in the service metadata document even if they are not exposed on a page as controls.

To obtain a service metadata (EDMX) document

  1. You can obtain service metadata documents for either page or query web services. This example uses a page web service. Register and publish a page web service by using the RoleTailored client. For more information, see Walkthrough: Creating and Interacting with a Page Web Service (OData).

  2. Start Windows Internet Explorer. In the Address field, enter a URI in this format:

    Copy Code
     http://<Server>:<WebServicePort>/<ServerInstance>/OData/$metadata

    If Microsoft Dynamics NAV Server is running on the local computer and is using the default Microsoft Dynamics NAV Server instance and OData port, then the address is:

    Copy Code
    http://localhost:7048/DynamicsNAV90/OData/$metadata

    The browser should now show the complete metadata for the page web service that you have published. The beginning of this document looks like this:

See Also

Concepts

OData Web Services


How to: Use OData to Return/Obtain a JSON Document

You can publish a page as a web service and consume it using JavaScript Object Notation (JSON).

To obtain a document based on JSON

  1. You can build applications that consume and display Microsoft Dynamics NAV data using JSON. This example assumes that you have registered and published a page web service in Microsoft Dynamics NAV. For more information, see Walkthrough: Creating and Interacting with a Page Web Service (OData).

  2. Start Windows Internet Explorer. In the Address field, enter a URI in this format:

    Copy Code
    http://<Server>:<WebServicePort>/<ServerInstance>/OData/<web service>?$format=json

    If Microsoft Dynamics NAV Server is running on the local computer and is using the default Microsoft Dynamics NAV Server instance and OData port, and you have published a web service that is based on page 21 that is called Customer, then the address is:

    Copy Code
    http://localhost:7048/DynamicsNAV/OData/Customer?$format=json

    This generates a text file that contains metadata and data from the web service. You can open the file from the browser, or you can save it to disk.

    Note
    The value of the format attribute must be lowercase: ?$format=json.

    If you want to consume the web service as JSON-P, you can add the ?$callback=<callback function name> parameter.

    You can use a similar URI to return the web service as an AtomPub document, in which case the attribute is ?$format=atom. For more information, see How to: Use OData to Return/Obtain an AtomPub Document.

See Also

Concepts

Using OData Web Services to Modify Data


Using Filter Expressions in OData URIs

You can use filter expressions in OData URIs to limit the results that are returned in an AtomPub document. This topic identifies the filter expressions that you can use, describes the equivalent field or table filter that you can use in C/AL, and presents examples to show the syntax for using filter expressions in OData web service URIs and applications.

Filter Expressions

To add a filter to an OData URI, add $filter= to the end of the name of the published web service. For example, the following URI filters the City field in the Customer page to return all customers who are located in Miami:

Copy Code
http://localhost:7048/DynamicsNAV/OData/Company('CRONUS International Ltd.')/Customer?$filter=City eq 'Miami'

The following table shows the filters that are supported in Microsoft Dynamics NAV OData web services and the equivalent C/AL filter expressions. All examples are based either on page 21, Customer (published as Customer), or on page 20, General Ledger Entry (published as GLEntry).

Note
Filters that do not have equivalent C/AL expressions might take longer to process compared to filters that do have equivalent C/AL expressions. The reason is that filters that do not have equivalent C/AL expressions are processed on the Microsoft Dynamics NAV Server tier, while filters that do have equivalent C/AL expressions are processed on the Microsoft Dynamics NAV database tier.

Definition Example and explanation Equivalent C/AL expression

Select a range of values

Copy Code
filter=Entry_No gt 610 and Entry_No lt 615

Query on GLEntry service. Returns entry numbers 611 through 614.

..

And

Copy Code
filter=Country_Region_Code eq 'ES' and Payment_Terms_Code eq '14 DAYS'

Query on Customer service. Returns customers in Spain where Payment_Terms_Code=14 DAYS.

&

Or

Copy Code
filter= Country_Region_Code eq 'ES' or Country_Region_Code eq 'US'

Query on Customer service. Returns customers in Spain and the United States.

Important
You can use OR operators to apply different filters on the same field. However, you cannot use OR operators to apply filters on two different fields.

|

Less than

Copy Code
filter=Entry_No lt 610

Query on GLEntry service. Returns entry numbers that are less than 610.

<

Greater than

Copy Code
filter= Entry_No gt 610

Query on GLEntry service. Returns entry numbers 611 and higher.

>

Greater than or equal to

Copy Code
filter=Entry_No ge 610

Query on GLEntry service. Returns entry numbers 610 and higher.

>=

Less than or equal to

Copy Code
filter=Entry_No le 610

Query on GLEntry service. Returns entry numbers up to and including 610.

<=

Different from (not equal)

Copy Code
filter=VAT_Bus_Posting_Group ne 'EXPORT'

Query on Customer service. Returns all customers with VAT_Bus_Posting_Group not equal to EXPORT.

<>

endswith

Copy Code
filter=endswith(VAT_Bus_Posting_Group,'RT')

Query on Customer service. Returns all customers with VAT_Bus_Posting_Group values that end in RT.

*

startswith

Copy Code
filter=startswith(Name, 'S')

Query on Customer service. Returns all customers names beginning with “S”.

substringof

Copy Code
filter=substringof(Name, ‘urn’)

Query on Customer service. Returns customer records for customers with names containing the string “urn”.

length

Copy Code
filter=length(Name) gt 20

Query on Customer service. Returns customer records for customers with names longer than 20 characters.

indexof

Copy Code
filter=indexof(Location_Code, ‘BLUE’) eq 0

Query on Customer service. Returns customer records for customers having a location code beginning with the string BLUE.

replace

Copy Code
filter=replace(City, 'Miami', 'Tampa') eq 'CODERED'

substring

Copy Code
filter=substring(Location_Code, 5) eq 'RED'

Query on Customer service. Returns true for customers with the string RED in their location code starting as position 5.

tolower

Copy Code
filter=tolower(Location_Code) eq 'code red'

toupper

Copy Code
filter=toupper(FText) eq '2ND ROW'

trim

Copy Code
filter=trim(FCode) eq 'CODE RED'

concat

Copy Code
filter=concat(concat(FText, ', '), FCode) eq '2nd row, CODE RED'

day

Copy Code
filter=day(FDateTime) eq 12

month

Copy Code
filter=month(FDateTime) eq 12

year

Copy Code
filter=year(FDateTime) eq 2010

hour

Copy Code
filter=hour(FDateTime) eq 1

minute

Copy Code
filter=minute(FDateTime) eq 32

second

Copy Code
filter=second(FDateTime) eq 0

round

Copy Code
filter=round(FDecimal) eq 1

floor

Copy Code
filter=floor(FDecimal) eq 0

ceiling

Copy Code
filter=ceiling(FDecimal) eq 1

Referencing Different Data Types in Filter Expressions

You must use the appropriate notation for different data types with filter expressions.

  • String values must be delimited by single quotation marks.

  • Numeric values require no delimiters.

  • DateTime values must be delimited by single quotation marks and preceded by the word datetime, such as datetime'2010-01-25T02:13:40.1374695Z'.

For more information about data types and other information about conventions and standards for OData URIs, see Atom Publishing Protocol: URI Conventions. Conventions for data types are addressed in section 2.2.2, "Abstract Type System."

See Also

Concepts

OData Web Services


How to: Use FlowFilters in OData URIs

You can set FlowFilters on the data that your OData web service extracts from the Microsoft Dynamics NAV database.

FlowFilters are a special kind of filter that you use to set ranges on calculations that are shown in FlowFields. For more information, see FlowFilters. FlowFilters for a page are included in the metadata for that page when it is published as a web service. You can then use FlowFilters as filters in a URI that specifies a query against page data. However, only those FlowFilters that are required to calculate the FlowFields that are exposed on the page as controls are included.

Using FlowFilters to Query Data on the Item Card Page

In this procedure, you create and publish a web service from the Item Card page in Microsoft Dynamics NAV and then query the data in that web service by using a FlowFilter.

To query data on the Item Card page using a FlowFilter

  1. Register and publish a page web service by using the RoleTailored client as described in Walkthrough: Creating and Interacting with a Page Web Service (OData). Register and publish page 30, Item Card, and name the service ItemCard.

  2. Start Windows Internet Explorer, and then in the Address field, enter a URI in this format:

    Copy Code
     http://<Server>:<WebServicePort>/<ServerInstance>/OData/$metadata

    If Microsoft Dynamics NAV Server is running on the local computer and uses the default Microsoft Dynamics NAV Server instance and the default OData port, then the address is:

    Copy Code
    http://localhost:7048/DynamicsNAV/OData/$metadata

  3. Examine the metadata that is returned by this URI. At the end of the list is a set of parameters that end in the word Filter. This is the list of FlowFilters for the page:

    Copy Code
    <Property Type="Edm.String" Name="Location_Filter" Nullable="true"/>
<Property Type="Edm.String" Name="Drop_Shipment_Filter" Nullable="true"/>
<Property Type="Edm.String" Name="Variant_Filter" Nullable="true"/>
<Property Type="Edm.String" Name="Lot_No_Filter" Nullable="true"/>
<Property Type="Edm.String" Name="Serial_No_Filter" Nullable="true"/>
<Property Type="Edm.String" Name="Date_Filter" Nullable="true"/>
    Note
    The set of FlowFilters that is listed in the page metadata may not match the set of FlowFilters on the equivalent page in the RoleTailored client. This is because the RoleTailored client shows all FlowFilter fields that are defined on the table on which the page is based. The metadata only shows the FlowFilters that are used to calculate the FlowField controls that are exposed on the page.

  4. Create a URI that returns information for a single item card. For example:

    Copy Code
    http://localhost:7048/DynamicsNAV/OData/Company('CRONUS%20International%20Ltd.')/ItemCard('1906-S')

    This is the "ATHENS Mobile Pedestal" item. The value for the Qty_on_Sales_Order parameter is 33:

    Copy Code
    <d:Qty_on_Sales_Order m:type="Edm.Decimal">33</d:Qty_on_Sales_Order>

  5. Apply a FlowFilter to that item and specify GREEN as the value for the Location_Filter:

    Copy Code
    http://localhost:7048/DynamicsNAV/OData/Company('CRONUS%20International%20Ltd.')/ItemCard('1906-S')?$filter=Location_Filter eq 'GREEN'

    The item is returned as before, the value of the FlowField that has changed. The value for the Qty_on_Sales_Order parameter is now 27:

    Copy Code
    <d:Qty_on_Sales_Order m:type="Edm.Decimal">27</d:Qty_on_Sales_Order>

    This indicates that there are 27 ATHENS Mobile Pedestals on sales orders designated for the GREEN location.

See Also

Concepts

OData Web Services


Server-Driven Paging in OData Web Services

Server-driven paging ensures that the quantity of data that is returned by an OData URI does not overwhelm Microsoft Dynamics NAV Server or client program that you use to capture data, while optimizing performance.

Note
The term page in this topic refers only to a page that contains OData results and is not related to Microsoft Dynamics NAV page objects.

Configuring Server-Driven Paging

You configure server-driven paging with the Max Page Size setting in the configuration for the Microsoft Dynamics NAV Server instance that you are using for OData services. To modify the setting, you can use Microsoft Dynamics NAV Server Administration Tool or Microsoft Dynamics NAV Windows PowerShell Cmdlets. For more information about Max Page Size and other Microsoft Dynamics NAV Server parameters, see Configuring Microsoft Dynamics NAV Server.

The Max Page Size setting specifies the maximum number of entities returned per page of OData results. The default value is 1000. You can consider a page to be a chunk of data. A large data feed is divided into chunks of data. Each chunk contains no more entities than the value of Max Page Size. An increase in the value of Max Page Size creates fewer chunks (or pages) per request, which in turn, decreases the processing time. However, an increase in the Max Page Size will increase the memory consumption on the Microsoft Dynamics NAV Server or client. If the value is too large, it can overload the memory on Microsoft Dynamics NAV Server. For performance reasons, you should try to set the value of the Max Page Size as large as possible without overloading Microsoft Dynamics NAV Server. If the computer that is running Microsoft Dynamics NAV Server is returning out of memory exceptions, then you should reduce the value of Max Page Size until the errors stop.

When using OData with queries that are set with a top number of rows by either the TopNumberOfRows Property and TOPNUMBEROFROWS Function, you should set the Max Page Size value greater than the value of the TopNumberOfRows property and TOPNUMBEROFROWS function. For more information, see Using OData with Queries That are Set with a Top Number of Rows.

Note
In the CustomSettings.config file for Microsoft Dynamics NAV Server, the Max Page Size setting is called ODataServicesPageMaxSize.

See Also

Concepts

OData Web Services
Managing Microsoft Dynamics NAV Server Instances


Using Containments and Associations

Containments and associations are relationships between pages in Microsoft Dynamics NAV. OData web services in Microsoft Dynamics NAV 2016 support navigation between pages using containments and associations.

  • Containments: Some pages in Microsoft Dynamics NAV contain subpages. When you publish such a page, the subpages are automatically available in the web service as containments.

  • Associations: When a field on a page has a TableRelation property, the specified table has a LookupPageId property that points to a different page. When you publish a page containing such a field as a web service, you must also publish the page that is pointed to by LookupPageId property. You can then link from the first page to the second page in a single URI.

Identifying Containments and Associations in Metadata

OData metadata shows containments and associations with the NavigationProperty tag. For example, if you published page 42, Sales Order, and page 22, Customer List, and then obtained the service metadata document for the server instance, you would see this tag in the metadata:

Copy Code
<NavigationProperty Name="SalesOrderSalesLines" ToRole="SalesOrderSalesLines" FromRole="SalesOrder" Relationship="NAV.SalesOrder_SalesOrderSalesLines"/>

This tag is followed by metadata that specific to the SalesOrderSalesLines subpage. This page metadata indicates that this NavigationProperty tag is a containment:

Copy Code
<EntityType Name="SalesOrderSalesLines">
<Key>
     <PropertyRef Name="Document_No"/>
     <PropertyRef Name="Document_Type"/>
     <PropertyRef Name="Line_No"/>
</Key>
     <Property Name="Document_Type" Nullable="false" Type="Edm.String"/>
     <Property Name="Document_No" Nullable="false" Type="Edm.String"/>
     .......many additional properties........
     <Property Name="ShortcutDimCode_x005B_7_x005D_" Nullable="true" Type="Edm.String"/>
     <Property Name="ShortcutDimCode_x005B_8_x005D_" Nullable="true" Type="Edm.String"/>
</EntityType>

Elsewhere in the metadata, you would see additional NavigationProperty lines and a series of Association tags. Two of these tags have a Multiplicity parameter with a value of 0..1:

Copy Code
<Association Name="SalesOrder_Sell_to_Customer_No_Link">
     <End Type="NAV.SalesOrder" Multiplicity="*" Role="SalesOrder"/>
     <End Type="NAV.CustomerList" Multiplicity="0..1" Role="Sell_to_Customer_No_Link"/>
</Association>
<Association Name="SalesOrder_Bill_to_Customer_No_Link">
     <End Type="NAV.SalesOrder" Multiplicity="*" Role="SalesOrder"/>
     <End Type="NAV.CustomerList" Multiplicity="0..1" Role="Bill_to_Customer_No_Link"/>
</Association>

These tags describe two associations from the Sales Order page to the Customer List page:

  • The Sell-to Customer No. field.

  • The Bill-to Customer No. field.

Using Containments

When you publish a page that has a subpage, you can identify that subpage in the AtomPub document that is returned for the published page. For example, when you publish page 42, Sales Order, you can access a single record on the page using a URI such as the following:

Copy Code
http://localhost:7048/DynamicsNAV90/OData/Company('CRONUS%20International%20Ltd.')/SalesOrder(Document_Type='Order',No='101005')/

The following line in the returned AtomPub document for the record provides link information for a containment:

Copy Code
<link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/SalesOrderSalesLines"
             type="application/atom+xml;type=feed" title="SalesOrderSalesLines"
             href="SalesOrder(Document_Type='Order',No='101005')/SalesOrderSalesLines" />

Notice the type=feed in the line above. To access the subpage data feed, use a URI that incorporates the link that was identified in the previous document:

Copy Code
http://localhost:7048/DynamicsNAV90/OData/Company('CRONUS%20International%20Ltd.')/SalesOrder(Document_Type='Order',No='101005')/SalesOrderSalesLines

Using Associations

Associations are possible when two published pages are linked. Here is an example:

  • Page 42, Sales Order, has its SourceTable property set to table 36, Sales Header. The source expression for the Sell_to_Customer_No control on page 42 is field 2, Sell-to Customer No., in table 36.

  • Field 2, Sell-to Customer No., in table 36 has a TableRelation property set to table 18, Customer, field No.

  • Table 18, Customer, has a LookupPageId property set to page 22, Customer List.

Thus if both page 42, Sales Order, and page 22, Customer List, are published as web services, then an OData URI can link from the Sell_to_Customer_No control on page 42 to the related entity on page 22.

Because of this association, you can create OData URIs to access data on the Customer List page as you work with data on the Sales Order page.

If you publish pages 42 and 22 as web services, then you can return an AtomPub document for the Sales Order page. The following URI returns data for a single record on the page, which is order number 101005:

Copy Code
http://localhost:7048/DynamicsNAV90/OData/Company('CRONUS%20International%20Ltd.')/SalesOrder(Document_Type='Order',No='101005')/

A set of three tags near the top of the returned document show one containment (SalesOrderSalesLines) and two associations (Sell_to_Customer_No and Bill_to_Customer_No) on the page. Notice the type=entry in the following lines:

Copy Code
<link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/SalesOrderSalesLines"
             type="application/atom+xml;type=feed" title="SalesOrderSalesLines"
             href="SalesOrder(Document_Type='Order',No='101005')/SalesOrderSalesLines" />
<link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Sell_to_Customer_No_Link"
             type="application/atom+xml;type=entry" title="Sell_to_Customer_No_Link"
             href="SalesOrder(Document_Type='Order',No='101005')/Sell_to_Customer_No_Link" />
<link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Bill_to_Customer_No_Link"
              type="application/atom+xml;type=entry" title="Bill_to_Customer_No_Link"
              href="SalesOrder(Document_Type='Order',No='101005')/Bill_to_Customer_No_Link" />

This information provides the necessary information to create a URI to access a record on the Customer List page by using an association:

Copy Code
http://localhost:7048/DynamicsNAV90/OData/Company('CRONUS%20International%20Ltd.')
             /SalesOrder(Document_Type='Order',No='101005')/Sell_to_Customer_No_Link

The following URI returns the same information with direct access to the Customer List page:

Copy Code
http://localhost:7048/DynamicsNAV90/OData/CustomerList('30000')

See Also

Concepts

OData Web Services


Using OData with Queries That are Set with a Top Number of Rows

Microsoft Dynamics NAV queries include the TopNumberOfRows Property and TOPNUMBEROFROWS Function that can be used to specify the maximum number of rows to include in the resulting dataset. The OData configuration includes the Max Page Size setting that specifies the maximum number of entities returned per page of OData results. The default value is 1000.

To ensure that the OData results include the correct number of entities when you are using a query that is set with a top number of rows, you should set the Max Page Size value greater than the value that is set by the TopNumberOfRows property and TOPNUMBEROFROWS function. Otherwise, the TopNumberOfRows property and TOPNUMBEROFROWS function are ignored and the query dataset will be returned in the OData results.

Note
Typically, the TopNumberOfRows property or TOPNUMBEROFROWS function are used to return a relatively small number of entities, such as the top five, ten, or 100 entities. Therefore, in most cases, the value of the TopNumberOfRows property and TOPNUMBEROFROWS function will be less than the Max Page Size, so that you will not have to change the Max Page Size setting.

For information about how to change the Max Page Size setting, see Configuring Microsoft Dynamics NAV Server and Server-Driven Paging in OData Web Services.


Using OData Web Services to Modify Data

You can write to the Microsoft Dynamics NAV database using an OData web service that exposes a writable page. For example, you can expose a page as an OData web service and implement it in a portal that is based on Microsoft SharePoint Online. Users of the portal can then modify the data.

Modifying Data Using OData Web Services

If an editable page is exposed as a web service, the data in the underlying table can be accessed and modified by an OData call. Microsoft Dynamics NAV supports the following OData operations for modifying data.

OData call | Data impact | Triggers run on page and table in Microsoft Dynamics NAV
POST | Creates a new entity. | OnNewRecord and OnInsert
PUT and MERGE | Modifies the specified existing entity. | OnModify
DELETE | Deletes the specified existing entity. | OnDelete

All calls fail if the user does not have the relevant permissions, and if the relevant property on the page, InsertAllowed, ModifyAllowed, or DeleteAllowed, is set to No.

You can use an OData web service in applications where you want users to be able to modify Microsoft Dynamics NAV data without using the Microsoft Dynamics NAV Windows client or the Microsoft Dynamics NAV Web client. For example, you can show fields from the Customer table on a mobile device or in a browser so that a user can create, update, or delete customers in the Microsoft Dynamics NAV database.

Company-Specific and Tenant-Specific OData Calls

In your implementation of the web service, you can specify which company in the database that a user can write to in the URIs that expose the web services. Similarly, you can specify the specific tenant that the change applies to if the database handles more than one tenant.

If you do not specify a company, Microsoft Dynamics NAV will identify a default company. The default company is found in the following order of sequence:

  1. The ServicesDefaultCompany setting in the Tenants.config file.

  2. The ServicesDefaultCompany setting in the CustomSettings.config file for Microsoft Dynamics NAV Server.

  3. The company in the current tenant when there is only one company.

    If the OData request is for modifying metadata, Microsoft Dynamics NAV will return the first company in the tenant database because metadata applies to all companies in the database.

If no default company can be found based on the criteria, an error message appears.

See Also

Tasks

How to: Use OData to Return/Obtain a JSON Document
Walkthrough: Creating and Interacting with a Page Web Service (OData)

Concepts

OData Web Services


Web Service Walkthroughs

The walkthroughs in this section demonstrate how to create simple applications that interact with Microsoft Dynamics NAV 2016. These walkthroughs may be useful as foundations upon which you can build actual web service client applications.

To | See
Create an extension codeunit for an existing page, expose the page, and then write code that calls the page. | Walkthrough: Creating a Web Service using Extension Codeunits (SOAP)
Create and consume a simple codeunit web service. | Walkthrough: Creating and Using a Codeunit Web Service (SOAP)
Create and consume a page as a SOAP web service. | Walkthrough: Registering and Using a Page Web Service (SOAP)
Create and consume an OData web service that updates Microsoft Dynamics NAV data. | Walkthrough: Creating and Interacting with a Page Web Service (OData)
View and analyze Microsoft Dynamics NAV page data in Microsoft Excel using Microsoft PowerPivot for Excel, which is a data analysis add-in. | Walkthrough: Viewing Page Data in Excel Using PowerPivot (OData)
Make web service communication more secure. | Walkthrough: Configuring Web Services to Use SSL (SOAP and OData)
Combine data from Microsoft Dynamics NAV 2016 with data from Microsoft Azure Marketplace. | Walkthrough: Combining Data from Microsoft Dynamics NAV Queries and Pages with Data from Azure DataMarket (OData)

See Also

Concepts

Microsoft Dynamics NAV Web Services Overview


Walkthrough: Creating and Using a Codeunit Web Service (SOAP)

Web services provide easy communication and data exchange in a secured environment. In Microsoft Dynamics NAV 2016, you can create, publish, and use web services. For example, you can publish a web service that lists all your customers and have that web service be immediately available for authorized requests over the network.

About This Walkthrough

This walkthrough provides an overview of how to create and use a simple SOAP web service. The walkthrough illustrates to the following tasks:

  • Creating a codeunit in Microsoft Dynamics NAV.

  • Publishing the codeunit as a web service.

  • Verifying web service availability.

  • Using the web service from a console application that you create in Visual Studio.

Note
You can publish codeunits only as SOAP services, not as OData web services.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 with a developer license.

  • CRONUS International Ltd. demonstration database.

  • Visual Studio 2012 or Visual Studio 2010. You can use any edition of Visual Studio that supports adding web references. In this walkthrough, you will use Visual Studio 2012. You also have the option of using service references instead of web references, or of using the web service proxy generating tools svcutil.exe and wsdl.exe, which are included in the Microsoft .NET Framework SDK.

Creating a Codeunit

In this procedure, you create a codeunit called Letters that takes a lowercase input string and returns an uppercase string.

To create a codeunit

  1. Open the Microsoft Dynamics NAV development environment and then connect to the CRONUS International Ltd. company.

    Object Designer opens automatically in the development environment.

  2. In Object Designer, choose Codeunit, and then choose New

    The C/AL Editor opens.

  3. On the View menu, choose C/AL Globals.

  4. In the C/AL Globals window, choose the Functions tab, and then enter Capitalize as the function name.

  5. Select the Capitalize function, in the View menu, choose Properties, and then set the Local property to No.

    Setting this property makes the function accessible from the other objects. For more information about this property, see Local Property.

  6. In the C/AL Globals window, choose the Locals button.

  7. On the Parameters tab, type inputstring in the Name field, and then select Text in the DataType field. Set the length to 250.

  8. On the Return Value tab, enter outputstring in the Name field, and then select Text in the Return Type field. Set the length to 250.

  9. Close the C/AL Locals window, and then close the C/AL Globals window.

  10. In the C/AL Editor, under Capitalize, add the following line of code:

    Copy Code
    outputstring := UPPERCASE(inputstring);

  11. Choose Save from the File menu.

  12. When you are prompted, enter 50000 for the codeunit ID, then enter Letters for the name, make sure the compile check box is checked, and then choose OK.

Publishing the Web Service

After the codeunit is created and saved, you publish it using the RoleTailored client.

To publish the web service

  1. Open the RoleTailored client, and then connect to the CRONUS International Ltd. company.

  2. In the Search box, enter Web Services, and then press Return.

  3. In the Web Services page, choose New.

  4. In the Object Type column, select Codeunit, then in the Object ID column enter 50000, and then enter Letters in the Service Name column.

  5. Mark the check box in the Published column and choose OK to close the New - Web Services page.

Verifying Web Service Availability

Note
After publishing a web service, verify that the port that web service applications will use to connect to your web service is open. The default port for SOAP-based web services is set to 7047. You can configure this value by using the Microsoft Dynamics NAV Server Administration Tool.

To verify availability of the web service

  1. Start Windows Internet Explorer.

  2. In the Address field, enter an address in the following format: http://<Server>:<WebServicePort>/<ServerInstance>/WS/<CompanyName>/services.

    For example:

    http://localhost:7047/DynamicsNAV/WS/CRONUS%20International%20Ltd./services

    Note
    The company name is case-sensitive.

    The page should list the web service that you just published (Codeunit/Letters).

Using the Web Service

In this walkthrough we use Visual Studio 2012 to call and use the web service.

To call the web service

  1. In Visual Studio, on the File menu, select New, and then choose Project.

  2. Under Installed Templates, expand the Visual C# node, select Windows, and then, select Console Application.

  3. Enter the name UsingLettersService for the application and choose OK to close the New Project page.The sample code in this walkthrough expects this exact application name, so do not change it.

  4. In Solution Explorer, right-click the References node in the project, and then choose Add Service Reference.

  5. In the Add Service Reference window, choose the Advanced button.

  6. In the Service Reference Settings window, choose the Add Web Reference button, type or paste the URL that you used when you checked the WSDL, such as http://localhost:7047/DynamicsNAV/WS/Services, and then choose Go (the green button with the arrow).

  7. When the Letters service is displayed on the discovery Page, choose View Service, then in the Web reference name text box, rename localhost to WebService, and then choose Add Reference.

  8. In Solution Explorer, choose Program.cs and replace the existing code with the following code:

    C# Copy Code
    using System;
using System.Collections.Generic;
using System.Text;
namespace UsingLettersService
{
    // Imports newly generated web service proxy.
    using WebService;
    class Program
    {
        static void Main(string[] args)
        {
            // Creates a new instance of the service.
            Letters ws = new Letters();

            // Uses default credentials for authenticating
            // with Microsoft Dynamics NAV.
            ws.UseDefaultCredentials = true;
            ws.Url = "http://localhost:7047/DynamicsNAV90/WS/CRONUS%20International%20Ltd./Codeunit/Letters";
            // Declares variables to work with.
            string inputstring, outputstring;
            inputstring = "microsoft dynamics nav web services!";

            // Calls the Microsoft Dynamics NAV codeunit web service.
            outputstring = ws.Capitalize(inputstring);
            // Writes output to the screen.
            Console.WriteLine("Result: {0}", outputstring);
            // Keeps the console window open until you press ENTER.
            Console.ReadLine();
        }
    }
}

  9. On the Build menu, select Build Solution to build your project and then, from the Debug menu, choose Start Debugging to run the application in debug mode. You should see a console window that prints the text MICROSOFT DYNAMICS NAV WEB SERVICES! in uppercase letters.

  10. Press Enter to close the application.

Next Steps

This walkthrough illustrated how you can publish a codeunit as a web service from Microsoft Dynamics NAV and write a program that uses the web service. The next step is to expose a page as a web service and then interact with data from that page. For details, see Walkthrough: Registering and Using a Page Web Service (SOAP).

See Also

Tasks

How to: Publish a Web Service
Walkthrough: Configuring Web Services to Use SSL (SOAP and OData)

Concepts

Web Services
SOAP Web Services
Microsoft Dynamics NAV Web Services Overview
Web Service Alternatives: SOAP and OData


Walkthrough: Registering and Using a Page Web Service (SOAP)

This walkthrough focuses on publishing a Microsoft Dynamics NAV page as a SOAP web service and then using it in a Visual Studio 2012 console application. When you publish a page as a web service, you expose a default set of operations for managing common record-handling tasks to developers. The walkthrough shows how to use some of these operations. Compare this walkthrough with Walkthrough: Creating and Interacting with a Page Web Service (OData).

About This Walkthrough

This walkthrough provides an overview of how to publish a page as a web service and then interact with data from that page in a Visual Studio console application. This walkthrough uses a SOAP web service, although you can also create an OData web service to interact with page data. The walkthrough illustrates the following tasks:

  • Publishing an existing page as a web service.

  • Verifying the web service availability from a browser.

  • Using the web service in a Visual Studio console application.

  • Making calls to the Create, Read, Update, and Delete functions on a page web service.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 with a developer license.

  • CRONUS International Ltd. demonstration database.

  • Visual Studio 2012, Visual Studio 2010, or Visual Studio 2008. You can use any edition of Visual Studio that supports adding web references. In this walkthrough, you will use Visual Studio 2012. You also have the option of using service references instead of web references, or of using the web service proxy generating tools svcutil.exe and wsdl.exe, which are included in the Microsoft .NET Framework SDK.

Publishing a Page as a Web Service

You publish a web service using the RoleTailored client.

To publish a page as a web service

  1. Open the Microsoft Dynamics NAV Windows client, and then connect to the CRONUS International Ltd. company.

  2. In the Search box, enter Web Services, and then press Return.

  3. In the Web Services page, choose New.

  4. In the Object Type column, select Page, and then enter 21 in the Object ID column and Customer in the Service Name column.

  5. Mark the check box in the Published column.

  6. Choose OK to close the New - Web Services page.

Verifying Web Services Availability

Note
After publishing a web service, verify that the port that web service applications will use to connect to your web service is open. The default port for SOAP-based web services is set to 7047. You can configure this value by using the Microsoft Dynamics NAV Server Administration Tool.

To verify availability of a Microsoft Dynamics NAV web service

  1. Start Windows Internet Explorer.

  2. In the Address field, enter an address of the following type: http://<Server>:<WebServicePort>/<ServerInstance>/WS/<CompanyName>/services. For example:

    http://localhost:7047/ DynamicsNAV90/WS/CRONUS%20International%20Ltd./services

    Note
    The company name is case-sensitive.

    The browser should now show the web service that you have published:

    Copy Code
    <contractRef xmlns="http://schemas.xmlsoap.org/disco/scl/" ref="http://localhost:7047/DynamicsNAV90/WS/CRONUS International Ltd/Page/Customer"/>

Calling the Web Service

In this walkthrough we use Visual Studio 2012 to call and use the web service.

To call the web service

  1. In Visual Studio, on the File menu, point to New, and then choose Project.

  2. Expand the Visual C# node, select Windows, and then, under Visual Studio installed templates, select Console Application. Enter the name PrintCustomerList for the application.

    Important
    The sample code in this walkthrough expects this exact application name, so you should not change it.

  3. Choose OK to close the New Project page.

  4. In Solution Explorer, right-click References in the project, and then choose Add Service Reference.

  5. Choose the Advanced button, choose the Add Web Reference button, type or paste the URL that you used when you checked the WSDL, such as http://localhost:7047/DynamicsNAV90/WS/Services, and then choose Go.

  6. When the Customer service is displayed, choose View Service, rename localhost to WebService, and then choose Add Reference.

  7. On the Program.cs tab, replace the existing code with the following code:

    C# Copy Code
    using System;
using System.Collections.Generic;
using System.Text;
namespace PrintCustomerList
{
    // Import newly generated web service proxy.
    using WebService;

    class Program
    {
        static void Main(string[] args)
        {
            // Creates instance of service and sets credentials.
            Customer_Service service = new Customer_Service();
            service.UseDefaultCredentials = true;
            // Creates instance of customer.
            Customer cust = new Customer();
            cust.Name = "Customer Name";
            Msg("Pre Create");
            PrintCustomer(cust);

            // Inserts customer.
            service.Create(ref cust);
            Msg("Post Create");
            PrintCustomer(cust);
            // Creates filter for searching for customers.
            List<Customer_Filter> filterArray = new List<Customer_Filter>();
            Customer_Filter nameFilter = new Customer_Filter();
            nameFilter.Field = Customer_Fields.Name;
            nameFilter.Criteria = "C*";
            filterArray.Add(nameFilter);
            Msg("List before modification");
            PrintCustomerList(service, filterArray);
            cust.Name = cust.Name + "Updated";
            service.Update(ref cust);
            Msg("Post Update");
            PrintCustomer(cust);
            Msg("List after modification");
            PrintCustomerList(service, filterArray);
            service.Delete(cust.Key);
            Msg("List after deletion");
            PrintCustomerList(service, filterArray);
            Msg("Press [ENTER] to exit program!");
            Console.ReadLine();
        }
        // Prints list of filtered customers.
        static void PrintCustomerList(Customer_Service service, List<Customer_Filter> filter)
        {
            Msg("Printing Customer List");

            // Runs the actual search.
            Customer[] list = service.ReadMultiple(filter.ToArray(), null, 100);
            foreach (Customer c in list)
            {
                PrintCustomer(c);
            }
            Msg("End of List");
        }
        static void PrintCustomer(Customer c)
        {
            Console.WriteLine("No: {0} Name: {1}", c.No,c.Name);
        }
        static void Msg(string msg)
        {
            Console.WriteLine(msg);
        }
    }
}

  8. On the Build menu, select Build Solution to build your project and then, from the Debug menu, choose Start Debugging to run the application in debug mode. You should now see a console window that prints a list of customers from the CRONUS International Ltd. company. One customer in the list is created, then is modified, and is finally deleted.

See Also

Tasks

Walkthrough: Creating and Interacting with a Page Web Service (OData)


Walkthrough: Creating a Web Service using Extension Codeunits (SOAP)

This walkthrough shows how to publish and consume a Microsoft Dynamics NAV page as a web service and how you can extend the Basic Page Operations.

About This Walkthrough

This walkthrough illustrates the following tasks:

  • Registering and publishing a page as a web service.

  • Creating an extension codeunit.

  • Connecting the extension codeunit to the published page.

  • Verifying the service's availability.

  • Calling the web service from a console application that you create in Visual Studio.

Prerequisites

To complete this walkthrough, you need:

  • Microsoft Dynamics NAV 2016 with a developer license.

  • CRONUS International Ltd. demonstration database.

  • Visual Studio 2012 or Visual Studio 2010. You can use any edition of Visual Studio that supports adding web references. In this walkthrough, you will use Visual Studio 2012. You also have the option of using service references instead of web references, or of using the web service proxy generating tools svcutil.exe and wsdl.exe, which are included in the Microsoft .NET Framework SDK.

Publishing a Page as a Web Service

You publish a web service using the RoleTailored client.

To register and publish a page as a web service

  1. Open the RoleTailored client, and then connect to the CRONUS International Ltd. demonstration database.

  2. In the Search box, enter Web Services, and then press Return.

  3. In the Web Services page, choose New.

  4. In the Object Type column, select Page, then enter 21 in the Object ID column and then enter PageWithCapitalization in the Service Name column.

  5. Choose to select the field in the Published column.

  6. Choose OK to close the New - Web Services page.

    Do not close the RoleTailored client or navigate away from the Web Services page.

Creating an Extension Codeunit

After you publish the page, you create a codeunit that extends its functionality. Follow the steps in this procedure to create a codeunit called CapitalizeName, which takes a customer name as input and outputs the same customer name capitalized. The codeunit must take the record type of the page as the first parameter.

To create an extension codeunit

  1. Open the Microsoft Dynamics NAV 2016 development environment, and then connect to the CRONUS International Ltd. demonstration database.

  2. On the Tools menu, choose Object Designer.

  3. In Object Designer, choose Codeunit, and then choose New.

  4. On the View menu, choose C/AL Globals.

  5. In the C/AL Globals window, choose the Functions tab, and then enter CapitalizeName in the name column.

  6. Select the CapitalizeName function, in the View menu, choose Properties, and then set the Local property to No.

    Setting this property makes the function accessible from the other objects. For more information about this property, see Local Property.

  7. In the C/AL Globals window, choose the Locals button.

  8. On the Parameters tab, enter Cust in the Name field, and then select Record in the DataType field.

  9. In the SubType field, choose the arrow to open the Table list window and select Customer.

  10. Choose OK to close the Table list window.

  11. Close the C/AL Locals window, and then close the C/AL Globals window.

  12. In the CapitalizeName method, insert the following lines of code:

    Copy Code
    Cust.Name := UPPERCASE(Cust.Name);
Cust.MODIFY(TRUE);

  13. Close the C/AL Editor.

  14. When prompted, enter 50012 in the ID text box, enter CapitalizeName in the Name text box then select the Compile check box and then choose OK.

Connecting the Codeunit to the Exposed Page

After the codeunit is created and saved, register it under the published page so that the codeunit extends the published page. The codeunit itself should not be marked as Published.

To connect the codeunit to the exposed page

  1. Navigate to the RoleTailored client again, and on the Web Services page, choose New.

  2. In the Object Type field, select Codeunit, and then select object ID 50012. In the Service Name field, enter PageWithCapitalization, which is the same name that you gave the page web service.

  3. Clear the Published check box.

  4. Choose OK to close the New - Web Services page.

Verifying Web Services Availability

Note
When exposing a web service, you must open the port for other consumers of your web service to access it. You can have your system administrator add the port through Windows Firewall on the computer running Microsoft Dynamics NAV Server. The default port for SOAP web services is 7047. Use the Microsoft Dynamics NAV Server Administration Tool to configure the port for the Microsoft Dynamics NAV Server instance; the option is on the SOAP Web Services tab.

To verify availability of the web service

  1. Start Windows Internet Explorer.

  2. In the Address field, enter the following address where the keys are replaced with the values that are specified in the CustomSettings.config file: http://<Server>:<WebServicePort>/<ServerInstance>/WS/<CompanyName>/services.

    For example:

    http://localhost:7047/DynamicsNAV/WS/CRONUS%20International%20Ltd./services

    Note
    The company name is case-sensitive.

    The page should list the page web service that you have published: Page/PageWithCapitalization.

  3. Close the browser.

Calling the Web Services

Now you can create an application that uses both the page and the codeunit web services. When you add a reference in Visual Studio, methods from both the page and the extension codeunit are available.

To call the web services

  1. In Visual Studio, on the File menu, select New, and then choose Project.

  2. Under Installed Templates, expand the Visual C# node, select Windows, and then, select Console Application.

  3. Enter the name UsingExtensionCodeunit for the application.

    Note
    The sample code in this walkthrough expects this exact application name, so do not change it.

  4. Choose OK to close the New Project page.

  5. In Solution Explorer, right-click the References node in the project, and then choose Add Service Reference.

  6. In the Add Service Reference dialog box, choose the Advanced button, choose the Add Web Reference button, in the URL text box, type or paste the URL that you used when checking the WSDL, such as http://localhost:7047/DynamicsNAV/WS/Services, and then choose Go.

  7. When the services are displayed, select the Page service (Page/PageWithCapitalization. Then choose View Service.

    Note the first service listed: CapitalizeName. This is the codeunit you have created to enhance the basic functionality available with a page web service.

  8. In the Web reference name text box, rename localhost to WebService, and then choose Add Reference.

  9. If the program.cs file is not already open, choose the Program.cs tab, to open the code editor and replace the existing code with the following code:

    C# Copy Code
    using System;
using System.Collections.Generic;
using System.Text;
namespace UsingExtensionCodeunit
{
    using WebService;
    class Program
    {
        static void Main(string[] args)
        {
            // Creates instance of service and set credentials.
            PageWithCapitalization_Service service = new PageWithCapitalization_Service();
            service.UseDefaultCredentials = true;

            // Creates instance of customer.
            PageWithCapitalization cust = new PageWithCapitalization();
            cust.Name = "Louis Taylor";

            // Inserts customer using the default operation.
            service.Create(ref cust);
            Console.WriteLine(cust.Name);
            // Calls extension codeunit to capitalize customer name.
            service.CapitalizeName(cust.Key);

            // Refreshes customer.
            cust = service.Read(cust.No);
            Console.WriteLine(cust.Name);
            Console.ReadLine();
            service.Delete(cust.Key);
        }
    }
}

  10. On the Build menu, select Build Solution to build your project and then, from the Debug menu, choose Start Debugging to run the application in debug mode. You should now see a console window that creates a new customer using a default page operation and then capitalizes the customer name using the extension codeunit.

See Also

Concepts

Microsoft Dynamics NAV Web Services Overview


Walkthrough: Configuring Web Services to Use SSL (SOAP and OData)

Secure Sockets Layer (SSL) is a cryptographic protocol that helps provide security and data integrity for data communications over a network. By encrypting your Microsoft Dynamics NAV web services using SSL, you make your data and the network more secure and more reliable.

Microsoft Dynamics NAV Web Services and SSL

Microsoft Dynamics NAV supports SSL authentication for SOAP and OData web services. The server authenticates itself to the client, but the client does not authenticate itself to the server. When the web service client connects to the Microsoft Dynamics NAV Server instance, the server replies by sending its digital certificate to the client. This certificate contains the server's public encryption key and the name of the authority that granted the certificate. The client verifies the certificate using the authority's public key.

About This Walkthrough

This walkthrough illustrates the following tasks:

  • Configuring Microsoft Dynamics NAV Web Services to Use SSL

  • Obtaining an SSL Certificate

  • Importing the SSL Certificate into the Local Computer Store of the Microsoft Dynamics NAV Server computer

  • Granting Permissions to the Certificate's Private Key to Microsoft Dynamics NAV Server

  • Obtaining the Certificate's Thumbprint

  • Configuring the Access Control List and the Web Services Ports for SSL

  • Verifying the Configuration

  • Restart the Microsoft Dynamics NAV Server Instance

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 with a developer license.

  • The makecert.exe tool (Certificate Creation Tool) for creating SSL certificates.

    The makecert.exe generates certificates for testing purposes. It is available with Microsoft Visual Studio and Microsoft Windows SDK. For more information, see Certificate Creation Tool (Makecert.exe) in the MSDN Library.

    Note
    The makecert.exe tool is only required if you do not already have an SSL certificate and you want to create a certificate for test purposes.

Story

Victor, who is a business systems developer at CRONUS International Ltd., knows that his implementation of web services applications for Microsoft Dynamics NAV is unlikely to pass a company security audit unless he encrypts sensitive data that is transmitted over the company intranet. He decides to protect web services communication with SSL.

Configuring Microsoft Dynamics NAV Web Services to Use SSL

The first step is to prepare Microsoft Dynamics NAV to use SSL. This involves configuring the relevant Microsoft Dynamics NAV Server instance to specify SSL.

You can configure Microsoft Dynamics NAV Server instances with the Microsoft Dynamics NAV Server Administration Tool or Microsoft Dynamics NAV Windows PowerShell Cmdlets. For more information, see Managing Microsoft Dynamics NAV Server Instances.

The following procedure uses Microsoft Dynamics NAV Server Administration tool to configure the Microsoft Dynamics NAV Server instance.

To configure the Microsoft Dynamics NAV Server instance to use SSL

  1. Choose the Start button, and in the Search programs and files box, type Microsoft Dynamics NAV Administration, and then choose the related link.

  2. In Microsoft Dynamics NAV Server Administration tool, in the left pane, under Console Root, expand the node for the Microsoft Dynamics NAV Server computer. This is typically named Microsoft Dynamics NAV (Local), which is the local computer.

    The Microsoft Dynamics NAV Server instances on the computer appear in the left pane and center panes.

    Console root with two server instances

  3. In the left pane, choose the relevant instance to display settings for that instance in the center pane.

  4. At the bottom of the center pane, choose Edit.

  5. To configure SOAP web services to use SSL, expand the SOAP Web Services tab, and then select the Enable SSL option.

    Make a note of the port that is used by SOAP web services. You will need the port number later on in this walkthrough.

  6. To configure OData web services to use SSL, expand the OData Web Services tab, and then select the Enable SSL option.

    Make a note of the port that is used by OData web services. You will need the port number later on in this walkthrough.

  7. Choose Save at the bottom of the center pane.

  8. In the right pane, under Actions, choose Login Account.

  9. Make a note of the service account information. You will need this information later on in this walkthrough.

Obtaining an SSL Certificate

The certificate is a file that Microsoft Dynamics NAV Server uses to prove its identity and establish a trusted connection with the client that is trying to connect. In a production environment, you obtain an SSL certificate from a certification authority. Some large organizations may have their own certification authorities, and other organizations can request a certificate from a third-party organization. In a test environment, if you do not have certificate, then you can create your own test certificate by using the makecert.exe tool as described in the following procedure.

In the following procedure, you use the makecert.exe tool to create a test certificate file (.cer) with a private key file (.pvk), and then generate a personal information file (.pfx) from the two files. You will use the .pxf in the next procedure for importing the certificate on the computer running Microsoft Dynamics NAV Server.

Note
If you have a certificate, then you can skip this procedure and continue to Importing the SSL Certificate into the Local Computer Store of the Microsoft Dynamics NAV Server computer.

To create a test SSL certificate using the makecert.exe tool

  1. On the computer that is installed with Microsoft Visual Studio 2012 or Windows SDK, create a folder called My Certificates for working with and storing certificates.

    You can work on the same computer that is running Microsoft Dynamics NAV Server or a different computer.

  2. Open the command prompt as follows:

    If your computer is installed with Then

    Microsoft Visual Studio 2012

    1. Choose the Start button, choose All Programs.

    2. Choose Microsoft Visual Studio, choose Visual Studio Tools, and then right-click Visual Studio Command Prompt and choose Run as Administrator.

    Microsoft Windows SDK

    1. Choose the Start button, choose All Programs.

    2. Choose Microsoft Windows SDK, choose Microsoft Windows SDK, and then right-click Windows SDK Command Prompt and choose Run as Administrator.

  3. At the command prompt, change to the folder that you created for the certificates. For example, type cd\My Certificates, and then press Enter.

  4. To create the SSL certificate with a private key file, type the following command.

    Copy Code
    makecert -r -pe -n "CN=Nav Test Cert" -b 01/01/2015 -e 01/01/2016 -sv NavTestCert.pvk NavTestCert.cer

    A certificate file called NavTestCert.cer and a private key file called NavTestCert.pvk are created in the temporary folder.

    Tip
    If you are working on the computer running Microsoft Dynamics NAV Server, you can use the following command to create and install the certificate, so you can skip the next procedure for importing the certificate.

    makecert -r -pe -n "CN=NavTestCert" -b 01/01/2015 -e 01/01/2016 -ss my -sr localmachine -sky exchange

  5. To generate a personal information exchange (.pfx) file from the NavTestCert.cer and NavTestCert.pvk files, type the following command. Substitute mypassword with a password of your own.

    Copy Code
    pvk2pfx -pvk NavTestCert.pvk -spc NavTestCert.cer -pfx NavTestCert.pfx -po mypassword

    This creates a file called NavTestCert.pfx file in the temporary folder. The file is assigned a password of by the po option. You will use this password when you import the certificate into the local machine.

  6. If you are not working on the computer running Microsoft Dynamics NAV Server, then copy the .pfx to the Microsoft Dynamics NAV Server computer.

Important
To avoid validation errors, make sure that the certificate that you create and self-sign has the same name as the host name, which is accessed from all the remote machines. The machine name is specified in “CN=<machine name>”. If you use the http://hostname:Port/NAVserver/ link to access your Microsoft Dynamics NAV service, then you should specify the -n “CN=hostname” flag to the makecert command instead.

Importing the SSL Certificate into the Local Computer Store of the Microsoft Dynamics NAV Server computer

Once you obtain a certificate, you must import it into the local computer store on the computer running Microsoft Dynamics NAV Server. The certificate file will have the extension .cer or .pfx.

To import an SSL certificate into the local computer store

  1. On the computer running Microsoft Dynamics NAV Server, choose Start, and then choose Run.

  2. In the Open box, type mmc, and then choose OK.

    Note
    This procedure assumes that you do not already have the Certificates snap-in installed in Microsoft Management Console. If the Certificates snap-in is already installed, skip steps 3 to 7 and go to step 8.

  3. On the File menu, choose Add/Remove Snap-in.

  4. In the Add/Remove Snap-in dialog box, choose Certificates, and then choose Add.

  5. In the Certificates snap-in dialog box, choose Computer account, and then choose Next.

  6. In the Select Computer dialog box, choose Local computer, and then choose Finish.

  7. In the Add/Remove Snap-in dialog box, choose OK.

  8. In the left pane of the console, double-click and expand the Certificates (Local Computer).

  9. Right-click Personal, point to All Tasks, and then choose Import.

  10. On the Welcome to the Certificate Import Wizard page, choose Next.

  11. On the File to Import page, choose Browse, locate your certificate file, for example NavTestCert.pfx.

    If the certificate is in a personal information exchange file (.pfx), set the box next to File name to Personal Information Exchange (*.pfx;*.p12), and then browse for the certificate file.

  12. Select the certificate file, and then choose Open, and then choose Next.

  13. If prompted for a password, type the password on the Password page, and then choose Next.

  14. On the Certificate Store page, choose Place all certificates in the following store, and then choose Next.

  15. Choose Finish, and then choose OK to confirm that the import was successful.

Granting Permissions to the Certificate's Private Key to Microsoft Dynamics NAV Server

If the certificate has a private key, then you must give the service account of Microsoft Dynamics NAV Server access to the private key.

To grant access to the certificate’s private key to the service account for Microsoft Dynamics NAV Server

  1. In the left pane of MMC, expand the Certificates (Local Computer) node, expand the Personal node, and then choose the Certificates folder.

  2. In the center pane, right-click the certificate that you imported, choose All Tasks, and then choose Manage Private Keys.

  3. In the Permissions for private keys dialog box, choose Add.

  4. In the Select Users, Computers, Service Accounts, or Groups dialog box, in the Enter the object names to select box, type the name of the service account for Microsoft Dynamics NAV Server, and then choose OK.

  5. On the Security tab, under Allow, select Full Control and Read, and then choose OK.

Obtaining the Certificate's Thumbprint

The thumbprint is a string of hexadecimal characters that identifies the certificate. You use the thumbprint when you configure the web service's port to use the certificate. To perform this task, you continue working in the Certificates snap-in in Microsoft Management Console.

To obtain the certificate's thumbprint

  1. In the left pane under Console Root, expand the Certificates (Local Computer) node, expand the Personal folder, and then choose the Certificates folder

    The center pane displays all the certificates.

  2. Right-click the certificate that you imported, and then choose Open.

  3. In the Certificate dialog box, choose the Details tab.

  4. Scroll through the list of fields, and then choose Thumbprint.

  5. Copy the hexadecimal characters from the box, and then paste them in a text editor, such as Notepad. These characters make up the thumbprint.

  6. In the text editor, delete all spaces from the thumbprint string.

    For example, if the thumbprint is c0 d0 f2 70 95 b0 3d 43 17 e2 19 84 10 24 32 8c ef 24 87 79, then change it to c0d0f27095b03d4317e219841024328cef248779.

  7. Keep the file open or save it. You will use the thumbprint later on.

Configuring the Access Control List and the Web Services Ports for SSL

An access control list (ACL) is part of the Windows security infrastructure and features. The ACL controls who can access resources on a computer. For more information, see Access Control Lists.

Note
These procedures use the netsh tool (netsh.exe) for configuring the HTTP server. The netsh tool is supplied with Windows. By default the netsh tool is located in the c:\Windows\System32 folder.

To configure the ACL

  1. On the computer running Microsoft Dynamics NAV Server, open a command prompt as an administrator as follows:

    1. From the Start menu, choose All Programs, and then choose Accessories.

    2. Right-click Command Prompt, and then choose Run as administrator.

  2. At the command prompt, type the following command to change to the Windows\System32 directory.

    Copy Code
    cd\Windows\System32

  3. To view the ACL for the web services ports to determine if any entries are already using the relevant host name and port, type the following command:

    Copy Code
    netsh http show urlacl

    Each entry is listed by the Reserved URL field, which has the format http://hostname:port. hostname is the name of the computer running the service and port is the port number the service runs on. A '+' (plus sign) in the Reserved URL field represents localhost, which indicates the computer that you are working on.

    By default, SOAP and OData web services in Microsoft Dynamics NAV use ports 7047 and 7048, respectively, and connect to a Microsoft Dynamics NAV Server instance namedDynamicsNAV90. The default reserved URL entries for these services are: http://+:7047/DynamicsNAV90/ and http://+:7048/DynamicsNAV90/.

  4. You must delete any entries that use the same port as the SOAP or OData web services.

    To delete an entry, type the following command:

    Copy Code
    netsh http delete urlacl url=http://hostname:Port/NAVserver/

    Substitute Port with the port number of the SOAP or OData web service and NAVserver with the name of the Microsoft Dynamics NAV Server instance.

    For example, to delete the default entries for SOAP and OData, use the following two commands:

    Copy Code
    netsh http delete urlacl url=http://+:7047/DynamicsNAV90/
    Copy Code
    netsh http delete urlacl url=http://+:7048/DynamicsNAV90/

  5. To register the ports for the SOAP and OData web service with https, type the following command for each service:

    Copy Code
    netsh http add urlacl url=https://hostname:port/navserver user=DOMAIN\user

    Substitute the following options with the proper values:

    Option Description

    hostname

    The name of the computer running Microsoft Dynamics NAV Server. Use + for localhost.

    port

    The port that is used by the web service.

    navserver

    The name of the Microsoft Dynamics NAV Server instance to use with the web service. The default is DynamicsNAV90.

    DOMAIN\username

    The domain and user name of the service account for Microsoft Dynamics NAV Server. If the service account for Microsoft Dynamics NAV Server is Network Service, then use "NT AUTHORITY\NETWORKSERVICE".

    For example, if the service account for Microsoft Dynamics NAV Server has the domain ABC and the user name xyz, and then the command for the SOAP web service is as follows:

    Copy Code
    netsh http add urlacl url=https://+:7047/DynamicsNAV90 user="NT AUTHORITY\NETWORKSERVICE"

    If the service account for Microsoft Dynamics NAV Server is Network Service, then the command is as follows:

    Copy Code
    netsh http add urlacl url=https://+:7047/DynamicsNAV90 user="NT AUTHORITY\NETWORKSERVICE"

  6. To verify that your port has been registered, repeat step 3.

To configure the port to use the SSL certificate

  1. At the command prompt, type the following command to view the current port configurations:

    Copy Code
    netsh http show sslcert

    All port bindings to SSL certificates are listed. Each entry is indicated by the IP:port field, where IP is the IP address that uses the port (0.0.0.0 indicates all IP addresses) and port is the port number.

  2. If SSL is already configured on the address and port that you want to use for SOAP or OData web services, then use the following command to delete the entry:

    Copy Code
    netsh http delete ssl ipport=ipaddress:port

    Substitute ipaddress and port with the IP address and port number of the entry that you want to delete.

    For example, to delete the entry on the default SOAP port, use the following command:

    Copy Code
    netsh http delete ssl ipport=0.0.0.0:7047

  3. To bind an SSL certificate to the SOAP or OData web service port, use the following command:

    Copy Code
    netsh http add sslcert ipport=ipaddress:port certhash=thumbprint appid={id}

    Substitute the following options with the proper values:

    Option Description

    ipaddress

    The IP address that can use the web service. Use 0.0.0.0 to include all IP addresses.

    port

    The port that is used by the web service.

    thumbprint

    The certificate thumbprint that you pasted to NotePad previously.

    id

    A 32-digit hexadecimal number that identifies the Microsoft Dynamics NAV application. The id must be in the format {NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN). If you do not know the appid, then use any value, such as {00112233-4455-6677-8899-AABBCCDDEEFF}.

    For example, the following command binds a certificate that has the thumbprint c0d0f27095b03d4317e219841024328cef248779 to port 7047 for all IP addresses:

    Copy Code
    netsh http add sslcert ipport=0.0.0.0:7047 certhash=c0d0f27095b03d4317e219841024328cef248779 appid={00112233-4455-6677-8899-AABBCCDDEEFF}

Restart the Microsoft Dynamics NAV Server Instance

You can use the Microsoft Dynamics NAV Server Administration Tool to restart the Microsoft Dynamics NAV Server instance.

To restart Microsoft Dynamics NAV Server

  1. In Microsoft Dynamics NAV Server Administration tool, in the left pane, under Console Root, choose the Microsoft Dynamics NAV Server computer.

  2. In the center pane, choose the Microsoft Dynamics NAV Server instance that you have configured, and then in the right pane under Actions, choose Restart.

  3. After the instance restarts, close Microsoft Dynamics NAV Server Administration tool.

Verifying the Configuration

You should now be able to use web services that are encrypted with SSL. To verify this, type the following URL in the address bar for your browser.

https://localhost:7047/DynamicsNAV90/WS/services

The page lists any web services that have been published.

Next Steps

You can now try out any other SOAP web service and OData walkthroughs with SSL. The only change that is required for using these walkthrough with SSL is that you use "https" instead of "http" in your URLs.

See Also

Concepts

Security and Protection
Web Service Walkthroughs


Walkthrough: Creating and Interacting with a Page Web Service (OData)

This walkthrough illustrates how you can publish a Microsoft Dynamics NAV page as an OData web service, use it in a Visual Studio console application, and change data in Microsoft Dynamics NAV through the web service.

About This Walkthrough

This walkthrough provides an overview of how to expose a page as a web service and how to use the web service in a C# console application. The walkthrough illustrates the following tasks:

  • Publishing a Microsoft Dynamics NAV page as a web service.

  • Verifying web service availability from a browser.

  • Adding the published web service as a service reference in a console application that you create in Visual Studio.

  • Changing the data in the console application.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 with a developer license.

  • CRONUS International Ltd. demonstration database.

  • Visual Studio 2012 or Visual Studio 2010. You can use any edition of Visual Studio that supports adding web references. In this walkthrough, you will use Visual Studio 2012. You also have the option to use service references instead of web references, or use the web service proxy generating tools svcutil.exe and wsdl.exe, which are included in the Microsoft .NET Framework SDK.

Publishing a Page as a Web Service

You publish a web service by using the Microsoft Dynamics NAV Windows client or the Microsoft Dynamics NAV Web client.

To register and publish a page as a web service

  1. Open the RoleTailored client and connect to the CRONUS International Ltd. company.

  2. In the Search box, enter Web services, and then choose the related link.

  3. In the Web Services page, on the Home tab, choose New.

  4. In the Object Type column, select Page. In the Object ID column, enter 21, and in the Service Name column, enter Customer.

  5. Select the check box in the Published column.

  6. Choose the OK button.

Verifying Web Service Availability

Note
After publishing a web service, verify that the port that web service applications will use to connect to your web service is open. The default port for OData web services is 7048. You can configure this value by using the Microsoft Dynamics NAV Server Administration Tool.

To verify availability of a Microsoft Dynamics NAV web service

  1. Start Internet Explorer.

  2. In the Address field, enter a URI in this format: http://<Server>:<WebServicePort>/<ServerInstance>/OData. For example:

    http://localhost:7048/DynamicsNAV/OData

    1. Server is the name of the computer that is running Microsoft Dynamics NAV Server.

    2. WebServicePort is the port that OData is running on. The default port is 7048.

    ServiceInstance is the name of the Microsoft Dynamics NAV Server instance for your solution. The default name is DynamicsNAV90.

    For example, if the Microsoft Dynamics NAV Server is running on the computer that you are working on, then you can use: http://localhost:7048/DynamicsNAV/OData/

    The browser should now show the web service that you have published, in the format of an AtomPub document.

    Basic AtomPub document for a page

Creating the Console Application

Next, you create a C# console application in Visual Studio 2012.

To create the C# project

  1. In Visual Studio, on the File menu, point to New, and then choose Project.

  2. Expand the Installed node, expand the Templates node, expand the Visual C# node, chose Windows, and then choose Console Application. Enter the name NAVCustomers for the application.

  3. Choose the OK button to exit the New Project page.

  4. In the Solution Explorer pane, right-click References, and then choose Add Service Reference.

  5. In the Address field, enter the URI for your OData web service, such as http://localhost:7048/DynamicsNAV/OData/.

    Security Note
    In this example, we use the HTTP protocol to illustrate the use of OData web services. We recommend that you use the more secure HTTPS protocol when you consume web services.

  6. Choose Go, and then, in the Services field, choose NAV, and then choose the OK button.

The project is created, and your OData web service is added as a service reference. Next, you add the code that will show a list of existing customers, add a customer and then rename the new customer.

To add code to your console application

  1. Add the following using statement after the namespaces that are automatically added to your project:

    Copy Code
    using NAVCustomers.ServiceReference1;

  2. After the Main method, add the following method:

    Copy Code
    private static void PrintCustomersCalledCust(NAV nav)
  {
    var customers = from c in nav.Customer
                    where c.Name.StartsWith("Cust")
                    select c;
    Boolean customerFound = false;
    foreach (Customer customer in customers)
    {
      customerFound = true;
      Console.WriteLine("No.: {0} Name: {1}", customer.No, customer.Name);
    }
    if (!customerFound)
    {
      Console.WriteLine("There are no customers that start with 'Cust'.");
    }
  }

    The PrintCustomersCalledCust method reads the OData web service that you created, Customer, and creates a list of customers where the customer name begins with the letters Cust. Next, you add code to the Main method that uses the web service to write to Microsoft Dynamics NAV.

  3. In the Main method, add the following code to establish the connection to Microsoft Dynamics NAV through the web service:

    Copy Code
      NAV nav = new NAV(new Uri("http://localhost:7048/DynamicsNAV/OData/Company('CRONUS%20International%20Ltd.')"));
  nav.Credentials = CredentialCache.DefaultNetworkCredentials;

    In the example, the name of the Microsoft Dynamics NAV company that you modify data for is CRONUS International Ltd.. You must replace this with the name of the company that you have access to. To find the correct URI, you can paste the following URI into your browser and then see the exact URI that you must use: http://localhost:7048/DynamicsNAV/OData/Company.

  4. Add the following code to the method:

    Copy Code
      Console.WriteLine("Printing list of current customers:");
  PrintCustomersCalledCust(nav);
  Console.WriteLine("Adding new customer.");
  Customer newCustomer = new Customer();
  newCustomer.Name = "Customer Name";
  nav.AddToCustomer(newCustomer);
  nav.SaveChanges();
  Console.WriteLine("Printing list of current customers:");
  PrintCustomersCalledCust(nav);
  newCustomer.Name += "Changed";
  nav.UpdateObject(newCustomer);
  nav.SaveChanges();
  Console.WriteLine("Printing list of current customers:");
  PrintCustomersCalledCust(nav);

    In this code, a customer is created and then renamed. The code prints a list of the customers that currently exist in the Customer table when each change has been made.

  5. Build and run the project.

To verify the inserted and modified data in Microsoft Dynamics NAV

  1. Open the Microsoft Dynamics NAV Windows client or the Microsoft Dynamics NAV Web client.

  2. Open the list of customers, filter for a customer with the name Customer NameChanged.

    This is the customer that the console application created and modified.

Next Steps

You have built a console application that uses an OData web service to modify Microsoft Dynamics NAV data. You can use similar OData web services in other applications when you want to allow users to modify data outside Microsoft Dynamics NAV.

See Also

Tasks

Walkthrough: Registering and Using a Page Web Service (SOAP)

Concepts

Microsoft Dynamics NAV Web Services Overview
Using OData Web Services to Modify Data
Web Service Walkthroughs
Web Service Alternatives: SOAP and OData


Walkthrough: Viewing Page Data in Excel Using PowerPivot (OData)

This walkthrough describes how you can use OData to expose a Microsoft Dynamics NAV 2016 page as a web service and then analyze the page data using Microsoft PowerPivot for Excel 2013. Similar steps also apply to PowerPivot for Excel 2010. For information about PowerPivot, see Microsoft PowerPivot.

About This Walkthrough

With OData and PowerPivot, you gain access to a powerful set of tools and technologies for data exchange and analysis. This walkthrough illustrates the following tasks:

  • Publishing a Microsoft Dynamics NAV page as a web service.

  • Verifying web service availability from a browser.

  • Using the PowerPivot add-in for Excel to import the table data as a new worksheet.

    This procedure also includes optional instructions about how to use a web service access key.

  • Creating a PivotTable from the worksheet, selecting relevant fields, and then organizing and formatting the data to highlight strategic data.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 with a developer license.

  • CRONUS International Ltd. demonstration database.

  • Excel 2013 with the PowerPivot add-in enabled. For more information, see Download PowerPivot page.

  • Optionally, if you want to use a web service access key to authenticate access to the web service, Microsoft Dynamics NAV must meet the following requirements:

    • The Microsoft Dynamics NAV Server is configured to authenticate users by using the NavUserPassword credential type.

    • There is a Microsoft Dynamics NAV user account that has a web service access key. In this walkthrough, the user account has the user name NavTest.

    For more information, see Users and Credential Types.

Publishing a Page as a Web Service

You can publish a web service by using the Microsoft Dynamics NAV Web client or the Microsoft Dynamics NAV Windows client.

To register and publish a page as a web service

  1. Open the RoleTailored client and connect to the CRONUS International Ltd. company.

  2. In the Search box, enter Web Services, and then choose the related link.

  3. In the Web Services page, choose New.

  4. In the Object Type column, select Page. In the Object ID column, enter 21, and in the Service Name column, enter Customer.

    This exposes the Customer Card page as an OData web service.

  5. Select the check box in the Published column.

  6. Choose the OK button to close the New - Web Services page.

Verifying the Web Service’s Availability

Security Note
After publishing a web service, verify that the port that web service applications will use to connect to your web service is open. The default port for OData web services is 7048. You can configure this value by using the Microsoft Dynamics NAV Server Administration Tool.

To verify availability of a Microsoft Dynamics NAV web service

  1. Start Windows Internet Explorer.

  2. In the Address field, enter a URI using the following format: http://<Server>:<WebServicePort>/<ServerInstance>/OData/

    • Server is the name of the computer that is running Microsoft Dynamics NAV Server.

    • WebServicePort is the port that OData is running on. The default port is 7048.

    • ServiceInstance is the name of the Microsoft Dynamics NAV Server instance for your solution. The default name is DynamicsNAV90.

    For example, if the Microsoft Dynamics NAV Server is running on the computer that you are working on, you can use: http://localhost:7048/DynamicsNAV90/OData/

    The browser should now show the web service that you have published, as shown in the following illustration.

    OData services listed in a browser
Note
If the browser cannot find the web service, it may indicate that the specified Microsoft Dynamics NAV Server instance is not running. For more information, see Managing Microsoft Dynamics NAV Server Instances.

Importing Microsoft Dynamics NAV Data into Excel

In the following procedures, you use PowerPivot to import Microsoft Dynamics NAV data into Excel. If you will be using a web service access key for authentication, only perform the second procedure; otherwise, only perform the first procedure.

To import Microsoft Dynamics NAV data into Excel

  1. Start Microsoft Excel.

  2. In Excel, on the PowerPivot tab, choose Manage. This opens the PowerPivot for Excel window.

  3. In PowerPivot, on the Home tab, choose Get External Data, choose From Data Service, and then choose From OData Data Feed.

    The Table Import Wizard opens.

  4. If your Microsoft Dynamics NAV implementation requires that you use a web service access key, you must specify the NavUserPassword credentials as described in the following steps:

    1. In the Advanced dialog box, in the Security section, set the Integrated Security field to Basic.

      If your OData is configured to use SSL, then set the field to SSPL.

    2. In the Password field, type the web service access key.

    3. In the UserID field, type the user name for the Microsoft Dynamics NAV user account. For this walkthrough, use NavTest.

    4. In the Source section, in the Service Document URL field, type the URL for the OData web service that you verified in the previous procedure, for example, http://localhost:7048/DynamicsNAV90/OData/.

    5. Choose the OK button to return to the Table Import Wizard.

  5. In the Connect to a Data Feed page, in the Data Feed Url field, enter the OData URI that you verified in the previous procedure, for example http://localhost:7048/DynamicsNAV90/OData/. Choose the Next button.

    Important
    The URI must end with a slash (/) as shown in the example.

  6. Verify that Customer appears in the Source Table column.

  7. Select the check box next to the Customer web service, and then choose Finish.

  8. After you see the Success message, choose the Close button.

The data from the Customer OData web service displays, and you can use the data to build pivot-based views in the Excel workbook.

Creating a PivotTable Containing Key Microsoft Dynamics NAV Data

In this procedure, you use the Excel workbook with data from the Customer web service to create a PivotTable from the worksheet. You select relevant fields and then organize and format the data to highlight strategic data. Building a pivot table is a way to select and arrange data so as to highlight and focus on key elements.

To create a PivotTable

  1. In Excel, select the cell where you want the PivotTable located.

  2. In the ribbon, choose the Insert tab, and then in the Tables group, choose PivotTable.

  3. In the Create PivotTable dialog box, select Use an external data source, and then choose the Choose Connection button.

  4. In the Existing Connections dialog box, on the Connections tab, under Connections in this Workbook, choose the data feed for your OData web service, and then choose the Open button.

  5. Choose the OK button to add the PivotTable to the Excel worksheet.

    The PowerPivot Field pane on the right side includes a list of fields from the Customer web service that where imported from PowerPivot.

  6. In the PowerPivot Field List pane, choose Location_Code.

    Tip
    To quickly find a field in the field list, type part or all of the field name in the Search text box that is above the list of fields, and then press Enter to highlight the first field that contains the text. You can then choose the right arrow to proceed to the next field, and so on.

  7. Select the Balance_LCY field.

  8. Select the Name field.

    You can now see the data in the body of the worksheet, as shown in the following illustration.

    PivotTable after selecting fields

    The PivotTable shows customers by location and individual customer balances, and also adds the balances by location. To make the information more readable, you can update the headings on the PivotTable.

  9. Select the cell that has the heading Sum of Balance_LCY, and then, in the formula field, type Balance.

  10. Select the cell that has the heading Row Labels, and then in the formula field, type Customers by location.

  11. Select the empty cell that is below the Customers by location cell, and then, in the formula field, type Location not specified.

The following illustration shows how the worksheet looks after you make these changes.

PivotTable during setup

Next Steps

Now that you have created your PivotTable, you can continue to enhance the data to make it more useful and readable. You can:

  • Add a column to the data that shows average balance by region.

  • Enhance data presentation with a graph.

  • Post the data in a Microsoft SharePoint environment with live data from Microsoft Dynamics NAV 2016.

For more information about how to use Microsoft Dynamics NAV data with PowerPivot information, see Walkthrough: Combining Data from Microsoft Dynamics NAV Queries and Pages with Data from Azure DataMarket (OData).

See Also

Concepts

Web Service Walkthroughs
OData Web Services


Walkthrough: Combining Data from Microsoft Dynamics NAV Queries and Pages with Data from Azure DataMarket (OData)

This walkthrough describes how you can use OData to combine data from Microsoft Dynamics NAV 2016 with data from Microsoft Azure Markeplace.

About This Walkthrough

This walkthrough illustrates the following tasks:

  • Creating a Microsoft Dynamics NAV query.

  • Publishing your query as a web service.

  • Publishing a page as a web service.

  • Verifying the availability of the web services that use a browser.

  • Using the PowerPivot add-in for Excel to import data from your Microsoft Dynamics NAV web services as new worksheets.

  • Connecting to demographic data available from Azure Marketplace.

  • Creating a pivot table in Excel that combines Microsoft Dynamics NAV data with data from Azure Marketplace.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 with a developer license.

  • CRONUS International Ltd. demonstration database.

  • Microsoft Excel 2013 with Microsoft PowerPivot enabled, or Microsoft Excel 2010 with the PowerPivot add-in for Excel 2010 installed. For more information, see PowerPivot Download Page.

  • A Microsoft account for accessing data from Azure Marketplace. For more information about Microsoft account, see the What is a Microsoft account?. To obtain a Microsoft account, go to the sign-up page.

Story

Victor, the business system developer at CRONUS International Ltd., has been asked by his manager Tim to create a data visualization that will show total sales to customers in different countries/regions, and how those countries/regions align with Key Development Indicators, which are a measure of national/regional affluence. Tim tells Victor that he can find information about Key Development Indicators on zure Marketplace. Victor assesses the assignment and decides that he can use OData web services to bring Microsoft Dynamics NAV data to Excel, where he can merge it with economic data from Azure Marketplace.

Creating a Microsoft Dynamics NAV Query

You create a query to capture data about sales to individual customers.

Note
For more information about how to create more advanced queries that combine data from multiple Microsoft Dynamics NAV pages, see Walkthrough: Creating a Query to Link Two Tables, Walkthrough: Creating a Query That Uses a Totaling Method and Sorting, or Walkthrough: Creating a Query to Link Three Tables.

To create a query to capture data about sales to customers

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Query, and then choose New.

  3. In Query Designer, on the first line, in the Data Type column, choose DataItem from the drop-down list box.

  4. In the Data Source column, choose the Lookup button, choose the Sales Line table from the Table List window, and then choose the OK button.

  5. On the View menu, choose Field Menu.

  6. Select the following fields. To select multiple fields, hold down the Ctrl key and select all relevant lines.

    • Document Type

    • Sell-to Customer No.

    • Document No.

    • No.

    • Quantity

    • Amount

  7. Choose the OK button. When prompted, “Do you want to add the fields that are selected in the field menu?”, choose the Yes button.

    You should see the following in Query Designer.

    SalesOrderInfo query definition

  8. On the File menu, choose Save.

  9. In the Save As window, in the ID field, enter 50005. In the Name field, enter SalesOrderInfo. Verify that the Compiled check box is selected, and then choose the OK button.

    Note
    If 50005 is already being used by another query, you will get an error when you try to save the query. If so, use another ID.

  10. In Object Designer, choose query 50005, and then choose Run. When you run a query, you can view the data in the dataset.

    SalesOrderInfo query result

  11. Close Query Designer and the development environment.

Publishing a Query and a Page as Web Services

You register and publish a web service by using the Microsoft Dynamics NAV Windows client.

  1. In the Microsoft Dynamics NAV Windows client in the Search box, enter Web services, and then choose Web Services.

    The Web Services page opens.

  2. In the Web Services page, choose New.

    The New - Web Services page opens.

  3. In the Object Type column, select Page. In the Object ID column, enter 21, and then in the Service Name column, enter Customer.

  4. Select the Published column.

  5. Press the Tab key to move the pointer to a new line in the New - Web Services page.

  6. In the Object Type column, select Query. In the Object ID column, enter 50005, and then in the Service Name column, enter SalesOrderInfo.

  7. Select the Published column.

  8. Choose the OK button to exit the New - Web Services page.

Verifying Web Service Availability

You should verify that the web services that you just created are available over the Internet. When exposing a web service, you must open the port for consumers of your web service to access it. If necessary, have your system administrator add the port through Windows Firewall on the computer that is running Microsoft Dynamics NAV Server. The default port for OData web services is 7048 and can be configured by using Microsoft Dynamics NAV Server Administration tool. For more information, see Microsoft Dynamics NAV Server Administration Tool.

To verify web service availability

  1. Start Internet Explorer.

  2. In the Address field, enter a URI in this format: http://<Server>:<WebServicePort>/<ServerInstance>/OData.

    For example:http://localhost:7048/DynamicsNAV72/OData

    The browser should now show the web services that you have published, in the format of an AtomPub document.

    Two web services
    Important
    You may want to modify your Internet Explorer settings to display the actual XML for a feed instead of the feed content that has changed. Choose Internet Options, choose Content, choose Feeds and Web Slices, and then clear the Turn on feed reading view check box. Restart Internet Explorer to enable the new setting.

Importing Microsoft Dynamics NAV Data into Excel

In this procedure, you import Microsoft Dynamics NAV web service data into Excel.

To import Microsoft Dynamics NAV data into Excel

  1. Start Microsoft Excel. In Excel, on the PowerPivot tab, in the Data Model group, choose Manage to open the PowerPivot Window.

  2. In PowerPivot, on the Home tab, choose Get External Data, choose From Data Service, and then choose From OData Data Feed.

  3. In the Data Feed Url field, enter the OData URI, such as http://localhost:7048/DynamicsNAV72/OData. Choose the Next button.

  4. Verify that Customer and SalesOrderInfo appear in the Source Table column. Place a check mark in the left column next to these two rows, and then choose Finish.

  5. After you see the Success message, choose the Close button.

You should now see data from the Customer page and the SalesOrderInfo query displayed as Excel workbooks. You can switch between pages using the tabs at the bottom of the Excel window.

Enhancing the Microsoft Dynamics NAV Data by Adding a Column

Examine the SalesOrderInfo workbook in Excel. Notice that it has a Quantity column and an Amount column. In your final output you may want to show total sales per company, this is the Quantity multiplied by Amount. An easy way to achieve that is to add a column to the workbook that calculates that product.

To enhance Microsoft Dynamics NAV data by adding a column

  1. In the SalesOrderInfo workbook, choose Add Column, which is on the right side of the last data column.

  2. Move the pointer down to the first cell in the new column and type an equal sign (=).

    This indicates that you are creating a formula.

  3. Click the header row of the Quantity column.

    This starts to build your formula.

    Copy Code
    =SalesOrderInfo[Quantity]

  4. Type an asterisk (*) at the end of the formula to indicate multiplication.

  5. Click the header row of the Amount column.

    This completes the formula.

    Copy Code
    =SalesOrderInfo[Quantity]*SalesOrderInfo[Amount]
    Note
    If you prefer, you can type the complete formula instead of clicking the header row.

  6. Press Return to indicate that the formula is finished.

  7. Right-click the header of CalculatedColumn1 and choose Rename Column.

  8. Type QuantityByAmount as the new column name.

  9. Save the modified SalesOrderInfo workbook.

Importing Data from Azure Marketplace

The Azure Marketplace is an online market where you can buy and sell finished Software as a Service (SaaS) applications and premium datasets. The Azure Marketplace offers many different kinds of data, including demographic, environment, financial, retail, and sports data. In this walkthrough, you use demographic data about development standards in different countries and regions.

To import data from Azure DataMarket

  1. In PowerPivot, on the Home tab, in the Get External Data, choose From Data Service, and then choose From (Windows) Azure Marketplace.

    This opens a web page titled Microsoft Azure Marketplace Catalog which shows the available Azure Marketplace datasets.

  2. Choose My Data and use your Microsoft account to create a free Azure Marketplace account.

  3. After you are signed up, choose Data to return to the list of available datasets.

  4. In the left panel, choose Free, choose Demographics, and then scroll down to choose World Development Indicators.

  5. Read about the dataset, and then choose SIGN UP to subscribe to this data feed. On the Subscription page, choose SIGN UP again.

  6. On the Thank You page, choose Explore This Dataset.

    This takes you to a Build Your Query page. In the Build Query area on the right side, verify these values:

    • Query: GetCountries

    • Format: Atom

    • Language Code: en

  7. Choose the Run Query button.

    You now see a view of the table data. Notice that the table contains two-letter country/region codes, country/region names, and additional data about the countries/regions listed. This data has enough in common with your Microsoft Dynamics NAV data to support a link between the two.

  8. Choose Export from the narrow column on the right side of the page. Choose Excel PowerPivot, and then choose Download.

    In response to the question, Do you want to open or save ServiceQuery.atomsvc from datamarket.azure.com?, choose Open.

  9. In Excel, a dialog box prompts that you select a workbook to import the atom feed to.

    Small PowerPivot dialog box

    Choose the OK button.

  10. You are now back in the Table Import Wizard. The only thing that you need to set up is your account key.

    Next to the Account key field, choose Find.

  11. Copy the default account key value from the web page.

  12. Switch back to the Table Wizard and paste the key in the Account key field.

  13. Choose the Next button.

  14. Choose the Finish button.

  15. Choose the Close button.

You now have three workbooks in PowerPivot:

  • Customer, which has data from a Microsoft Dynamics NAV page.

  • SalesOrderInfo, which has data from a Microsoft Dynamics NAV query.

  • World Development Indicators, which has data from Azure Marketplace.

These are the data sources that you will work with to create your pivot table.

Creating Relationships Between Data Sources

By creating relationships between your data sources in Excel, you make it possible to display data from multiple sources in the same pivot table.

Start by creating a relationship between the two Microsoft Dynamics NAV data sources: the Customer page and the SalesOrderInfo query. Both sources have a column that identifies the customer number, so this link is straightforward.

Then create a relationship between the respective columns on the Customer tab and on the World Development Indicators tab that use two-letter abbreviations to identify countries/regions.

To create relationships between data sources

  1. Go to the SalesOrderInfo tab in PowerPivot for Excel, right-click the header row for the Sell_to_Customer_No column, and then from the list of commands, select Create Relationship.

    Creating a relationship between two data sources

  2. In the Create Relationship dialog box, in the Related Lookup Table field, choose Customer.

  3. In the Related Lookup Column field, choose No.

  4. Choose the Create button.

  5. In PowerPivot for Excel, go to the Customer tab, right-click the header row for the Country_Region_Code column, and from the list of commands, select Create Relationship.

  6. In the Create Relationship dialog box, in the Related Lookup Table field, choose World Development Indicators.

  7. In the Related Lookup Column field, choose CodeIso2Letter.

  8. Choose the Create button.

Building a Pivot Table

All your previous work comes together as you build a pivot table to integrate data from your sources. Building a pivot table is a way to select and arrange data so that you can highlight and focus on key elements.

To build a pivot table

  1. In the PowerPivot ribbon, choose PivotTable and then, in the list of commands, choose PivotTable again.

    PivotTable from the PivotTable menu

  2. In the Create Pivot Table dialog box, choose the OK button to accept the default, New Worksheet.

    The pivot table window opens. The PowerPivot Field List on the right side lists all of the available columns in all of your data sources.

  3. In the PowerPivot Field List, choose Country_Region_Code from the Customer field.

    Tip
    To quickly find a field in the field list, type part or all of the field name in the Search box that is above the list of fields, and then press Enter to highlight the first field that contains the text. You can then choose the right arrow to proceed to the next field, and so on.

  4. In the Customer field, choose No.

  5. In the SalesOrderInfo list, choose QuantityByAmount.

    PowerPivot automatically assigns these values to categories in the pivot table. Country_Region_Code and No are categorized as row labels, and QuantityByAmount as a sum.

    Adding fields to the PivotTable

    You can design a pivot table by moving values from one to list to another, configuring items in a list, or moving items up or down in a list.

    Here is what the pivot table looks like at this point. Customers are arranged by country/region, with total sales amounts.

    PivotTable, first look

  6. One enhancement is to replace the Country_Region_Code with the actual name of the country/region, which is available as a field in the World Development Indicators field.

    Choose Name from the World Development Indicators field.

  7. Clear the Country_Region_Code from the Customer field.

  8. Move Name up to the top of the Row Labels list.

    Move Name up

  9. Choose RegionName from the World Development Indicators field, and then move it to the top of the Row Labels list.

  10. Choose IncomeLevelName from the World Development Indicators field and then move it to second position in the Row Labels list.

    This completes the list of fields. The final list looks like this.

    Final pivot field list

    The actual pivot table looks like this.

    Final pivot table

  11. Save the pivot table as Customers by Economic Region.xlsx.

Next Steps

Viktor’s results show that all customers are in countries/regions that are categorized as “High income.” For a different result, open page 22 Customer List in the Microsoft Dynamics NAV Windows client and reassign some companies to countries/regions that are in other income level categories. Then do the following:

  1. Go the Customer workbook in PowerPivot, choose Refresh, and then choose Refresh All.

  2. Go to your pivot table, choose Refresh All, and then choose Refresh All.

Now the final pivot table has a different result, as shown in the following example.

Final pivot table after modification

See Also

Concepts

OData Web Services
Web Services Best Practices
Web Services


Events in Microsoft Dynamics NAV

This section describes how you can use events in Microsoft Dynamics NAV. The use of events is a proven and established programming concept that can ease application upgrade and limit or even eliminate the need for code modifications in customized applications because of application platform changes.

In This Section

This section contains the following topics about events.

  • Introducing Events

  • Publishing Events

  • Raising Events

  • Subscribing to Events

  • Debugging Events

  • Best Practices with Microsoft Dynamics NAV Events

  • Walkthrough: Using Events in Microsoft Dynamics NAV

  • Walkthrough: Implementing New Workflow Events and Responses


Introducing Events

You can use events to design the application to react to specific actions or behavior that occur. Events enable you to separate customized functionality from the application business logic. By using events in the application where customizations are typically made, you can lower the cost of code modifications and upgrades to the original application.

  • Code modifications to customized functionality can be made without having to modify the original application.

  • Changes to the original application code can be made with minimal impact on the customizations.

Events can be used for different purposes, such as generating notifications when certain behavior occurs or the state of an entity changes, distributing information, and integrating with external systems and applications. For example, in the CRONUS International Ltd. demonstration database, events are used for extensively for workflow and Microsoft Dynamics CRM integration.

How Events Work

The basic principal is that you program events in the application to run customized behavior when they occur. Events in Microsoft Dynamics NAV are modelled after Microsoft .NET Framework. There are three major participants involved in events: the event, a publisher and a subscriber.

  • An event is the declaration of the occurrence or change in the application. An event is declared by a C/AL function, which is referred to as an event publisher function. An event publisher function is comprised of a signature only and does not execute any code.

  • A publisher is the object that contains event publisher function that declares the event. The publisher exposes an event in the application to subscribers, essentially providing them with a hook-up point in the application.

    Publishing an event does not actually do anything in the application apart from making the event available for subscription. The event must be raised for subscribers to respond. An event is raised by adding logic to the application that calls into the publisher to invoke the event (the event publisher function).

    Partners or subsystems can then take advantage of the published event in their solutions. An ISV that delivers vertical solutions, and Microsoft itself, are the typical providers of published events.

    There are three different event types: business, integration, and trigger events. For more information about each type, see Event Types. Business and integration type events must be explicitly declared and published, which means that you must create event publisher functions and add them to objects manually. On the other hand, trigger events, which occur on table and page operations, are published and raised implicitly by the Microsoft Dynamics NAV runtime. Therefore, no coding is required to publish them.

  • A subscriber listens for and handles a published event. A subscriber is a C/AL function that subscribes to a specific event publisher function and includes the logic for handling the event. When an event is raised, the subscriber function is a called and it code is run. A subscriber enables partners to hook into the core Microsoft Dynamics NAV application functionality without having to do traditional code modifications. Any Microsoft Dynamics NAV solution provider, which also includes Microsoft, can use event subscribers.

There can by multiple subscribers to a single event publisher function. However, a publisher has no knowledge of subscribers, if any. Subscribers can reside in different parts of the application than publishers.

How to Implement Events

Implementing events in Microsoft Dynamics NAV consists of the following tasks:

  1. Publish the event.

    For business and integration events, create and configure a function in an application object to be an event publisher function. For more information, see Publishing Events.

  2. Raise the event.

    Add code that calls the event publisher function. For more information, see Raising Events.

  3. Subscribe to the event.

    At the consumer end, add one or more subscriber functions that subscribe to published events when they are raised. For more information, see Subscribing to Events.

See Also

Concepts

Event Types
Events in Microsoft Dynamics NAV


Event Types

Microsoft Dynamics NAV supports different types of events for different purposes. This topic describes the different types.

Business Events

A business event is a custom event. It defines a formal contract that carries an implicit promise not to change in future releases. It is the expectation that business events are published by solution ISVs, including Microsoft.

Business events can be compared with publicly released APIs on which 3rd party solution provider develop integrations and additions. Therefore, the downstream cost of making changes to a business event implementation can be considerable for those who use the event in their applications. There may be some cases where changes are required; however, you should keep these to an absolute minimum.

Development considerations

A typical business event reflects changes in “state” with regards to a process. This makes them very well suited for workflow. An example of a business event could be when a sales order has been posted. It is important to note that business events should not be tied to the implementation-details, such as the tables or fields in which the data is stored. Preferably, the event publisher developer should be free to change the implementation, while still keeping the business event intact.

Documentation

Business events must be documented with the solution, including the before-state and after-state of the events.

Integration Events

An integration event is also a custom event, like a business event, except that it does not carry the same promise of not changing, nor does it have the restriction not to expose implementation details.

The main purpose of integration events is to enable the integration of other solutions with Microsoft Dynamics NAV without having to perform traditional code modifications.

Development considerations

An integration event can be changed to a business event later. At which time, it must adhere to the same implied contract and commitment as any business event. It can also simply be designed-in hook points for external add-ons.

Documentation

There are no formal requirements for integration events because they follow local partner best practices.

Trigger Events

Unlike business and integration events which must be programmed, trigger events are predefined events. Trigger events are raised by the system when it performs database table operations, such as deleting, inserting, modifying, and renaming a record. Trigger events are closely associated with the table triggers for database operations: OnDelete, OnInsert, OnModify, OnRename, and OnValidate (for fields).

Available Trigger Events

For each database operation, there is a "before" and "after" trigger event with a fixed signature. The following table describes the available trigger events:

Trigger event with signature | Description
OnBeforeDeleteEvent(VAR Rec: Record, RunTrigger: Boolean) | Executed before a record is deleted from a table.
OnAfterDeleteEvent(VAR Rec: Record, RunTrigger: Boolean) | Executed after a record is deleted from a table.
OnBeforeInsertEvent(VAR Rec: Record, RunTrigger: Boolean) | Executed before a record is inserted in a table.
OnAfterInsertEvent(VAR Rec: Record, RunTrigger: Boolean) | Executed after a record is inserted in a table.
OnBeforeModifyEvent(VAR Rec: Record, VAR xRec: Record, RunTrigger: Boolean) | Executed before a record is modified in a table.
OnAfterModifyEvent(VAR Rec: Record, VAR xRec: Record, RunTrigger: Boolean) | Executed after a record is modified in a table.
OnBeforeRenameEvent(VAR Rec: Record, VAR xRec: Record, RunTrigger: Boolean) | Executed before a record is renamed in a table.
OnAfterRenameEvent(VAR Rec: Record, VAR xRec: Record, RunTrigger: Boolean) | Executed after a record is renamed in a table.
OnBeforeValidateEvent(VAR Rec: Record, VAR xRec: Record, RunTrigger: Boolean; CurrentFieldNo: Integer) | Executed before a field is validated when its value has been changed.
OnAfterValidateEvent(VAR Rec: Record, VAR xRec: Record, RunTrigger: Boolean; CurrentFieldNo: Integer) | Executed after a field is validated when its value has been changed.

The following table describes the parameters of the trigger events:

Parameter | Type | Description
Rec | Record | The table that raises the event.
xRec | Record | The table that raises the event.
RunTrigger | Boolean | Specifies whether to execute the code in the event trigger when it i invoked. If this parameter is true, the code will be executed. If this parameter is false, then the code is not executed.
CurrentFieldNo | Integer | The number of the field that raises the event.

Development Considerations

Trigger events are published by the runtime and cannot be raised programmatically.

The relative order of execution of trigger events, table triggers, and database operations is as follows:

Order | Item | Example
1 | Trigger event (before) | OnBeforeDeleteEvent
2 | Table trigger | OnDelete
3 | Global table trigger in codeunit 1 | OnDatabaseDelete
4 | Database operations | Delete the record
5 | Trigger event (after) | OnAfterDeleteEvent

Trigger events do not appear in C/AL Editor from the Table Designer in the Microsoft Dynamics NAV Development Environment.

Subscriber functions cannot access the sender and or access global variables.

Documentation

There are no formal requirements for trigger events as it follows that of database triggers.


Publishing Events

The first phase of implementing an event is publishing the event. Publishing an event exposes it in the application. This provides hook up points for subscribers to register to the event, and eventually handle the event if it is raised. An event is published by adding C/AL function that is specifically set up as an event publisher.

  • Business and integration events require that you manually create an event publisher function for each event that you want to publish. An event publisher function declares the event in the application and makes it available for subscription; however, it does not raise the event. After an event is published, you can raise it in your application, as needed, from where event subscribers can react and handle the event.

  • Trigger events, on the other hand, do not require that you create publisher functions. Trigger events are by predefined event publisher functions that are called automatically at runtime. This means that trigger events are readily available to subscribers by default.

Creating an Event Publisher Function to Publish Business and Integration Events

You create an event publisher function the same way you create any function in C/AL, except that there are specific properties that you set to make it an event publisher. Additionally, an event publisher function has the following requirements and restrictions that you must follow, otherwise you not able to compile your code changes:

  • An event publisher function cannot include any code except comments.

  • An event publisher function cannot have a return value, variables, or text constants.

The following procedure provides an outline of the tasks that are involved in creating an event publisher function for declaring an event. The tasks are performed from the Microsoft Dynamics NAV Development Environment. For detailed step-by-step instructions for the tasks, see Walkthrough: Using Events in Microsoft Dynamics NAV.

To create an event publisher function

  1. Decide where you want to include the event publisher function.

    You can include an event publisher function in the C/AL code of any object type, such as codeunit, page, or table. You can create a new object or use and existing object.

  2. Add a C/AL function to the object.

    We recommend that you give the function a name that has the format On[Event], where [Event] is text that indicates what occurred, such as OnCancelCustomerApprovalRequest.

  3. Set the function Event Property to Publisher and the EventType Property to either Business or Integration.

  4. Set the function EventType Property to Business or Integration.

    For more information, see Event Types.

  5. If you want to make the event available to event subscribers that are defined in the current object, set the Local Property to No.

  6. If you want to make global functions in the object available to event subscribers, set the IncludeSender Property to Yes.

  7. Add parameters to the function as needed.

    You can include as many parameters of any type as necessary.

    Make sure to expose enough information as parameters to enable subscriber functions to add value to the application. On the other hand, especially with business events, do not expose unnecessary parameters that may constrain you from changing or extending functionally in the future.

You can now add code to the application that raises the event by calling the publisher function. You can also create subscriber functions that handle the event when it is raised.

See Also

Concepts

Raising Events
Subscribing to Events
Events in Microsoft Dynamics NAV


Raising Events

After an event has been published by an event publisher function, you can modify the application to raise the event where it is needed. Subscribers of an event will not react on the event until it is raised in the application.

To raise an event, you add logic in C/AL code of the application to call the event publisher function that declares the event. The procedure for calling the event publisher function is the same as calling any other function in C/AL.

When the code that calls the event publisher function is run, then all event subscriber functions that subscribe to the event are run. If there are multiple subscribers, then each event subscriber function is run one after another. The order in which the event subscribers run is random and cannot it cannot be specified.

If there are no subscribers to the published event, then the line of code that calls the event publisher function is ignored and not executed.

Example

You want to raise an event when a user changes the Address field on the page 21 Customer Card. The event is published by the event publisher function OnAddressedLineChanged in the codeunit My Publishers. The event publisher function OnAddressedLineChanged accepts a single text parameter. To raise the event this, you complete the following steps in the Microsoft Dynamics NAV Development Environment:

  1. Add the following C/AL variable to page 21 Customer Card.

    Variable name DataType Subtype

    Publisher

    Codeunit

    My Publisher

  2. In C/AL code, add code on the Address - OnValidate () trigger to call the OnAddressLineChanged function.

    Copy Code
    Publisher.OnAddressLineChanged(Address);

For step-by-step instructions for this example, see Walkthrough: Using Events in Microsoft Dynamics NAV.

See Also

Concepts

Publishing Events
Subscribing to Events
Events in Microsoft Dynamics NAV
Introducing Events


Subscribing to Events

To handle events, you design event subscribers. Event subscribers determine what actions to take in response to an event that has been raised. An event subscriber is a C/AL function that subscribes to, or listens for, a specific event that is declared by an event publisher function. The event subscriber includes code that defines the business logic to handle the event. When the published event is raised, the event subscriber is called and its code is run.

Subscribing to an event tells the runtime that the subscriber function must be called whenever the publisher function is run, either by code (as with business and integration events) or by the system (as with trigger events). The runtime establishes the link between an event raised by the publisher and its subscribers by looking for event subscriber functions.

There can be multiple subscribers to the same event from various locations in the application code. When an event is raised, the subscriber functions are run one at a time in random order. You cannot specify the order in which the subscriber functions are called.

Be aware that changing the state may not only impact the publishing code but other subscribers as well.

Creating an Event Subscriber Function

You create an event subscriber function the same way as other functions except that you specify properties that set up the subscription to an event publisher. The procedure is slightly different for trigger events than business and integration events because business and integration events are raised by event publisher functions in application code; trigger events are predefined system events that are raised on tables.

To create an event subscriber function for business and integration events

  1. Decide which codeunit to use for the event subscriber function.

    You can create a new codeunit or use and existing one..

  2. Add a C/AL function to the codeunit.

    We recommend that you give the function a name that indicates what the subscriber does, and has the format [Action][Event]. [Action] is text that describes what the function does and [Event] is the name of the event publisher function to which it subscribes. For more information about naming, see Best Practices with Microsoft Dynamics NAV Events.

  3. Set the function Event Property to Subscriber.

  4. Set the function EventPublisherObject Property to the object that contains the event publisher function that declares the event that you want to subscribe to.

  5. Set the function EventFunction Property to the event publisher function that declares the event that you want to subscribe to.

  6. If you are prompted whether to overwrite the edited functions signature, choose the Yes button.

    The function signature will automatically be updated to include any the parameters from the event publisher function settings.

    Note
    The parameter list is determined by the publisher function. With business events, you cannot deviate from the parameters that are defined in the publisher function. Integration events are not a restricted and allow you to deviate from the parameters that are defined in the publisher function.

  7. Add code to the function for handing the event.

To create an event subscriber function for a trigger event

  1. Decide which codeunit to use for the event subscriber function.

    You can create a new codeunit or use and existing one.

  2. Add a C/AL function to the codeunit.

    We recommend that you give the function a name that indicates what subscriber does, and has the format [Action][Event]. [Action] is text that describes what the function does and [Event] is the name of the event publisher function to which it subscribes. For more information about naming, see Best Practices with Microsoft Dynamics NAV Events.

  3. Set the function Event Property to Subscriber.

  4. Set the function EventPublisherObject Property specify the table that contains trigger event that you want to subscribe to.

  5. Set the function EventFunction Property to the event that you want to subscribe to.

    You choose from the trigger events defined on the table that is specified by the EventPublisherObject property.

  6. When prompted to overwrite the edited functions signature, choose the Yes button.

    The function signature will automatically be updated to include any the parameters from the event publisher function settings.

  7. If you set the EventFunction Property to OnBeforeValidEvent or OnAfterValidEvent event, you must set the OnValidateEventField Property to the table field on which you want to subscribe the event.

  8. There are few other properties related event subscriber functions that you can set. For more information, see the following topics:

    • EventSubscriberInstance Property

    • OnMissingLicense Property

    • OnMissingPermission Property

  9. Add code to the function for handing the event.

For step-by-step instructions about creating a subscriber, see Walkthrough: Using Events in Microsoft Dynamics NAV.

See Also

Concepts

Publishing Events
Raising Events
Introducing Events
Events in Microsoft Dynamics NAV


How to: View the Event Subscriptions

You can view information about all the subscribers to events in an application from Event Subscriptions page. You can open this page directly from the development environment or from the Session List page in the Microsoft Dynamics NAV client

To view the event subscription from the development environment

  • On the Tools menu, choose Debugger, and then choose Event Subscriptions.

To view the event subscription from a Microsoft Dynamics NAV client

  1. Start the Microsoft Dynamics NAV client.

  2. In the Search box, enter Sessions, and then choose the related link.

  3. On the Home tab, in the Events group, choose Subscriptions.

The 9510 Event Subscriptions page lists the event subscribers in the application. For information about the fields for each entry, see Event Subscriptions

See Also

Concepts

Events in Microsoft Dynamics NAV
Subscribing to Events
Event Errors


Debugging Events

You can debug events to help you find and correct errors. Debugging events is similar to debugging other C/AL code in an application, where the basic concept is the breakpoint. To debug an event, you can add multiple breakpoints on event-related lines of code that cover each phase of the event, as described in the following list:

Event Phase | Breakpoint | Description
On publishing an event | Add a breakpoint in the event publisher function that declares an event. Although an event publisher function does not contain any code, except comments, you can add a breakpoint on a non-code line. For more information about publishing and event, see Publishing Events. | This enables you to step into the event handler code in event subscriber functions that subscribe to the event, without executing code that raises an event.
On raising an event | Add a breakpoint on the line of code that calls the event publisher function which raises the event. | This enables you to step into event handler code in event subscriber functions from where the events are raised. For more information about raiding and event, see Raising Events.
On subscribing to an event | Add breakpoints on lines of code in the event subscriber function that subscribes to a raised event. | This enables you to step through code that handles an event. For more information about publishing and event, see Subscribing to Events.

For more information about debugging and breakpoints, see Debugging.

See Also

Concepts

Events in Microsoft Dynamics NAV
Event Errors


Event Errors

When the runtime detects raised publisher events, it tries to identify subscribers for handling the events. If event subscribers are not correctly configured to subscribe to published events, errors will occur. For example, errors can occur when an event subscriber points to a non-existing event publisher object or function, or there is a mismatch between the signatures of an event publisher and subscriber functions. When errors occur, the event subscriber function for handling the event is disabled and tagged with an error in the database, which you can view from the Event Subscriptions page. For more information, see How to: View the Event Subscriptions.

The following table describes the errors that can occur when subscribing to events.

Error code | Cause
ErrorOriginalApplicationObjectNotFound | The event publisher object, which contains the publisher function to subscribe to, is not available. The event publisher object is specified by the EventPublisherObject Property of the event subscriber function.
ErrorOriginalMethodNotFound | The event publisher function that the event subscriber function subscribes to is not available. The event publisher function is specified by the EventFunction Property of the event subscriber function.
ErrorParameterMismatch | The parameters in the event subscriber function's signature do not match the parameters in the publisher function.
ErrorGlobalVariableNotFound | A global variable that is referenced in the event subscriber function signature is not available in the object that contains the event publisher function (specified by the EventPublisherObject Property of the event subscriber function).
ErrorFieldNotFound | The table field that is specified by the OnValidateEventField Property of the event subscriber function is not available. This error pertains to OnBeforeValidateEvent or OnAfterValidateEvent trigger events on a table.
ErrorOriginalApplicationObjectTypeNotSupported | The application object that contains the event publisher function that the subscriber function subscribes to is not supported. The application object is specified by the EventPublisherObject Property of the event subscriber function.
ErrorGlobalVariableAccessNotAllowed | A global variable that is referenced in the event subscriber function signature is not accessible. Verify that the GlobalVarAccess Property of the event publisher function that the event subscriber function subscribes to is set to Yes.
ErrorIncludeSenderNotAllowed | The event subscriber function signature includes a Sender parameter for accessing the object that contains the event publisher function to which the event subscriber subscribes. However, the event publisher function does not allow sender access as specified by the IncludeSender Property.
ErrorSenderParameterIsWrongType | The Sender parameter that is declared in the event subscriber function has a subtype value that does not match the event publisher object that raises the event.

See Also

Concepts

Events in Microsoft Dynamics NAV
Publishing Events
Raising Events
Subscribing to Events


Best Practices with Microsoft Dynamics NAV Events

This topic provides naming and coding guidelines for using events in Microsoft Dynamics NAV.

Naming Conventions

Item | Guideline | Example
Event publisher function | The name should indicate the circumstances when the published event is raised. Begin the name with On followed by a descriptive name that can be easily identified. | OnCancelCustomerApprovalRequest
Event subscriber function | The name should indicate what the operation that the subscriber performs. Begin the name with a phrase that indicates what the subscriber does, followed by the name of the publisher function to which it subscribes. | RunWorkflowOnCancelCustomerApprovalRequest
Variables and parameters | Follow the naming conventions that are defined in Naming Conventions. It is important that you define appropriate names from the beginning because the name becomes part of the interface definition. |

Coding Guidelines

  • Whenever possible, make events local, so that all pre and post validation can remain in the object.

  • Use VAR parameters with care because they form a stricter coupling between the publisher and the subscriber.


Walkthrough: Using Events in Microsoft Dynamics NAV

This walkthrough uses a simple example scenario to demonstrate how to program events in the application.

About This Walkthrough

The walkthrough illustrates to the following tasks:

  • Creating an event publisher function to publish an event.

  • Adding code to application to raise the published event.

  • Creating an event subscriber function to subscribe to a published event.

  • Adding code to the event subscriber function to handle the raised event

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 with a developer license.

  • CRONUS International Ltd. demonstration database.

Story

When users change the address of a customer, you want to check that the address does not include invalid characters, which in this walkthrough is a plus sign (+). To accomplish this, you will publish an event that is raised when the Address field on page 21 Customer Card is changed. To handle the event when it is raised, you will add an event subscriber function that includes logic that checks the address value and returns a message to the user if it contains a plus sign.

Note
Most of the tasks are performed from the Microsoft Dynamics NAV Development Environment.

Publishing the Event

To publish an event, you create a C/AL function that is set up to be an event publisher. An event publisher function can be added in any object, such as a codeunit, page, or table. This procedure will add the event publisher function to a new codeunit, in which you can potentially add more event publisher functions for other events later. Because you might want to change this event implementation in the future, you decide to create an integration event type. The event publisher requires a single text parameter for handling the address of the customer.

To create a new codeunit

  1. Open the development environment, and then connect to the CRONUS International Ltd. company.

    For more information, see How to: Open Databases.

  2. On the Tools menu, choose Object Designer, choose Codeunit, and then choose New.

    The C/AL Editor opens.

  3. On the File menu, choose Save.

  4. On the Save window, enter 50000 in the ID field and enter My Publishers in the Name field.

  5. Make sure the Compiled check box is selected, and then choose the OK button.

The codeunit for the event publisher is created. Keep the C/AL editor open for the next task. You can now add the event publisher function to publish the event.

To create the event publisher function to publisher the event

  1. On the View menu, choose C/AL Globals.

  2. In the C/AL Globals window, choose the Functions tab.

  3. In a blank row, in the Name field, enter OnAddressLineChanged.

  4. To open the properties for the OnAddressLineChanged function, select the function, and then in the View menu, choose Properties. Set the properties as follows:

    1. Set the Local property to No.

      Setting this property makes the function available to be called from the other objects. For more information about this property, see Local Property.

    2. Set the Event property to Publisher. This makes the function an event publisher.

      For more information, see Event Property.

    3. Set the EventType property to Integration.

      For more information, see EventType Property.

    4. Close the Properties window.

  5. Add a local parameter to the function for the address of the customer as described in the following steps:

    1. On the Functions tab, select the OnAddressLineChanged function, and then choose the Locals button.

      The C/AL Locals window opens.

    2. On the Parameters tab, in the Name field, enter line.

    3. Set the DataType field to Text.

    4. Set the Length field to 100.

      Important
      An event publisher function cannot have a return value, variables, or text constants; otherwise you will not be able to compile the function.

    5. Close the C/AL Locals window.

  6. Close the C/AL Globals window.

The new function appears in the C/AL Editor with the following signature:

[IntegrationEvent] OnAddressLineChanged(line : Text[100])

You can now raise the event in the application.

Raising the Event

After you create the event publisher function to publish the event, you can add code to the application to raise the event where it is required. In this case, you want to raise the event when the Address field is changed on the page 21 Customer Card. Therefore, you will add code to the Address - OnValidate() trigger in C/AL code of the page. Raising an event basically involves calling the event publisher function that publishes the event.

To raise the event

  1. In the development environment, open page 21 Customer Card as follows:

    1. On the Tools menu, choose Object Designer, and then choose Page.

    2. Select page 21 Customer Card, and then choose the Design button.

  2. Add a C/AL variable that specifies the object that publishes the event. In this case, the event publisher object is codeunit 50000 My Publishers, which contains the event publisher function OnAddressLineChanged that you created in the previous procedure.

    1. On the View menu, choose C/AL Globals.

    2. On a blank row, in the Name field, enter Publisher.

    3. Set the DataType field to Codeunit.

    4. In the Subtype field, select codeunit 50000 My Publishers.

    5. Close the C/AL Globals window.

  3. In C/AL code, add the following code on the Address - OnValidate() trigger to raise the event:

    Copy Code
    Publisher.OnAddressLineChanged(Address);

    This calls the event publisher function to raise the event.

  4. On the File menu, choose Save to save and compile the changes to the page.

The event can now be subscribed to and handled.

Subscribing to and Handling an Event

Once an event has been published you can add code to the application that subscribes to and handles the event when it is raised. For example, in this walkthrough, when a user changes the address of a customer (the event), you want code that checks that the value does not contain a plus sign. Subscribing to and handling an event is accomplished by creating a C/AL function that is set up as an event subscriber and subscribes to a specific event (defined by an event publisher function). The event subscription function contains the application logic for handling the raised event. For this walkthrough, you will create an event subscriber function that subscribes to the OnAddressLineChanged function in codeunit 50001 My Publishers.

Unlike an event publisher function, an event subscriber function can only reside in a codeunit object. This procedure will add the event subscriber function to a new codeunit, in which you can potentially add more event subscriber functions for other events later.

To create a new codeunit

  • In the development environment, create a new codeunit that has the ID 50001 and the name My Subscribers.

    For more information, see To create a new codeunit.

To create the event subscriber function to subscribe to and handle the event

  1. On the View menu, choose C/AL Globals.

  2. In the C/AL Globals window, choose the Functions tab.

  3. In a blank row, in the Name field, enter CheckAddressLine.

  4. To open the properties for the CheckAddressLine function, select the function, and then in the View menu, choose Properties. Set the properties as follows:

    1. Set the Event property to Subscriber to make the function an event subscriber.

    2. Set the EventPublisherObject property to Codeunit My Publishers.

      This is the codeunit that contains the event publisher function (OnAddressLineChanged) that you want to subscribe to.

    3. In the EventFunction property, select the OnAddressLineChanged integration event.

      This field reads all the published events in the event publisher object.

      Note
      When you get a message that asks whether you want to overwrite the edited function's signature, choose Yes to continue.

    4. Close the Properties window to return to the C/AL Globals window.

  5. A local parameter that has the name line and the data type Text has been automatically added to the new CheckAddressLine function. To verify this, select the function in C/AL Globals window, choose the Locals button, and then see the Parameters tab.

    Close the C/AL Locals window when done.

  6. Close the C/AL Globals window.

    The new function appears in the C/AL Editor with the following signature:

    LOCAL [EventSubscriber] CheckAddressLine(line : Text[100])

    You can now add code to handle the event.

  7. To handle the event, add the following code to the CheckAddressLine function in the C/AL editor:

    Copy Code
    IF (STRPOS(line, '+') > 0) THEN BEGIN
 MESSAGE('Cannot use a plus sign (+) in the address [' + line + ']');
END

    This code checks the value of the Address field on page 21 Customer Card when is has been changed and returns a message if the value contains a plus sign.

Viewing the New Event Subscription

After you create an event subscriber, you can view information about it in page 9510 Event Subscriptions. This page provides information about all the current event subscriptions in the application. You can open this page directly from the development environment or from a Microsoft Dynamics NAV client.

To view the event subscription from the development environment

  • On the Tools menu, choose Debugger, and then choose Event Subscriptions.

To view the event subscription from a Microsoft Dynamics NAV client

  1. Start the Microsoft Dynamics NAV client.

  2. In the Search box, enter Sessions, and then choose the related link.

  3. On the Home tab, in the Events group, choose Subscriptions.

Testing the Event

To test the event implementation, you can run page 21 Customer Card from the development environment.

To test the event

  1. In Object Designer, choose Page.

  2. Select page 21 Customer Card, and then choose the Run button.

    A customer card opens in the Microsoft Dynamics NAV Windows client.

  3. On the Home tab, in the Manage group, choose Edit.

  4. In the Address field, add a plus sign, and then choose the OK button.

    The following message appears:

    Cannot use a plus sign (+) in the address [].

    [] contains the value of the Address field.

See Also

Concepts

Events in Microsoft Dynamics NAV
Introducing Events
Publishing Events
Raising Events
Subscribing to Events
Debugging Events


Walkthrough: Implementing New Workflow Events and Responses

If a business scenario requires a workflow event or a workflow response that is not supported in a Microsoft Dynamics NAV solution, you must implement it by customizing the application code.

In the Workflow window, the workflow administrator creates a workflow by listing the involved steps on the lines. Each step consists of a workflow event, moderated by event conditions, and a workflow response, customized by response options. You define workflow steps by filling fields on workflow lines from fixed lists of event and response values representing scenarios that are supported by the application code. For more information, see How to: Create Workflows in Application Help.

The following procedure describes how to add a new workflow event and a new workflow response to the application code and then register the involved object relations, so that the new elements can be used in workflows. The workflow administrator can then select the new workflow event and response from the Workflow window to incorporate them in new or existing workflow steps.

Important
To ensure that custom workflow records are upgraded correctly, you must add new workflow events, workflow responses, and workflow table relations to dedicated extension points, as described in this procedure. During an upgrade to the next version, the libraries of workflow events, responses, and table relations are removed and then recreated with the latest content from Microsoft. By adding your custom workflow records using subscriptions to the Microsoft-provided extension points, you ensure that your custom record library gets recreated after an upgrade.

Note
This topic refers to two types of events:

  • Workflow Event: An occurrence in the application that users can select from the Workflow window to define workflow steps. For more information, see Workflow in Application Help.

  • Event: The declaration of the occurrence or change in the application. Workflow events typically subscribe to events. For more information, see Events in Microsoft Dynamics NAV.

The development work involved in creating a new workflow event and a related workflow response consists of the following tasks, as a minimum:

  1. Creating a workflow event

    1. Creating a workflow event code that identifies the workflow event

    2. Adding the workflow event code to the Workflow Event table

    3. Creating and publishing an event that the workflow event subscribes to

    4. Raising the event

    5. Subscribing to the event and implement the workflow event

  2. Creating a workflow response

    1. Creating a workflow response code that identifies the workflow response

    2. Adding the workflow response code to the Workflow Response table

    3. Implementing the workflow response

    4. Enabling that the workflow response can be executed

    5. Adding a new workflow response option

  3. Registering workflow event/response combinations needed for the new workflow response

  4. Registering workflow event hierarchies needed for the new workflow event

  5. Creating table relations between entities used when the new workflow event and response are used

  6. Adding a FactBox that shows how a record participates in a workflow

Note
Data and code samples in this procedure refer loosely to a workflow step of sending a notification when a purchase header is posted. However, the procedure alone does not result in a complete solution.

To follow similar steps in a data-driven demo script with screenshots, see the “Build Your Own Workflow Event” demo script, which is available on the Microsoft Dynamics NAV 2016 readiness landing page.

Creating a Workflow Event

Create a code to identify the workflow event, add the workflow event to the library, create an event that the workflow event subscribes to, raise the event, and then subscribe to the event and implement the workflow event.

To create a workflow event code that identifies the workflow event

  1. Create a new codeunit that will be used for new workflow events. Name it to reflect that it is used to identify the new workflow event, such as My Workflow Events. For more information, see How to: Create a Codeunit.

  2. Create a global function in the codeunit. Name the function to reflect that it is used to identify the workflow event, such as MyWorkflowEventCode. For more information, see How to: Add a Function to a Codeunit.

  3. Open the C/AL Locals window to add a local return value. For more information, see C/AL Locals.

  4. On the Return Value tab, fill the fields as described in the following table.

    Return Type Length

    Code

    128

To add the workflow event code to the Workflow Event table

  1. Create another function in the codeunit. Name it to reflect that it is used to add the workflow event to the library, such as AddMyWorkflowEventsToLibrary.

  2. In the Properties window, fill the fields as described in the following table.

    Property Value

    Event

    Subscriber

    EventPublisherObject

    Codeunit Workflow Event Handling

    EventFunction

    OnAddWorkflowEventsToLibrary

  3. Open the C/AL Locals window to add a local variable.

  4. On the Variables tab, fill the fields as described in the following table.

    Name DataType Subtype

    WorkflowEventHandling

    Codeunit

    Workflow Event Handling

  5. In the function, write code that handles the event, such as the following code.

    Copy Code
    WorkflowEventHandling.AddEventToLibrary(MyWorkflowEventCode,DATABASE::”Purchase Header”,’A purchase header is posted.’,0,FALSE);

To create and publish an event that the workflow event subscribes to

  1. Create a function in the codeunit where you want to raise the event, such as the Purch.-Post codeunit. Name the function to reflect that it is used as the publisher event, such as OnAfterPostPurchaseHeader.

  2. In the Properties window, fill the fields as described in the following table.

    Property Value

    Event

    Publisher

    EventType

    Select the event type that is relevant for the workflow event, such as Integration. For more information, see Event Types.

  3. Open the C/AL Locals window to add a local parameter.

  4. On the Parameters tab, fill the fields as described in the following table.

    Name DataType Subtype

    Purchase Header

    Record

    Purchase Header

For more information, see Publishing Events.

To raise the event

  1. Go to the code in your solution where you want to raise the event, such as the Purch.-Post codeunit.

  2. In the function, write code that raises the event, such as the following code.

    Copy Code
    OnAfterPostPurchaseHeader(PurchaseHeader);

For more information, see Raising Events.

To subscribe to the event and implement the workflow event

  1. Create another function in the codeunit where you created the identification code, MyWorkflowEventCode. Name the function to reflect that it is used to subscribe to and implement the workflow event, such as RunWorkflowOnAfterPostPurchaseHeader.

  2. In the Properties window, fill the fields as described in the following table.

    Property Value

    Event

    Subscriber

    EventPublisherObject

    Select the object that contains the definition of the added event, such as the Purch.-Post codeunit.

    EventFunction

    OnAfterPostPurchaseHeader

  3. Choose Yes to overwrite your local parameters with the event parameters.

  4. Open the C/AL Locals window to add a local variable.

  5. On the Variables tab, fill the fields as described in the following table.

    Name DataType Subtype

    WorkflowManagement

    Codeunit

    Workflow Management

  6. In the function, write code that handles the event, such as the following code.

    Copy Code
    WorkflowManagement.HandleEvent(MyWorkflowEventCode,PurchaseHeader);

Another task that you can perform at this point is to specify which filter fields appear in the Event Conditions window. For more information, see Dynamic Request Page Entity.

For more information, see Subscribing to Events.

You have now created a new workflow event. Proceed to create a new workflow response that relates to the workflow event.

Creating a Workflow Response

Create a code to identify the workflow response, add the workflow response code to the library, implement the workflow response, and then enable that the workflow response can be executed.

To create a workflow response code that identifies the workflow response

  1. Create a new codeunit that will be used for the new workflow responses. Name it to reflect that it handles your new responses, such My Workflow Responses.

  2. Create a function in the codeunit. Name the function to reflect that it is used to identify the workflow response, such as MyWorkflowResponseCode.

  3. Open the C/AL Locals window to add a local return value.

  4. On the Return Value tab, fill the fields as described in the following table.

    Return Type Length

    Code

    128

To add the workflow response code to the Workflow Response table

  1. Create another function in the codeunit. Name it to reflect that it is used to add the workflow response to the library, such as AddMyWorkflowResponsesToLibrary.

  2. In the Properties window, fill the fields as described in the following table.

    Property Value

    Event

    Subscriber

    EventPublisherObject

    Codeunit Workflow Response Handling

    EventFunction

    OnAddWorkflowResponsesToLibrary

  3. Open the C/AL Locals window to add a local variable.

  4. On the Variables tab, fill the fields as described in the following table.

    Name DataType Subtype

    WorkflowResponseHandling

    Codeunit

    Workflow Response Handling

  5. In the function, write code that registers the response, such as the following code.

    Copy Code
    WorkflowResponseHandling.AddResponseToLibrary(MyWorkflowResponseCode,DATABASE::"Purchase Header",'Send a notification.','GROUP 0')
    Note
    In the “To add a new workflow response option” procedure, you will change the GROUP value to, for example, 50000.

To implement the workflow response

  1. Create another function in the codeunit. Name it to reflect that it is used to implement the workflow response, such as MyWorkflowResponse.

  2. Open the C/AL Locals window to add a local parameter.

  3. On the Parameters tab, fill the fields as described in the following table.

    Name DataType Subtype

    Purchase Header

    Record

    Select the relevant record, such as Purchase Header table.

  4. In the function, write code that handles the response, such as the following code.

    Copy Code
    CODEUNIT.RUN(CODEUNIT::"Purch.-Post",PurchaseHeader);

To enable that the workflow response can be executed

  1. Create another function in the codeunit. Name it to reflect that it is used to enable the new workflow response to be executed alongside existing workflow responses, such as ExecuteMyWorkflowResponses.

  2. In the Properties window, fill the fields as described in the following table.

    Property Value

    Event

    Subscriber

    EventPublisherObject

    Codeunit Workflow Response Handling

    EventFunction

    OnExecuteWorkflowResponse

  3. Choose Yes to overwrite your local parameters with the event parameters.

  4. In the function, write code that enables the response, such as the following code.

    Copy Code
    IF WorkflowResponse.GET(ResponseWorkflowStepInstance."Function Name") THEN
  CASE WorkflowResponse."Function Name" OF
    MyWFResponseCode:
      BEGIN
        MyWorkflowResponse(Variant);
        ResponseExecuted := TRUE;
      END;
  END;

To add a new workflow response option

  1. Open table 1523, Workflow Step Argument, in design mode.

  2. Add a field that reflects your new response option, such as My New Response Option. For more information, see How to: Add Fields to a Table.

  3. Open page 1523, Workflow Response Options, in design mode.

  4. Add a group and a control for the new field.

  5. For the Visibility property of the group, enter, for example, "Response Option Group" = 'GROUP 50000'.

  6. Open the AddMyWorkflowResponsesToLibrary function.

  7. In the function code, change ‘GROUP 0’ to ‘GROUP 50000’.

  8. To make sure that the new workflow response is updated, delete the Send a notification. response from the Workflow Response table.

    To use the new option in the MyWorkflowResponse function, proceed to add a local parameter and a local variable.

  9. Open the C/AL Locals window to add a local parameter and a local variable.

  10. On the Parameters tab, fill the fields as described in the following table.

    Name DataType Subtype

    WorkflowStepInstance

    Record

    Workflow Step Instance

  11. On the Variables tab, fill the fields as described in the following table.

    Name DataType Subtype

    WorkflowStepArgument

    Record

    Workflow Step Argument

  12. In the function, write code that enables the response, such as the following code:

    Copy Code
    IF WorkflowStepArgument.GET(WorkflowStepInstance.Argument) THEN;

    You now have access to your new field on the Workflow Step Argument table that you can use as a workflow response option.

  13. In the ExecuteMyWorkflowResponses function, make the following code change:

    Change from this code: MyWorkflowResponse(Variant);

    Change to this code: MyWorkflowResponse(Variant,ResponseWorkflowStepInstance);

You have now created the actual workflow event and response. Proceed to perform various tasks that enable them to be used in workflows.

Registering Workflow Event/Response Combinations Needed for the New Workflow Response

Add new workflow event/response combinations to the WF Event/Response Combination table so that they appear correctly in the Workflow Events and Workflow Responses windows.

To register workflow event/response combinations needed for the new workflow response

  1. Open the codeunit that you created in the “To create a workflow response” procedure, My Workflow Responses.

  2. Create another function in the codeunit. Name it to reflect that it is used to add the workflow event/response combinations to the WF Event/Response Combination table, such as AddMyWorkflowEventResponseCombinationsToLibrary.

  3. In the Properties window, fill the fields as described in the following table.

    Property Value

    Event

    Subscriber

    EventPublisherObject

    Codeunit Workflow Response Handling

    EventFunction

    OnAddWorkflowResponsePredecessorsToLibrary

  4. Choose Yes to overwrite your local parameters with the event parameters.

  5. Open the C/AL Locals window to add two local variables.

  6. On the Variables tab, fill the fields as described in the following table.

    Name DataType Subtype

    MyWorkflowEvents

    Codeunit

    My Workflow Events

    WorkflowResponseHandling

    Codeunit

    Workflow Response Handling

  7. In the function, write code that registers event/response combinations that you want to support in your application, using a CASE statement, such as the following code.

    Copy Code
    CASE ResponseFunctionName OF
  MyWorkflowResponseCode:
    WorkflowResponseHandling.AddResponsePredecessor(MyWorkflowResponseCode,MyWorkflowEvents.MyWorkflowEventCode);
END;

You can also do this work from the user interface. For more information, see Workflow Event/Response Combinations.

Registering Workflow Event Hierarchies Needed for the New Workflow Event

Add new workflow event/event combinations to the WF Event/Response Combination table so that they workflow events appear in the correct hierarchy in the Workflow Events window.

To register workflow event hierarchies needed for the new workflow event

  1. Open the codeunit that you created in the “To create a workflow event” procedure, My Workflow Events.

  2. Create another function in the codeunit. Name it to reflect that it is used to add the workflow event hierarchies to the WF Event/Response Combination table, such as AddWorkflowEventHierarchiesToLibrary.

  3. In the Properties window, fill the fields as described in the following table.

    Property Value

    Event

    Subscriber

    EventPublisherObject

    Codeunit Workflow Event Handling

    EventFunction

    OnAddWorkflowEventPredecessorsToLibrary

  4. Choose Yes to overwrite your local parameters with the event parameters.

  5. Open the C/AL Locals window to add a local variable.

  6. On the Variables tab, fill the fields as described in the following table.

    Name DataType Subtype

    WorkflowEventHandling

    Codeunit

    Workflow Event Handling

  7. To make sure that the new workflow event is updated, delete the A purchase header is posted. event from the Workflow Event table.

  8. In the function, write code that registers event hierarchies that you want to support in your application, using a CASE statement, such as the following code.

    Copy Code
    CASE EventFunctionName OF
  MyWorkflowEventCode:
    WorkflowEventHandling.AddEventPredecessor(MyWorkflowEventCode,WorkflowEventHandling.[your desired predecessor event code]);
END;

You can also do this work from the user interface. For more information, see Workflow Event Hierarchies.

Creating Table Relations Between Entities Used when the New Workflow Event and Response are Used

Workflows events can be executed on different types of records. To keep track of these, you must define relations between the involved records.

To create table relations between entities that are processed when the new workflow event and response are used in workflows

  1. Open the codeunit that you created in the “To create a workflow event” procedure, My Workflow Events.

  2. Create another function in the codeunit. Name it to reflect that it is used add workflow table relations in the Workflow - Table Relation table, such as AddWorkflowTableRelationsToLibrary.

  3. In the Properties window, fill the fields as described in the following table.

    Property Value

    Event

    Subscriber

    EventPublisherObject

    Codeunit Workflow Event Handling

    EventFunction

    OnAddWorkflowTableRelationsToLibrary

  4. Open the C/AL Locals window to add a local variable.

  5. On the Variables tab, fill the fields as described in the following table.

    Name DataType Subtype

    WorkflowSetup

    Codeunit

    Workflow Setup

  6. To make sure that the new workflow event is updated, delete the A purchase header is posted. event from the Workflow Event table.

  7. In the function, write code that registers table relations that you want to support in your application, such as the following code.

    Copy Code
    WorkflowSetup.InsertTableRelation(DATABASE::”Purchase Header”,1,DATABASE::”Approval Entry”,2);

You can also do this work from the user interface. For more information, see Workflow - Table Relations.

Adding a FactBox that Shows How a Record Participates in a Workflow

Add a FactBox to relevant pages so that users can view when and how the new workflow event and response participate in workflows for records shown on the page.

To add a FactBox that shows how a record participates in a workflow

  1. Open, in design mode, the page from where users need to see related workflows that use the new workflow event and response.

  2. Add a FactBox. Name it WorkflowStatus. For more information, see How to: Add a FactBox to a Page.

  3. Open the C/AL Globals window to add a global variable.

  4. On the Variables tab, fill the fields as described in the following table.

    Name DataType Subtype

    ShowWorkflowStatus

    Boolean

  5. To make the FactBox visible, in the Properties window, fill the fields as described in the following table.

    Property Value

    Visible

    ShowWorkflowStatus

  6. On the page, add the following code to the OnAfterGetCurrentRecord function to make the FactBox find the workflow that relates to the record.

    Copy Code
    ShowWorkflowStatus := CurrPage.WorkflowStatus.PAGE.SetFilterOnWorkflowRecord(RECORDID);

You have now enabled a new workflow scenario by implementing the required workflow event and response in the application code. The workflow administrator can now select the workflow event and workflow response from the Workflow window to define new or edit existing workflows. For more information, see How to: Create Workflows.

See Also

Workflow Event
Workflow Response
How to: Create Workflows
Workflow
Developer and IT Pro Help for Microsoft Dynamics NAV 2016

Concepts

Events in Microsoft Dynamics NAV


Extending Microsoft Dynamics NAV

This section describes how you can extend the functionality of Microsoft Dynamics NAV 2016 by using the following features.

Feature Description See

Component Object Model (COM) technologies

You can extend the functionality by implementing automation and custom controls. The Microsoft Dynamics NAV Windows client supports automation servers by acting as an automation controller and using OCXs (custom controls).

Note
COM is not supported by the Microsoft Dynamics NAV Web client.

Extending Microsoft Dynamics NAV Using COM

Microsoft .NET Framework interoperability

You can extend the RoleTailored clients and Microsoft Dynamics NAV Server with functionality that is available in Microsoft .NET Framework assemblies. You can take advantage of .NET Framework interoperability so that Microsoft Dynamics NAV objects can interact with the .NET Framework objects.

Extending Microsoft Dynamics NAV Using Microsoft .NET Framework Interoperability

Control add-ins

A control add-in is a custom control, or visual element, for displaying and modifying data on pages in the Microsoft Dynamics NAV Windows client. Control add-ins are delivered as Microsoft .NET Framework-based assemblies. Microsoft Dynamics NAV includes the client extensibility API for creating your own control add-ins.

Extending the Windows Client Using Control Add-ins

Note
When Microsoft Dynamics NAV data is consumed in a browser or by a Microsoft .NET Framework assembly, users cannot be authenticated if their user name or password contains Unicode characters. This is a limitation in the basic authentication mechanism that is defined in the HTTP/1.1 specification.

The same limitation applies to exposing Microsoft Dynamics NAV data in web services.

See Also

Concepts

Extending Microsoft Dynamics NAV Using COM
Extending Microsoft Dynamics NAV Using Microsoft .NET Framework Interoperability
Extending the Windows Client Using Control Add-ins


Extending Microsoft Dynamics NAV Using COM

This section describes how you can extend the Microsoft Dynamics NAV Windows client by using Component Object Model (COM) technologies. The Microsoft Dynamics NAV Windows client supports Automation servers by acting as an Automation controller and using OCXs (custom controls).

See Also

Tasks

How to: Create an Automation Controller

Concepts

COM Overview
Using COM Technologies in Microsoft Dynamics NAV


COM Overview

This topic describes how you can use Component Object Model (COM) technologies in the Microsoft Dynamics NAV Development Environment to extend the functionality of Microsoft Dynamics NAV. In the development environment, you can use two types of COM technologies: Automation and custom controls.

Only non-visual controls are supported. A control cannot be used to add graphical or user-interface elements to a Microsoft Dynamics NAV object. For example, you cannot add a third-party control to a page. However, the control can display information and interact with the user in a window of its own.

Important
COM technologies are not supported by Microsoft Dynamics NAV Web client.

Automation

Automation is a client-server infrastructure that enables one application to access and communicate with another application. By using Automation, an application, such as Microsoft Office Word, exposes its internal functions and routines as Automation objects that Microsoft Dynamics NAV can access through an Automation controller that is run on the Microsoft Dynamics NAV Windows client. The application that exposes the Automation object, such as Word, acts as the Automation server, and the Automation controller acts as the client.

Automation enables tasks that are typically run manually to be run automatically instead. For example, you can write a script to extract data from a database, put the data into a Microsoft Office Excel workbook, and then display the data graphically.

For examples of Automation in Microsoft Dynamics NAV 2016, see Walkthrough: Using Automation to Write a Letter in Microsoft Office Word and Walkthrough: Using Automation to Create a Graph in Microsoft Excel.

Custom Controls

Custom controls are OLE Control Extensions (OCX) or ActiveX controls, which are specific types of Automation objects. OCX and ActiveX controls are generally small programs or application objects that you can start from your Microsoft Dynamics NAV application to perform a specific function or task. You can use custom controls for various types of tasks. By default, there are several custom controls available in Microsoft Dynamics NAV from the Tools menu in the development environment. To develop custom controls, you can use tools such as Microsoft Visual C++ or Microsoft Visual Basic. Both products use wizards to make it easy to develop COM objects. You can also develop functional controls without understanding the complex details of COM.

If you will use existing custom controls from the development environment, then you do not have to know anything about COM. Using the functionality provided by a COM object is no different from using any C/AL function.

See Also

Concepts

Extending Microsoft Dynamics NAV Using COM
Using COM Technologies in Microsoft Dynamics NAV
Best Practices for Using Automation with the Microsoft Dynamics NAV Windows Client


Using COM Technologies in Microsoft Dynamics NAV

Microsoft Dynamics NAV supports COM technologies in two ways: using custom controls (OCXs) and as an automation controller.

Limitations

The COM support has the following limitations:

  • Only non-visual controls are supported. A control cannot be used to add graphical elements to a Microsoft Dynamics NAV object. For example, you cannot add a third-party control to a page. However, the control can display information and interact with the user in a window of its own.

  • Exception handling is not supported. Information about exceptions cannot be retrieved from a control or automation server through the Invoke method of the IDispatch interface and the EXCEPINFO structure.

  • Unlike Microsoft Dynamics NAV 2009, automation objects in Microsoft Dynamics NAV 2016 cannot target the computer that is running the Microsoft Dynamics NAV Server. Only client-side automation objects are supported. Instead of implementing server-side automation object, you can use Microsoft .NET Framework Interoperability. For more information, see Extending Microsoft Dynamics NAV Using Microsoft .NET Framework Interoperability.

Parameters, Return Values, and Data Types

The mechanisms for calling methods in a control, passing parameters, and receiving return values are somewhat complex. Using tools such as the wizards in Microsoft Visual C++ shields you from most of the complexities. However, there is no one-to-one relationship between the data types that you can use when you implement methods in, for example, Visual C++ and the data types in C/AL. Some of the COM data types are not supported in C/AL and some have a limitation imposed on their usage.

When you use the C/AL Symbol Menu, you can see the syntax for a method or property that has the return value and the parameters shown with the COM data types.

Mapping C/AL Data Types to COM Data Types

The following table shows how C/AL data types map to COM data types.

C/AL data type | COM data type | Comment
Boolean Data Type | VARIANT_BOOL (VT_BOOL) |
Option Data Type | long (VT_I4) |
Integer Data Type | long (VT_I4) |
BigInteger Data Type | long (VT_I4) |
Decimal Data Type | CURRENCY (VT_CY) | The CURRENCY type in COM is a special data type with a fixed point that has 15 digits to the left of the decimal point and 4 to the right. The Decimal type in C/AL does not have a fixed point and can have a total of 18 digits. This could lead to rounding being performed when a Decimal type number is passed to a method that expects a CURRENCY. The server changes that number and returns it as a CURRENCY. No matter how many digits the original Decimal had to the right of the decimal point, the returned CURRENCY will have no more than 4 digits.
Char Data Type | BSTR (VT_BSTR) |
Text Data Type | BSTR (VT_BSTR) |
Code Data Type | BSTR (VT_BSTR) |
Date Data Type | DATE (VT_DATE) |
Time Data Type | void (VT_VOID) |
DateTime Data Type | DATE (VT_DATE) |
Automation Data Type | TypedObject, UntypedObject (VT_DISPATCH) |
InStream | VT_STREAM |
OutStream | VT_STREAM |
Variant Data Type | VARIANT (VT_VARIANT) |

Mapping COM Data Types to C/AL Data Types

The following table shows how to map COM data types to C/AL data types.

COM data type | C/AL data type | Comment
VT_UNKNOWN | InStream and OutStream Data Types | Only the IID_IStream and IID_SequentialStream interfaces are supported. If you pass any other IUnknown interface, an error will occur at runtime.
short (VT_I2) | Integer Data Type |
long (VT_I4) | Integer Data Type BigInteger Data Type |
float (VT_R4) | Decimal Data Type |
double (VT_R8) | Decimal Data Type |
CURRENCY (VT_CY) | Decimal Data Type | The CURRENCY type in COM is a special data type with a fixed point, which has 15 digits to the left of the decimal point and 4 to the right. The Decimal type does not have a fixed point and can have a total of 18 digits.
DATE (VT_DATE) | Date Data Type DateTime Data Type | The COM DATE type contains both a date and a time value. C/AL has Date and Time as separate data types. Therefore, the time part of a COM DATE type will be lost when the COM DATE type is mapped to the Date C/AL data type. To keep the date and the time, map the COM Date type to the C/AL DateTime data type.
BSTR (VT_BSTR) | Text Data Type |
VARIANT_BOOL (VT_BOOL) | Boolean Data Type |
TypedObject/ UntypedObject (VT_DISPATCH) | Automation Data Type OCX Data Type |
VT_EMPTY | Text Data Type |
VARIANT (VT_VARIANT) | Variant Data Type |

Unsigned char (VT_UI1), SCODE (VT_ERROR), and SAFEARRAY (VT_ARRAY)

You can use the C/AL variant data type to pass unsigned char, SCODE, or SAFEARRAY to another variant that supports these types. You cannot assign them to C/AL data types.

Remarks

When you call a method with a ByRef parameter, the typical C/AL type conversions do not occur. For example, this means that if the parameter is of type float, you have to use a C/AL variable of type Decimal. You cannot use Integer and have C/AL convert it for you.

Note
If the value that you want to pass has the incorrect type, when, for example, it is a value from a database record field, then you can assign it to a C/AL variable of the correct type before you call the COM object method.

You will sometimes see a COM object method or a property in the C/AL Symbol Menu that has type IDispatch. This means that the method or property returns or expects a COM object. In this case, you must use a C/AL Automation variable that has been declared, through the Subtype, to be the correct COM object. You will have to study the documentation for the automation server to gain the necessary information.

You will also see properties and methods that do not have one of the expected types. For example, a method in Microsoft Office Excel can have a return value of type WORKBOOK. This means that the automation server has implemented a USERDEF type. Microsoft Dynamics NAV supports USERDEF types in two contexts: IDispatch and Enumeration.

If the USERDEF type is an IDispatch, it means that it is an interface (sometimes also called class or object) with a specific GUID. You will have to use the same object for a return value or parameter. You do this by creating an Automation variable with the correct subtype. For example, Microsoft Excel has several methods that return a WORKBOOK variable. This means that you must declare a variable of type Automation and subtype 'Microsoft Excel 8.0 Object Library'.Workbook.

If the USERDEF type is an enumeration, you cannot use the symbolic name, for example, xl3DPie, but instead must use the enumerator, for example, -4102. For Microsoft Office products, you can find this value by using the VBA Object Browser.

See Also

Reference

Automation Data Type
Variant Data Type

Concepts

Extending Microsoft Dynamics NAV Using COM
COM Overview


How to: Create an Automation Controller

To implement Automation in Microsoft Dynamics NAV, create an Automation controller in C/AL code of the Microsoft Dynamics NAV object. By using variables that have an Automation data type, an Automation controller implements and runs Automation objects from an Automation server. This topic outlines the procedure for creating an Automation controller.

To create an Automation controller that uses an Automation server

  1. Declare the top-level interface of the Automation server as a variable of the data type Automation.

  2. Declare all other objects and interfaces (classes) as variables of the Automation data type.

  3. Call the C/AL CREATE function on the variable that you declared in step 1 as shown in the following code:

    Copy Code
    CREATE(AutomationVariable [,True|False] ,True)

    The last parameter must be set to True so that the automation controller targets the Microsoft Dynamics NAV Windows client.

    Note
    You can also use define a Boolean type variable instead of setting the parameter to True. The variable must evaluate to True for the controller to be created at run time. If variable evaluates to False, then you will see an error at run time.

    For more information, see CREATE Function (Automation).

  4. Use the methods and properties of the Automation server in your C/AL code.

  5. If needed, use the CLEAR function (destroy) for the top-level object. Otherwise, it will be cleared automatically when the variable goes out of scope.

You write most of your code during step 4 by using the methods and the properties of the Automation server. The syntax and the semantics of these methods and properties are documented in the documentation for each Automation server. Using these methods and properties in C/AL does not require any new or changed syntax.

For examples of creating an Automation controller, see Walkthrough: Using Automation to Write a Letter in Microsoft Office Word and Walkthrough: Using Automation to Create a Graph in Microsoft Excel.

See Also

Concepts

Extending Microsoft Dynamics NAV Using COM
Using COM Technologies in Microsoft Dynamics NAV
COM Overview
Best Practices for Using Automation with the Microsoft Dynamics NAV Windows Client


Best Practices for Using Automation with the Microsoft Dynamics NAV Windows Client

With Automation, Windows-based applications, such as Microsoft Office products, expose Automation objects that Microsoft Dynamics NAV can access and run using an Automation controller in the development environment. Automation objects are always run on the computer running Microsoft Dynamics NAV Windows client.

Because Automation objects expose a COM interface, Automation can affect the performance and security of your solution. This topic provides best practices and recommendations to follow when implementing Automation in the RoleTailored client to help limit potential performance and security issues.

Note
You specify an Automation objects to run on the Microsoft Dynamics NAV Windows client by using the CREATE Function (Automation) in C/AL code of the object that runs the Automation object.

Automation Object Implementation and Support in the Microsoft Dynamics NAV Windows client

Use the following figure and table to help you determine whether the Automation object is supported on the Microsoft Dynamics NAV Windows client based on the Automation object's characteristics.

Microsoft Dynamics NAV automation object overview

Automation object | Supported by Microsoft Dynamics NAV Windows client | Remarks
Native code Automation objects that use out-of-process Automation servers | Yes | This includes Microsoft Office Automation Objects. For more information, see Native and Managed Automation Objects.
Automation objects, including OCX types, which do not add user-interface to Microsoft Dynamics NAV objects | Yes |
Automation objects, including OCX types, which add user-interface to Microsoft Dynamics NAV objects | No | The control can display information and interact with the user in a window of its own.
Automation objects that execute as single-threaded apartments | Yes | For more information, see Using Multithreaded Apartment Automation Objects.
Automation objects that execute as multithreaded apartments | Yes | There are performance considerations with multithreaded apartments. For more information, see Using Multithreaded Apartment Automation Objects.
Managed code Automation objects | Yes | For more information, see Native and Managed Automation Objects.
Native code Automation objects that use in-process Automation servers | Yes | This includes DLLs, such as MSXML.dll. For more information, see Native and Managed Automation Objects.
Automation objects that stream parameters and are configured to receive events | No | In the development environment, an Automation variable includes a WithEvents property, but this property does not have any impact and must be set to No.

Using Multithreaded Apartment Automation Objects

Automation objects can be designed to execute as multithreaded apartments (MTA). MTA Automation objects are designed for highly reentrant, stressed environments with high throughput for multiple clients and are most suitable for running an a server. However, you can use an MTA Automation object on with the Microsoft Dynamics NAV Windows client because the .NET Framework manages marshaling between MTA and STA. If you do, you may decrease performance. Some Automation objects are available in both MTA and STA versions, so you can choose STA. For example, see the DOMDocument and FreeThreadedDOMDocument Automation objects of the Microsoft XML Core Services (MSXML2) library. To read more about these objects and implications on performance, see the Microsoft Support Knowledge Base article PRB: MSXML Performance Bottleneck in ShareMutex Under Stress.

Native and Managed Automation Objects

The Microsoft Dynamics NAV Windows client supports Automation objects that are created from either native or managed code. Automation in Microsoft Dynamics NAV uses the common language runtime (CLR), which allows managed code to call unmanaged and native Automation objects. The CLR generates a runtime-callable wrapper (RCW) proxy that implements all interfaces of the underlying Automation object. Additionally, the CLR has a built-in marshaling layer that maps the types between the native and managed domains.

Data Type Mapping Between C/AL, COM, and CLR

The following table lists the type mappings between C/AL, COM, and the corresponding .NET CLR types.

C/AL type | COM type | CLR type
Automation | VT_DISPATCH | System.Object
BigInteger | VT_I8 | System.Int64
Boolean | VT_BOOL | System.Boolean
Char | VT_BSTR | System.Byte
Code | VT_BSTR | System.String
Date | VT_DATE | System.DateTime
DateTime | VT_DATE | System.DateTime
Decimal | VT_CY | System.Decimal
Decimal | VT_R4 | System.Single
Decimal | VT_R8 | System.Double
InStream | VT_STREAM | System.Object
Integer | VT_I2 | System.Int16
Integer | VT_I4 | System.Int32
OCX | VT_DISPATCH | System.Object
Option | VT_I4 | System.Int32
OutStream | VT_STREAM | System.Object
Text | VT_BSTR | System.String
Time | VT_DATE | System.DateTime
Variant | VT_VARIANT | System.Object

Automation objects are late-bound activated, which means that they must implement the IDispatch interface. This allows the reflection API, which represents the classes, interfaces, and objects in the .NET runtime, to invoke members. The RCW recognizes managed Automation objects as being managed objects, and standard CLR reflection invocation takes place. As a result, in-process (DLL) and out-of-process (EXE) Automation behaves identically when the Automation objects are created in a managed language.

Implementing Automation Objects as VAR Parameters

You can implement an automation object as a VAR parameter in a function call, which means that it is called by reference. If an automation method returns IUnknown or IDispatch objects in the parameter list, then you must create the automation variable before it can be used; otherwise, you will get an error at runtime. For example, the following C/AL code creates an automatioObject variable and calls a method that will return an IDispatch object in the created variable..

Copy Code
create(automationObject, true, true);
somereturnValue := otherObjectReturningIDispatch(automationObject);
automationObject.CallObjectMember();

If the automationObject is used without being created first, the following error will appear at runtime:

System.Runtime.InteropServices.COMException (0x80020005): Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))

Security - User Account for In-Process Automation Objects and OCX Controls

In-process Automation objects and OCX controls always run under the same user account as the Microsoft Dynamics NAV Windows client. This is because in-process Automation objects are hosted by the current running process and inherit the security properties of the active user.

See Also

Tasks

How to: Create an Automation Controller
Walkthrough: Using Automation to Write a Letter in Microsoft Office Word
Walkthrough: Using Automation to Create a Graph in Microsoft Excel

Concepts

COM Overview
Programming Best Practices
Security and Protection


Walkthrough: Using Automation to Write a Letter in Microsoft Office Word

Automation lets you use the capabilities and features of Microsoft Office products, such as Microsoft Word or Microsoft Excel, in your Microsoft Dynamics NAV application. In this walkthrough, you will implement Word Automation from a customer card in the Microsoft Dynamics NAV Windows client. You will set up the customer card so that if the customer has bought goods for more than LCY 2,500 during the past year, then the user can choose a menu item or action to automatically create a letter in Word that offers the customer 3% discount. The letter will include information about the customer, such as the customer's name and the address, and the name of the contact to whom you will address the letter.

Note
The Microsoft Dynamics NAV Web client does not support automation.

About This Walkthrough

This walkthrough illustrates the following tasks:

  • Creating a template in Word that will be used for Word documents that are created from the Microsoft Dynamics NAV Windows client with Automation.

  • Creating a codeunit and declaring the Automation variables that are required for using Microsoft Office Word Automation.

  • Writing C/AL code in the codeunit to instantiate the Automation object that creates a Word document from a template.

  • Adding C/AL code to the Automation codeunit to transfer data from a table record to a Word document.

  • Calling the Automation codeunit from an action on a page.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 with a developer license.

  • The CRONUS International Ltd. demonstration database.

  • Microsoft Word 2013 or Microsoft Word 2010.

Where to Get the Information for the Letter

Most information that you need to transfer to Word is in the Customer table. The Customer table contains a FlowField called Sales (LCY) that contains the aggregated sales for the customer. For this walkthrough, you are learning about Automation, so you use the existing value. In a real customer installation, you would need to set up an appropriate date filter to get the sales for the past year only.

You also need to retrieve the information about your own company that you will use in the letterhead and in the greeting of the letter. This information is contained in the Company Information and User tables.

Where to Place Automation Code

In this walkthrough, you put all code in a separate codeunit that is called from a menu item on the Customer Card page. You must consider the following issues when you are deciding where to place the code that uses Automation:

  • The Automation server must be installed on the computer that compiles an object that uses Automation. If you must recompile and modify an object on a computer that does not have the Automation server installed, then you must modify the code to compile it again. We recommend that you isolate code that uses Automation in separate codeunits.

  • Performance can be an issue if extra work is needed to create an Automation server with the CREATE system call. If the Automation server is to be used repeatedly, then you will gain better performance by designing your code so that the server is created only once instead of making multiple CREATE and CLEAR calls).

These two issues may clash, and you will have to make some tradeoffs that are based on the actual context in which your code will be used. In this walkthrough, you are not putting the Automation code on the customer card but are isolating it in a separate codeunit. Performance can be improved by putting the code on the customer card because you do not have to open and close Word for each letter that is created in the session.

You can work around this problem. If Word is already open when it is called from the code, then the running instance is reused. You can manually open Word or do not close Word after creating the first letter.

Using Word in This Example

You will extract and transfer data one customer at a time. You also will initiate this processing and the subsequent processing in Word from the customer card.

You will insert fields into the Word template and give these fields convenient mnemonic names that correspond to the names of the record fields that you are using.

To make this work, your C/AL code must make two extra calls to Microsoft Office Word. You must call the ActiveDocument.Fields.Update method before using the fields. After you have transferred all the information, you must call the ActiveDocument.Fields.Unlink method. This ensures that you can successfully use the Word fields as placeholders.

In addition, while you can name the Customer or Address fields, you must reference them by indexing into the Fields collection of the document. This can make the C/AL code harder to understand.

Creating the Word Template for Use by Automation

First, you create a Word template that you will use to create letters to customers that qualify for a discount. To create the template, you add mail merge fields for displaying data that is extracted from Microsoft Dynamics NAV that you want included in the customer letter, such as the customer's name, contact, and total sales.

You will create and save the template on the computer running the Microsoft Dynamics NAV Windows client, because you will configure the automation object to run on the client.

To create the template

  1. On the computer running Microsoft Dynamics NAV Windows client, open Word and create a new document.

  2. Choose where you want to insert the fields. Then, on the Insert tab, in the Text group, choose Quick Parts, and then choose Field.

  3. In the Categories list, select Mail Merge.

  4. In the Field names list, select MergeField.

  5. In the Field Name box under Field Properties, type Contact. This field will display the name of your contact person at the customer site as taken from the Customer table.

  6. Choose OK to add the field.

  7. Repeat steps 2 through 6 to add the remaining fields as follows:

    Field name Description Underlying table

    Name

    The name of the customer.

    Customer

    Address

    The address of the customer.

    Customer

    Sales (LCY)

    The total amount that the customer has purchased from you.

    Customer

    Company Name

    The name of your company.

    Company Information

  8. Save the Word document as a template with the name Discount.dotx at C:\Documents and Settings\All Users\Templates or a folder of your choice.

Creating the Codeunit and Declaring the Variables

The next step is to create the codeunit that calls Word and creates the letter.

To create the codeunit

  1. In Object Designer, choose Codeunit, and then choose the New button to create a new codeunit.

  2. On the View menu, choose Properties to open the Properties window of the codeunit.

  3. In the TableNo field, choose the AssistEdit button to open the Table List window.

  4. In the Table List window, select the Customer table, and then choose OK.

  5. Close the Properties window.

To declare the variables

  1. Choose the OnRun Trigger and on the View menu, choose C/AL Locals, and then choose the Variables tab.

  2. On a blank line, type wdApp in the Name field and set the Data Type field to Automation.

    Note
    When you create an Automation variable, some hidden events are also created for it. If you want to delete the variable, be aware that the events are also not deleted. This can cause issues if you then create a variable with the same name.

  3. In the Subtype field, choose the AssistEdit button. The Automation Object List window is displayed.

  4. In the Automation Server field, choose the AssistEdit button.

  5. In the Automation Server List, select Microsoft Word 15.0 Object Library if you are running Word 2013, or select Microsoft Word 14.0 Object Library if you are running Word 2010, and then choose OK.

  6. From the list of classes in the Automation Object List, select the Application class, and then choose OK.

  7. Repeat steps 2 through 6 to add the following two Automation variables:

    Name Data type Subtype Class

    wdDoc

    Automation

    Microsoft Word 14.0/15.0 Object Library

    Document

    wdRange

    Automation

    Microsoft Word 14.0/15.0 Object Library

    Range

  8. Add the following variables.

    Name Data type Subtype Length

    CompanyInfo

    Record

    Company Information

    TemplateName

    Text

    250

  9. Close the C/AL Locals window.

Writing the C/AL Code

Before you start writing the C/AL code that uses Automation, you must do some initial processing. You start by calculating the Sales (LCY) FlowField. Then, you check whether the customer qualifies for a discount. Finally, you retrieve the information from the Company Information and User tables that you use to fill in some of the fields in the letter.

To write the C/AL code

  1. In the C/AL Editor, add the following lines of code to the OnRun section.

    Copy Code
    CALCFIELDS("Sales (LCY)");
CompanyInfo.GET;

  2. To create an instance of Word before using it, enter the following line of code.

    Copy Code
    CREATE(wdApp, FALSE, TRUE);

    This statement creates the Automation object with the wdApp variable.

    • The first Boolean parameter in the statement (FALSE) tells the CREATE function to try to reuse an already running instance of the Automation server that is referenced by Automation before creating a new instance. If you change this to TRUE, then the CREATE function always creates a new instance of the Automation server.

    • The second Boolean parameter in the statement creates the Automation object on the client. This is necessary to use this codeunit on a page in the Microsoft Dynamics NAV Windows client.

    For more information, see CREATE Function (Automation).

  3. Enter the following lines of code to add a new document to Word that uses the template that you designed earlier. If required, replace C:\Documents and Settings\All Users\Templates with the correct folder path to the template that you defined in the procedure Creating the Word Template for Use by Automation.

    Copy Code
    TemplateName := 'C:\Documents and Settings\All Users\Templates\Discount.dotx';
wdDoc := wdApp.Documents.Add(TemplateName);
wdApp.ActiveDocument.Fields.Update;

    Because the Add method of the Documents collection requires that you pass the path to the template by reference, you must set up the TemplateName variable to hold this information. You will get a compilation error if you put the path into the call as a literal string.

    The Documents property returns a Documents collection that represents all open documents. You can also see that the Documents collection object has an Add method, and that the Add method has the following syntax.

    expression.Add(Template, NewTemplate, Document Type, Visible)

    expression is a required argument, and it must be an expression that returns a Documents object. All the arguments are optional. You will use Template to open a new document that is based on your template.

    For the syntax in the C/AL Symbol Menu, note that the Documents property returns an object of type DOCUMENTS, which is a user-defined type. The property returns a Documents class or IDispatch interface. This information helps the compiler perform a better type check during compilation. The following statement can also pass both the compile-time and the run-time type checks.

    wdDoc := wdApp.Documents.Add(TemplateName);

    Finally, the Add method returns a Document class. While you did not need to declare a C/AL variable for the interim Documents class, you have declared a variable for the wdDoc return value,.

    The third line contains a call that must be made to ensure that the template works as intended.

    wdApp.ActiveDocument.Fields.Update;

Transferring Data to Word

Now you can transfer the actual data from the Customer record to the placeholder fields in the Word document.

You have set up the first three fields in the template so that they can contain the contact, name, and address of the customer and you can transfer the data.

To transfer data to Word

  1. Transfer the data by adding the following lines of code.

    Copy Code
    wdRange := wdAPP.ActiveDocument.Fields.Item(1).Result;
wdRange.Text := Contact;
wdRange.Bold := 1;
wdRange := wdAPP.ActiveDocument.Fields.Item(2).Result;
wdRange.Text := Name;
wdRange.Bold := 1;
wdRange := wdAPP.ActiveDocument.Fields.Item(3).Result;
wdRange.Text := Address;
wdRange.Bold := 1;

    You cannot use the fields directly as variables and make an assignment such as Fields.Item(3) := Address. Instead, you use the Result property of the field. This property returns the result of the field as a range. You place this range in the wdRange Automation variable that you declared.

    You then set the Text property of the range to the desired values, which is the name of your contact person and the name and address of the customer. Finally, you add bold formatting.

    The data you are transferring must be in text format. If it is not in text format, then you get a compilation error. wdRange.Text expects arguments to be of type BSTR, which maps to either Text or Code. This means that any data that is not Text or Code must be converted before it is passed to Word. To convert a field to Text, you use the FORMAT function. All the fields that are transferred in this step are in text format, so no conversion is needed and the FORMAT function is not used. However, in this example, you also need to transfer the Sales (LCY) field, which is a Decimal field. To see how to convert the Sales (LCY) field, go to the next step.

  2. To transfer and format the data from the Sales (LCY) field, add the following code.

    Copy Code
    wdRange := wdAPP.ActiveDocument.Fields.Item(4).Result;
wdRange.Text := FORMAT("Sales (LCY)");
wdRange.Bold := 0;

    For more information about the FORMAT function, see FORMAT Function (Code, Text).

  3. To transfer the information from the Company Information table, add the following code.

    Copy Code
    wdRange := wdApp.ActiveDocument.Fields.Item(5).Result;
wdRange.Text := CompanyInfo.Name;

  4. To complete the processing in Word, add the following code.

    Copy Code
    wdApp.Visible := TRUE;
wdApp.ActiveDocument.Fields.Unlink;

    The first statement opens Word and shows you the letter that was created. The second statement makes the fields work as placeholders.

  5. Save and compile the codeunit and give it a number and a name. For this walkthrough, use Discount Letter.

To-Do List

Although this code will work, you must add a few things to make it complete:

  • We recommend that you do not use a hardcoded template name. You should keep the template name in a table, and the user should select it from a page. You can then have different templates for different types of letters that you want to send to your customers.

  • You should add some error-handling code. For example, the CREATE call fails if the user does not have Word installed or if the installation has been corrupted. You should check the return value of CREATE and give an appropriate message if it fails.

  • The user should get a message if the customer does not qualify for the discount. In the example, the codeunit closes without any message.

Calling the Codeunit from the Customer Card

The final task is to ensure that you can call the codeunit from the Customer Card page in the Microsoft Dynamics NAV Windows client.

To call the codeunit from the Customer card page in the Microsoft Dynamics NAV Windows client

  1. Open Object Designer, and then choose Page.

  2. Select the Customer Card page and then choose Design.

  3. On the View menu, choose Page Actions.

  4. To add a new action, locate the action container with the subtype set to ActionItems.

  5. Right-click the next line after the ActionItems container, and then choose New.

  6. In the Caption field of the new line, type Word Letter.

  7. Set the Type field to Action.

  8. With the new action selected, on the View menu, choose Properties.

  9. In the RunObject field, type codeunit Discount Letter.

    Note
    If you saved the codeunit that you created in the previous procedure under a different name, then substitute Discount Letter with the name that you used.

  10. Use the arrow buttons to make sure that the new action is indented only once from the ActionItems container above it

  11. Save and compile the Customer Card page.

To run the Customer Card and view the Word letter

  1. In Object Designer, choose the Page button.

  2. Select the Customer Card page, and then choose Run.

  3. In the ribbon, on the Actions tab, choose the Word Letter action.

    The letter document opens in Word.

Next Steps

The letter that you have just created only contains six fields and no body text. Before you can use this letter in an actual situation, you will need to add some more fields, such as the name and address of your own company, the date, and the currency code, and the main text of the letter. It will also need some formatting to make it look more attractive. If you alter the order in which the fields appear in the template, you must change the numbering of the fields in the codeunit to ensure that the correct data is inserted into the appropriate fields.

See Also

Tasks

How to: Create an Automation Controller

Concepts

Using COM Technologies in Microsoft Dynamics NAV
COM Overview


Walkthrough: Using Automation to Create a Graph in Microsoft Excel

In this walkthrough, you will transfer data from the G/L Entry table to Microsoft Excel and create a graph. This example shows how to handle enumerations by creating a graph in Excel that shows the distribution of personnel expenses by departments. In the chart of accounts, you can see that Total Personnel Expenses is the total of accounts 8700 to 8790. In the Dimension Value table, you can see that there are three departments: ADM, PROD, and SALES. You will create a codeunit that retrieves this data from the G/L Entry table, transfers it to Excel, and creates a graph that is similar to the one that is shown in the following figure:

You will run the codeunit directly from Object Designer. In a real application, you would call it from an appropriate place, such as from a menu in the chart of accounts window.

About This Walkthrough

This walkthrough illustrates the following tasks:

  • Creating a codeunit that declares the Automation variables that are required for using Excel Automation.

  • Adding C/AL code to the codeunit to run the Automation object that opens Excel.

  • Adding C/AL code to the Automation codeunit to transfer data from a table record to Excel.

  • Adding C/AL code that creates a graph in Excel.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 with a developer license.

  • The CRONUS International Ltd. demo data company.

  • Microsoft Excel 2013 or Microsoft Excel 2010.

  • The language in the regional settings of your computer matches the language version of Microsoft Excel.

    This is a known issue. For more information, see Bug: "Old Format or invalid type library" in the Microsoft Support site.

Creating the Codeunit and Declaring Variables

To implement Automation in a codeunit, you define the Automation variables. To define an Automation variable, you specify an Automation server and the Automation object.

To create the codeunit and declare variables

  1. In Object Designer, choose Codeunit, and then choose the New button to create a new codeunit.

  2. On the View menu, choose C/AL Globals.

  3. On the Variables tab, add the following variables:

    Note
    For the Automation data type variables, the subtype Microsoft Excel 15.0/14.0 Object Library defines the Automation server, and the class specifies the Automation object of the Microsoft Excel 15.0/14.0 Object Library.

    Name Data type Subtype Class

    GLEntry

    Record

    G/L Entry

    xlApp

    Automation

    Microsoft Excel 15.0 or 14.0 Object Library

    Application

    xlBook

    Automation

    Microsoft Excel 15.0 or 14.0 Object Library

    Workbook

    xlSheet

    Automation

    Microsoft Excel 15.0 or 14.0 Object Library

    Worksheet

    xlChart

    Automation

    Microsoft Excel 15.0 or 14.0 Object Library

    Chart

    xlRange

    Automation

    Microsoft Excel 15.0 or 14.0 Object Library

    Range

  4. Close the C/AL Globals window.

Adding the Code

Now you add the code for the codeunit.

To add the code

  1. In the C/AL Editor, set the key for the G/L Entry table, and then use SETFILTER to select the accounts by adding the following code to the OnRun trigger.

    Copy Code
    GLEntry.SETCURRENTKEY("G/L Account No.","Business Unit Code",
"Global Dimension 1 Code","Global Dimension 2 Code","Posting Date");
GLEntry.SETFILTER("G/L Account No.",'8700..8790');

  2. Create an instance of Excel by adding the following code.

    Copy Code
    CREATE(xlApp, FALSE, TRUE);

  3. Add a new workbook to Excel.

    Copy Code
    xlBook := xlApp.Workbooks.Add(-4167);
xlSheet:= xlApp.ActiveSheet;
xlSheet.Name := 'Personnel Expenses';

    The following describes the code:

    • In the first line, you use the Add method of the Workbooks collection to return a new workbook. The attribute -4167 is the enumerator value of worksheets as they apply to Workbook objects. For more information, see About the Enumerator Value.

    • In the second line, you use the ActiveSheet property of the Application class to ensure that what is done next affects the active sheet of the new workbook.

    • In the third line, you use the Name property to name the sheet.

About the Enumerator Value

In the preceding procedure, the Add method includes the attribute -4167. In the Microsoft Excel Visual Basic Help, the Add method as it applies to the Workbooks object takes one Template argument, which is of type VARIANT. The description in the Help says:

If this argument is a constant, the new workbook contains a single sheet of the specified type. Can be one of the following: XlWBATemplate constants: xlWBATChart, xlWBATExcel4IntlMacroSheet, xlWBATExcel4MacroSheet, or xlWBATWorkSheet.

For more information, see Workbooks.Add Method (Excel), http://go.microsoft.com/fwlink/?LinkId=404331.

Instead of passing xlWBATWorkSheet as the Template argument, you are passing the number -4167. In this case, the Template argument, which is of type VARIANT, is an enumeration. Enumerations are either USERDEF types or not. This is not a USERDEF type, so it looks like a VARIANT in the C/AL Symbol Menu. You have to look in the Microsoft Excel Visual Basic Help to figure out that it is actually an enumeration. Arguments can be constants with names like xl* in Excel, wd* in Word, and ol* in Outlook. In Microsoft Dynamics NAV, you cannot use the symbolic name xlWBATWorkSheet. You have to use the enumerator -4167. The following procedure describes how you can find an enumerator value if you need to.

To find an enumerator value

  1. Open Excel, and on the Developer tab, choose Visual Basic.

    Note
    If you do not see the Developer tab, then in the File menu, choose Options, and then choose Customize the Ribbon. Under Customize the Ribbon, choose Developer, and then choose OK.

  2. On the View menu of Visual Basic Editor, choose Object Browser.

  3. In the Project/Library list in the list box in the upper-left corner of the Object Browser, select Excel.

  4. In the Classes list, select XlWBATemplate.

  5. In the Members of ‘XlWBATemplate’ list, select xlWBATWorkSheet. You can see the value in the information pane at the bottom of the Object Browser. In the following example, the value is -4167..

    Const xlWBATWorksheet = -4167 (&HFFFFEFB9)

Transferring Data

To transfer the data, you must calculate the data and transfer the results of the calculation.

To transfer data

  1. In the C/AL Editor, on the codeunit, use SETRANGE to filter the entries in the G/L Entry table on the Global Dimension 1 Code field. The first department is ADM (Administration). Then, you use CALCSUMS(Amount) to get the sum for the ADM department. To do this, add the following code.

    Copy Code
    GLEntry.SETRANGE("Global Dimension 1 Code", 'ADM');
GLEntry.CALCSUMS(Amount);

  2. To transfer the data to Microsoft Excel, add the following code.

    Copy Code
    xlSheet.Range('A2').Value := 'Administration';
xlSheet.Range('A3').Value := GLEntry.Amount;

  3. Add this code for the PROD and SALES departments:

    Copy Code
    GLEntry.SETRANGE("Global Dimension 1 Code", 'PROD');
GLEntry.CALCSUMS(Amount);
xlSheet.Range('B2').Value := 'Production';
xlSheet.Range('B3').Value := GLEntry.Amount;
GLEntry.SETRANGE("Global Dimension 1 Code", 'SALES');
GLEntry.CALCSUMS(Amount);
xlSheet.Range('C2').Value := 'Sales';
xlSheet.Range('C3').Value := GLEntry.Amount;

Creating the Graph

The final step is to create the graph. You will use the ChartWizard method to create a 3-D pie chart. This is a fast and simple way to do it. You can more tightly control the design of the graph by setting it up using the methods and properties of the various Chart objects, such as ChartArea and Legend.

To create the graph

  1. In the C/AL Editor, on the current codeunit, define a range for the data in the graph.

    Copy Code
    xlRange := xlSheet.Range('A2:C3');

  2. Add a new chart sheet and give it a name.

    Copy Code
    xlChart := xlBook.Charts.Add;
xlChart.Name := 'Personnel Expenses - Graph';

  3. Create the graph.

    Copy Code
    xlChart.ChartWizard(xlRange,-4102,7,1,1,0,0,'Personnel Expenses');

    The following table describes the optional arguments that are used in the ChartWizard method.

    Argument Description Value in method call

    Source

    The range that contains the source data for the new chart.

    xlRange - The object returned by xlSheet.Range(‘A2:C3’).

    Gallery

    The chart type.

    -4102 - The enumerator for the xl3DPie XlChartType enumeration.

    Format

    The option number for the built-in auto formats.

    7

    PlotBy

    An integer specifying whether the data for each series is in rows or columns.

    1 - The enumerator for the xlRows XlRowCol enumerator.

    CategoryLabels

    An integer specifying the number of rows or columns within the source range that contains category labels.

    1 - There is one row with category labels (the department names).

    SeriesLabels

    An integer specifying the number of rows or columns within the source range that contains series labels.

    0 - There are no series labels in your data.

    HasLegend

    TRUE to include a legend.

    0

    Title

    VARIANT with the title of the chart.

    You pass a string such as ‘Personnel Expenses’.

  4. Make Excel visible by adding the following code.

    Copy Code
    xlApp.Visible := TRUE;

    Excel produces a General Protection Fault error when you close a new Excel worksheet that is created when Excel is invisible. To resolve this, you can make Excel visible immediately after you create a new worksheet. You can also make Excel visible just before you create a new Excel worksheet and then make it invisible again immediately after creating the new Excel worksheet. In this case, you would add the following code.

    Copy Code
    xlApp.Visible := TRUE;
xlBook := xlApp.Workbooks.Open(FileName);
xlApp.Visible := FALSE;

Saving and Running the Codeunit

You can test the codeunit for creating the graph by running the codeunit from Object Designer.

To save and run a codeunit

  1. On the File menu, choose Save.

  2. In the Save As window, enter an ID and name, and then choose the OK button.

  3. In Object Designer, select the codeunit, and then choose the Run button.

    The Microsoft Excel graph should appear.

    Note
    If you get an error states Old format or invalid type library, then make sure that the language in the regional settings of your computer matches the language version of Microsoft Excel. For more information, see Bug: "Old Format or invalid type library".

See Also

Tasks

How to: Create an Automation Controller
Walkthrough: Using Automation to Write a Letter in Microsoft Office Word


Extending Microsoft Dynamics NAV Using Microsoft .NET Framework Interoperability

You can extend the RoleTailored clients and Microsoft Dynamics NAV Server with functionality that is available in Microsoft .NET Framework assemblies. You can take advantage of .NET Framework interoperability so that Microsoft Dynamics NAV objects can interact with .NET Framework objects. In your Microsoft Dynamics NAV objects, you can reference .NET Framework assemblies and call their members directly from C/AL code. You can use assemblies from the .NET Framework class library, which are found in the global assembly cache; your own custom assemblies; or third-party assemblies. For more information, see Assembly Installation in the GAC.

.NET Framework interoperability offers an alternative to COM so that you can extend your solution. For example, you can use .NET Framework interoperability to:

  • Consume web services.

  • Integrate with Microsoft Office products.

  • Create .NET Framework applications that target the RoleTailored client.

Microsoft Dynamics NAV Web client support

For the Microsoft Dynamics NAV Web client, you can only implement Microsoft .NET Framework Interoperability objects that are configured to run on Microsoft Dynamics NAV Server. Client-side objects are not supported. For more information, see Setting .NET Framework Types to Target the Microsoft Dynamics NAV Windows Client or Server

See Also

Concepts

Calling .NET Framework Members from C/AL
Mapping Between .NET Framework and C/AL Types
Using Arrays
Using Collections
Using Enumerations
Using Generics
Using Interfaces
Calling External Web Services


Calling .NET Framework Members from C/AL

You can call .NET Framework type members, including methods, properties, and constructors, from C/AL code with the DotNet data type for C/AL variables. This section provides an overview of the DotNet data type, guidelines on its use, and aspects about calling members of a .NET Framework type. For information about how to create and use a DotNet variable to call members of a type, see How to: Call .NET Framework Types From C/AL Code.

DotNet Data Type

The DotNet type resembles the Automation type in C/AL except that it references a .NET Framework type in an assembly. Assemblies can be either part of assemblies that are installed in the global assembly cache or custom assemblies that you have installed for Microsoft Dynamics NAV. For more information about how to install assemblies in global assembly cache, see Assembly Installation in the GAC.

After you have defined a DotNet variable, you can call it in C/AL code to instantiate members of a .NET Framework type.

Constructors

A constructor is a method that creates an instance of an object and prepares it for use. Before you use a DotNet variable, you should verify whether the variable is static or is an object instance because this determines whether you have to use a constructor.

  • Static variables do not require a constructor because they do not have an instance.

  • Object instance variables require a constructor because they must be created before they can be accessed.

To find the constructor and other methods and property for your object, in Object Designer, choose Symbol.

Static and Instance Method Calls

Methods that you call from C/AL code can be either static or instance methods.

  • You use the same syntax to call static and instance methods.

  • Calling static methods provides a factory pattern for creating object instances. For example, to create a new System.TimeZoneInfo object, you call the type’s System.TimeZoneInfo.Local static method with the following code.

    Copy Code
    zone := zone.Local;
  • A static class or object is loaded one time for each Microsoft Dynamics NAV Server instance, and the class or object is shared between all clients that are connected to the server instance. The data that is maintained by the static class or object is visible by all clients that use the type. You should consider this in your .NET Framework interoperability design to help avoid disclosing private information.

C# Indexers

A C# indexer is represented as an Item property in C/AL. For example, in C#, the following code sets an array element N to the value M.

Copy Code
arrayVariable[N] = M;

In C/AL, the corresponding code is as follows.

Copy Code
arrayVariable.Item(N) := M;

Indexers can also be overloaded. In Object Designer, choose C/AL Symbol Menu to see the parameters and return types for the indexer.

Indexers for lists and arrays that are defined by .NET Framework variables are zero-based, which means that they start at 0. Other indexers in C/AL start at 1.

Operators for Comparing .NET Framework Objects

.NET Framework interoperability does not support direct use of operators to compare two DotNet variables. For example, the following scenario is not supported.

Copy Code
IF dotnetVar1 <= dotnetVar2 THEN

If you want to compare two DotNet variables, then you can use the Equals function on the DotNet variables as shown in the following example.

Copy Code
IF dnVersion1.Equals(dnVersion2) THEN …

You can perform comparisons by using .NET Framework methods and properties that return compatible C/AL types because these objects are implicitly converted to C/AL types before the comparison occurs. For example, the following C/AL code includes three DotNet variables for the System.Collections.Generic.List class: dotNetList1, dotNetList2, and dotNetList3. You cannot compare the DotNet variables directly because they do not return C/AL types. You can perform comparisons on the List.Capacity property because the List.Capacity property is a NET Framework integer type that returns a C/AL integer type. For more information about conversion between .NET Framework and C/AL types, see Mapping Between .NET Framework and C/AL Types.

Copy Code
dotNetList1 := dotNetList1.List(5);
dotNetList2 := dotNetList2.List(10);
dotNetList3 := dotNetList3.List(5);
IF dotNetList1.Capacity <> dotNetList3.Capacity THEN
  ERROR('List1 and List3 should have the same capacity.');
IF dotNetList1.Capacity = dotNetList2.Capacity THEN
  ERROR('List1 and List2 should not have the same capacity.');
IF dotNetList1.ToString() <> dotNetList2.ToString() THEN
  ERROR('List1 and List2 should have the same ToString output.');

Public Fields

Microsoft Dynamics NAV does not support public fields in the .NET Framework.

Case Sensitivity in Member Names

NET Framework member names in C/AL code are case-sensitive. If you use the incorrect case when you call a member, then you get an error when you compile the object. This behavior differs from other C/AL variables because you can mix cases and still compile the object. For other C/AL variables, the case is corrected automatically the next time that you open the object.

Local DotNet Variable Limitations

By default, a local DotNet variable is disposed when it goes out of scope. In this case, you should not assign the local DotNet variable to global C/AL or .NET Framework objects. However, local DotNet variables include the SuppressDispose property that you use to set the variable not to dispose when it goes out of scope, which lets you use the local variable outside the scope of its local function. For more information, see SuppressDispose Property.

See Also

Tasks

How to: Call .NET Framework Types From C/AL Code

Concepts

Handling Events with Microsoft .NET Framework Interoperability
Serializing .NET Framework Types


How to: Call .NET Framework Types From C/AL Code

You can call .NET Framework type members, including methods, properties, and constructors, from C/AL code. To call members, you define a DotNet type variable that references the .NET Framework assembly type that contains the member and then call the variable from C/AL code of the Microsoft Dynamics NAV object. A .NET Framework interoperability example is included in this topic.

To create a variable for a .NET Framework class in an assembly

  1. If the assembly that you want to reference is a custom assembly and not installed in the global assembly cache, then copy the assembly to the Add-ins folder of the Microsoft Dynamics NAV Windows client installation folder on the computer running the development environment.

    By default, the path to the installation folder is C:\Program Files\Microsoft Dynamics NAV\90\RoleTailored Client or C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client. You can place the assembly in a subfolder.

    For more information about the global assembly cache, see Assembly Installation in the GAC in the MSDN Library.

    Tip
    You can install the assembly in the global assembly cache with the GAC utility. For more information, see Global Assembly Cache Tool in the MSDN Library.

  2. In the development environment, open Object Designer, and then open the object that will use .NET Framework interoperability, such as the page or codeunit.

  3. To open the C/AL code for the object, on the View menu, choose C/AL Code.

  4. To create the variable for .NET Framework interoperability, do one of the following steps:

    • To create a global variable, on the View menu, choose C/AL Globals.

    • To create a local variable, on the View menu, choose C/AL Locals.

      Important
      A local DotNet variable, including any resources that it references, is disposed after its C/AL function is run.

  5. On the Variables tab, in the Name field, type a name for the variable.

  6. Set the DataType field to DotNet.

  7. In the SubType field, choose the AssistEdit button to open the .NET Type List window.

  8. In the Assembly field, choose the AssistEdit button to open the Assembly List window.

  9. If the assembly that you want to reference is in the global assembly cache, then choose the .NET tab. If the assembly is in the Add-ins folder of your Microsoft Dynamics NAV installation, then choose the Dynamics NAV tab.

  10. In the list of assemblies, select the assembly, and then choose OK to return to the .NET Type List window.

    If you do not see the assembly that you want, then make sure that you have installed it correctly. For more information, see step 1 of this procedure.

  11. In the .NET Type List window, select the type that contains the member that you want to call from the Microsoft Dynamics NAV object, and then choose OK.

    The .NET Type List window displays all available types, including classes, enumerations, structs, and interfaces, which are available in the selected assembly.

    By default, variables are set to run the assembly instance on Microsoft Dynamics NAV Server. If you want to run the assembly instance on the Microsoft Dynamics NAV Windows client, see How to: Set .NET Framework Types to Run on the Microsoft Dynamics NAV Windows Client or Microsoft Dynamics NAV Server Computers.

To call methods and properties in a .NET Framework class

  1. Open the C/AL code for the object.

  2. On the View menu, choose C/AL Symbol Menu.

    You use the C/AL Symbol Menu window to help you call members and properties of the .NET Framework class.

  3. In your C/AL code, add the following code to call the constructor that creates a new instance of the type. If you are calling a static method, then a constructor is not required, and you can skip this step.

    Copy Code
    MyVariableName.ConstructorName(arguments);
    • MyVariableName represents the name of the .NET Framework variable.

    • ConstructorName represents the same as the type name.

    • arguments represents any parameters that you must set for the constructor.

  4. Add the following code to call the methods or properties.

    Copy Code
    MyVariableName.MethodPropertyName(arguments);

    MethodPropertyName represents the name of the method or property that you want to call, and arguments represents any arguments of the method or property.

    Important
    Some types in the System namespace of the .NET Framework class library are automatically converted to C/AL types. You cannot assign values to .NET Framework variables for these types. For more information, see Mapping Between .NET Framework and C/AL Types.

    Tip
    Methods can be overloaded. Therefore see the description at the bottom of the C/AL Symbol Menu, which shows the parameter and return types for each method. Also, method and property names that are longer than 128 characters will be truncated, and you cannot compile the Microsoft Dynamics NAV object. For more information, see Calling .NET Framework Members from C/AL.

Example

The following code example uses .NET Framework interoperability to display headlines from the RSS feed http://blogs.msdn.com/inside_office_online/rss.xml. This example accesses classes in the System.XML assembly that is found in Global Assembly Cache. To implement this example, create a codeunit that has the following local variables:

The following code example uses .NET Framework interoperability to display headlines from an RSS feed from the Microsoft Dynamics NAV team blog, which has the following URL:

http://feeds.feedburner.com/MicrosoftDynamicsNavTeamBlog?format=xml.

This example calls members of the System.XML assembly, which is part of the Microsoft .NET Framework class library and is installed in the global assembly cache.

To implement this example, you create a codeunit that has the following local variables.

Variable name | DataType | SubType
xml | DotNet | 'System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Xml.XmlDocument
items | DotNet | 'System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Xml.XmlNodeList
i | Integer |
title | DotNet | 'System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Xml.XmlNode

After you create the codeunit, add the following code to its OnRun trigger:

Copy Code
xml := xml.XmlDocument();
xml.Load('http://feeds.feedburner.com/MicrosoftDynamicsNavTeamBlog?format=xml');
items := xml.SelectNodes('/rss/channel/item');
FOR i := 0 TO items.Count - 1 DO
BEGIN
    title := items.Item(i).SelectSingleNode('title/text()');
    MESSAGE( title.Value );
END

To see the example in the Microsoft Dynamics NAV Windows client, you can create an action on a page that opens the codeunit.

See Also

Concepts

Extending Microsoft Dynamics NAV Using Microsoft .NET Framework Interoperability
Mapping Between .NET Framework and C/AL Types
Serializing .NET Framework Types
Handling Events with Microsoft .NET Framework Interoperability


Setting .NET Framework Types to Target the Microsoft Dynamics NAV Windows Client or Server

To extend a Microsoft Dynamics NAV object by using .NET Framework interoperability, you define a C/AL variable that calls members of a .NET Framework type in an assembly. When the variable is called from the C/AL code of the Microsoft Dynamics NAV object, it creates an instance of the .NET Framework type. You can set the type instance to target the Microsoft Dynamics NAV Windows client (client-side object) or Microsoft Dynamics NAV Server (server-side object). By default, a type is set to target Microsoft Dynamics NAV Server. However, you can set the type to target the RoleTailored client.

Microsoft Dynamics NAV Web Client Support

For the Microsoft Dynamics NAV Web client, you can only implement Microsoft .NET Framework interoperability objects that target Microsoft Dynamics NAV Server. Microsoft .NET Framework interoperability objects that target the client are not supported.

Best Practices

Use the following best practices when you extend Microsoft Dynamics NAV objects:

  • To optimize performance, you should limit the calls between client-side and server-side objects. If possible, you should run objects server-side, especially for advanced operations.

  • If the client-side and server-side objects will share data, such as return values and parameters, then the .NET Framework types that define the objects must be capable of being serialized.

See Also

Tasks

How to: Set .NET Framework Types to Run on the Microsoft Dynamics NAV Windows Client or Microsoft Dynamics NAV Server Computers

Concepts

Serializing .NET Framework Types


How to: Set .NET Framework Types to Run on the Microsoft Dynamics NAV Windows Client or Microsoft Dynamics NAV Server Computers

This topic describes how to set .NET Framework objects that are instantiated by DotNet variables to target either the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Server. By default, a type is set to target Microsoft Dynamics NAV Server. However, you can set the type to target the Microsoft Dynamics NAV Windows client.

For more information, see Setting .NET Framework Types to Target the Microsoft Dynamics NAV Windows Client or Server

Setting the .NET Framework Type to Target the Microsoft Dynamics NAV Windows Client

To set a .NET Framework type instance to target the Microsoft Dynamics NAV Windows client, you must complete the following tasks as described in this section:

  • Set the DotNet variable for the .NET Framework type to target the Microsoft Dynamics NAV Windows client.

  • Unless the NET Framework assembly is included in the global assembly cache, you must do one of the following:

    • Import the .NET Framework assembly into the Microsoft Dynamics NAV database,

      You import the assembly into the table 2000000069 Add-ins. The .NET Framework assembly will be automatically deployed on the client computer when an operation from the client requires it. The assembly will be deployed to the %TEMP%\Microsoft Dynamics NAV\Add-Ins folder of the user who is running the client. The deployed assembly will be then be used whenever it is required by the client. If a .NET Framework assembly is updated and its version number changes, Microsoft Dynamics NAV Server will deploy the updated assembly to the client computer the next time that the client requests the assembly. The updated assembly is put in a subfolder of the %TEMP%\Microsoft Dynamics NAV\Add-Ins folder, where the subfolder has the assembly's version number as its name.

      For more information, see To import a .NET Framework assembly into the database.

      Note
      To be deployed, an assembly must comply with the following Microsoft Dynamics NAV Server configuration settings: Chunk Size, Max Upload Size, and Prohibited File Types. For more information about these settings, see Configuring Microsoft Dynamics NAV Server.

    • Copy the .NET Framework assembly to the computer that is running the Microsoft Dynamics NAV Server.

      Similar to importing the .NET Framework assembly into the database, if you copy a .NET Framework assembly on computer that is running the Microsoft Dynamics NAV Server, then Microsoft Dynamics NAV Server automatically deploys the assembly on the client computer when an operation from the client requires the .NET Framework assembly.

      For more information, see To copy a .NET Framework assembly to the computer that is running Microsoft Dynamics NAV Server.

    • Copy the assembly to each computer that is running the Microsoft Dynamics NAV Windows client.

      For more information, see To copy a .NET Framework assembly to a computer that is running the Microsoft Dynamics NAV Windows client.

Important
For the Microsoft Dynamics NAV Web client, you cannot implement Microsoft .NET Framework interoperability objects that target the client.

To set the .NET Framework type to target the Microsoft Dynamics NAV Windows client

  1. In Object Designer, open the C/AL code of the Microsoft Dynamics NAV object that uses .NET Framework interoperability.

  2. Do one of the following steps:

    • For a global variable, on the View menu, choose C/AL Globals.

    • For a local variable, select the trigger that uses the variable, and then on the View menu, choose C/AL Locals.

  3. On the Variables tab, select the DotNet variable, and then on the View menu, choose Properties.

  4. In the Properties window, set the RunOnClient property to Yes.

To copy a .NET Framework assembly to a computer that is running the Microsoft Dynamics NAV Windows client

  • On the computer that is running the Microsoft Dynamics NAV Windows client, copy the.NET Framework assembly to the Add-ins folder of the Microsoft Dynamics NAV Windows client installation.

    By default, the path of this folder is C:\Program Files\Microsoft Dynamics NAV\90\RoleTailored Client\Add-ins or C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client\Add-ins.

    Note
    You can also put assemblies in a subfolder of the Add-ins folder. This can be useful when you have multiple versions of the same assemblies and dependencies.

Setting the .NET Framework Type to Target Microsoft Dynamics NAV Server

To set a .NET Framework type instance to target Microsoft Dynamics NAV Server, you must complete the following tasks as described in this section:

  • Set the variable for the NET Framework type to target Microsoft Dynamics NAV Server.

  • Copy the .NET Framework assembly to the computer that is running Microsoft Dynamics NAV Server.

    Note
    If the assembly is included in the global assembly cache of the computer that is running Microsoft Dynamics NAV Server, then you do not have to do this task.

To set the .NET Framework type to target Microsoft Dynamics NAV Server

  1. In the development environment, in Object Designer, open the object that uses the .NET Framework variable.

  2. Do one of the following steps:

    • For a global variable, on the View menu, choose C/AL Globals.

    • For a local variable, in the C/AL Editor, select the trigger that uses the DotNet variable, and then on the View menu, choose C/AL Locals.

  3. On the Variables tab, select the NET Framework variable type, and then on the View menu, choose Properties.

  4. In the Properties window, set the RunOnClient property to No.

To copy a .NET Framework assembly to the computer that is running Microsoft Dynamics NAV Server

  • On the computer that is running Microsoft Dynamics NAV Server, copy the.NET Framework assembly to the Add-ins folder of the Microsoft Dynamics NAV Server installation folder.

    By default, the path of the Microsoft Dynamics NAV Server installation folder is C:\Program Files\Microsoft Dynamics NAV\90\Service\Add-ins.

    You can also put assemblies in a subfolder of the Add-ins folder. This can be useful when you have multiple assemblies and dependencies.

    Note
    If you are working in the development environment, to compile and test Microsoft Dynamics NAV objects, you must also copy the assembly to the Add-ins folder of the Microsoft Dynamics NAV Windows client installation on the computer that is running the development environment. By default, the path of this folder is C:\Program Files\Microsoft Dynamics NAV\90\RoleTailored Client\Add-ins or C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client\Add-ins.

To import a .NET Framework assembly into the database

  1. Get the public key token for the .NET Framework assembly.

    The public key token is a 16-character key that is given to the assembly when it is built and signed in Microsoft Visual Studio. To determine the public token key, run the Microsoft .NET Strong Name Utility (sn.exe) on the assembly. For more information, see How to: Determine the Public Key Token of the Windows Client Control Add-in and .NET Framework Assembly and Strong-Named Signing.

  2. Create a compressed (.zip type) file that contains the .NET Framework assembly in the desired folder structure.

  3. You can import the compressed (.zip) file when you register the NET Framework assembly from the Control Add-ins page in Microsoft Dynamics NAV.

  4. In the Search box, enter Control Add-ins and then choose the related link.

  5. In the Control Add-ins window, choose New, and then in the Control Add-in Name column, enter the control add-in name. In the Public Key Token column, enter the public key token that you obtained earlier.

  6. Choose Import.

  7. In the Import Control Add-in Resource window, locate the.zip file, and then choose Open.

  8. Choose the OK button to close the Control Add-in page.

For more information about registering a control add-in, see How to: Register a Windows Client Control Add-in.

Tip
You can also register the control add-in and import the files by using the New-NAVAddin cmdlet or Set-NAVAddin cmdlet from the Microsoft Dynamics NAV 2016 Administration Shell.

See Also

Tasks

How to: Call .NET Framework Types From C/AL Code

Concepts

Calling .NET Framework Members from C/AL


Serializing .NET Framework Types

In Microsoft .NET Framework, serialization is the process of converting an object into a format that can transmitted across a network connection. Microsoft Dynamics NAV .NET Framework interoperability uses serialization for communication between client-side .NET Framework objects and server-side .NET Framework objects. When you configure DotNet variables in a Microsoft Dynamics NAV object, you can specify .NET Framework objects to target either the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Server. In some cases, a client-side object and a server-side object must communicate and share data, such as return values and parameters. The serialization occurs when the following conditions are true:

  • When a server-side object is assigned to a client-side object, and vice-versa.

  • When a server-side object is passed as a parameter in a method call from the server to a client-side object, and vice-versa.

Serialization requires that the .NET Framework types that are used by the DotNet variables are serializable. Many types in the Microsoft .NET Framework class library are already serializable. If you are using a .NET Framework type that cannot be serialized, then you must modify the type to make it serializable.

Important
For the Microsoft Dynamics NAV Web client, you cannot implement Microsoft .NET Framework interoperability objects that target the client.

Making a Type Serializable

There are two ways that you can make a .NET Framework type serializable. You can implement basic serialization by applying the System.SerializableAttribute attribute to the type or you can implement custom serialization by using System.Runtime.Serialization.ISerializable interface.

Basic Serialization Using SerializableAttribute

Basic serialization uses the .NET Framework to automatically serialize an object. To implement basic serialization on a type, you decorate the type with the SerializableAttribute class as shown in the following example.

Copy Code
[Serializable]
public class MyObject
{
    code
}

This method requires that you have access to the source code of the .NET Framework assembly.

Basic Serialization of Date Fields

You can use basic serialization only if all data fields in the type are serializable. Fields that are calculated at runtime cannot be serialized. If a field cannot be serialized, then at runtime, the serialization process will throw an exception and the C/AL code execution will fail.

You can exclude fields from the serialization process by decorating the field with the System.NonSerializedAttribute class.

Custom Serialization Using ISerializable Interface

With custom serialization, you can create an object that controls the serialization of types in another object. This method is useful when you do not have access to the source code of the assembly that contains the .NET Framework types that you are implementing with .NET Framework interoperability. The custom object specifies which types will be serialized and how serialization will be done.

To implement custom serialization, you create a class that implements the ISerializable interface, and decorate the class with SerializableAttribute. In most cases, you must also implement the System.Runtime.Serialization.ISerializable.GetObjectData method and a special constructor that is used when the source object is deserialized. You use the GetObjectData method to populate the SerializationInfo the data that is required to serialize the source object at runtime.

The common language runtime calls the constructor during deserialization to construct a replica of the source object. The constructor takes two parameters, a SerializationInfo type and a System.Runtime.Serialization.StreamingContext type. The StreamingContext parameter describes the source and destination of a given serialized stream.

Custom Serialization Example

The following code example demonstrates a custom serialization object that implements the basic functionality that is required for compliance with the ISerializable interface. In the first procedure of this example, you create a .NET Framework assembly that includes a serializable type. In the second procedure, in the Microsoft Dynamics NAV development environment, you create a codeunit that includes two DotNet variables for the serializable type. You set one variable to target the Microsoft Dynamics NAV Windows client and the other to target the Microsoft Dynamics NAV Server. In C/AL code, you add code that transfers the value for the DotNet variable on the Microsoft Dynamics NAV Server to the Microsoft Dynamics NAV Windows client. You will also add code that verifies that the data transfer is successful.

To create the custom serialization object

  1. In Microsoft Visual Studio, create a C# Class Library project called SerializationSample.

  2. Add the following code.

    C# Copy Code
    using System;
using System.Runtime.Serialization;
[Serializable]
public class SerializeWithInterface : ISerializable
{
    // Defines a field that will not be serialized.
    [NonSerialized]
    private string notSerializedField;
    // Defines two fields that will be serialized.
    private int serializedIntField;
    private string serializedStringField;
    // Specifies literal field names.
    private const string serializedIntFieldName = “serializedIntField”;
    private const string serializedStringFieldName = “serializeStringField”;
    // Defines a default constructor that initializes the object with default values.
    public SerializeWithInterface()
    {
        this.serializedIntField = 1;
        this.notSerializedField = string.Empty;
        this.serializedStringField = string.Empty;
    }
    // Defines the protected constructor that is required by the ISerializable interface.
    // Data is stored in the SerializationInfo argument and is extracted using the GetValue method.
    protected SerializeWithInterface(SerializationInfo si, StreamingContext context)
    {
        this.serializedStringField = (string)si.GetValue(serializedStringFieldName, typeof(string));
        this.serializedIntField = (int)si.GetValue(serializedIntFieldName, typeof(int));
    }
    // Fills the SerializationInfo object with data that must to be sent to the replicated object.
    // Data is stored in the dictionary using the AddValue method.
    // The SerializationInfo object is a key/value dictionary.
    // The name you use to store the value must match the name used in the constructor.
    // For this reason, a string constant is used.
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue(serializedStringFieldName, this.serializedStringField);
        info.AddValue(serializedIntFieldName, this.serializedIntField);
    }

    // Remaining class implementation is irrelevant for the serialization process.
    // The SerializedStringField property is used by C/AL code to verify that the contained data is transferred between the server and client.
    // SerializedStringField gets or sets the internal serialized string field.
    public string SerializedStringField
    {
        get { return this.serializedStringField; }
        set { this.serializedStringField = value; }
    }
}

  3. Build the project.

  4. Copy the SerializationSample.dll to the Add-ins folder of the Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Server installation folders.

    By default, the path of the Microsoft Dynamics NAV Windows client installation folder is C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client\Add-ins.

    By default, the path of the Microsoft Dynamics NAV Server installation folder is C:\Program Files\Microsoft Dynamics NAV\90\Service\Add-ins.

To test the serialization object

  1. In the Microsoft Dynamics NAV Development Environment, create a codeunit called SerializationSample.

  2. For the OnRun function, add the following local variables.

    Variable name DataType SubType Comments

    ServerObject

    DotNet

    SerializationSample.SerializeWithInterface

    The DotNet variable should target Microsoft Dynamics NAV Server. Set the variable RunOnClient Property to No.

    ClientObject

    DotNet

    SerializationSample

    The DotNet variable should target the Microsoft Dynamics NAV Windows client. Set the variable RunOnClient Property to Yes.

  3. Add the following code to the OnRun function.

    Copy Code
    // Constructor that instantiates the ServerObject object on the server.
ServerObject := ServerObject.SerializeWithInterface();
// Constructor that instantiates the ClientObject object on the server.
ClientObject := ClientObject.SerializeWithInterface();
// Assign unique values to the data members in the two objects.
ServerObject.SerializedStringField := ‘ServerSide’;
ClientObject.SerializedStringField := ‘ClientSide’;
// Transfer the server object to the client object using serialization.
ClientObject := ServerObject;
// Test if the objects contain the same data.
If ClientObject.SerializedStringField <> ServerObject.SerializedStringField then
  Error(‘Client object does not match the server object.’);
Message(‘Server data has been serialized to the client object.’);

  4. Save and compile the codeunit.

  5. In Object Designer, run the codeunit.

    The line that contains assignment of the ServerObject to the ClientObject causes the serialization process to run. When completed, the message Server data has been serialized to the client object appears, which verifies that the server object has been transferred to the client object.

See Also

Tasks

How to: Call .NET Framework Types From C/AL Code

Concepts

Calling .NET Framework Members from C/AL


Mapping Between .NET Framework and C/AL Types

In C/AL, some .NET Framework data types, such as strings, DateTime, integers, and decimals, are automatically converted to C/AL types. Because the types are converted, the .NET Framework versions of these types are not supported in C/AL. For example, instead of using a .NET Framework integer data type in your C/AL code, you should use a C/AL integer data type. When the C/AL integer is sent back to a .NET Framework object, such as through a method call, then the C/AL integer is automatically converted to a .NET Framework integer.

Conversion Table for .NET Framework and C/AL Types

The following table lists the automatic data type conversions between.NET Framework and C/AL types.

Note
The System.String type and System.DateTime type are converted differently than other types that are listed in the table. For more information, see Conversion of System.String and System.DateTime Types.

.NET Framework Data Type (range) C/AL Data Type (range) Comments

System.Byte

(0...255)

Byte

(0...255)

Single unsigned byte that represents a value from 0...255.

System.SByte

(-128...127)

Integer

(-128...127)

Single signed byte that represents a value from -128...127.

System.Char

(0...65535)

Char

(0...65535)

Unicode character that is represented internally as a 16-bit unsigned integer.

System.Int16

(-32768...32767)

Integer

(±2,147,483,647)

System.Int32

(-2,147,483,648...2,147,483,647)

Integer

(±2,147,483,647)

System.Int64

(-9,223,372,036,854,775,808...9,223,372,036,854,775,807)

BigInteger

(±9,223,372,036,854,775,807)

System.UInt16

(0...65335)

Integer

(±2,147,483,647)

Microsoft Dynamics NAV does not have a corresponding type, but values can be stored in an integer.

System.UInt32

(0...4,250,000,000)

BigInteger

(±9,223,372,036,854,775,807)

Microsoft Dynamics NAV does not have a corresponding type, but values can be stored in a big integer.

System.UInt64

(0...18,446,744,073,709,551,615)

Decimal

(0...18,446,744,073,709,551,615)

Microsoft Dynamics NAV does not have a corresponding type, but values can be stored in a big integer or decimal.

System.Single

(±3.402823e38)

Decimal

(±3.402823e38)

System.Double

(±1.79769313486232e308)

Decimal

(±1.79769313486232e308)

System.Decimal

(±79,228,162,514,264,337,593,543,950,335)

Decimal

(-999,999,999,999,999.99...999,999,999,999,999.99)

An internal range that is not persisted to a field but is the type’s native value range.

System.Int32

(±2,147,483,647)

Option

(±2,147,483,647)

Option values can be freely converted to numeric values. The range is the same as an integer.

System.Enum

(-32768...32767)

Integer

(±2,147,483,647)

An enumeration is a named constant with an underlying type that is any integer type except Char. If no underlying type is explicitly declared, then Int32 is used.

Microsoft Dynamics NAV has no information about the constant’s name, only the value is known.

System.Bool

(TRUE, FALSE)

Boolean

(TRUE, FALSE)

System.String

(0 to 1024 bytes)

Text

(0 to 1024 bytes)

BigText

(up to 2 gigabytes)

Denotes a text string with a maximum length of 1024 characters. Text strings are single-byte only.

For more information, see Conversion of System.String and System.DateTime Types.

System.String

(0 to 1024 bytes)

Code

(0 to 1024 bytes.)

Denotes an alphanumeric string with maximum length of 1024 characters. The value is stored in uppercase.

For more information, see Conversion of System.String and System.DateTime Types.

System.DateTime

3 January year 1 ... 31 December 9999

Date

1 January year 1753 ... 31 December 9999

The common language runtime only supports DateTime. In Microsoft Dynamics NAV, Date must be converted to a DateTime value type when passing as a parameter, such as for CREATEDATETIME(d, 000000T);

For more information, see Conversion of System.String and System.DateTime Types.

System.DateTime

Time

(00:00:00...23:59:59.999)

The common language runtime only supports DateTime. In Microsoft Dynamics NAV, Date must be converted to a DateTime value type when passing it as a parameter, such as for CREATEDATETIME( 0D, t);

The common language runtime DateTime object that will be used for storing a Microsoft Dynamics NAV Time value must handle daylight saving time and time zone. The time value does not change.

For more information, see Conversion of System.String and System.DateTime Types.

System.DateTime

DateTime

(January 1, 1753, 00:00:00.000 to December 31, 9999, 23:59:59.999)

The common language runtime DateTime value type represents dates and times with values ranging from 12:00:00 midnight, January 1, 1753 Common Era (CE) through 11:59:59 P.M., December 31, 9999 CE.

For more information, see Conversion of System.String and System.DateTime Types.

TimeSpan

(Resolution is 100 nanoseconds)

Duration

(Resolution is 1 milliseconds)

A time interval is the duration of time or elapsed time that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. Duration is internally represented as a 64-bit integer.

System.Guid

(128 bit number)

GUID

(128 bit number)

System.IO.Stream

inStream

Streams require a context specific conversion and specialized stream types such as {Stream,String,Text}{Reader,Writer} classes. BLOB-related streams typically use MemoryStreams.

System.IO.Stream

Outstream

Conversion of System.String and System.DateTime Types

Unlike the types in the previous table, the System.String and System.DateTime types are not converted automatically to C/AL data types when the DotNet variable is instantiated. The System.String and System.DateTime types are only converted when assigned to a compatible C/AL data type. This lets you create an instance of the System.String type or System.DateTime type, and then call the DotNet variable like any other DotNet variable.

Note
You cannot use a DotNet variable for the System.String type or System.DateTime type in comparisons with C/AL types because in these cases, there is no implicit type conversion.

Example

The following C/AL code example illustrates how a DotNet variable for the System.String type is converted to a C/AL text data type.

In a Microsoft Dynamics NAV object, such as a codeunit, define the following global variables.

Variable name | DataType | SubType | Comments
alVariable | Text |  |
dotNetVariable | DotNet | System.String | Located in the mscorlib assembly.

In the C/AL code, add the following code.

Copy Code
alVariable := ‘sample text’;
dotNetVariable := ‘sample text’;
// Compares the objects using the Equals method on the DotNet object.
if not dotNetVariable.Equals(alVariable) then
  error(‘Object should contain same data’);
// Converts the DotNet object to a C/AL text type by calling the ToString method on the object.
// This forces an implicit type conversion to the C/AL text type and the standard C/AL comparison can be used.
if dotNetVariable.ToString() <> alVariable then
  error(‘Objects should contain same data, compared with ToString()’);

See Also

Tasks

How to: Call .NET Framework Types From C/AL Code

Concepts

Extending Microsoft Dynamics NAV Using Microsoft .NET Framework Interoperability


Using Arrays

An array is a data structure that contains several variables of the same type. The variables are treated as a single collection. Although you can already create arrays in C/AL, you can now use arrays from the .NET Framework. Choosing whether to use a C/AL array or a .NET Framework array depends on how you intend to use the data.

For this scenario | Use this array type
Your C/AL code uses .NET Framework interoperability extensively, and you must share the array among many methods. | .NET Framework array
Your C/AL code mostly uses basic C/AL types and does not interoperate with the .NET Framework. | C/AL array

To use a .NET Framework array in C/AL, you must use the System.Array class in the .NET Framework class library, which is the class from which all arrays inherit. When interfacing with an array in C/AL, you must use the following methods of the System.Array class to create and access elements in the array.

Method | Description
CreateInstance | Creates a new array instance that is passed to a method or property.
SetValue | Sets a value in an array element.
GetValue | Gets a value from an array element

Many .NET Framework classes implement these methods. Therefore, they are available for you to use in C/AL code. If you are writing your own .NET Framework code and want to use it in Microsoft Dynamics NAV, then you must implement these methods yourself.

In C/AL, some .NET Framework data types, such as strings, integers, and decimals, are automatically converted to C/AL types. If a .NET Framework array contains these data types, then you create an assembly that contains methods that return the information about the data types and then reference the assembly in the C/AL code. This concept is illustrated in the following examples.

Example: Using Native C/AL Data Types in a .NET Framework Array

The following example shows how you can use a .NET Framework array for an integer data type.

  1. In Visual Studio, create a C# class library project called NavInteropHelper that contains a method that returns the information about the integer type as follows:

    C# Copy Code
    namespace Microsoft.Dynamics.Nav.NavInteropHelper;
{
    public class WrapInt32
    {
        public static Type GetTypeOfInt32()
        {
            return typeof(Int32);
        }
    }
}
  2. Build the project, and then copy the assembly to the Add-ins folder of the Microsoft Dynamics NAV Windows client installation folder. By default, the path of the installation folder is C:\Program Files\Microsoft Dynamics NAV\90\RoleTailored Client or C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client.

  3. In the development environment, open a Microsoft Dynamics NAV object, open the C/AL code, and then create the following C/AL variables.

    Variable name DataType SubType

    varDotNet

    DotNet

    'NavInteropHelper, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.Microsoft.Dynamics.Nav.NavInteropHelper.WrapInt32

    varArray

    DotNet

    'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Array

    arraySize

    Integer

    i

    Integer

    alData

    Integer

  4. On a trigger of the Microsoft Dynamics NAV object, add the following C/AL code to create, fill, and implement the array.

    Copy Code
    // Sets the number of elements in the .NET Framework array.
arraySize := 10;
// Creates an instance of the .NET Framework array that contains the Int32 type.
varArray := varArray.CreateInstance(varDotNet.GetTypeOfInt32(), arraySize);
// Clears the object instance because it is no longer used.
clear(varDotNet);
// Sets the data in the array.
FOR i := 0 TO (arraySize -1) DO
  varArray.SetValue(i+100,i);
// Gets the array data and validates the content. The object that is returned by
// GetValue is automatically converted into a C/AL integer in the assignment.
FOR i := 0 TO (arraySize -1) DO
BEGIN
  alData := varArray.GetValue(i);
  if alData <> (i+100) then
    error('Invalid array data in element %1, expected %2, actual %3', i, i+100, alData);
END;

Example: Using User-Defined Classes in a .NET Framework Array

This example shows how you can use a .NET Framework array that includes user-defined classes.

  1. In Visual Studio, create a C# class library project called NavInteropHelper that contains methods that return the information about the types as follows.

    C# Copy Code
    namespace Microsoft.Dynamics.Nav.NavInteropHelper;
{
    public class WrapInt32
    {
        public int Data { get; set; }
        public WrapInt32(Int32 value)
        {
            Data = value;
        }
    }
}
  2. Build the project, and then copy the assembly to the Add-ins folder of the Microsoft Dynamics NAV Windows client installation folder. By default, the path of the installation folder is C:\Program Files\Microsoft Dynamics NAV\90 RoleTailored Client or C:\Program Files (x86)\Microsoft Dynamics NAV\90 RoleTailored Client.

  3. In the development environment, open a Microsoft Dynamics NAV object, open the C/AL code, and then create the following C/AL variables.

    Variable name DataType SubType

    varDotNet

    DotNet

    'NavInteropHelper, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.Microsoft.Dynamics.Nav.NavInteropHelper.WrapInt32

    varArray

    DotNet

    'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Array

    arraySize

    Integer

    i

    Integer

    alData

    Integer

  4. On a trigger of the Microsoft Dynamics NAV object, add the following C/AL code to create, fill, and implement the array.

    Copy Code
    // Sets the number of elements in the .NET Framework array.
arraySize := 10;
// Creates an instance of the .NET Framework object so the type information can be retrieved.
varDotNet := varDotNet.WrapInt32(1);
// Creates an instance of the .NET Framework array that contains the user-defined type.
varArray := varArray.CreateInstance(varDotNet.GetType(), arraySize);
// Clears the object instance because it is no longer used.
clear(varDotNet);
// Sets data in the array.
FOR i := 0 TO (arraySize -1) DO
BEGIN
  varDotNet := varDotNet.WrapInt32(i+100);
  varArray.SetValue(varDotNet,i);
END;
// Gets array data and validates content.
FOR i := 0 TO (arraySize -1) DO
BEGIN
  varDotNet := varArray.GetValue(i);
 // Gets the integer value from the .NET Framework object using the Data property.
  alData := varDotNEt.Data;
  if alData <> (i+100) then
    error('Invalid array data in element %1, expected %2, actual %3', i, i+100, alData);
END;

See Also

Concepts

Extending Microsoft Dynamics NAV Using Microsoft .NET Framework Interoperability


Using Collections

In Microsoft Dynamics NAV, a common development task is to write code that loops through a set of records and performs an operation on each record in the set. You can do the same task in the .NET Framework with a collection, which is a .NET Framework object that you can iterate over. To loop through a collection in Microsoft Dynamics NAV, the .NET Framework object must support the System.Collections interface. Many types in the .NET Framework and assemblies that inherit from .NET Framework types support the System.Collections interface. The following example shows how you can write C/AL code to handle collections for a type that supports the System.Collections interface.

Example

The following example implements the System.ArrayList interface and uses the GetProcesses method from the System.Diagnostics.Process type to display a list of process IDs in message boxes. Although this is not a typical example for an ERP product such as Microsoft Dynamics NAV, it shows the flexibility that you get with the .NET Framework.

The example requires that you define the following C/AL variables.

Variable name | DataType | SubType
MyProcessList | DotNet | 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Array
Process | DotNet | 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Diagnostics.Process
I | Integer |
Copy Code
MyProcessList := Process.GetProcesses();
FOR I:=0 TO (MyProcessList.Length()-1) DO
BEGIN
    Process := MyProcessList.GetValue(I);
    MESSAGE(FORMAT(Process.Id));
END;

See Also

Concepts

Extending Microsoft Dynamics NAV Using Microsoft .NET Framework Interoperability


Using Enumerations

In the .NET Framework, an enumeration typically represents constant values as symbolic or literal names. For example, if you have the type Color, then instead of using the values 0, 1, and 2, you can use Red, Green, and Blue. The following is a C# code example for the Color enumeration.

C# Copy Code
namespace Microsoft.Dynamics.Nav.EnumSample
{
  public class DataValues
  {
    public enum Color
    {
      Red,
      Green,
      Blue,
    }
  }
}

.NET Framework interoperability supports symbolic names in enumerations. In C/AL code, enumerations are handled like static fields on the .NET Framework type.

Creating and Calling DotNet Variables for Enumerations in C/AL

You create DotNet variables for enumerations similar to other .NET Framework types. When you create a DotNet variable for an enumeration in the development environment, the enumeration name in the .NET Type List is preceded by a plus sign. The following illustration shows the .NET Type List for the enumeration in the previous code example.

.NET Type List showing enumeration

To call an enumeration from C/AL code, you can use the C/AL Symbol Menu, which displays all the values for the enumeration. The following illustration shows an example in the C/AL Symbol Menu.

C/AL Symbol Menu showing enumeration values

The following C/AL code assigns the Red value to the Color enumeration.

Copy Code
Color := Color.Red;

After the value is assigned, you can use the enumeration value in the C/AL code similar to a C/AL option data type. You must reference .NET Framework enumerations by using the DotNet variables that define them.

Example

In the following C/AL code example, the DotNet variable EnumTarget defines a method called MyMethod that has an enumeration type parameter. In the example, the MyMethod method is invoked by using the Color enumeration that is discussed in the previous sections of this topic.

Copy Code
EnumTarget.MyMethod(Color.Red);
EnumTarget.MyMethod(0); // Assumes that the enumeration value Red has the numerical value of 0.

The common language runtime automatically maps the value 0 to the correct enumeration value of Red.

See Also

Concepts

Calling .NET Framework Members from C/AL
Extending Microsoft Dynamics NAV Using Microsoft .NET Framework Interoperability


Using Generics

In the .NET Framework, you can use generics to customize a method, class, structure, interface, field, or property according to the data type that it acts upon. Instead of writing a method, class, structure, interface, field, or property for a particular type, you can write it to use any type. When a generic is declared, the type is specified. For example, in C#, if you use the generic type parameter T, then you can write a List<T> class that is declared as either List<int>, List<string>, or List<MyClass>.

With .NET Framework interoperability, you can define DotNet variables for generics. You cannot specify generic type names in C/AL. When a generic is instantiated by a constructor in C/AL, all type names are set to the System.Object type. For example, if you have a mylist DotNet variable for the System.List<T> generic, you create an instance of mylist in C/AL as shown. mylist is instantiated as a List<Object> type.

Copy Code
mylist := mylist.List();

If a method returns an instance of a generic whose type name is defined, then the type name is applied. In the following C/AL example, the method returns a List<String> instance, and mylist is instantiated as a List<String> type.

Copy Code
mylist := x.GetAStringList();

Example

The following C/AL example constructs a string list, fills the list with data, and then uses the Item method to validate whether the list contains the expected data. The Item method is equivalent to a C# index operator.

Variable name | Data Type | SubType | Length
varDotNet | DotNet | 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Collections.Generic.List`1 |
textResult | Text |  | 30
i | Integer |  |
capacity | Integer |  |
Copy Code
capacity := 5;
varDotNet := varDotNet.List(capacity);
FOR i:= 0 TO (capacity-1) DO
  varDotNet.Add(FORMAT(i));
IF varDotNet.Count <> capacity THEN
  ERROR('Wrong list count, expected {0}, actual {1}', capacity,
    varDotNet.Count);
FOR i:= 0 TO (capacity-1) DO
BEGIN
  textResult := varDotNet.Item(i);
  IF textResult <> FORMAT(i) THEN
    ERROR('List index [%1] contains the wrong data, expected %2, actual
      %3', i, FORMAT(i), textResult);
END;

See Also

Concepts

Extending Microsoft Dynamics NAV Using Microsoft .NET Framework Interoperability


Using Interfaces

With .NET Framework interoperability in C/AL, you can define variables for .NET Framework interface types. This is useful when you have a class that explicitly implements an interface. In the .NET Framework, when an interface is explicitly implemented, you cannot call methods that belong to the interface directly from the class instance. To call a method, you must cast to the interface. This condition is similar in C/AL except that C/AL does not have a cast operation. In C/AL, you cannot call a method of an explicitly implemented interface directly on the DotNet variable for the class. Instead, you do the following steps:

  1. Create a DotNet variable for the interface.

  2. Assign the class variable to the interface.

  3. Call the interface methods on the DotNet variable for the interface.

Example

In the following C# example, you have the Sample class that explicitly implements the ISample interface.

C# Copy Code
class Sample : ISample
{
    ...
    string ISample.Name()
    {
        ...
    }
}

To call the ISample.Name method from C/AL code, you create the following variables.

Variable name | DataType | SubType (simplified)
cvar | DotNet | Sample
ivar | DotNet | ISample

After you create the variables, add the following C/AL code that assigns the class variable to the interface variable and then calls the interface’s method.

Copy Code
// Assigns the class variable to the interface variable.
ivar := cvar;
...
// Calls the method of the interface.
ivar.Name();
...


Calling External Web Services

In Microsoft Dynamics NAV, you can use the Windows Communication Foundation, which provides a set of reliable objects for calling web services to use with .NET Framework interoperability.

Example

The following code example uses a proxy web service class and calls a Read method from the Microsoft Dynamics NAV web service. To set up this example, you expose page 42 as a web service in the Web Service table and then generate and compile the proxy class. For more information, see Working with Web Services in the MSDN Library.

The example requires the following variables.

Variable name | DataType | SubType | Length
navBinding | DotNet | 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.ServiceModel.BasicHttpBinding |
address | text |  | 256
salesOrderService | DotNet | 'SalesOrderService, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.NAV.SalesOrderService.SalesOrder_PortClient |
endpointAddress | DotNet | 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.ServiceModel.EndpointAddress |
salesOrder | DotNet | 'SalesOrderService, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.NAV.SalesOrderService.SalesOrder |
Copy Code
navBinding := navBinding.BasicHttpBinding;
// Set security mode to BasicHttpSecurityMode.TransportCredentialOnly
navBinding.Security.Mode := 4;
address :=
    'http://localhost:7047/DynamicsNAV70/WS/CRONUS%20International%20Ltd./Page/SalesOrder';
// Set client credential type to HttpClientCredentialType.Windows
navBinding.Security.Transport.ClientCredentialType := 4;
salesOrderService := salesOrderService.SalesOrder_PortClient(navBinding,
    endpointAddress.EndpointAddress(address);
// Set impersonation level to System.Security.Principal.TokenImpersonationLevel.Delegation
salesOrderService.ClientCredentials.Windows.AllowedImpersonationLevel := 4;
// Include the sales order ID to be read.
salesOrder := salesOrderService.Read('10000');


Handling Events with Microsoft .NET Framework Interoperability

With Microsoft .NET Framework interoperability, a DotNet type variable of a Microsoft Dynamics NAV object can subscribe to events that are published by a .NET Framework class. In .NET Framework, an event enables an object to notify other objects when something occurs. Typical events in a graphical user interface might be the click of a button or the change of a field. The object that raises the event is the publisher and the object that handles the event is called the subscriber.

This topic discusses the following subjects:

  • Understanding How Events Work in .NET Interoperability

  • Client-side and Server-side Events

  • Understanding Synchronous and Asynchronous Events

  • Updating Event Triggers

  • Limitations on Events and Event Triggers

Understanding How Events Work in .NET Interoperability

You set up a DotNet variable to subscribe to events by setting the variable’s WithEvents Property to true. The DotNet variable is exposed to all events that are published by the .NET Framework type that the variable references. For each event, Microsoft Dynamics NAV automatically adds a blank trigger in the C/AL code of the Microsoft Dynamics NAV object. You add C/AL code to the trigger to handle the event. When an instance of the .NET Framework type raises the event, the corresponding trigger in C/AL code is invoked and its code is run.

For more information, see How to: Subscribe to Events in a .NET Framework Type.

Client-side and Server-side Events

You can configure a DotNet type variable to instantiate the .NET Framework type to target the Microsoft Dynamics NAV Windows client or the Microsoft Dynamics NAV Server. As a result, events that are published by the .NET Framework type will also target either the Microsoft Dynamics NAV Windows client (client-side) or the Microsoft Dynamics NAV Server (server-side).

Client-Side Events

Client-side events are supported on pages only. A page can subscribe to events from the following sources:

  • DotNet variable that is defined as a global variable.

  • Events published by a control add-in. For more information about events in control add-ins, see Exposing Events and Calling Respective C/AL Triggers from a Windows Client Control Add-in.

Understanding Synchronous and Asynchronous Events

Events published by .NET Framework objects can be classified as synchronous or asynchronous. Synchronous events are raised immediately when something occurs in the running application code. Asynchronous events are raised after something occurs. An asynchronous event can be a timer event, which is implemented by the System.Timers.Timer class, or an event that is raised by a network listener or other external source, which is handled by an event sink.

Considerations for Asynchronous Events

  • Timer events and event sinks are only active as long as the Microsoft Dynamics NAV object that implements the DotNet variable is running. By using an asynchronous event, it is possible that Microsoft Dynamics NAV object closes before the event trigger is run. To avoid this condition, you can declare the DotNet variable in a single instance codeunit. Single instance codeunits remain instantiated until you close the Microsoft Dynamics NAV Windows client or close the company database. For more information about single instance codeunits, see Using Codeunits.

  • When asynchronous events are raised, they are added to the event queue of the .NET Framework, and processed when the connection between the Microsoft Dynamics NAV Windows client and the Microsoft Dynamics NAV Server is idle. A connection is idle when no Microsoft Dynamics NAV objects are communicating over the connection. If there is a long process that is running over the connection, then you might experience a delay when you run event triggers.

Updating Event Triggers

Event triggers in C/AL code do not update automatically when events are changed or added to the .NET Framework assembly that is used by a DotNet variable. If you want to update event triggers in the Microsoft Dynamics NAV object to changes in the .NET Framework assembly, then you must delete existing triggers and subscribe to the events again.

Limitations on Events and Event Triggers

Event triggers that are published by .NET Framework types have the following limitations:

  • Events are only supported on global variables.

  • Events must adhere to the delegation event model of the .NET Framework. For more information about this model, see Events and Delegates.

  • Reference parameters in client-side events are not supported.

  • Events cannot have parameters that are enumeration types.

  • Return values on event triggers are not supported.

See Also

Tasks

How to: Subscribe to Events in a .NET Framework Type

Concepts

Calling .NET Framework Members from C/AL


How to: Subscribe to Events in a .NET Framework Type

With .NET Framework interoperability in Microsoft Dynamics NAV objects, you can configure a DotNet variable to subscribe to events that are published by a .NET Framework type. Events are handled by triggers in the C/AL code of the Microsoft Dynamics NAV object. To configure a DotNet variable to subscribe to events published by a .NET Framework class, you set the WithEvents Property of the DotNet variable. A trigger is automatically added in the C/AL code for each event that is exposed by the .NET Framework type. For more information about events in NET Framework Interoperability, see Handling Events with Microsoft .NET Framework Interoperability.

Important
You can only subscribe to events on a DotNet variable that is defined as global variable.

To subscribe to events published by a .NET Framework type

  1. In the development environment, open the Microsoft Dynamics NAV object that uses .NET Framework interoperability, and then open the C/AL code.

  2. On the View menu, choose C/AL Globals.

  3. On the Variables tab, select the DotNet variable, and then on the View menu, choose Properties.

  4. In the Properties window, set the WithEvents property to Yes.

    For each event that is exposed by the .NET Framework class, a blank trigger is added to the C/AL code. The triggers have the following format.

    Copy Code
    DotNetVariable :: Event (sender : Variant;e DotNet "EventArgs")
    • DotNetVariable is the name of the DotNet variable that subscribes to the event.

    • Event is the name of the event published by the .NET Framework class

    • () will contain any parameters that the event has.

  5. Add code to the event triggers to handle the events.

Example

The following code example implements a simple synchronous event that will invoke a C/AL trigger without any parameters. You will create a .NET Framework assembly that contains the event, and then subscribe to the event in the C/AL code of a Microsoft Dynamics NAV codeunit.

To create and deploy the assembly that includes an event

  1. In Visual Studio, create a C# class library project that is called MyEvent.

  2. Add the following code that implements the ChangedEvent event in the EventsNoArgs class.

    C# Copy Code
    namespace MyEvent
{
    public class EventsNoArgs
    {
        public delegate void ChangedEventHandler();
        public event ChangedEventHandler ChangedEvent;
        // Invoke the ChangedEvent
        protected virtual void OnChangedEvent()
        {
            if (ChangedEvent != null)
            {
                ChangedEvent();
            }
        }
        // The following method is exposed to C/AL and will invoke the event trigger that is registered in the ChangedEvent variable.
        public void FireEvent()
        {
            OnChangedEvent();
        }
    }
}

  3. Build the project.

  4. Copy the MyEvent.dll file to the computer that is running the Microsoft Dynamics NAV development environment. You must copy the assembly to the Add-ins folder of the Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Server installation folders. The default path of the Microsoft Dynamics NAV Windows client installation folder is C:\Program Files\Microsoft Dynamics NAV\90\RoleTailored Client or C:\Program Files (x86)\Microsoft Dynamics NAV\90RoleTailored Client. The default path of the Microsoft Dynamics NAV Server installation folder is C:\Program Files\Microsoft Dynamics NAV\90\Service.

To subscribe to the event in C/AL

  1. In the development environment, create a new codeunit.

  2. Create the following global C/AL variables.

    Variable name DataType SubType

    eventVar

    DotNet

    MyEvent.EventsNoArgs

    counter

    Integer

  3. Open the properties for the eventVAR variable, and then set the WithEvents Property to Yes.

    The eventVar::ChangedEvent() trigger is added to the C/AL.

  4. On the OnRun trigger, add the following code.

    Copy Code
    //Reset the global counter to zero.
counter := 0;
// Construct the DotNet object that implements the event.
eventVar := eventVar.EventsNoArgs();
// Fire the event three times.
eventVar.FireEvent();
eventVar.FireEvent();
eventVar.FireEvent();
// Inspect the counter and raise an error if the count does not match the number of events fired.
if counter <> 3 then error(‘Unexpected count value, %1’, counter);
message(‘Received %1 events’, counter);

  5. On the eventVar::ChangedEvent() trigger, add the following code to increment the counter variable.

    Copy Code
    counter += 1;

  6. Save and compile the codeunit.

  7. To test the event, in Object Designer, select the codeunit, and then choose Run.

    The Microsoft Dynamics NAV Windows client opens and the message “Received 3 events” appears.

    If you remove one of the eventVar.FireEvent(); statements, and then compile and run the codeunit again, you will get an error message.

See Also

Concepts

Handling Events with Microsoft .NET Framework Interoperability
Extending Microsoft Dynamics NAV Using Microsoft .NET Framework Interoperability
Calling .NET Framework Members from C/AL


Extending Microsoft Dynamics NAV Using Control Add-ins

You can use client control add-ins to add custom functionality to Microsoft Dynamics NAV Role Centers and pages. The extensibility framework has changed with Microsoft Dynamics NAV 2013 R2 and it is now possible to develop control add-ins that can be used on any display target.

Add-ins that are developed with Microsoft Dynamics NAV 2013 are still supported and displayed on a Microsoft Dynamics NAV Windows client only. Using that framework you can continue to write add-ins for the Microsoft Dynamics NAV Windows client. Using the new framework in Microsoft Dynamics NAV 2013 R2, you can write add-ins that can be run from any client.

See Also

Concepts

Extending the Windows Client Using Control Add-ins
Extending Any Microsoft Dynamics NAV Client Using Control Add-ins


Extending the Windows Client Using Control Add-ins

In Microsoft Dynamics NAV 2016, Microsoft Dynamics NAV Windows client control add-ins add custom functionality to Role Centers and pages. The following sections provide an overview of the documentation that is available to develop and use control add-ins.

Note
To learn how to write control add-ins that can be used both on Microsoft Dynamics NAV Windows client and on Microsoft Dynamics NAV Web client, see Extending Any Microsoft Dynamics NAV Client Using Control Add-ins.

Getting an Overview of Control Add-ins

To | See
Get a general overview about control add-ins and where they fit in the Microsoft Dynamics NAV 2016 architecture. | Windows Client Control Add-in Overview

Developing Control Add-ins

To See

Get a general overview about how to develop control add-ins, including design considerations.

Developing Windows Client Control Add-ins

Learn how to create a control add-in.

How to: Create a Windows Client Control Add-in

Learn how control add-ins bind with data in the Microsoft Dynamics NAV database.

Binding a Windows Client Control Add-in to the Database

Learn how control add-ins use events to call C/AL triggers on a page.

Exposing Events and Calling Respective C/AL Triggers from a Windows Client Control Add-in

Learn about how to expose methods and properties to C/AL code.

Exposing Methods and Properties in a Windows Client Control Add-in

Learn about how to change the size of a control add-in.

Sizing a Control Add-in on a Page

Learn about the client extensibility API that you use to create control add-ins.

Client Extensibility API Overview

Note
For more information about the API, see the Client Extensibility Reference for Microsoft Dynamics NAV in the Technical Reference section.

Follow a walkthrough that leads you from the development of a simple control add-in through its implementation on a page.

Walkthrough: Creating and Using a Windows Client Control Add-in

Learn about the Interactive Timeline Business Data Visualization add-in.

Interactive Timeline Business Data Visualization

Using Microsoft Dynamics NAV Windows client Control Add-ins on Pages

To | See
Get a general overview about how to use control add-ins on Microsoft Dynamics NAV Windows client pages. | Installing and Configuring Windows Client Control Add-ins on Pages
Learn how to install control add-ins on computers that are running the Microsoft Dynamics NAV Windows client. | How to: Install a Windows Client Control Add-in Assembly
Learn how to register a control add-in in the Microsoft Dynamics NAV database so that it is available to use on pages. | How to: Register a Windows Client Control Add-in
Learn how to use a control add-in on a page. | How to: Set Up a Windows Client Control Add-in on a Page
Follow a walkthrough that leads you from the development of a simple control add-in through its implementation on a page. | Walkthrough: Creating and Using a Windows Client Control Add-in

See Also

Tasks

How to: Determine the Public Key Token of the Windows Client Control Add-in and .NET Framework Assembly

Concepts

Extending Any Microsoft Dynamics NAV Client Using Control Add-ins
Pages

Other Resources

Touring the RoleTailored Client for Developers


Windows Client Control Add-in Overview

With Microsoft Dynamics NAV 2016, you use Microsoft Dynamics NAV control add-ins to extend the Microsoft Dynamics NAV with custom functionality. A control add-in is a custom control, or visual element, for displaying and modifying data on Microsoft Dynamics NAV pages. The following illustration shows a control add-in example that displays a gauge control on a page.

Control add-in example of a gauge control

Control add-ins can exchange data with the Microsoft Dynamics NAV Server on various data types and can respond to user interaction to raise events in the Microsoft Dynamics NAV Windows client that execute additional C/AL code.

Control add-ins for Microsoft Dynamics NAV are built with the Microsoft .NET Framework-based assemblies that you install on computers that are running the Microsoft Dynamics NAV Windows client.

Important
With Microsoft Dynamics NAV 2013 R2, you can write control add-ins that can be displayed on both the Microsoft Dynamics NAV Web client and the Microsoft Dynamics NAV Windows client. For more information, see Extending Any Microsoft Dynamics NAV Client Using Control Add-ins.

Important
In general, add-ins are built with the technology of the client.

In Microsoft Dynamics NAV Server, you register the control add-in, and you can then use it with Microsoft Dynamics NAV Windows client pages. For more information, see Installing and Configuring Windows Client Control Add-ins on Pages.

You can use Microsoft Visual Studio to create your own control add-ins. For more information, see Developing Windows Client Control Add-ins.

Windows Client Control Add-in Model

The following illustration shows the Microsoft Dynamics NAV Windows client in the Microsoft Dynamics NAV architecture.

RoleTailored client control add-in model

You install control add-in assemblies on the computer that is running the Microsoft Dynamics NAV Windows client, not the computer that is running Microsoft Dynamics NAV Server. Unlike pages that are instantiated by C/AL code, control add-ins are instantiated by using metadata that is in the Microsoft Dynamics NAV database.

If the assembly that contains the add-in also contains other .NET objects that are used in C/AL code on the server, it might be necessary to have the assembly on the server, too. As a best practice, those cases should be extracted into a separate assembly to store the code for the client add-in only on the client computer.

Interfaces Overview

The following table describes the interfaces that you can implement in a control add-in.

Interface | Description | See
Data Binding interface | Displays data from the Microsoft Dynamics NAV database. | Binding a Windows Client Control Add-in to the Database
Event Interface | Selected public events in a control add-in that convert into C/AL triggers on a page that sends data back to the Microsoft Dynamics NAV Server. | Exposing Events and Calling Respective C/AL Triggers from a Windows Client Control Add-in
Methods and Properties | Selected public methods and properties in a control add-in that can be called from C/AL triggers on a page. | Exposing Methods and Properties in a Windows Client Control Add-in
Site Interface | Provides information about a control add-in and allows the control add-in to call functionality inside the Microsoft Dynamics NAV framework, such as retrieving metadata (visible, caption, and so on). This interface is implemented by the default definition interfaces and base classes of the client extensibility API. | Client Extensibility API Overview IControlAddInSite

Control Add-ins That Are Not Supported

Control add-ins are not supported in the Microsoft Dynamics NAV Web client. If the page is displayed in the Microsoft Dynamics NAV Web client, the control add-in is ignored.

See Also

Concepts

Installing and Configuring Windows Client Control Add-ins on Pages
Developing Windows Client Control Add-ins


Developing Windows Client Control Add-ins

Microsoft Dynamics NAV 2016 includes the client extensibility API for creating Microsoft Dynamics NAV Windows client control add-ins. The client extensibility API is provided in the Microsoft.Dynamics.Framework.UI.Extensibility.dll assembly, which is installed with the Microsoft Dynamics NAV Windows client. You develop control add-ins using Microsoft Visual Studio and distribute them as Microsoft .NET Framework-based assemblies for deployment to computers that are running the Microsoft Dynamics NAV Windows client.

Design Considerations When Developing Control Add-ins

This section includes things to consider when you develop control add-ins.

Using a Control Add-in on Pages

  • You apply control add-ins on field controls of Microsoft Dynamics NAV Windows client pages.

    Important
    To develop control add-ins that supported both by the Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client, see Extending Any Microsoft Dynamics NAV Client Using Control Add-ins.

  • You can apply control add-ins on more than one field control on a page.

  • You can use control add-ins on all page types except a RoleCenter page type.

    Note
    To include a control add-in on a Role Center, you apply the control add-in on a page that is assigned to a part of the Role Center.

  • You can use control add-ins on pages that are included in parts and FactBoxes of other pages.

  • You can design the user interface of the control add-in to fill the page part area partially or completely.

  • You cannot use control add-ins on the following areas:

    • On a field under a repeater control, this is used display data in a list, such as in a list place

    • Ribbon

    • Command bar

    • Filter pane

Binding a Control Add-in to the Database to Display Data

A control add-in can bind with data in the Microsoft Dynamics NAV database, which lets you create control add-ins that can display and update data in the database. For more information, see Binding a Windows Client Control Add-in to the Database.

Exposing Events and Calling Respective C/AL Triggers on a Page

By firing exposed events, a control add-in can call the OnControlAddin trigger or other triggers that correspond to those events on a page for a field that is equipped with the control add-in. For more information, see Exposing Events and Calling Respective C/AL Triggers from a Windows Client Control Add-in.

Exposing Methods and Properties to C/AL code

To extend UI controls on a page, you can expose methods and properties in a control add-in assembly so that they can be called by C/AL code on most any page code. For more information, see Exposing Methods and Properties in a Windows Client Control Add-in.

See Also

Tasks

How to: Create a Windows Client Control Add-in

Concepts

Client Extensibility API Overview
Binding a Windows Client Control Add-in to the Database
Exposing Events and Calling Respective C/AL Triggers from a Windows Client Control Add-in
Installing and Configuring Windows Client Control Add-ins on Pages
Windows Client Control Add-in Overview


Client Extensibility API Overview

Microsoft Dynamics NAV 2016 includes the client extensibility API, which defines the model for creating Microsoft Dynamics NAV Windows client control add-ins. The client extensibility API uses .NET interfaces as the binding mechanism between the control add-ins on a page and the Microsoft Dynamics NAV framework. When you develop a control add-in, you can choose among various definition interfaces and base classes to implement based on the control add-in requirements. Additionally, you can create custom interfaces to add user interface controls to a page. This topic provides an overview of the available definition interfaces and base classes. For information about how to create custom interfaces, see Exposing Methods and Properties in a Windows Client Control Add-in.

Control Add-in Definition Interfaces

You can develop a control add-in to bind with data in the Microsoft Dynamics NAV database and raise events that call the OnControlAddin trigger on a page field control that is applied with the control add-in. For more information, see Binding a Windows Client Control Add-in to the Database and Exposing Events and Calling Respective C/AL Triggers from a Windows Client Control Add-in.

To support data binding and events in a control add-in, you must implement one of the control add-in definition interfaces that are described in the following table.

Interface Use

Microsoft.Dynamics.Framework.UI.Extensibility.IValueControlAddInDefinition

Base interface that binds the control add-in with System.String or System.Object data types as defined by the T parameter.

Displays text strings or binary data from the Microsoft Dynamics NAV database.

Note
The Microsoft.Dynamics.Framework.UI.Extensibility.WinForms.StringControlAddInBase base class implements this interface with a System.String data type.

Microsoft.Dynamics.Framework.UI.Extensibility.IEventControlAddInDefinition

Base interface that defines a Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInEventHandler event.

Uses events to call the OnControlAddin Trigger of a page field control.

Note
The Microsoft.Dynamics.Framework.UI.Extensibility.WinForms.StringControlAddInBase class implements this interface.

Microsoft.Dynamics.Framework.UI.Extensibility.IObjectControlAddInDefinition

Base interface that binds the control add-in with a System.Object data type and raises a Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInEventHandler event.

Displays binary data from a Microsoft Dynamics NAV database and uses events to call the OnControlAddin trigger of a page field control.

Microsoft.Dynamics.Framework.UI.Extensibility.IStringControlAddInDefinition

Base interface that binds the control add-in with a System.String data type and provides a control add-in definition interface that raises a Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInEventHandler event.

Displays text strings from Microsoft Dynamics NAV Server and uses events to call the OnControlAddin trigger of a page field control.

Note
The Microsoft.Dynamics.Framework.UI.Extensibility.WinForms.StringControlAddInBase class implements this interface.

Microsoft.Dynamics.Framework.UI.Extensibility.IBooleanControlAddInDefinition

Base interface that binds the control add-in with a System.Boolean data type and raises a Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInEventHandler event.Displays binary data from a Microsoft Dynamics NAV database and uses events to call the OnControlAddin trigger of a page field control.

Microsoft.Dynamics.Framework.UI.Extensibility.ICharControlAddInDefinition

Base interface that binds the control add-in with a System.Char data type and raises a Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInEventHandler event.Displays binary data from a Microsoft Dynamics NAV database and uses events to call the OnControlAddin trigger of a page field control.

Microsoft.Dynamics.Framework.UI.Extensibility.IDateTimeControlAddInDefinition

Base interface that binds the control add-in with a System.DateTime data type and raises a Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInEventHandler event.Displays binary data from a Microsoft Dynamics NAV database and uses events to call the OnControlAddin trigger of a page field control.

Microsoft.Dynamics.Framework.UI.Extensibility.IDecimalControlAddInDefinition

Base interface that binds the control add-in with a System.Decimal data type and raises a Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInEventHandler event.Displays binary data from a Microsoft Dynamics NAV database and uses events to call the OnControlAddin trigger of a page field control.

Microsoft.Dynamics.Framework.UI.Extensibility.IGuidControlAddInDefinition

Base interface that binds the control add-in with a System.Guid data type and raises a Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInEventHandler event.Displays binary data from a Microsoft Dynamics NAV database and uses events to call the OnControlAddin trigger of a page field control.

Microsoft.Dynamics.Framework.UI.Extensibility.IInt32ControlAddInDefinition

Base interface that binds the control add-in with a System.Int32 data type and raises a Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInEventHandler event.Displays binary data from a Microsoft Dynamics NAV database and uses events to call the OnControlAddin trigger of a page field control.

Microsoft.Dynamics.Framework.UI.Extensibility.IInt64ControlAddInDefinition

Base interface that binds the control add-in with a System.Int64 data type and raises a Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInEventHandler event.Displays binary data from a Microsoft Dynamics NAV database and uses events to call the OnControlAddin trigger of a page field control.

Microsoft.Dynamics.Framework.UI.Extensibility.ITimeSpanControlAddInDefinition

Base interface that binds the control add-in with a System.TimeSpan data type and raises a Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInEventHandler event.Displays binary data from a Microsoft Dynamics NAV database and uses events to call the OnControlAddin trigger of a page field control.

Control Add-in Base Classes

To develop control add-ins that target Windows Forms-based displays, the client extensibility API includes the Microsoft.Dynamics.Framework.UI.Extensibility.WinForms.IWinFormsControlAddIn interface. You can implement this interface explicitly and override its members, or you can implement an available abstract base class that implements the interface for you. Use the following table to decide which base class to use.

Base class Use

Microsoft.Dynamics.Framework.UI.Extensibility.WinForms.WinFormsControlAddInBase

Base class that targets Windows forms displays with a control add-in.

You can use this base class for any control add-in with an appropriate control add-in definition interface.

Microsoft.Dynamics.Framework.UI.Extensibility.WinForms.StringControlAddInBase

Base class that implements the Microsoft.Dynamics.Framework.UI.Extensibility.IValueControlAddInDefinition and Microsoft.Dynamics.Framework.UI.Extensibility.IEventControlAddInDefinition

interfaces.

This base class overrides the Microsoft.Dynamics.Framework.UI.Extensibility.IValueControlAddInDefinition.Value property to bind the control add-in to a System.String data type in Microsoft Dynamics NAV Server. It also defines the Microsoft.Dynamics.Framework.UI.Extensibility.WinForms.StringControlAddInBase.RaiseControlAddInEvent(System.Int32,System.String) method for raising events.

You can use this base class for a control add-in that displays text strings from a simple text box control and supports events that call the C/AL trigger on the page.

See Also

Tasks

How to: Create a Windows Client Control Add-in

Concepts

Developing Windows Client Control Add-ins
Binding a Windows Client Control Add-in to the Database
Exposing Events and Calling Respective C/AL Triggers from a Windows Client Control Add-in
Installing and Configuring Windows Client Control Add-ins on Pages
Windows Client Control Add-in Overview


Binding a Windows Client Control Add-in to the Database

Similar to other field controls on a page, a Microsoft Dynamics NAV Windows client control add-in can bind with data in the Microsoft Dynamics NAV database. This lets you create control add-ins that can display and update data in the database. Data binding is accomplished through Microsoft Dynamics NAV Server with the SourceExpr Property of the field control that is applied with the control add-in, as shown in the following illustration.

RoleTailored client control add-in data binding

The control add-in must implement the Microsoft.Dynamics.Framework.UI.Extensibility.IValueControlAddInDefinition interface that exposes the Microsoft.Dynamics.Framework.UI.Extensibility.IValueControlAddInDefinition.Value property as shown in the following example for a DateTime data type.

C# Copy Code
[ControlAddInExport("MyControlAddIn")]
public class MyControlAddIn : IValueControlAddInDefinition<DateTime>
{
    ...
}

When a control add-in is instantiated on a page, the SourceExpr property value is passed to the control add-in Microsoft.Dynamics.Framework.UI.Extensibility.IValueControlAddInDefinition.Value property. The SourceExpr property can be a field or row in a database table or a C/AL global variable.

Note
The SourceExpr property value can be passed to the Microsoft.Dynamics.Framework.UI.Extensibility.IValueControlAddInDefinition.Value property multiple times as long as a page is open, depending on application code or state in the Microsoft Dynamics NAV Windows client.

For more information about how to implement the Microsoft.Dynamics.Framework.UI.Extensibility.IValueControlAddInDefinition interface, see How to: Create a Windows Client Control Add-in.

For more information about how to set the SourceExpr property for a control add-in, see How to: Set Up a Windows Client Control Add-in on a Page.

Supported Data Types

A control add-in can bind with several data types from the database. Each data type in C/AL maps to a corresponding .NET Framework data type in the control add-in as listed in the following table.

C/AL data type | Control add-in data type
BigInteger | Int64
BigText | String
BLOB | Object
Boolean | Boolean
Byte | Byte
Char | Char
Code | System.String
Date | DateTime
DateFormula | String
DateTime | DateTime
Decimal | Decimal
Duration | TimeSpan
Guid | Guid
Integer | Int32
Option | Int32
RecordID | String
Text | String
Time | DateTime

Data Mapping and Multiple Data Types

The mapping between the C/AL data type of the page control and the .NET Framework data type occurs when the control add-in is instantiated on a page in the Microsoft Dynamics NAV Windows client. For example, if a page contains a control that uses a Date data type in C/AL and the control add-in implements the Boolean data type (IValueControlAddInDefinition<Boolean>), then an error occurs.

A control add-in can support multiple .NET Framework data types by implementing the Microsoft.Dynamics.Framework.UI.Extensibility.IValueControlAddInDefinition interface for each data type. For example, to support both a string and an integer data type, include the following code.

C# Copy Code
public class MyControlAddIn : IValueControlAddInDefinition<String>, IValueControlAddInDefinition<Int32>

See Also

Tasks

How to: Create a Windows Client Control Add-in

Concepts

Developing Windows Client Control Add-ins
Client Extensibility API Overview
Exposing Events and Calling Respective C/AL Triggers from a Windows Client Control Add-in
Installing and Configuring Windows Client Control Add-ins on Pages
Windows Client Control Add-in Overview


Exposing Events and Calling Respective C/AL Triggers from a Windows Client Control Add-in

The Microsoft Dynamics NAV Windows client pages include an all-purpose OnControlAddin Trigger on field controls that control add-ins can invoke to run C/AL code. No code is needed to introduce this event into C/AL. To invoke the OnControlAddIn trigger, a control add-in sends an event to Microsoft Dynamics NAV Server, as shown in the following illustration.

RoleTailored client control add-in events

Events allow the control add-in to react to user interaction in the Microsoft Dynamics NAV Windows client. An example of an event is when a user clicks a button in the control add-in display on the page. To program events in a control add-in, you implement the Microsoft.Dynamics.Framework.UI.Extensibility.IEventControlAddInDefinition interface, as shown in the following example.

C# Copy Code
[ControlAddInExport("MyControlAddIn")]
public class MyControlAddIn : IEventControlAddInDefinition
{
    ...
}

By firing the ControlAddIn event declared in the base interface, the add-in sends data to Microsoft Dynamics NAV Server in two attributes: Index and Data. The Index attribute value is an integer data type. The Data attribute value is a text string data type. You add C/AL code to the OnControlAddIn trigger to process the data.

Copy Code
if (this.ControlAddIn != null)
{
    this.ControlAddIn(100, "Test data");
}
Note
The Data attribute on the OnControlAddIn trigger supports both Text and BigText data types from Microsoft Dynamics NAV Server. The data type is determined by the SourceExpr property of the field control that is applied with the control add-in. If the SourceExpr property value is BigText, then the Data attribute is BigText. Otherwise, the Data attribute is Text[1024]. For more information about data types, see C/AL Functions.

For more information about how to create events in a control add-in, see How to: Create a Windows Client Control Add-in.

For more information about how to set up the OnControlAddin trigger on a page, see How to: Set Up a Windows Client Control Add-in on a Page.

Exposing Custom Events

To expose a public event in a control add-in, you add the event code to the control add-in class and mark it by using the managed attribute ApplicationVisibleAttribute in the control add-in class.

The following code example is from a control add-in class that exposes a simple method and property.

Copy Code
public delegate void TransactionEventHandler(string refNo);
[ControlAddInExport("MyControlAddIn")]
public class MyControlAddIn : WinFormsControlAddInBase, ...
{
    ...

    //Exposes an event
    [ApplicationVisible]
    public event TransactionEventHandler TransactionChanged;
    ...

In the example a trigger called OnTransationChanged will be created in the page for the respective field as soon as the add-in is assigned to the field. You can write C/AL code in the trigger, which will be run on the server when the add-in on the client fires the event.

See Also

Tasks

How to: Create a Windows Client Control Add-in

Concepts

Developing Windows Client Control Add-ins
Client Extensibility API Overview
Binding a Windows Client Control Add-in to the Database
Installing and Configuring Windows Client Control Add-ins on Pages
Windows Client Control Add-in Overview


How to: Create a Windows Client Control Add-in

You develop Microsoft Dynamics NAV Windows client control add-ins using the API that is defined in the Microsoft.Dynamics.Framework.UI.Extensibility assembly. A control add-in is defined as a class in a Visual C# solution. You can include more than one control add-in a single solution. When you have finished developing a control add-in, you build and sign an assembly before you install it on the computer that is running the Microsoft Dynamics NAV Windows client.

To create a control add-in, you need the following prerequisites:

  • Microsoft Visual Studio 2005, Microsoft Visual Studio 2008, Visual C# 2008 Express Edition, Microsoft Visual Studio 2010, or Microsoft Visual Studio 2012.

  • Microsoft.Dynamics.Framework.UI.Extensibility.dll assembly.

    The assembly is installed with the Microsoft Dynamics NAV Windows client. By default, the path of the assembly is C:\Program Files\Microsoft Dynamics NAV\90\RoleTailored Client. For more information, see Deployment.

  • Windows Forms library (System.Windows.Forms.dll).

To create the Microsoft Dynamics NAV Windows client control add-in

  1. In Visual Studio, create a Visual C# project type by using the Class Library template.

  2. In the project, add references to the following assemblies:

    • Microsoft.Dynamics.Framework.UI.Extensibility.dll assembly

      By default, the path of the assembly is C:\Program Files\Microsoft Dynamics NAV\90\RoleTailored Client. This reference is required for all control add-ins.

    • System.Windows.Forms

      Contains classes for creating user interfaces for Windows-based applications.

    Add additional references as required.

  3. Open the class.cs file and add the following using directives.

    C# Copy Code
    using Microsoft.Dynamics.Framework.UI.Extensibility;
using Microsoft.Dynamics.Framework.UI.Extensibility.WinForms;
using System.Windows.Forms;

    Add additional references as required.

  4. Declare a class for the control add-in that uses the Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInExportAttribute attribute. Derive the class from an abstract base class and implement the control add-in definition interface, as shown in the following examples.

    C# Copy Code
    [ControlAddInExport("MyCompany.MyProduct.MyAddin")]
public class MyFieldPopupAddin : WinFormsControlAddInBase, IObjectControlAddInDefinition

    C# Copy Code
    [ControlAddInExport("MyCompany.MyProduct.MyAddin")]
public class MyFieldPopupAddin : StringControlAddInBase

    For information about the base classes and interfaces, see Client Extensibility API Overview.

    The Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInExportAttribute attribute declares the class in the assembly to be a control add-in that is identified by its Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInExportAttribute.Name property, which in this case is MyCompany.MyProduct.MyAddin in C#. Because an assembly can contain more than one control add-in, the Microsoft Dynamics NAV Windows client uses the Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInExportAttribute attribute to differentiate each control add-in that is found in an assembly. The Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInExportAttribute.Name is used to register the control add-in in Microsoft Dynamics NAV Server.

    Tip
    If you give the control add-in the same name as the assembly, then you do not have to install the assembly on the client computer. In this case, you only install the assembly on the computer that is running Microsoft Dynamics NAV Server. When a client requests the control add-in, Microsoft Dynamics NAV Server will automatically deploy the assembly to the client.

    For more information, see How to: Register a Windows Client Control Add-in.

  5. Implement the abstract base method Microsoft.Dynamics.Framework.UI.Extensibility.WinForms.WinFormsControlAddInBase.CreateControl and add code that defines the control add-in.

    C# Copy Code
    protected override Control CreateControl()
       {
           /// Include control add-in code here.
       }

  6. Add code to override additional base class members as required for your control add-in.

    For example, a field control on a Microsoft Dynamics NAV Windows client can have a caption. If you do not want a caption, then override the Microsoft.Dynamics.Framework.UI.Extensibility.WinForms.WinFormsControlAddInBase.AllowCaptionControl property and return false (the default value is true).

    C# Copy Code
    public override bool AllowCaptionControl
{
get
{
 return false;
}

    The caption will span the caption column and the data column of the page.

  7. To bind the control add-in to data in the Microsoft Dynamics NAV database, add the following code that gets or sets the Microsoft.Dynamics.Framework.UI.Extensibility.IValueControlAddInDefinition.Value property.

    C# Copy Code
    /// Gets a value indicating whether the Value property has
/// changed its value.
public bool HasValueChanged { get; set; }
/// Gets or sets the Value Property.
public object Value
{
    get
    {
        // Include value handling code here.
        return null;
    }
    set
    {
        // Include value handling code here.

    }
}
    Note
    The Microsoft.Dynamics.Framework.UI.Extensibility.WinForms.StringControlAddInBase class already overrides the Microsoft.Dynamics.Framework.UI.Extensibility.IValueControlAddInDefinition.Value property to transfer data between the control add-in and the Microsoft Dynamics NAV database.

    For more information, see Binding a Windows Client Control Add-in to the Database.

  8. To define events that call the OnControlAddin C/AL trigger of a page field control, add the following C# code to declare an event handler.

    C# Copy Code
       public event ControlAddInEventHandler ControlAddIn;

    Add code to raise the event where appropriate.

    For more information, see Exposing Events and Calling Respective C/AL Triggers from a Windows Client Control Add-in.

  9. To add an event that will be represented by a new trigger in C/AL code of a Microsoft Dynamics NAV page object, use the managed attribute ApplicationVisibleAttribute and add code for C# methods and properties.

    C# Copy Code
    [ApplicationVisible]
     public void DrillDown(int nodeId)
     {
      …
     }
     public int SelectedNode
     {
      get {…}
      set {…}
     }

    The methods and properties must be public. For more information, see Exposing Methods and Properties in a Windows Client Control Add-in.

  10. To add a method or property that can be called from the C/AL code of a Microsoft Dynamics NAV page object, use the managed attribute ApplicationVisibleAttribute and add code for C# methods and properties.

    C# Copy Code
    /// <summary>
/// Event will be fired when the AddIn is ready for communication through its API
/// </summary>
[ApplicationVisible]
public event MethodInvoker AddInReady;

    The methods and properties must be public. For more information, see Exposing Methods and Properties in a Windows Client Control Add-in.

  11. Build and sign the solution.

Signing an Assembly That Contains a Control Add-in

To use an assembly that contains a control add-in with the Microsoft Dynamics NAV Windows client, it must be signed. Signing gives the assembly a public token key, which is a unique identity that is used to make sure that the control add-in runs code from a trusted assembly. When you register a control add-in in Microsoft Dynamics NAV Server, you provide the public token key. At run time, the Microsoft Dynamics NAV Windows client uses the public token key to load the appropriate control add-in.

Assemblies are signed with a key file that contains the public key token and an optional password. You can sign an assembly that contains a control add-in by creating a new key file or using an existing one. For more information about how to sign assemblies, see How to: Sign Assemblies and Strong-Name Signing for Managed Applications.

To sign the Microsoft Dynamics NAV Windows client add-in assembly

  1. Open the project's properties.

  2. On the Properties window, choose the Signing tab.

  3. Select the Sign the assembly check box.

  4. In the Choose a strong name key file box, select New to create a new key file or Browse to use an existing key file.

  5. Choose the OK button.

For information about how to determine the public token key, see How to: Determine the Public Key Token of the Windows Client Control Add-in and .NET Framework Assembly.

Example

The following code illustrates a control add-in that implements the Microsoft digital ink control on a Microsoft Dynamics NAV Windows client page field. For example, you could use this control add-in on a sales order page to allow customers to sign their sales orders with a tablet PC. The control add-in is designed to bind with a table field in the Microsoft Dynamics NAV database to store and retrieve signatures. Because the signatures are transferred as binary data, the example implements the Microsoft.Dynamics.Framework.UI.Extensibility.IObjectControlAddInDefinition interface.

C# Copy Code
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Ink;
using System.Drawing;
using Microsoft.Dynamics.Framework.UI.Extensibility;
using Microsoft.Dynamics.Framework.UI.Extensibility.WinForms;
using System.Windows.Forms;
namespace NavInkControl
{
    [ControlAddInExport("MyCompany.MyProduct.MyNavInkControlAddin")]
    public class NavInkContol : WinFormsControlAddInBase, IObjectControlAddInDefinition
    {
        InkPicture _inkControl;
        private bool _loaded = false;
        /// Creates the control for displaying and adding signatures.
        protected override Control CreateControl()
        {
            _inkControl = new InkPicture();
            _inkControl.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            _inkControl.MinimumSize = new Size(40, 50);
            _inkControl.MaximumSize = new Size(Int16.MaxValue, 100);
            return _inkControl;
        }
        #region IObjectControlAddInDefinition Members
        public event ControlAddInEventHandler ControlAddIn;
        /// Gets a value indicating whether the Value property instance has changed. true if this instance has changed its value; otherwise, false.
        public bool HasValueChanged
        {
            get { return _inkControl.Ink.Dirty; }
        }
        /// Gets or sets the value.
        public object Value
        {
            get
            {
                return this._inkControl.Ink.Save();
            }
            set
            {
                if (value is byte[])
                {
                    byte[] data = (byte[])value;
                /// Specifies that the data loads only once so that data cannot load while the user is drawing.
                    if (data != null && !this._loaded)
                    {
                        this._inkControl.Ink.Load(data);
                        this._loaded = true;
                    }
                }
            }
        }
        #endregion
    }

See Also

Tasks

Walkthrough: Creating and Using a Windows Client Control Add-in

Concepts

Developing Windows Client Control Add-ins
Client Extensibility API Overview
Binding a Windows Client Control Add-in to the Database
Exposing Events and Calling Respective C/AL Triggers from a Windows Client Control Add-in
Installing and Configuring Windows Client Control Add-ins on Pages
Windows Client Control Add-in Overview


How to: Determine the Public Key Token of the Windows Client Control Add-in and .NET Framework Assembly

To use a Microsoft Dynamics NAV Windows client control add-in on a Microsoft Dynamics NAV Windows client page, you must register the assembly that contains the control add-in on the Control Add-ins page of the Microsoft Dynamics NAV 2016 database. To register an assembly, you provide the assembly's public key token. The public key token is a unique 16-character key that is given to the assembly when it is built and signed in Microsoft Visual Studio. To determine the public token key, you can run the Strong Name tool (sn.exe) on the assembly. The sn.exe is available with the Microsoft .NET Framework SDK. For more information about how to sign assemblies, see Strong Name Signing (sn.exe) or How to: Create a Windows Client Control Add-in.

To determine the public key token

  1. Locate the sn.exe file.

    The default folder for the Microsoft .NET Framework SDK is C:\Program Files\Microsoft SDKs\Windows\v7.0\Bin.

  2. At the command prompt, change to the directory that contains the sn.exe utility.

  3. Type the following command.

    Copy Code
    sn.exe -T <assembly>

    Replace <assembly> with the add-in assembly's path and file name, such as C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client\Add-ins\MyCompany.MyProduct.RtcAddins.dll.

  4. Press Enter and note the public token key that is displayed.

See Also

Tasks

How to: Create a Windows Client Control Add-in
How to: Install a Windows Client Control Add-in Assembly

Concepts

Windows Client Control Add-in Overview
Developing Windows Client Control Add-ins
Installing and Configuring Windows Client Control Add-ins on Pages


Exposing Methods and Properties in a Windows Client Control Add-in

Control add-ins let you add custom user interface (UI) controls to pages in the Microsoft Dynamics NAV Windows client. By using the basic control add-in definition interfaces, a control add-in is bound to a page only through the field that is applied with the control add-in. It is also bound to the page through the SourceExpr Property, the OnControlAddin Trigger, and other triggers for exposed events. To extend UI controls on a page, you can expose methods and properties in a control add-in assembly so that they can be called by C/AL code on most page triggers.

Exposing Methods and Properties

To expose a public method or property in a control add-in, you add the method or property to the control add-in class and mark it by using the managed attribute Microsoft.Dynamics.Framework.UI.Extensibility.ApplicationVisibleAttribute in control add-in class.

The following code example is from a control add-in class that exposes a simple method and property.

C# Copy Code
[ControlAddInExport("MyControlAddIn")]
public class MyControlAddIn : WinFormsControlAddInBase, ...
{
    ...

    //Exposes a method
    [ApplicationVisible]
    public string Add(int param1, int param2)
    {
        return FormatNumber(param1 + param2, this.Notation);
    }

    //Exposes a property
    [ApplicationVisible]
    public Notation Notation
    {
        get { return this.notation; }
        set { this.notation = value; }
    }

Calling Methods and Properties in the Control Add-in From C/AL Triggers

Exposed methods and properties in a control add-in can be invoked from C/AL code on page triggers. The invoking mechanism resembles other .NET Framework types with the .NET Framework interoperability except that you can call the control add-in methods and properties using C/AL without defining a variable.

To call a method in C/AL code on a page trigger, use the following code.

C# Copy Code
CurrPage.ControlName.MyMethod(parameter)

To call a property in C/AL code, use the following code.

C# Copy Code
CurrPage.ControlName.MyProperty

ControlName is the name of the field control that is applied with the control add-in. The name is specified by the Name Property. MyMethod and MyProperty are the names of method and property of the control add-in to be invoked.

Triggers That Are Not Supported

You cannot invoke control add-in methods and properties from the following triggers because the triggers are invoked before the page is instantiated:

  • OnInit Trigger

  • OnOpenPage Trigger

  • OnNewRecord Trigger

See Also

Tasks

How to: Create a Windows Client Control Add-in

Concepts

Extending the Windows Client Using Control Add-ins
Extending Microsoft Dynamics NAV Using Microsoft .NET Framework Interoperability


Sizing a Control Add-in on a Page

By default, the size of a control add-in on a page is determined by the System.Drawing.Size class of the control. The size is static, so when the page is resized in the Microsoft Dynamics NAV Windows client, the control add-in size will remain the same.

Changing the Size of a Control Add-in

To change the size of the control add-in and set it to resize with the page window size, you implement the Microsoft.Dynamics.Framework.UI.Extensibility.WinForms.WinFormsControlAddInBase.ApplySize(Microsoft.Dynamics.Framework.UI.Extensibility.WinForms.DisplaySize,Microsoft.Dynamics.Framework.UI.Extensibility.WinForms.DisplaySize) method. This method has the following syntax.

C# Copy Code
public void ApplySize(DisplaySize width, DisplaySize height);

Each dimension is defined by the DisplaySize method. This method has the following syntax.

C# Copy Code
DisplaySize.DisplaySize(int minimum, int preferred, int maximum)

The DisplaySize parameters specify the control add-in size as follows.

Parameter | Description
minimum | An integer that sets the minimum width or height, in pixels, of the control add-in. The control add-in will not resize smaller than this value regardless of the size of the page window.
preferred | An integer that sets the initial width or height, in pixels, of the control add-in when the page first opens.
maximum | An integer that sets the minimum width or height, in pixels, of the control add-in. The control add-in will not resize larger than this value regardless of the size of the page window.

Example

The following code example shows the control add-in width (in pixels) set to: minimum 100, preferred 600, and maximum 1000. The height (in pixels) is set to: minmum 10, preferred 20, and maximum 200.

C# Copy Code
this.ApplySize(new DisplaySize(101, 600, 1000), new DisplaySize(10, 20, 200));

Sizing a Control Add-in According to the Size of Other Page Controls

There might be instances when you want the control add-in to use the same size of other controls on the page. By using page controls, Microsoft Dynamics NAV automatically determines the size based on the control’s data type. To set this behavior on the control add-in, for each dimension, use either DisplaySize.Default or null. You can set one dimension to default and the other to custom values.

Example

The following code example shows the control add-in width in pixels set to default and the minimum height to 10, a preferred height set to 20, and the maximum height set to 200.

C# Copy Code
this.ApplySize(DisplaySize.Default, new DisplaySize(10, 20, 200));

In this case, the control add-in width resembles other field controls that have the same C/AL data type on the page.

Calling the ApplySize Method

You can use the Microsoft.Dynamics.Framework.UI.Extensibility.WinForms.WinFormsControlAddInBase.ApplySize(Microsoft.Dynamics.Framework.UI.Extensibility.WinForms.DisplaySize,Microsoft.Dynamics.Framework.UI.Extensibility.WinForms.DisplaySize) method multiple times in the control add-in code to change the width and height. However, you should use it as part of the CreateControl method.

See Also

Tasks

How to: Create a Windows Client Control Add-in

Concepts

Extending the Windows Client Using Control Add-ins


Installing and Configuring Windows Client Control Add-ins on Pages

In the Microsoft Dynamics NAV Windows client, control add-ins add custom controls or visual elements, on Windows client page fields for displaying and editing data. When a control add-in is developed, it is compiled into a .NET Framework-based assembly, which is .dll file. To use a control add-in on Microsoft Dynamics NAV Windows client pages, you must install and configure the control add-in assembly in the Microsoft Dynamics NAV Windows client environment, which is divided between two tiers: Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV 2016 SQL server database.

RoleTailored client control add-in installation

The following table outlines the tasks that you must perform on each tier.

Tier Tasks For more information, see

Microsoft Dynamics NAV Windows client computer

Install the control add-in assemblies.

How to: Install a Windows Client Control Add-in Assembly

SQL database

Use the Microsoft Dynamics NAV Development Environment to:

  1. Register the control add-ins that are found in the assemblies in the Client Add-in table.

  2. Set up control add-ins on pages.

How to: Register a Windows Client Control Add-in

How to: Set Up a Windows Client Control Add-in on a Page

See Also

Tasks

Walkthrough: Creating and Using a Windows Client Control Add-in

Concepts

Developing Windows Client Control Add-ins
Windows Client Control Add-in Overview


How to: Install a Windows Client Control Add-in Assembly

Microsoft Dynamics NAV Windows client control add-ins are provided in one or more Microsoft Framework .NET-based assemblies, which are .dll type files. To run a control add from the Microsoft Dynamics NAV Windows client, the control add-in assembly must be installed on the computer on which the Microsoft Dynamics NAV Windows client is installed. In some cases during development, such as when you compile an object that uses a control add-in, the control add-in assembly must also be installed on the computer that is running the development environment.

You can install control add-ins the following ways:

  • Install the control add-in assemblies manually on the Microsoft Dynamics NAV Windows client or development environment computer.

    For more information, see To install control add-in assemblies on the Microsoft Dynamics NAV Windows client manually.

  • Install the control add-in assemblies on the computer that is running the Microsoft Dynamics NAV Server or in the database.

    The assemblies will be automatically deployed to the Microsoft Dynamics NAV Windows client computer. For more information, see Automatic Deployment of Control Add-ins.

To install control add-in assemblies on the Microsoft Dynamics NAV Windows client manually

  • On the computer that is running the Microsoft Dynamics NAV Windows client, copy the assemblies that contain the control add-ins to the Add-ins folder of the Microsoft Dynamics NAV Windows client installation.

    By default, the path of this folder is C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client\Add-ins.

    Note
    You can also include assemblies in a subfolder of the Add-ins folder. This can be useful if you have multiple assemblies and dependencies.

Automatic Deployment of Control Add-ins

If a control add-in has the same name as the assembly, the system can automatically deploy control add-in assembly, and any associated files, to the computer running the Microsoft Dynamics NAV Windows client. There are two ways that you set up the automatic deployment of a control add-in:

  • You can install the control add-in assembly directly on the computers running the Microsoft Dynamics NAV Server

  • Or you can import the control add-in assembly into the database.

When an operation from the Microsoft Dynamics NAV Windows client client requires a control add-in, such as running a page that contains the control add-in, the control add-in is deployed as follows:

  1. The client looks for the control add-in assembly in the local Add-ins folder (by default, C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client\Add-ins).

    • If the assembly is available, it is used.

    • If the assembly is not available, the client requests the assembly from Microsoft Dynamics NAV Server.

  2. The Microsoft Dynamics NAV Server looks for the control add-in assembly in the local Add-ins folder (by default, C:\Program Files\Microsoft Dynamics NAV\90\Service\Add-ins).

    • If the assembly is available, it is deployed to the Microsoft Dynamics NAV Windows client computer.

      The control add-in is installed in the %TEMP%\Microsoft Dynamics NAV\Add-Ins folder of the user who is running the client.

    • If the control add-in assembly is not there, the add-in is deployed from the database to the Microsoft Dynamics NAV Windows client.

  3. The control add-in assembly is streamed from the database to Microsoft Dynamics NAV Server instance and eventually the Microsoft Dynamics NAV Windows client computer.

    On the Microsoft Dynamics NAV Windows client computer, the control add-in is installed in the %TEMP%\Microsoft Dynamics NAV\Add-Ins folder of the user who is running the client.

The deployed assembly will be then be used whenever the page is run until the control add-in has been updated with a version change.

If the control add-in assembly is updated and its version number changes, Microsoft Dynamics NAV Server will deploy the updated assembly to the client computer the next time that the client requests the assembly. The updated assembly is put in a subfolder of the %TEMP%\Microsoft Dynamics NAV\Add-Ins folder, where the subfolder has the assembly's version number as its name. This implementation means that you do have to remove the older versions of assemblies that are stored on the client computer.

The process is similar when the development environment requires a control add-in, for example, when you compile an object. the control add-in assembly will be deployed to the local temporary folder for the current user on the computer that is running the development environment.

Note
To be deployed automatically, a control add-in must have the same name as its assembly and the assembly must comply with the following Microsoft Dynamics NAV Server configuration settings: Chunk Size, Max Upload Size, and Prohibited File Types. For more information about these settings, see Configuring Microsoft Dynamics NAV Server.

To install the control add-in on Microsoft Dynamics NAV Server

  • On the computer that is running the Microsoft Dynamics NAV Server, copy the assembly that contains the control add-in to the Add-ins folder of the Microsoft Dynamics NAV Server installation.

    By default, the path is C:\Program Files\Microsoft Dynamics NAV\90\Service\Add-ins.

To import the control add-in to the database

  1. Create a compressed (.zip type) file that contains the control add-in assembly files in the desired folder structure.

  2. You can import the compressed (.zip) file when you register the control add-in from the Control Add-ins page in Microsoft Dynamics NAV. In the Search box, enter Control Add-ins and then choose the related link.

  3. In the Control Add-ins window, choose New, and then in the Control Add-in Name column, enter the control add-in name. In the Public Key Token column, enter the public key token that you obtained earlier.

  4. Choose Import.

  5. In the Import Control Add-in Resource window, locate the.zip file, and then choose Open.

  6. Choose the OK button to close the Control Add-in page.

For more information about registering a control add-in, see How to: Register a Windows Client Control Add-in.

Tip
You can also register the control add-in and import the files by using the New-NAVAddin cmdlet or Set-NAVAddin cmdlet from the Microsoft Dynamics NAV 2016 Administration Shell.

See Also

Tasks

How to: Set Up a Windows Client Control Add-in on a Page
How to: Install a Windows Client Control Add-in Assembly
Walkthrough: Creating and Using a Windows Client Control Add-in

Concepts

Installing and Configuring Windows Client Control Add-ins on Pages
Developing Windows Client Control Add-ins
Installing and Configuring Windows Client Control Add-ins on Pages
Windows Client Control Add-in Overview


How to: Register a Windows Client Control Add-in

A Microsoft Dynamics NAV Windows client control add-in is delivered as a Microsoft .NET Framework-based assembly, which is a .dll file. An assembly for Microsoft Dynamics NAV Windows client add-ins can contain more than one control add-in where each control add-in has a unique name. Before you can use a control add-in on pages, you use the development environment to register it on the Control Add-ins page of your Microsoft Dynamics NAV database.

To register a control add-in, provide the following information.

Information Description

Control add-in name

The name is defined in the assembly's source code by the Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInExportAttribute attribute value for control add-in class definition, as shown in the following example code snippet.

C# Copy Code
[ControlAddInExport("MyCompany.MyProduct.FieldPopupAddin")]
public class MyFieldPopupAddin : StringControlAddInBase, IStringControlAddInDefinition

In this example, the control add-in name is MyCompany.MyProduct.FieldPopupAddin. For more information, see How to: Create a Windows Client Control Add-in.

Public key token

The public key token is a 16-character key that is given to the assembly when it is built and signed in Microsoft Visual Studio. To determine the public token key, run the Microsoft .NET Strong Name Utility (sn.exe) on the assembly. For more information, see How to: Determine the Public Key Token of the Windows Client Control Add-in and .NET Framework Assembly and Strong-Named Signing.

To register a Microsoft Dynamics NAV Windows client control add-in

  1. Open Microsoft Dynamics NAV Windows client.

  2. In the Search box, enter Control Add-ins and then choose the related link.

  3. On a blank line on the Control Add-ins page, fill in the Control Add-In Name and Public Key Token fields.

  4. Close the Control Add-ins page.

See Also

Tasks

How to: Set Up a Windows Client Control Add-in on a Page
How to: Install a Windows Client Control Add-in Assembly
How to: Determine the Public Key Token of the Windows Client Control Add-in and .NET Framework Assembly
Walkthrough: Creating and Using a Windows Client Control Add-in

Concepts

Installing and Configuring Windows Client Control Add-ins on Pages
Developing Windows Client Control Add-ins
Windows Client Control Add-in Overview


How to: Set Up a Windows Client Control Add-in on a Page

After you have registered a Microsoft Dynamics NAV Windows client control add-in, you can use it on Microsoft Dynamics NAV Windows client pages. To use a control add-in on a page, you add it to a field control. Depending on the design of the control add-in, you may also need to follow these steps:

  • Bind the control add-in field to a data source.

    Control add-ins can use data from a field in the table that is associated with the page or from a C/AL global variable.

  • Modify the OnControlAddin Trigger to process data that is sent from the Microsoft Dynamics NAV Windows client.

  • Add C/AL code to triggers that call methods and properties in the control add-in.

Preparing to Set Up the Control Add-in

To prepare for setting up the control add-in

  1. If the control add-in uses data from a table that does not exist, then create the table.

    For more information, see How to: Create a Table.

  2. If the page to which you want to add the control add-in does not exist, then create the page. As appropriate, associate the page with the table that you created in step 1.

    For more information, see How to: Create a Page.

Setting Up a Control Add-in on a Page Field

To set the ControlAddIn property on a field

  1. Open the Microsoft Dynamics NAV Development Environment.

  2. On the Tools menu, choose Object Designer, and then choose the Page button.

  3. Select the page, and then choose the Design button.

  4. In Page Designer, add a field control for the control add-in or use an existing field control.

  5. Select the field, and then on the View menu, choose Properties.

  6. In the ControlAddIn property value, choose the up arrow.

  7. In the Client Add-in window, select the control add-in from the Client Add-in window, and then choose the OK button.

    For more information, see the ControlAddin Property.

  8. To bind the field to data in a table field or C/AL global variable, set the SourceExpr property.

    Note
    If the SourceExpr property is set to a C/AL global variable, then in the C/AL code, add code to the OnAfterGetRecord trigger to populate the global variable. For more information, see OnAfterGetRecord Trigger.

  9. Close the Properties window.

Modifying the Microsoft Dynamics NAV Windows Client Control Add-in Event Trigger

When invoked on a page, a control add-in can raise an event that sends data to Microsoft Dynamics NAV Server. In the C/AL code for the page, the event calls the OnControlAddIn trigger of the field control that is applied with the control add-in. To process the event data, you add C/AL code to the OnControlAddIn trigger. For more information, see Exposing Events and Calling Respective C/AL Triggers from a Windows Client Control Add-in.

To add C/AL code to the control add-in event trigger

  1. On the View menu, choose C/AL Code.

  2. In the C/AL Editor, locate the following field control trigger.

    Copy Code
    Fieldname - OnControlAddIn(Index : Integer;Data : Text[1024])

    Fieldname is the name of the field control that is applied with the control add-in.

    Note
    If the data type of the field's SourceExpr property is BigText, then the Data attribute is BigText instead of Text[1024].

  3. Add the C/AL code to the trigger.

  4. Close the C/AL Editor.

  5. On the File menu, choose Save, select Compiled, and then choose the OK button.

Calling Control Add-in Methods and Properties From C/AL

Control add-ins can expose methods and properties that you can call using C/AL code from triggers on a page to extend the control add-in user interface. To complete this procedure, you must know the method or property names. For more information, see Exposing Methods and Properties in a Windows Client Control Add-in.

To call a control add-in method or property

  1. In the C/AL Editor, locate the trigger from which you want to call the method or property.

    Note
    You cannot call control add-in methods or properties from the OnInit, OnOpenPage, or OnNewRecord triggers.

  2. Add the C/AL code to the trigger that calls the method or property.

    • To call a method, add the following code.

      Copy Code
      CurrPage.ControlName.MyMethod(parameter)
    • To call a property, add the fowlloing code.

      Copy Code
      CurrPage.ControlName.MyProperty

    ControlName is the name of the field control that is applied with the control add-in. The name is specified by the Name Property. MyMethod and MyProperty are the names of the method and property of the control add-in to be invoked.

  3. Save the page.

See Also

Tasks

How to: Install a Windows Client Control Add-in Assembly
How to: Register a Windows Client Control Add-in
How to: Install a Windows Client Control Add-in Assembly
Walkthrough: Creating and Using a Windows Client Control Add-in

Reference

ControlAddin Property

Concepts

Windows Client Control Add-in Overview
Installing and Configuring Windows Client Control Add-ins on Pages
Developing Windows Client Control Add-ins


Walkthrough: Creating and Using a Windows Client Control Add-in

The following walkthrough demonstrates how to develop a Microsoft Dynamics NAV Windows client add-in and use it on a Microsoft Dynamics NAV Windows client page. Add-ins are Microsoft .NET Framework assemblies that enable you to add custom functionality to the Microsoft Dynamics NAV Windows client. An API lets you develop add-ins without having to access the Microsoft Dynamics NAV source code.

Note
With Microsoft Dynamics NAV 2013 R2 you can develop control add-ins that are displayed on both Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client. For more information, see Extending Any Microsoft Dynamics NAV Client Using Control Add-ins.

In a typical business scenario, .NET Framework developers create add-ins using Microsoft Visual Studio Express, Visual Studio 2008, Visual Studio 2010, or Visual Studio 2012. Implementers of Microsoft Dynamics NAV solutions then use the add-ins on Microsoft Dynamics NAV Windows client pages.

About This Walkthrough

This walkthrough illustrates the following tasks:

  • Creating an Add-in with Visual Studio .

  • Copying the Add-in Assembly to the Microsoft Dynamics Windows Client.

  • Registering the Add-in in Microsoft Dynamics NAV.

  • Setting Up the Add-in on a Page.

Roles

This walkthrough demonstrates tasks performed by the following user roles:

  • Microsoft .NET Framework developer

  • Microsoft Dynamics NAV developer and IT Professional

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 with a developer license. For more information, see System Requirements for Microsoft Dynamics NAV 2016.

  • CRONUS International Ltd. demonstration database

  • Microsoft Visual Studio Express, Microsoft Visual Studio 2008, Microsoft Visual Studio 2010, or Microsoft Visual Studio 2012.

  • Microsoft .NET Strong Name Utility (sn.exe). This is included with Visual Studio SDKs.

    By default, the Microsoft .NET Strong Name Utility is located in C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools.

  • Experience using Visual Studio.

Story

Simon is a software developer working for CRONUS International Ltd. He has been told that users of the Microsoft Dynamics NAV Windows client want a way to see all the content of page fields when the content extends beyond the field size. He decides to create an add-in that can be applied on a field that enables the user to select the field to display its full content. Fields that have add-ins are displayed in blue. When the user selects the field, a pop-up window opens that shows all of the field's content.

Creating an Add-in with Visual Studio

Microsoft Dynamics NAV 2016 includes the Microsoft.Dynamics.Framework.UI.Extensibility.dll assembly that defines the model for creating Microsoft Dynamics NAV Windows client add-ins. The Microsoft Dynamics NAV 2016 API provides the binding mechanism between the Microsoft Dynamics NAV Windows client add-in and the Microsoft Dynamics NAV 2016 framework.

To create the add-in

  1. In Visual Studio, on the File menu, choose New, and then choose Project.

  2. Under Installed Templates, choose Visual C#, and then choose Class Library.

  3. In the Solution Name text box, enter the name of your solution. For example, you can enter MyCompany.MyProduct.RtcAddins and then choose the OK button.

    Yow will add references to the following assemblies:

    1. Microsoft.Dynamics.Framework.UI.Extensibility.dll

    2. System.Windows.Forms

    3. System.Drawing

  4. In Solution Explorer, right-click your project, and then choose Add Reference.

  5. In the Add Reference window, on the Browse tab, navigate to the location of the Microsoft.Dynamics.Framework.UI.Extensibility.dll assembly on your computer and then choose the OK button. By default, the path of the assembly is C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client.

    Important
    The assembly cannot be placed outside of the RoleTailored Client folder.

  6. In Solution Explorer, choose Reference, and on the shortcut menu, choose Add Reference.

  7. In the Add Reference window, choose the .NET tab, then under Component Name, choose System.Windows.Forms, and then choose the OK button.

    The namespace contains classes for creating user interfaces for Windows-based applications.

  8. Repeat the previous step and add a reference to the System.Drawing namespace. This namespace provides access to basic graphics functionality.

  9. Open the Class1.cs file and add the following using directives.

    C# Copy Code
    using Microsoft.Dynamics.Framework.UI.Extensibility;
using Microsoft.Dynamics.Framework.UI.Extensibility.WinForms;
using System.Windows.Forms;
using System.Drawing;

  10. In the ClassLibrary1 namespace, add the following code to declare a new class named MyFieldPopupAddin for the add-in.

    C# Copy Code
    [ControlAddInExport("MyCompany.MyProduct.FieldPopupAddin")]
public class MyFieldPopupAddin : StringControlAddInBase
{
}

    The class uses the ControlAddInExportAttribute attribute and derives from the Microsoft.Dynamics.Framework.UI.Extensibility.WinForms.StringControlAddInBase class and Microsoft.Dynamics.Framework.UI.Extensibility.IStringControlAddInDefinition interface. The Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInExportAttribute attribute declares the class in the assembly to be a control add-in that is identified by its Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInExportAttribute.Name property, which is MyCompany.MyProduct.FieldPopupAddin. Because an assembly can contain more than one control add-in, the Microsoft Dynamics NAV Windows client uses the Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInExportAttribute attribute to differentiate each control add-in that is found in an assembly.

    Note
    You will use the name MyCompany.MyProduct.FieldPopupAddin later in the walkthrough when you register the add-in in Microsoft Dynamics NAV 2016. When naming the control add-in, it is good practice to follow the .NET Framework naming convention for classes, which is CompanyName.ProductName.ControlName.

    The Microsoft.Dynamics.Framework.UI.Extensibility.IStringControlAddInDefinition interface determines how data transfers to and from the add-in and how events are raised to call triggers on the Microsoft Dynamics NAV Server.

  11. In the MyFieldPopupAddin class, add the following code to implement the abstract Microsoft.Dynamics.Framework.UI.Extensibility.WinForms.WinFormsControlAddInBase.CreateControl method and define the add-in functionality.

    C# Copy Code
    /// Defines the text box control.
    protected override Control CreateControl()
    {
        TextBox control = new TextBox();

        control.MinimumSize = new Size(50, 0);
        control.MaximumSize = new Size(500, Int32.MaxValue);

        control.BackColor = Color.LightBlue;
        control.Font = new Font("Tahoma", 9, FontStyle.Bold);
        control.DoubleClick += control_DoubleClick;

        return control;
    }
/// Raises an event when the user double-clicks the text box.
    private void control_DoubleClick(object sender, EventArgs e)
    {
        int index = 0;
        string data = this.Control.Text;
        this.RaiseControlAddInEvent(index, data);

    }
    Note
    If you want to create an add-in that spans both the caption column and the data column of the page, override the Microsoft.Dynamics.Framework.UI.Extensibility.WinForms.IWinFormsControlAddIn.AllowCaptionControl property and return false (default value is true).

An assembly must be signed that can be used in the Microsoft Dynamics NAV Windows client. You will now sign the assembly.

To sign the assembly

  1. In Visual Studio, on the Project menu, choose MyCompany.MyProduct.RtcAddins properties.

  2. In the Properties window, choose Signing, and then select the Sign the assembly check box.

  3. In the Choose a strong name key file drop-down list, select New.

  4. In the Key file name text box, enter RtcAddins and clear the Protect my key file with a password check box.

    In this walkthrough, you will not protect the key file with a password. However, you can choose whether to use a password. For more information, see Strong-Name Signing for Managed Applications.

  5. Choose the OK button.

  6. In Solution Explorer, choose the Class1.cs file to open it. Notice the RtcAddins.snk file that is added in Solution Explorer.

  7. On the Build menu, choose Build <Your Solution> to build the project. Verify that the build succeeds. In this example, your solution is MyCompany.MyProduct.RtcAddins.

Copying the Add-in Assembly to the Microsoft Dynamics Windows Client

After you build the add-in, you copy the output assembly file to the computer that is running the Microsoft Dynamics NAV Windows client.

To copy the add-in assembly to the Microsoft Dynamics NAV Windows client

  1. On the development computer, locate and copy the add-in assembly file (.dll file) in the add-in project's output folder.

    By default, this folder is C:\ Documents\Visual Studio\Projects\[Your Addin Project]\[Your Class Library]\bin\Debug. In this case, the location of the assembly is C:\ \Documents\Visual Studio 2012\Projects\MyCompany.MyProduct.RtcAddins\ MyCompany.MyProduct.RtcAddins\bin\Debug.

  2. On the computer that is running the Microsoft Dynamics NAV Windows client, paste the assembly in the Microsoft Dynamics NAV Windows client\Add-ins folder in the Microsoft Dynamics NAV 2016 installation folder.

    By default, the path of this folder is C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client\Add-ins.

Registering the Add-in in Microsoft Dynamics NAV

To register an add-in, you include it on the Control Add-ins page in Microsoft Dynamics NAV. To include an add-in on the page, you must provide the following information:

  • Control Add-in name.

    The control add-in name is determined by the Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInExportAttribute attribute value of add-in class definition that you specified when you created the control add-in. The name in this walkthrough is MyCompany.MyProduct.FieldPopupAddin, as shown in the following code snippet from interface definition.

    C# Copy Code
    [ControlAddInExport("MyCompany.MyProduct.FieldPopupAddin")]
public class MyFieldPopupAddin : StringControlAddInBase
  • Public key token.

    This is a 16-character key that is given to the assembly when it is signed and built in Visual Studio. You can determine the public token key by running the Microsoft .NET Strong Name Utility (sn.exe) on the assembly. You must run the utility from the Visual Studio command prompt. The sn.exe utility is available with the Visual Studio 2008, Visual Studio 2010 SDKs, and Visual Studio 2012.

To determine the public key token for the add-in

  1. On the Windows taskbar, choose Start, choose All Programs, choose Microsoft Visual Studio 2012, choose Visual Studio Tools, and then choose Visual Studio Command Prompt (2012) to open the command prompt.

  2. At a command prompt, change to the directory that contains the assembly that you copied.

    For example, C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client\Add-ins.

  3. Type the following command.

    Copy Code
    sn -T <assembly>

    Replace <assembly> with the assembly name, such as ClassLibrary1.dll.

  4. Press Enter and note the public token key that is displayed.

To include the add-in on the Control Add-ins page

  1. In the Microsoft Dynamics NAV Windows client, in the Search box, enter Control Add-ins, and then choose the relevant link.

  2. On a new row, in the Control Add-ins page, enter the Control Add-in name, and the Public Key Token.

    In this walkthrough, the add-in name is MyCompany.MyProduct.FieldPopupAddin.

  3. Choose the OK button to close the Control Add-ins page.

Setting Up the Add-in on a Page

In this section, you will modify the Customer Card page to use the new add-in on the name field. This involves the following tasks:

  • Setting the ControlAddin Property of the field to the add-in.

  • Setting the OnControlAddin Trigger.

    In the C/AL Editor, you set the trigger that is called when a user selects the field to open a pop-up window. When a field is double-clicked, the add-in raises the Microsoft.Dynamics.Framework.UI.Extensibility.IEventControlAddInDefinition.ControlAddIn event, which in turn calls the trigger.

To set the ControlAddIn property on the field

  1. In Microsoft Dynamics NAV, in Object Designer, choose Page.

  2. Select page 21, Customer Card, and then choose Design.

  3. In the Page Designer, in the Name column, select the Name field, and then on the View menu, choose Properties.

  4. In the <Name> Properties window, in the Property column, locate ControlAddIn.

  5. In the Value column, choose the up arrow, and then select MyCompany.MyProduct.FieldPopupAddin from the Client Add-in window. Choose the OK button to close the Client Add-Ins window. The public key token is inserted into the Value field.

  6. Close the Properties window.

To set the add-in trigger in the C/AL Code

  1. On the View menu, choose C/AL Code.

  2. In the Page 21 Customer card -C/AL Editor, locate the following trigger.

    Copy Code
    Name - OnControlAddIn(Index : Integer;Data : Text[1024])

  3. Add the following code.

    Copy Code
    Message(Data);

  4. Close the C/AL Editor.

  5. On the File menu, choose Save, select the Compiled check box, and then choose the OK button.

  6. Close the C/AL window.

To test the add-in

  1. In Object Designer, choose Page. In the Name column, select the Customer Card page, and then choose Run. The customer card view is displayed. Notice the color of the Name field.

  2. Double-click the Name field. The contents of the Name field are displayed in a pop-up window.

  3. On the Action menu, choose Next until you find a name that extends beyond the field size, and then double-click the field. All of the content for the field is displayed in a pop-up window.

See Also

Tasks

How to: Create a Windows Client Control Add-in
How to: Determine the Public Key Token of the Windows Client Control Add-in and .NET Framework Assembly
How to: Install a Windows Client Control Add-in Assembly
How to: Register a Windows Client Control Add-in
How to: Set Up a Windows Client Control Add-in on a Page

Concepts

Windows Client Control Add-in Overview
Developing Windows Client Control Add-ins
Client Extensibility API Overview
Binding a Windows Client Control Add-in to the Database
Exposing Events and Calling Respective C/AL Triggers from a Windows Client Control Add-in
Installing and Configuring Windows Client Control Add-ins on Pages


Interactive Timeline Business Data Visualization

The Interactive Timeline Business Data Visualization for Microsoft Dynamics NAV provides a unique view on business data with an interactive user interface (UI) to change the business data. It targets the class of business data that represents a series of changes that measures value over time, such as:

  • The future inventory level of an item from known and expected supply and demand events.

  • The balance of an account over time, as influenced by the account-related transactions.

The visualization helps identify periods of time during which the value falls under zero. You can add multiple horizontal target lines to the visualization for additional visual comparison with target levels. You can also visually mark special dates, such as today, or a work date.

Chart of the projected inventory for item bicycle

Visualization lets you compare multiple what-if scenarios, for example, by taking a certain forecast into consideration.

Visualization also includes an interactivity option. Interactivity allows a user to change the amount and date of a transaction directly in the visualization by dragging the visual point of a transaction to the new amount or new date. The changed transaction will be tagged visually with the nature of the changes. The projected result of the change will be shown immediately.

Characteristics of the Business Data Visualization

The Interactive Timeline Business Data Visualization provides a visual representation of the data that is transformed into a mental model. This lets users understand the influence of transactions over time, on a certain measure. The visualization provides insight into business transactions by displaying the projected aggregated consequences over time. It visually highlights problematic situations, such as time periods and amounts that go under zero. Optionally, it provides visual comparisons of defined amounts throughout the time period.

The visualization provides interactive access to amounts and schedule of transactions in the graphical presentation. It also lets you create new transactions and delete existing transactions. The visualization shows the projected consequences on the observed measure when you modify the transactions in the visualization, before the changes have been posted to the business logic.

The business data visualizations are characterized by the following pillars.

Pillar | Description
Picture the business (delivers mental models) | Visualizations provide a mental model for business data and data dependencies. By seeing a visual representation of data and dependencies, even non-expert users can more easily understand business data.
Understand the business; know state and trends (provides insight) | Visualizations are an entry point for understanding the current state of a business and trends. Users can drill down and filter data to provide intuitive, ad hoc analysis.
Know how to act (identifies actionable items and tasks) | Users can use business data to find items of interest and outliers that are based on certain objectives or measures. The outliers can be converted into high-priority actionable tasks and possible actions.
Act wisely (provides decision support, problem solvers, and optimization) | Problem solvers and optimizers help users decide on a strategy. They can provide suggestions for an action strategy that could lead to an optimal result for one or more objectives.
Understand consequences (visualizes consequences before acting) | Visualizations help users to understand the effect of actions before they are committed. Visualizers can explain dependencies, predict the outcome of actions, and provide visualizations to users.

See Also

Concepts

Interactive Timeline Business Data Visualization Overview
Extending the Windows Client Using Control Add-ins


Interactive Timeline Business Data Visualization Overview

This topic provides an overview of the various features in the timeline visualization add-in.

Visual Overview of Timeline Visualization Add-in

Description | Example
Shows filled step lines that indicate quantity over time. Low quantity is shown with a dotted fill. Place the mouse pointer over the corner points of steps to see information about transactions. | Dotted fill
Shows three inventory scenarios that can be compared in any combination, such as booked transactions, forecast, and changes from planning activities. The color saturation automatically changes for visual comparison, but still maintains consistency. |
Scroll and zoom in on data by using your mouse or keyboard. Each transaction is marked by a green circle. To see information about the transaction, place the mouse pointer over the green circle. Icons above the circle indicate that the transaction has changed from its original state, for example, an amount has decreased or a date has changed. To zoom in or out on a range, press Ctrl, while you rotate the wheel button of your mouse. To return to the original view, press Ctrl+0 (zero). | Green circle with zoom
Shows the chart axis label rendering with date anchor, dynamic month, and day label density. | Chart axis
Provides a reusable set of supply transaction types (initial/supply/demand; fixed/adjustable/expected). You can use this visualization for other application scenarios. | Transaction types
Change supply quantity and schedule in the chart by dragging data points interactively. Other levels affected by changes are automatically adjusted. The chart visualizes the combination of changes to each transaction that result from interactions, such as, rescheduling to an earlier or later date, increasing or decreasing supply/demand, deleting, or creating a new transaction. | Dragging data points
Access macro functions for interactive charting through the right-click menu. Macro functions are create, read, update, and delete (CRUD) operations. An automatic adjustment function changes a supply to balance the inventory until the next supply. | Shortcut menu options

See Also

Concepts

Interactive Timeline Business Data Visualization
Extending the Windows Client Using Control Add-ins


Using the PingPong Add-in

The Microsoft Dynamics NAV PingPong add-in can be invoked to request a callback after a specified timeout. The PingPong add-in does one callback on request. The callback is requested from C/AL code by specifying the time to wait in milliseconds.

Note
Using the PingPong add-in instead of a timer is recommended, because you can run all of the C/AL code on the trigger. If you use a server timer, you cannot trigger events on the client.

Using PingPong Events

Copy Code
PingPong::AddInReady()
      CurrPage.PingPong.Ping(500);

Copy Code
PingPong::Pong()
      CurrPage.PingPong.Ping(1000);


Extending Any Microsoft Dynamics NAV Client Using Control Add-ins

With Microsoft Dynamics NAV you can write control add-ins that add custom functionality to Role Centers and pages on all display targets, using the same extensibility framework. The following sections provide an overview of the documentation that is available to develop and use control add-ins.

Control add-ins that are designed with Microsoft Dynamics NAV 2013 R2, Microsoft Dynamics NAV 2015, or Microsoft Dynamics NAV 2016 using a .NET 4.5 assembly and a manifest file, can be used on all display targets. Control add-ins that were written for earlier versions, will still run on the Microsoft Dynamics NAV Windows client.

Note
Javascript-based client add-ins in repeater controls, such as lists, listparts, list subpages, and worksheets, are not supported on any of the Microsoft Dynamics NAV clients.

Getting an Overview of Client Control Add-ins

To | See
Get a general overview about client control add-ins and where they fit in the Microsoft Dynamics NAV 2016 architecture. | Extending Any Microsoft Dynamics NAV Client Using Control Add-ins
Go through an example of how to implement a simple control add-in, creating a .NET assembly, a manifest file, and a page to display the control add-in from. | Walkthrough: Creating and Using a Client Control Add-in
Review an example of a manifest file. | Manifest Overview
Get reference Help on the available methods for the extensibility framework. | InvokeExtensibilityMethod Method, GetImageResource Method, and GetEnvironment Method.

See Also

Reference

Control Add-ins

Concepts

Developing for the Microsoft Dynamics NAV Universal App
Developing for the Microsoft Dynamics NAV Web Client


Walkthrough: Creating and Using a Client Control Add-in

This walkthrough demonstrates how to create a Microsoft Dynamics NAV control add-in and use it on a Microsoft Dynamics NAV page. A client control add-in enables you to add custom functionality to the Microsoft Dynamics NAV Windows client and the Microsoft Dynamics NAV Web client by creating a control add-in that can run on both client platforms.

Important
This walkthrough addresses the Microsoft Dynamics NAV implementation of extensibility. This makes it possible to write control add-ins for all display targets. For information about how to write control add-ins specifically for Microsoft Dynamics NAV Windows client, see Extending the Windows Client Using Control Add-ins.

In a typical business scenario, developers create control add-ins using Microsoft Visual Studio Express, or Visual Studio 2013. Implementers of Microsoft Dynamics NAV solutions then use the control add-ins on Microsoft Dynamics NAV client pages, such as the Microsoft Dynamics NAV Windows client, the Microsoft Dynamics NAV Web client, or the Microsoft Dynamics NAV Tablet client.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV with a developer license. For more information, see System Requirements for Microsoft Dynamics NAV 2016.

  • CRONUS International Ltd. demonstration database.

  • Microsoft Visual Studio Express or Microsoft Visual Studio 2013.

  • Microsoft .NET Strong Name Utility (sn.exe). This is included with Windows SDKs.

  • Experience using Visual Studio.

Story

Simon is a software developer working for CRONUS International Ltd. He has been told that the users of the Microsoft Dynamics NAV Web client want to see Bing Maps displayed on the Web client. He wants to use the client extensibility framework to test how to do this on a separate page first.

Creating a Control Add-in With Visual Studio

Microsoft Dynamics NAV includes the Microsoft.Dynamics.Framework.UI.Extensibility.dll assembly that defines the model for creating Microsoft Dynamics NAV control add-ins. The Microsoft Dynamics NAV API provides the binding mechanism between the Microsoft Dynamics NAV control add-in and the Microsoft Dynamics NAV framework.

To create the control add-in

  1. In Visual Studio, on the File menu, choose New, and then choose Project.

  2. Under Installed Templates, choose Visual C#, and then choose Class Library.

  3. In the Solution Name text box, enter the name of your solution. For example, you can enter BingMapsControlAddIn and then choose the OK button.

  4. You will add a reference to the following assembly: Microsoft.Dynamics.Framework.UI.Extensibility.dll

  5. In Solution Explorer, right-click your project, and then choose Add Reference.

  6. In the Add Reference window, on the Browse tab, navigate to the location of the Microsoft.Dynamics.Framework.UI.Extensibility.dll assembly on your computer, and then choose the OK button. By default, the path of the assembly is C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client.

  7. Open the Class1.cs file and add the following using directive.

    Copy Code
    using Microsoft.Dynamics.Framework.UI.Extensibility;

  8. In the BingMapsControlAddIn namespace, add the following code to declare a new interface named BingMapsControlAddIn.

    Copy Code
    namespace BingMapsControlAddIn
{
    [ControlAddInExport("BingMapsControl")]
    public interface IBingMapsControlAddIn
    {
        [ApplicationVisible]
        event ApplicationEventHandler ControlAddInReady;
        [ApplicationVisible]
        event ApplicationEventHandler MapLoaded;
        [ApplicationVisible]
        void LoadMap(double latitude, double longitude);
        [ApplicationVisible]
        void ShowMiniMap(bool show);
        [ApplicationVisible]
        void ShowPushpin(string title, string imageName);
    }
}

  9. You will use the name BingMapsControl later in the walkthrough when you register the control add-in in Microsoft Dynamics NAV.

The assembly must now be signed to be used with Microsoft Dynamics NAV. The next steps will discuss how to sign the assembly.

To sign the assembly

  1. In Visual Studio, on the Project menu, choose BingMapsControlAddIn properties.

  2. In the Properties window, choose Signing, and then select the Sign the assembly check box.

  3. In the Choose a strong name key file drop-down list, select New.

  4. In the Key file name text box, enter BingMapsControlAddIn, and then clear the Protect my key file with a password check box.

  5. Choose the OK button.

  6. In Solution Explorer, notice the BingMapsControlAddIn.snk file that is added in Solution Explorer.

  7. On the Build menu, choose Build <Your Solution> to build the project. Verify that the build succeeds.

Copying the Control Add-in Assembly to the Microsoft Dynamics NAV Development Environment

After you build the control add-in, you copy the output assembly file to the computer that is running the development environment.

To copy the control add-in assembly to the Microsoft Dynamics NAV Development Environment

  1. On the computer, locate and copy the control add-in assembly file (.dll) file in the control add-in project’s output folder.

  2. By default, this folder is C:\Documents\MyDocuments\Visual Studio\Projects\[Your Addin Project]\[Your Class Library]\bin\Debug.

  3. On the computer that is running the development environment, paste the assembly in the Add-ins folder.

    By default, this folder is C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client\Add-ins.

Creating the Manifest File

After you create an interface in Visual Studio that exposes a number of properties for the BingMapsControlAddIn, you must create a manifest file. A manifest file is written in XML and contains information such as where to look for resource files, references to external JavaScripts, and the size of the control add-in. For more information, see Manifest Overview. In the next steps, you will create a manifest file that loads a BingMaps control and you will register this manifest in the Client Add-in page.

To create the manifest file

  1. Copy this sample manifest and paste it into any text editor.

    Copy Code
    <?xml version="1.0" encoding="utf-8"?>
<Manifest>
    <Resources>
        <Script>Script.js</Script>
    </Resources>
    <ScriptUrls>
      <ScriptUrl>http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.3</ScriptUrl>
    </ScriptUrls>

    <Script>
        <![CDATA[
           InitializeMap('controlAddIn');
           Microsoft.Dynamics.NAV.InvokeExtensibilityMethod('ControlAddInReady', null);
        ]]>
    </Script>

    <RequestedHeight>300</RequestedHeight>
    <RequestedWidth>700</RequestedWidth>
    <VerticalStretch>false</VerticalStretch>
    <HorizontalStretch>false</HorizontalStretch>
</Manifest>

  2. Save the manifest to a file that is in same directory that the assembly is saved in, the Add-ins directory.

    Name the manifest Manifest and make sure to add the .xml extension to the file, so that the file name will now be Manifest.xml.

The next step is to create a JavaScript file containing code that calls C/AL in Microsoft Dynamics NAV.

Creating a JavaScript File

Now you must create a JavaScript file to hold all of the code that calls C/AL in Microsoft Dynamics NAV.

To create the JavaScript file

  1. Copy this sample script and paste it into any text editor.

    Copy Code
    var map = null;
    function InitializeMap(controlId) {
        map = new VEMap(controlId);
        map.HideScalebar();
        map.onLoadMap = function () {
        Microsoft.Dynamics.NAV.InvokeExtensibilityMethod ('MapLoaded', null);
        };
    }
    function LoadMap(latitude, longiture) {
        var mapOptions = new VEMapOptions();
        mapOptions.DashboardColor = "black";
        mapOptions.EnableSearchLogo = false;
        map.LoadMap(
            new VELatLong(latitude, longiture), // Center
            1,                                  // Zoom level 1-19
            VEMapStyle.Birdseye,                // Map style
            false,                              // Fixed map
            VEMapMode.Mode2D,                   // Map mode
            true,                               // Map mode switch
            0,                                  // Tile buffer
            mapOptions                          // Options
        );
    }
    function ShowMiniMap(show) {
        if (show)
            map.ShowMiniMap();
        else
            map.HideMiniMap();
    }
    function ShowPushpin(title, imageName) {
        map.Clear();
        if (title != '') {
            var point = map.GetCenter();
            var pushpin = map.AddPushpin(point);
            pushpin.SetTitle(title);
        }
    }

  2. Save and name the script Script and make sure to add the .js extension to the file, so that the file name will now be Script.js.

The next step is to create a .zip file containing the manifest and resource files and register this file with the control add-in in Microsoft Dynamics NAV.

Creating a Resource .Zip File

Before registering the control add-in in Microsoft Dynamics NAV, you must create one single file containing the manifest and any resource files. This single file is a .zip file and it will be registered in the Client Add-in page. The .zip file must contain a certain structure for it to be recognized by the Client Add-in page. In the next steps, you will create the right structure and a .zip file.

To create a resource .zip file

  1. On your computer, in a folder of your own choice, create the following folder structure: Image, Script, and StyleSheet.

  2. Locate the Manifest.xml file that you created in the previous steps, and copy this to the same folder structure. Then locate the Script.js file that you created in the previous steps, and copy this to the Script folder. Your folder should now look like this:

    Folder structure before creating the .zip file

  3. Place images, scripts, and stylesheets in the right folders, but in this walkthrough we will leave the rest of these folders empty.

  4. In the Windows Explorer mark all of the folders and the manifest file and right-click, and then choose Send to…, and then choose Compressed (zipped) folder.

  5. Name the .zip file BingMapsControlAddIn.

Registering the Control Add-in in Microsoft Dynamics NAV

To register a control add-in, you include it in the Control Add-in page in Microsoft Dynamics NAV. To include a control add-in in the page, you must provide the following information:

  • Control Add-in name.

    The control add-in name is determined by the Microsoft.Dynamics.Framework.UI.Extensibility.ControlAddInExport attribute value of control add-in class definition that you specified when you created the control add-in. The name in this walkthrough is BingMapsControl.

  • Public key token.

    This is a 16-character key that is given to the assembly when it is signed and built in Visual Studio. You can determine the public key token by running the Microsoft .NET Strong name Utility (sn.exe) on the assembly. You must run the utility from the Visual Studio command prompt. The sn.exe utility is available with Visual Studio.

  • Resource.

    On the Control Add-in page, the Resource field is a BLOB data type and the content of the field cannot be viewed from the development environment.

    When this field is filled in, Microsoft Dynamics NAV identifies the registered control add-in as a type of control add-in that works on all display targets.

To determine the public key token for the control add-in

  1. On the Windows taskbar, choose Start, choose All Programs, choose Microsoft Visual Studio 2013, choose Visual Studio Tools, and then choose Developer Command Prompt for VS2013 to open the command prompt.

  2. At a command prompt, change to the directory that contains the assembly that you copied. For example, C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client\Add-ins.

  3. Type the following command: sn -T <assembly>

    Replace <assembly> with the assembly name, such as BingMapsControlAddIn.dll.

  4. Press Enter and note the public token key that is displayed.

To include the control add-in in the Control Add-in page

  1. Open Microsoft Dynamics NAV.

  2. In the Search box, enter Control Add-ins and then choose the related link.

  3. In the Control Add-ins window, choose New, and then in the Control Add-in Name column, enter the control add-in name. In the Public Key Token column, enter the public key token that you obtained earlier.

With the Control Add-in window still open, you will now import the .zip file for the BingMapsControlAddIn add-in.

To include the .zip file in the Control Add-in page

  1. Choose Import.

  2. In the Import Control Add-in Resource window, locate the BingMapsControlAddIn.zip file that you saved earlier, and then choose Open.

  3. Choose the OK button to close the Control Add-in page.

Creating a Page to Display the Control Add-in

You have set up the prerequisites for using a control add-in from a page. Now you need a way to display the BingMapsControlAddIn control. In this section, you will create a new page called Bing Maps that contains two fields to control the coordinates of the map and one field that contains the map control. This involves the following tasks:

  • Creating a new page called Bing Maps.

  • Setting variables and properties.

  • Adding C/AL triggers.

To create the Bing Maps page

  1. In the Microsoft Dynamics NAV Development Environment, in Object Designer, choose Page, and then choose New.

  2. In the New Page dialog, choose Create blank page and then choose the OK button.

  3. In Page Designer, on the first line, in the Name column, enter Control1, and go to the next line.

  4. In the Type column, choose Group, and in the Caption column, enter Coordinates.

  5. On a new line, in the Type column, choose Field. In the Name column, enter LatitudeControl, and in the Caption column, enter Latitude.

  6. On a new line, in the Type column, choose Field. In the Name column, enter LongitudeControl, and in the Caption column, enter Longitude.

  7. On a new line, choose Group, and in the Caption column, enter Map.

  8. On a new line, under the Map group, for the Type column set to Field, in the Name column, enter Bing Maps Control.

    Your page design should now look like this.

    The page design for the Bing Maps control

  9. Save and compile the page. Name the page Bing Maps.

Now you have created a page skeleton. The next step is to add code and call the control add-in from a control on the page.

To add variables and properties

  1. In the Microsoft Dynamics NAV Development Environment, in Object Designer, choose Page, and then choose the Bing Maps page.

  2. On the Tools menu, choose View, and then C/AL Globals.

  3. On the Variables tab, enter Latitude in the Name column, and set the DataType to Decimal.

  4. Create a new variable. Enter Longitude in the Name column, and set the DataType to Decimal.

  5. Create a new variable. Enter MiniMap in the Name column, and set the DataType to Boolean.

  6. Close the C/AL Globals window.

  7. In Page Designer, on LatitudeControl, set SourceExpr to Latitude in the C/AL Symbol Menu.

  8. On LongitudeControl, set SourceExpr to Longitude in the C/AL Symbol Menu.

  9. Select the BingMapsControl field, and then on the View menu, choose Properties.

  10. In the Properties window, locate the ControlAddIn property and choose the Up Arrow. Select the BingMapsControl control add-in from the Client Add-in window.

  11. Choose the OK button to close the Client Add-In window. The public key token is inserted into the Value field. Close the Properties window.

To add C/AL triggers

  1. With the Bing Maps page open in Object Designer, on the View menu, choose C/AL Code.

  2. In the Page Bing Maps - C/AL Editor window, locate the BingMapControl::ControlAddInReady() trigger, and add the following line of code.

    Copy Code
    CurrPage.BingMapControl.LoadMap(Latitude, Longitude);

  3. In the Page Bing Maps - C/AL Editor window, locate the BingMapControl::MapLoaded() trigger, and add the following line of code.

    Copy Code
    CurrPage.BingMapControl.ShowMiniMap(MiniMap);

  4. Finally, locate the OnInit() trigger, and add the following line of code.

    Copy Code
    Latitude := 40.689467;
Longitude :=  74.044444;

  5. Save and compile the Bing Maps page.

After you have saved and compiled the Bing Maps page, you can run the page directly from the development environment to verify that it works on the Microsoft Dynamics NAV Web client. For more information, see Opening a Page in the Microsoft Dynamics NAV Web Client by Using a URL.

Next Steps

Now you have created a Client Control Add-in that runs on the Microsoft Dynamics NAV Windows client, the Microsoft Dynamics NAV Web client, and the Microsoft Dynamics NAV Tablet client. A next step could be to implement a control add-in on an existing page or on the Role Center to display a Bing Map of where customers are located.

See Also

Concepts

Extending Microsoft Dynamics NAV Using Control Add-ins
Extending Any Microsoft Dynamics NAV Client Using Control Add-ins


Manifest Overview

For a control add-in to work on all display targets there has to be a manifest. The manifest contains a declarative description of the control add-in and is written in XML. The manifest is added together with any resource files in a .zip file and registered with the control add-in resources in the Client Add-in page. This topic explains the structure of a manifest by using an example of the manifest for the Bing Maps control add-in. For more information about the implementation of the Bing Maps control add-in, see Walkthrough: Creating and Using a Client Control Add-in.

Example of a Manifest

The syntax of a manifest file is illustrated in the following example. All tags inside the <manifest> tag are optional. Inside the <Manifest> tag, the <ScriptUrls> tag references other JavaScripts from the manifest. In this case the <ScriptUrls> tag points to online map controls. Inside the <Resources> tag, all of the resources such as the script, style sheet, and images that are required to display the Bing Maps control add-in are listed.

The <Script> tag contains the actual initialization code for the control add-in. The code must be written inside a <![CDATA[]]> tag to be parsed as code. The Microsoft.Dynamics.NAV.InvokeExtensibilityMethod is described in more detail in the reference documentation. For more information, see InvokeExtensibilityMethod Method.

Inside the <Manifest> tag, at the end of the script, the <RequestedHeight> and the <RequestedWidth> tags are set to definite sizes. It is recommended to apply some size to the add-in using these tags. The properties <VerticalStretch> and <HorizontalStretch> determine how the control add-in behaves in the client when the window it is displayed in is resized. The default value is false which means that the control add-in is not resized vertically, or horizontally. The value true means that the control add-in is resized vertically, or horizontally. The values in <RequestedHeight> and <RequestedWidth> determine the minimum resize value of the control add-in.

Copy Code
<?xml version="1.0" encoding="utf-8"?>
<Manifest>
    <Resources>
        <Image>PushpinBlue.png</Image>
        <Image>PushpinGreen.png</Image>
        <Image>PushpinRed.png</Image>
        <Script>Script.js</Script>
        <StyleSheet>StyleSheet.css</StyleSheet>
    </Resources>
    <ScriptUrls>
        <ScriptUrl>http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.3</ScriptUrl>
    </ScriptUrls>

    <Script>
        <![CDATA[
            InitializeMap('controlAddIn');
            Microsoft.Dynamics.NAV.InvokeExtensibilityMethod('ControlAddInReady', null);
        ]]>
    </Script>

    <RequestedHeight>300</RequestedHeight>
    <RequestedWidth>700</RequestedWidth>
    <MinimumHeight>200</MinimumHeight>
    <MinimumWidth>400</MinimumWidth>
    <MaximumHeight>800</MinimumHeight>
    <MaximumWidth>1000</MinimumWidth>
    <VerticalStretch>true</VerticalStretch>
    <HorizontalStretch>true</HorizontalStretch>
    <VerticalShrink>true</VerticalShrink>
    <HorizontalShrink>true</HorizontalShrink>
</Manifest>

Script Code in a Separate File

Code that is called from C/AL code must be put in a separate file under the \Script folder. The code below is called from the manifest file and initializes and loads the map.

Copy Code
var map = null;
    function InitializeMap(controlId) {
        map = new VEMap(controlId);
        map.HideScalebar();
        map.onLoadMap = function () {
            Microsoft.Dynamics.NAV.InvokeExtensiblityMethod('MapLoaded', null);
        };
    }
    function LoadMap(latitude, longiture) {
        var mapOptions = new VEMapOptions();
        mapOptions.DashboardColor = "black";
        mapOptions.EnableSearchLogo = false;
        map.LoadMap(
            new VELatLong(latitude, longiture), // Center
            1,                                  // Zoom level 1-19
            VEMapStyle.Birdseye,                // Map style
            false,                              // Fixed map
            VEMapMode.Mode2D,                   // Map mode
            true,                               // Map mode switch
            0,                                  // Tile buffer
            mapOptions                          // Options
        );
    }
    function ShowMiniMap(show) {
        if (show)
            map.ShowMiniMap();
        else
            map.HideMiniMap();
    }
    function ShowPushpin(title, imageName) {
        map.Clear();
        if (title != '') {
            var point = map.GetCenter();
            var pushpin = map.AddPushpin(point);
            pushpin.SetTitle(title);
        }
    }

Control Add-in HTML Element

When the control add-in is loaded into the Web browser one HTML element is provided for the control add-in to host its content. This HTML element is a DIV element and it is always named controlAddIn.

Copy Code
<div id='controlAddIn'>
    control add-in script code can add content here...
</div>

The following is an example of the script code for a control add-in

Copy Code
function initializeControlAddIn() {
    var controlAddIn = document.getElementById('controlAddIn');
    controlAddIn.innerHTML = "Hello World";
}

Sizing the Control Add-in

To control that the sizing of the control add-in always is optimal, even on smaller display targets, such as the phone, some settings are available when you write the manifest code. The settings make sure that resizing of the control add-in works on all client types.

VerticalShrink specifies that the control add-in can be made smaller vertically. This setting is optional.

Copy Code
bool VerticalShrink()

HorizontalShrink specifies that the control add-in can be made smaller horizontally. This setting is optional.

Copy Code
bool HorizontalShrink()

MinimumHeight specifies the minimum height that the control add-in can be shrunk to. This setting only applies if the VerticalShrink setting is specified.

Copy Code
int MinimumHeight()

MinimumWidth specifies the minimum width that the control add-in can be shrunk to. This setting only applies if the HorizontalShrink setting is specified.

Copy Code
int MinimumWidth()

MaximumHeight specifies the maximum height that the control add-in can be stretched to. This setting only applies if the VerticalStretch setting is specified.

Copy Code
int MaximumHeight()

MaximumWidth specifies the maximum width that the control add-in can be stretched to. This setting only applies if the HorizontalStretch setting is specified.

Copy Code
int MaximumWidth()

VerticalStretch specifies that the control add-in can be made larger vertically. This setting is optional.

Copy Code
bool VerticalStretch()

HorizontalStretch specifies that the control add-in can be made larger horizontally. This setting is optional.

Copy Code
bool HorizontalStretch()

RequestedHeight specifies the initial height of the control add-in.

Copy Code
int RequestedHeight()

RequestedWidth specifies the initial width of the control add-in.

Copy Code
int RequestedWidth()

Resource Files

The resource files can be described in the manifest file with or without a relative path; Microsoft Dynamics NAV supports both.

In the following example the files are described by using their file name only:

Copy Code
<Resources>
    <Image>Blue.png</Image>
    <Script>Script.js</Script>
    <StyleSheet>StyleSheet.css</StyleSheet>
</Resources>

To support the example earlier in this section, the resource files must be located in subfolders in the control add-in .zip file by using the following names:

Resource File Type | Resource Name | Subfolder Name
Image file | Blue.png | Image/Blue.png
Script file | Script.js | Script/Script.js
Style sheet file | StyleSheet.css | StyleSheet/StyleSheet.css

In the next example the resource files are described using a relative path in the manifest file:

Copy Code
<Resources>
    <Image>Images/Pushpins/Blue.png</Image>
    <Script>Scripts/Script.js</Script>
    <StyleSheet>StyleSheets/StyleSheet.css</StyleSheet>
</Resources>

To support this example, the resource files must be located in subfolders with the name of the relative path in the control add-in .zip file:

Resource File Type | Resource Name | Subfolder Name
Image file | Images/Pushpins/Blue.png | Images/Pushpins/Blue.png
Script file | Scripts/Script.css | Scripts/Script.css
Style sheet file | StyleSheets/StyleSheet.css | StyleSheets/StyleSheet.css

See Also

Tasks

Walkthrough: Creating and Using a Client Control Add-in

Concepts

Extending Microsoft Dynamics NAV Using Control Add-ins
Extending the Windows Client Using Control Add-ins
Extending Any Microsoft Dynamics NAV Client Using Control Add-ins


InvokeExtensibilityMethod Method

Invokes a C/AL trigger on the Microsoft Dynamics NAV Server on the page that contains the control add-in.

Method Signature

void Microsoft.Dynamics.NAV.InvokeExtensibilityMethod(name, arguments, skipIfBusy, callback)

Parameters

Parameter | Description
name | Type: String A string that contains the name of the C/AL trigger to invoke on the Microsoft Dynamics NAV Server. This must be the name of the event specified in the .NET interface using the [ApplicationVisible] attribute that defines the control add-in.
arguments | Type: Array An array that contains the arguments to pass to the C/AL trigger. Note that the arguments must be supplied in an array even when the trigger only takes one argument.
skipIfBusy | Type: Boolean A value to indicate whether to invoke the extensibility method if the client is busy. This parameter is optional and the default value is false.
callback | Type: function A function that is called when the extensibility method has finished execution on the server. This parameter is optional.
Important
The callback function is useful for synchronizing multiple calls to the server. This is used, for example, when transferring multiple data blocks to the server to prevent overflowing the communication channel between the client and the server.

Callback Function Syntax

The syntax of the callback function is the following:

function callback()

skipIfBusy Options

The following table illustrates the different settings of skipIfBusy combined with the client’s status.

skipIfBusy set to | Client is busy | Action
false | false | Method call invoked.
false | true | Method call is queued and will be invoked once the client is no longer busy.
true | false | Method call invoked.
true | true | No method call.

Example

For a detailed code example, see Walkthrough: Creating and Using a Client Control Add-in

Copy Code
var map = new VEMap('controlAddIn');
    map.onLoadMap = function () {
    var arguments = [map.GetCenter()];
    Microsoft.Dynamics.NAV.InvokeExtensibilityMethod('MapLoaded', arguments);
    };
    map.LoadMap(...);


GetImageResource Method

Used to get the URL for an image resource specified in the control add-in manifest. The image resource is stored in the NAV database as part of the .zip file for the control add-in and is exposed to the control add-in script running on the Microsoft Dynamics NAV client using the URL that this function returns.

Method Signature

string Microsoft.Dynamics.NAV.GetImageResource(imageName)

Parameters

Parameter | Description
imageName | Type: String A string that contains the name of the image resource to get a URL for. The image name is the name that is used in the control add-in manifest to reference the image.

Return Value

Type: String

Returns a URL for the specified image resource.

Example

For a detailed code example, see Walkthrough: Creating and Using a Client Control Add-in

Copy Code
var map = new VEMap('controlAddIn');
    map.LoadMap(...);
    var pushpin = map.AddPushpin(map.GetCenter());
    var imageUrl = Microsoft.Dynamics.NAV.GetImageResource('PushpinImage.png');
    pushpin.SetCustomIcon("<div><img src='" + imageUrl +"'/></div>");

See Also

Reference

InvokeExtensibilityMethod Method


Asynchronous Considerations

Writing control add-ins that work on all display targets, you have to consider some limitations regarding asynchronous communication. Compared to the Microsoft Dynamics NAV Windows client control add-in extensibility framework, the Microsoft Dynamics NAV framework has some limitations regarding the interface of the control add-in. The limitations come from the nature of the asynchronous communication between the clients and the Microsoft Dynamics NAV Server. All calls between the C/AL code running on the Microsoft Dynamics NAV Server and the script function running in the Web browser are asynchronous. This means that methods in the control add-in interface must be of type void and property methods should not be used.

To transfer a result from a C/AL trigger to the calling script function, just add a method to the control add-in interface that the C/AL trigger can invoke to send the result to the script.

To transfer a result from a script function to C/AL trigger, just add an event to the control add-in interface that the script function can use to invoke a C/AL trigger that receives the result.

See Also

Tasks

Walkthrough: Creating and Using a Client Control Add-in

Reference

InvokeExtensibilityMethod Method
GetImageResource Method

Concepts

Extending Microsoft Dynamics NAV Using Control Add-ins


GetEnvironment Method

Gets information about the environment that the control add-in is using.

Method Signature

object Microsoft.Dynamics.NAV.GetEnvironment()

Return Value

Returns an object that contains the following members:

Member Description

UserName

Type: String

The name of the user that is logged into the Microsoft Dynamics NAV Server.

CompanyName

Type: String

The name of the company that the current user is using on the Microsoft Dynamics NAV Server.

DeviceCategory

Type: Integer

An integer indicating the type of device that the control add-in is being rendered on. Possible values:

0 - Desktop client, either Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client.

1 - Microsoft Dynamics NAV Tablet client.

2 -Microsoft Dynamics NAV Phone client.

Busy

Type: Boolean

A boolean indicating whether the client is currently busy. The client could, for example, be busy performing an asynchronous call to the server.

OnBusyChanged

Type: Function

A function that is called when the Busy state of the client has changed.

Function Syntax

The syntax of the function is the following:

function callback()

Platform

Type: Integer

An integer indicating the underlying platform that the control add-in is being rendered on. Possible values:

0 -Microsoft Dynamics NAV Windows client.

1 -Microsoft Dynamics NAV Web client, Microsoft Dynamics NAV Tablet client, or Microsoft Dynamics NAV Phone client in a browser.

2 -Microsoft Dynamics NAV Universal App.

Example

This code example illustrates how you can assign members of the object return type to variables and use the Busy member to determine whether the client is busy or not.

Copy Code
var environment = Microsoft.Dynamics.NAV.GetEnvironment();
var userName = environment.UserName;
var companyName = environment.CompanyName;
environment.OnBusyChanged = function()
{
    if (environment.Busy) {
        // The client is now busy.
    }
    else {
        // The client is not busy anymore.
    }
}

See Also

Reference

InvokeExtensibilityMethod Method
GetImageResource Method

Concepts

Extending Any Microsoft Dynamics NAV Client Using Control Add-ins
Asynchronous Considerations


Developing for the Microsoft Dynamics NAV Web Client

Microsoft Dynamics NAV Web client is a web-based application that lets users interact with Microsoft Dynamics NAV data over the network from a web browser. The Microsoft Dynamics NAV Web client user interface resembles the Microsoft Dynamics NAV Windows client. Use the following guidelines to develop Microsoft Dynamics NAV Web client applications.

  • Understand the Business Scenario

  • Design the Data Model

  • Install the Development Tools

  • Create Microsoft Dynamics NAV Objects

  • Create Users and Grant Permissions to Objects

  • Create Profiles and Assign Users

Understand the Business Scenario

You must understand and define the business problem or scenario that you want your application to solve. It is helpful to know who will be using the application and what they will be trying to accomplish. Compared to the Microsoft Dynamics NAV Windows client, the Microsoft Dynamics NAV Web client is designed for occasional users who typically need an overview of their daily work status and perform relatively simple or light data entry. The Microsoft Dynamics NAV Web client does not support all the features that the Microsoft Dynamics NAV Windows client does.

Design the Data Model

After you understand the problem that you want your application to solve, you must design the structure of the database for your application. For more information about how to design the data model, see the following topics:

  • Designing Databases (SQL Server)

  • Database Basics (SQL Server)

Install the Development Tools

  • Microsoft Dynamics NAV Development Environment

    You use the development environment to create objects, such as tables, pages and reports, and implement the business logic for your application.

    For more information, see How to: Install C/SIDE Development Environment.

  • Microsoft Dynamics NAV Windows client (optional)

    There are many administration and operational tasks, such as creating profiles, setting users, and publishing web services, which cannot be done by using the development environment. Although you can use the Microsoft Dynamics NAV Web client for performing these tasks, it is sometimes easier and more efficient to use the Microsoft Dynamics NAV Windows client. Also, to configure or personalize the Microsoft Dynamics NAV Web client interface, you must use the Microsoft Dynamics NAV Windows client.

    For more information, see Client Option.

  • Microsoft Dynamics NAV Server Administration tool (optional)

    The Microsoft Dynamics NAV Server Administration tool is a Microsoft Management Console (MMC) snap-in that you can use to manage the Microsoft Dynamics NAV Server instance that is used by the Microsoft Dynamics NAV Web client.

    For more information, see Microsoft Dynamics NAV Server Administration Tool.

Create Microsoft Dynamics NAV Objects

The development experience for the Microsoft Dynamics NAV Web client application is like Microsoft Dynamics NAV Windows client. You use the Microsoft Dynamics NAV Development Environment to create Microsoft Dynamics NAV objects to support the logic for the business scenario. Some of the major tasks include the following:

  • Creating table objects in Microsoft Dynamics NAV to implement the design of your database.

  • Creating pages for entering and retrieving data.

  • Creating reports for viewing and presenting data.

  • Writing C/AL code on object triggers to perform runtime operations.

As you develop Microsoft Dynamics NAV Web client applications, you should consider the following factors.

  • The same objects can be used in the Microsoft Dynamics NAV Windows client and the Microsoft Dynamics NAV Web client.

  • The Microsoft Dynamics NAV Web client supports most of the features that the Microsoft Dynamics NAV Windows client supports, but there are some exceptions and limitations, which you must consider in your design. For more information, see Feature Limitations of the Microsoft Dynamics NAV Web Client.

  • Do you want your solution to be available on Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client as well? For more information, see Developing for the Microsoft Dynamics NAV Universal App.

For more information about how to develop Microsoft Dynamics NAV objects for Microsoft Dynamics NAV Web client applications, see Development.

Follow the Microsoft Dynamics NAV User Experience Guidelines

The Microsoft Dynamics NAV User Experience guidelines can help you develop high quality and consistent applications. The guidelines provide answers to specific user experience issues, such as determining which page type to use or which components to include on a page. You can use the guidelines to design new application or improve existing ones.

For more information, see Microsoft Dynamics NAV User Experience Guidelines in the MSDN Library.

Create Users and Grant Permissions to Objects

Like the Microsoft Dynamics NAV Windows client, you restrict access to Microsoft Dynamics NAV data by creating users in Microsoft Dynamics NAV and applying permission sets that grant access to Microsoft Dynamics NAV objects, such as pages and reports. You do not have to create separate user accounts for the Microsoft Dynamics NAV Web client and Microsoft Dynamics NAV Windows client. The same permission sets are applied to the user in both clients.

For more information, see Managing Users and Managing Permissions and Permission Sets.

Create Profiles and Assign Users

Profiles are collections of Microsoft Dynamics NAV users who share the same Role Center. You create a profile and then assign users to the profile. The profile is applied to the user in all clients.

For more information, see Profiles and Role Centers.

See Also

Concepts

Deploying the Microsoft Dynamics NAV Web Server Components
Application Design Overview
Accessibility Features of Microsoft Dynamics NAV Windows Client


Configuring and Personalizing the Microsoft Dynamics Web Client

A Microsoft Dynamics NAV page can consist of several different elements, such as FactBoxes, FastTabs, a Filter pane, actions, and more. Like the Microsoft Dynamics NAV Windows client, you can customize pages that display in the Microsoft Dynamics NAV Web client so that some elements are not shown. This lets you hide nonessential information and limit the space that a page occupies on the website. The difference with the Microsoft Dynamics NAV Web client is that you cannot perform customization tasks directly from the Microsoft Dynamics NAV Web client. Instead, you perform the customization tasks in the Microsoft Dynamics NAV Windows client, which means that any customization that is performed applies to both the Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client.

Note
Personalization by users is not supported by the Microsoft Dynamics NAV Web client. If a user has customized the Microsoft Dynamics NAV Windows client, then the custom settings are ignored for the user in the Microsoft Dynamics NAV Web client.

Configuring the Microsoft Dynamics Web Client

Configuration is typically performed by an administrator, SUPER user, or Microsoft Certified Partner. This person configures the pages based on a profile, which means that the customizations will be seen in the Microsoft Dynamics NAV Web client by all users who are assigned to the profile. For example, on the Sales Order List page for users who belong to the ORDER PROCESSOR profile, you can hide the FactBox area or decrease the number of columns that are shown in the list.

To configure the Microsoft Dynamics NAV Web client, you open the Microsoft Dynamics NAV Windows client in the configuration mode for a profile, and then use the customize feature to show or hide the elements. For more information, see the following topics:

  • How to: Open Microsoft Dynamics NAV in Configuration Mode

  • Working with Role Centers

  • Walkthrough: Configuring UI for the Order Processor Profile

Resetting Configuration Settings

As an administrator or SUPER user, you can reset configuration settings. For more information, see How to: Cancel UI Configuration.

Note
Performing this task affects the users in Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client.

See Also

Configure the User Interface
Personalize the User Interface


Managing Language, Regional Settings, and Time Zone in the Microsoft Dynamics NAV Web Client

This topic describes how to set the language, regional settings, and time zone for the Microsoft Dynamics NAV Web client.

Managing Languages

The Microsoft Dynamics NAV clients support multiple language versions of Microsoft Dynamics NAV. To enable Microsoft Dynamics NAV 2016 in another language, you install the language module for that language. A language module contains translated text strings for the user interface, the Microsoft Dynamics NAV database, and Microsoft Dynamics NAV Server, such as for logs and error reporting. After you install a language module, you configure the Microsoft Dynamics NAV Web Server components to use the language.

Installing a Language Module

You can obtain language modules from Language Modules for Microsoft Dynamics NAV 2013 (requires PartnerSource account). After you obtain a language module, you install its components on the computers that are running the Microsoft Dynamics NAV Web Server components, Microsoft Dynamics NAV Server, and Microsoft Dynamics NAV database.

For information about how to install a language module, see How to: Install Language Modules.

Changing the Language, Region, and Time Zone

You change the language, the region, and the time zone in the Microsoft Dynamics NAV Web client by using the My Settings page located in the upper right corner under the user name that you are signed in with. The regional settings determine the format of data such as dates, times, numbers, currency, and so on. The time zone specifies the time zone that is applied to date and time data that a user views or enters in the Microsoft Dynamics NAV Web client. You need to sign out and sign in again for the change to take effect.

See Also

My Settings
Selecting a Language

Tasks

How to: Install the Web Server Components
How to: Change the Language in the User Interface

Concepts

Language Modules


How to: Implement the Camera in C/AL

This example illustrates how you can add access to camera to a specific page from the development environment. Adding a camera option to the Item card, for example, lets you take a picture of a specific item and store it with the item. The example implements three actions; Take Picture, Take Picture High Quality, and Take Picture Low Quality on the Customer Card page, but does not include code that saves the picture to the database. For a Microsoft Dynamics NAV implementation of this, see Incoming Documents, for example on the Accounting Manager profile, when you use the Dynamics NAV app on a phone.

Important
The camera access is only available on devices that run the Microsoft Dynamics NAV Universal App and have a camera. This means that camera access is not available from the Microsoft Dynamics NAV Windows client or from a browser.

With the following steps, you will create two variables; the CameraAvailable variable is a Boolean that checks whether the current device has a camera. The Camera variable is a DotNet type that gets instantiated by adding code to the OnOpenPage trigger. Then, you will add actions to the Customer Card page that lets the user start the camera and write the code that is run on these actions. And finally, you will add a new trigger Camera::PictureAvailable to handle the incoming picture.

To implement the camera in C/AL

  1. In the development environment, on the Tools menu, choose Object Designer to open the Object Designer window.

  2. In Object Designer, choose Pages, select the Customer Card (page 21) and choose the Design button.

  3. From the Page Designer window, on the View menu, choose C/AL Globals.

  4. Create the following two variables:

    Variable name DataType SubType

    Camera

    DotNet

    Microsoft.Dynamics.Nav.Client.Capabilities.CameraProvider

    Important
    Choose the Microsoft.Dynamics.Nav.ClientExtensions dll on the Server tab, and then choose Microsoft.Dynamics.Nav.Client.Capabilities.CameraProvider.

    Make sure to set the properties RunOnClient and WithEvents to Yes.

    CameraAvailable

    Boolean

    -

  5. On the View menu, select C/AL Code and in the C/AL Editor locate the OnOpenPage trigger.

  6. Instantiate the Camera variable by adding the following code to the OnOpenPage trigger

    Copy Code
    IF Camera.IsAvailable THEN
BEGIN
  Camera := Camera.Create;
  CameraAvailable := TRUE;
END;

  7. Next, create the page actions. Choose the View menu, and then select Page Actions.

  8. Locate the ActionGroup named Customer and create three actions; TakePicture, TakePictureHigh, and TakePictureLow all of them with the following properties set as shown in the following table.

    Property Value

    Name

    TakePicture

    Visible

    CameraAvailable

    Promoted

    Yes

    PromotedCategory

    Process

    PromotedIsBig

    Yes

    Image

    Camera

  9. Next, you will add the code that is executed on the actions. On the TakePicture OnAction trigger, insert the following line of code:

    Copy Code
    Camera.RequestPictureAsync;

  10. On the TakePictureHigh OnAction trigger, insert the following lines of code:

    Copy Code
    CameraOptions := CameraOptions.CameraOptions();
CameraOptions.Quality := 100;
Camera.RequestPictureAsync(CameraOptions);

  11. On the TakePictureLow OnAction trigger, insert the following lines of code:

    Copy Code
    CameraOptions := CameraOptions.CameraOptions();
CameraOptions.Quality := 10;
Camera.RequestPictureAsync(CameraOptions);

  12. You now need to declare the local variable CameraOptions for the TakePictureHigh and TakePictureLow triggers. From the Page Designer window, on the View menu, choose C/AL Locals.

  13. Create the following variable:

    Variable name DataType SubType

    CameraOptions

    DotNet

    Microsoft.Dynamics.Nav.Client.Capabilities.CameraOptions

    Important
    Choose the Microsoft.Dynamics.Nav.ClientExtensions dll on the Server tab, and then choose Microsoft.Dynamics.Nav.Client.Capabilities.CameraOptions.

  14. You must now add code to handle the picture for when the camera has captured the picture and the picture has been uploaded to the Microsoft Dynamics NAV Server. In the C/AL Editor, on the PictureAvailable trigger, add code so that the PictureAvailable trigger looks like this.

    Copy Code
    Camera::PictureAvailable(PictureName : Text;PictureFilePath : Text)
      IncomingFile.OPEN(PictureFilePath);
      MESSAGE('Picture size: %1', IncomingFile.LEN);
      IncomingFile.CLOSE;
      FILE.ERASE(PictureFilePath);

    The PictureName contains the name of the file including its extension on the device. The naming scheme depends on the device platform. The PictureFilePath contains the path to the picture in a temporary folder on the server for the current user.

    Important
    It is important to clean up by using the FILE.ERASE command to avoid accumulating image files.

  15. Now, you need to declare the local variable IncomingFile used in the PictureAvailable trigger. From the Page Designer window, on the View menu, choose C/AL Locals.

  16. Create the following variable:

    Variable name DataType

    IncomingFile

    File

  17. Close the C/AL Editor, and then save and compile the page.

You can now test the modified Customer Card page in the Microsoft Dynamics NAV Universal App from either a tablet or a phone with a camera. To read more about different options that can be set for the camera, see CameraOptions Overview.

See Also

Concepts

Developing for the Microsoft Dynamics NAV Universal App
Differences and Limitations When Developing Pages for the Microsoft Dynamics NAV Universal App


CameraOptions Overview

When implementing camera access from C/AL, there are some options; Microsoft.Dynamics.Nav.Client.Capabilities.CameraOptions found in the Microsoft.Dynamics.Nav.ClientExtensions dll, that you can use to additionally specify picture quality, source type, and so on. These can optionally be passed to CameraProvider.RequestPictureAsync(options). Some of the options described in this article have been implemented in the example in the How to: Implement the Camera in C/AL topic.

For most scenarios it is not necessary to specify options.

CameraOptions

int Quality

The quality of the saved image expressed as a range from 0 to 100, where 100 is typically full resolution without loss from file compression. Default is 50. Quality is only used if EncodingType is JPEG.

Note
The Quality option is currently not supported on Windows phone.

string SourceType

The source of the picture. Possible values are as follows: Camera and PhotoLibrary. Default is Camera. The options Quality, EncodingType, and AllowEdit are only used if SourceType is Camera.

string MediaType

The type of media to select from. The SourceType option must be PhotoLibrary. Possible values are as follows: Picture, Video, AllMedia. The PhotoLibrary option will pick an already existing picture on the device.

string EncodingType

The encoding of the returned image file. Supported values are as follows: JPEG, PNG. Default is JPEG.

bool AllowEdit

A value indicating whether to enable simple editing of image before selection. Default is FALSE.

Note
The AllowEdit option is currently not supported on Windows phone.

See Also

Tasks

How to: Implement the Camera in C/AL


How to: Implement Location in C/AL

This example illustrates how you can retrieve location information. The example implements a GetLocation action on the Customer Card (page 21) that returns the GPS coordinates of the current customers address. It does not save this information to the database. Scenarios in which this functionality could be useful would be displaying a map that shows where your customer is located based on the GPS coordinates. Or, functionality to plan the next round of customer visits based on the addresses of your customers.

Important
The location information is only available on devices that run the Microsoft Dynamics NAV Universal App and have GPS capabilities. This means that location information is not available from the Microsoft Dynamics NAV Windows client or from a browser.

To implement location in C/AL

  1. In the development environment, on the Tools menu, choose Object Designer to open the Object Designer window.

  2. In Object Designer, choose Pages, select the Customer Card (page 21) and then choose the Design button.

  3. From the Page Designer window, on the View menu, choose C/AL Globals.

  4. Create the following variable:

    Variable name DataType SubType

    Location

    DotNet

    Microsoft.Dynamics.Nav.Client.Capabilities.LocationProvider

    Important
    Choose the Microsoft.Dynamics.Nav.ClientExtensions dll on the Server tab, and then choose Microsoft.Dynamics.Nav.Client.Capabilities.LocationProvider

    Make sure to set the properties RunOnClient and WithEvents to Yes.

    LocationAvailable

    Boolean

    -

  5. On the View menu, select C/AL Code and in the C/AL Editor locate the OnOpenPage trigger.

  6. Instantiate the Location variable by adding the following code to the OnOpenPage trigger.

    Copy Code
    IF Location.IsAvailable THEN
BEGIN
  Location := Location.Create;
  LocationAvailable := TRUE;
END;

  7. Next, create the page action. Choose the View menu, and then select Page Actions.

  8. Locate the ActionGroup named Customer and create a new action; GetLocation with the following properties.

    Property Value

    Name

    GetLocation

    Visible

    LocationAvailable

    Promoted

    Yes

    PromotedCategory

    Process

    PromotedIsBig

    Yes

  9. Now, in the C/AL Editor, on the GetLocation - OnAction trigger, insert the following line of code.

    Copy Code
    Location.RequestLocationAsync;

  10. While still in the C/AL Editor, on the LocationChanged trigger add the following code to handle the GPS coordinates. LocationChanged is called when the device has obtained a status.

    Copy Code
    Location::LocationChanged(Location : DotNet "Microsoft.Dynamics.Nav.Client.Capabilities.Location")
IF(Location.Status = 0) THEN
MESSAGE('Your position: %1 %2', Location.Coordinate.Latitude, Location.Coordinate.Longitude)
ELSE
MESSAGE('Position not available');
    Important
    Location.Status can be 0 = Available, 1 = NoData (no data could be obtained), 2 = TimedOut (location information not obtained in due time), or 3 = NotAvailable (for example user denied app access to location).

  11. Close the C/AL Editor, and then save and compile the page.

  12. You can now test the modified Customer Card page in the Microsoft Dynamics NAV Universal App from either a tablet or a phone with GPS capabilities.

See Also

Tasks

How to: Implement the Camera in C/AL

Concepts

LocationOptions Overview
Developing for the Microsoft Dynamics NAV Universal App
Differences and Limitations When Developing Pages for the Microsoft Dynamics NAV Universal App


LocationOptions Overview

When implementing location from C/AL, there are some options that you can optionally pass to LocationProvider.RequestLocationAsync(options). The options can be accessed by using Microsoft.Dynamics.Nav.Client.Capabilities.LocationOptions found in the Microsoft.Dynamics.Nav.ClientExtensions dll.

For most scenarios it is not necessary to specify options.

Location Options List

bool EnableHighAccuracy

A value to provide a hint to the device that this request must have the best possible location accuracy.

int Timeout

The maximum length of time (milliseconds) that is allowed to pass to a location request.

int MaximumAge

The maximum length of time (milliseconds) of a cached location.

See Also

Tasks

How to: Implement Location in C/AL


How to: Display Data as Bricks on Phone

The Microsoft Dynamics NAV Phone client uses a brick view to optimize space and readability for data that appears in page types that have Repeater controls, such as ListPart, ListPlus, and List. The brick view compresses up to six columns of data and is only displayed when the page is shown on the Microsoft Dynamics NAV Phone client. On all other Microsoft Dynamics NAV clients data will be displayed in a traditional list view mode.

It is worth noticing that on the phone brick layout some of the options that you have available on larger display types are not available:

  • You cannot delete directly in the list, but must be on the card to do so.

  • There is no concept of a currently selected row.

  • Factboxes, multi selection, custom sorting, and advanced filtering are not available options in the brick view.

  • The brick view does not support ShowAsTree indentation; the list is rendered as a flat list.

You must specify which data that you want shown in a brick view on the table’s Field Group. Depending on the number of columns that you define in the Field Group for the brick, the layout will dynamically change. Up to 6 fields can be displayed, and therefore, there are six possible layouts as shown in this illustration:

Illustrates how the six columns will lay out

The fields 2 and 3 are shown in a large font and should contain data that identifies the brick, for example, the Customer Name and Balance as you can see in the Customer list on the Microsoft Dynamics NAV Phone client.

Important
By default, the Field Group named DropDown is interpreted as Brick for the Microsoft Dynamics NAV Phone client when Brick has not been set. The DropDown is typically set on entities such as Customer, Vendor, and Items.

Tip
The brick layout supports using the Style Property and StyleExpr Property that lets you mark, for example, numbers as favorable or unfavorable.

To display data as bricks

  1. In the development environment, on the Tools menu, choose Object Designer to open the Object Designer window.

  2. In Object Designer, choose Tables, select a table, and then choose the Design button to open Table Designer. For example, select table 18, the Customer table.

  3. To open the Field Groups window, choose View, and then choose Field Groups.

  4. Select the first row in the Field Groups window, and in the Name field, type Brick.

  5. In the Field List window, make a selection from the fields in the source table. Select more rows by using the Shift key. Choose the OK button to add the fields to the Field Groups table.

  6. Close the windows and then choose Save and Compile.

See Also

Concepts

Developing for the Microsoft Dynamics NAV Universal App
Differences and Limitations When Developing Pages for the Microsoft Dynamics NAV Universal App


Scope Property

Specifies the scope of the action to be either page-specific, or specific to a repeater control. The Scope property has two options; Page and Repeater.

The Scope property is only used on pages that include a repeater control and it offers a way to determine the scope of an action to be the page or to be specific to the repeater control. The default behavior of the Scope property is Page.

The Scope property has the following effect:

  • On a Microsoft Dynamics NAV Windows client, the Scope property has no effect. All actions are shown in the ribbon.

  • On a Microsoft Dynamics NAV Web client, if the Scope property is set to Page, the action will be shown in the ribbon. If the Scope property is set to Repeater the action will be shown in both the repeater control and in the ribbon.

  • On a Microsoft Dynamics NAV Tablet client, if the Scope property is set to Page, the action will be shown in the page action menu. If the Scope property is set to Repeater, the action is moved from the page action menu to the repeater control shortcut menu.

  • On a Microsoft Dynamics NAV Phone client, if the Scope property is set to Page, the action will be shown in the page action menu. If the Scope property is set to Repeater, there are two scenarios:

    • If the list is associated with a card page, the developer must make sure to add the action functionality to this card page.

    • If the list is not associated with a card page, and the user taps a row in the list to view details, the action is available on the details page.

See Also

Concepts

Defining Action Scope for Microsoft Dynamics NAV Pages
Differences and Limitations When Developing Pages for the Microsoft Dynamics NAV Universal App


Troubleshooting: Icon Font Not Loaded

The Icon font is missing on the Microsoft Dynamics NAV Web client, Microsoft Dynamics NAV Tablet client, or Microsoft Dynamics NAV Phone client preventing you from seeing, for example, the plus sign in front of the New action.

Resolution

The reason is that the Font download option is disabled in your browser and the resolution is to add the Microsoft Dynamics NAV web site to your trusted sites.

  1. Launch Internet Explorer and then open the Microsoft Dynamics NAV web site.

  2. Go to Internet options, and choose the Security tab.

  3. Choose Trusted sites, and then choose the Sites button.

  4. Next to the Add this website to the zone field, choose the Add button, and then choose the Close button.

  5. In the Internet Options window, choose the OK button.

See Also

Troubleshooting Using Microsoft Dynamics NAV

Concepts

Troubleshooting the Microsoft Dynamics NAV Universal App


Troubleshooting: Device Date is Causing Connection Issues

You may experience connect issues when trying to log on to the Microsoft Dynamics NAV Universal App. The Microsoft Dynamics NAV Universal App only runs with https. Check if your device has the correct date set; this date is validated against the certificate. For more information, see Using HTTPS and Certificates.

See Also

Concepts

Troubleshooting the Microsoft Dynamics NAV Universal App


Troubleshooting: Client Returns Wrong CLIENTTYPE

Running, for example, the Microsoft Dynamics NAV Tablet client and the Microsoft Dynamics NAV Phone client simultaneously in the same browser session will return the same CLIENTTYPE.

If you have implemented code that checks for the CURRENTCLIENTTYPE, you must run each of the different clients in separate browser windows to make sure that the correct client type is returned for each of the clients.

See Also

Tasks

Troubleshooting: Client Returns Wrong CLIENTTYPE

Reference

CURRENTCLIENTTYPE Function
DEFAULTCLIENTTYPE Function

Concepts

Designing for Different Screen Sizes on Tablet and Phone


Troubleshooting: The Server Is Not Compatible

If the versions of the Microsoft Dynamics NAV Server and the Microsoft Dynamics NAV Universal App are not compatible, you will get an error.

On the tablet when connecting the Microsoft Dynamics NAV Universal App version 1.1 to Microsoft Dynamics NAV 2016, you will get the following error:

This version of the device app is not compatible with the Microsoft Dynamics NAV service. Please upgrade your app.

On the phone when connecting the Microsoft Dynamics NAV Universal App version 2.0 to Microsoft Dynamics NAV 2015, you will get the following error:

This server is not compatible and must be upgraded to a newer version. Please contact your system administrator.

The versions are compatible as described below:

  • If you have the latest version of the Microsoft Dynamics NAV Universal App on the tablet, you can connect to both Microsoft Dynamics NAV 2015 and Microsoft Dynamics NAV 2016.

  • If you have the latest version of the Microsoft Dynamics NAV Universal App on the phone, you can only connect to Microsoft Dynamics NAV 2016.

  • If you have an older version of the Microsoft Dynamics NAV Universal App, you cannot connect to Microsoft Dynamics NAV 2016 until you have updated the Microsoft Dynamics NAV Universal App to the latest version from the device store.

See Also

Concepts

Troubleshooting the Microsoft Dynamics NAV Universal App


Multilanguage Development

Microsoft Dynamics NAV is multilanguage enabled, which means that you can display the user interface (UI) in different languages.

A multilanguage version of Microsoft Dynamics NAV is not the same as a localized version.

  • A localized version is a version that is adapted to a local market. All text that is displayed to the user is translated into the local language, and all functional areas are adapted to the requirements of the local market. For example, the Canadian version of Microsoft Dynamics NAV has additional local functionality that applies to the Canadian market.

  • A multilanguage version is a localized version that you can run in different languages, but all local functionality remains the same. For example, you can run the Canadian version of Microsoft Dynamics NAV in both English and French, but it is still the Canadian localized version. It does not contain the same local functionality as the French localized version.

To be able to run a localized version in multiple languages, you must install language modules.

Installing Language Modules

You can install language modules so that you can view text in the user interface in different languages. Once you have installed a language module, you can select that language on the Select Language page in the UI to change the language of all text that is displayed in the UI in captions for text boxes, on command buttons, in menus, and so on.

Note
When you change the language of Microsoft Dynamics NAV, you are not changing the language of the data that is stored in Microsoft Dynamics NAV. Changing the text that is stored as application data is not part of the language modules. Examples of such text are the names of items in the inventory or the comments for a customer.

For more information, see Language Modules.

Developing Multilanguage Applications

After you install a language module, you must design your application to take advantage of the multilanguage functionality. For more information, see Developing Multilanguage-Enabled Applications.

Viewing the Application in Different Languages

The language that is displayed to end users in the application depends on several factors, including the language on the localized version of the application, whether a user has specified a global language, whether a developer has specified a global language in C/AL code, or whether a developer has specified a language for a particular object in C/AL code. For more information, see Viewing the Application in Different Languages.

See Also

Concepts

Development
Adding Languages to Microsoft Dynamics NAV
Language Modules
Developing Multilanguage-Enabled Applications
Viewing the Application in Different Languages

© 2015 Microsoft. All rights reserved.

Build Date:

2015-08-27


Language Modules

To view Microsoft Dynamics NAV in multiple languages, you install one or more language modules. The topic describes language modules in Microsoft Dynamics NAV. For more information about how to install language modules in the original version of Microsoft Dynamics NAV, see Language Modules for Microsoft Dynamics NAV (requires PartnerSource login).

Language Modules in Microsoft Dynamics NAV

A language module contains:

  • Translated strings for the UI in the Microsoft Dynamics NAV Windows client.

  • Translated strings for the database.

  • Translated strings for Microsoft Dynamics NAV Server, such as for logs and error reporting.

  • Translated strings for the Microsoft Office Outlook Add-in for Microsoft Dynamics NAV.

  • Translated strings for charts on Role Centers in the Microsoft Dynamics NAV Windows client.

  • Localized versions of the client Help.

Language modules are binary files that you cannot modify with external tools.

For more information about installing language modules in Microsoft Dynamics NAV, see How to: Install Language Modules.

If you have customized Microsoft Dynamics NAV, then after you install the appropriate language module, you should also translate the strings for the objects that you added or modified. For more information, see How to: Add Translated Strings By Importing and Exporting Multilanguage Files and How to: Add Translated Strings By Using the Multilanguage Editor.

Language Subdirectory

When you install a language module, a subdirectory for the language is created in the Microsoft Dynamics NAV directory structure. The .stx, .etx, .chm, and .hh files for each language are automatically installed in the subdirectory. The name of the subdirectory is the three-letter language code (Abbreviated Name) that is used by Windows for the particular language. For more information, see Windows Language Virtual Table.

See Also

Tasks

How to: Install Language Modules
How to: Add Translated Strings By Using the Multilanguage Editor
How to: Add Translated Strings By Importing and Exporting Multilanguage Files
How to: Uninstall Language Modules
How to: Delete Translated Strings

Concepts

Multilanguage Development


How to: Add Translated Strings By Using the Multilanguage Editor

To add string translations for UI elements in a standard country/region-specific version of Microsoft Dynamics NAV 2016, you install a language module so that end users can view the UI elements in a different language. If you have customized objects in the application, then you must also add translations for those objects. You can translate strings in the following ways:

  • By using the Translate tool in the development environment to import and export multilanguage files that contain translated strings for multiple objects

  • By using the Multilanguage Editor and editing the CaptionML property of individual objects

This topic describes how to use the Multilanguage Editor to edit the CaptionML property of objects. For more information about how to use the Translate tool, see How to: Add Translated Strings By Importing and Exporting Multilanguage Files.

To add a translation in Multilanguage Editor

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, select the object for which you want to add a translation, and then choose Design.

  3. In the designer, select the control for which you want to add a translation, choose View, and then choose Properties.

  4. In the CaptionML property, choose the AssistEdit button.

  5. In the Multilanguage Editor, enter the language and the translated text. For more information, see How to: Enter Text in the Multilanguage Editor.

To let the user select a specific language in the application, the following must be true:

  • You must have deployed the relevant language modules. For more information, see How to: Install Language Modules.

  • The language-specific subfolder must contain the correct fin.stx file.

  • The text strings in the database must be marked with the correct language ID.

  • The license file must contain the correct granule.

See Also

Tasks

How to: Delete Translated Strings

Concepts

Multilanguage Development


How to: Delete Translated Strings

After you add translated strings into a database, there is only one way to delete them. This procedure describes how to delete translated strings.

To delete a language layer

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, select the object for which you want to delete the translated strings.

  3. On the Tools menu, point to Language Module, and then choose Export.

  4. In the Language Module Export window, in the File Name field, enter the path and file name of the file that will contain the deleted strings.

  5. In the Language field, choose the AssistEdit button.

  6. In the Windows Language List window, select the language that you want to delete, and then choose OK.

  7. In the Language Module Export window, select the Delete language field, and then choose the OK button.

See Also

Tasks

How to: Add Translated Strings By Importing and Exporting Multilanguage Files
How to: Add Translated Strings By Using the Multilanguage Editor
How to: Uninstall Language Modules

Concepts

Multilanguage Development


Developing Multilanguage-Enabled Applications

Microsoft Dynamics NAV is enabled for multilanguage development by default. If you make sure that the names of objects are in English and all objects have values in the CaptionML property, your solution can be translated to other languages if you deploy your solution to other markets. Even if you do not have customers outside your own country/region, it is easier for you to upgrade to a new version of Microsoft Dynamics NAV if your code follows the same multilanguage-enabled structure as the standard version of Microsoft Dynamics NAV.

When you compile application objects that include multilanguage captions, Microsoft Dynamics NAV converts each CaptionML value into Unicode based on the specified language. For example, a text constant has the following CaptionML values: DAN=Danish text;ENU=English text. The Danish caption is converted based on code page 865, and the English (United States) caption is converted based on code page 437. If you have text that is not stored as a multilanguage caption, the text will be converted using the code page for the language that is specified for non-Unicode programs in the regional settings on the computer. Similarly, because Microsoft Dynamics NAV assumes that object names are English (United States), if you specify names in other languages, they may not display correctly after you compile the object.

When you are developing in a multilanguage-enabled environment, we recommend that you:

  • Set the language in the development environment to English (United States)

  • Specify the Name property in English (United States)

  • Use text constants in your code instead of using hardcoded text strings

  • Verify that everything that is displayed to the user has a Caption property

  • Use the DateFormula data type instead of Text or Code for date formulas

Setting the Language to English (United States)

Before you start working in a multilanguage-enabled database, you should set the language to English (United States). In the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Language, choose English (United States), and then choose OK.

Name Property

In Microsoft Dynamics NAV, the code base is in English (United States). This means that the Name Property of objects must always be in English (United States).

The code base in English (United States) includes the following:

  • Object names

  • Field names

  • Function and variable names

  • Comments

  • Option strings

  • Control names

Text Constants

In a multilanguage application, you must use text constants to define strings that you use in your code. A text constant can have multiple values for different languages.

The most common use of text constants is to define the strings that are used as parameters in the following functions:

  • ERROR Function (Dialog)

  • MESSAGE Function (Dialog)

  • CONFIRM Function (Dialog)

  • STRMENU Function (Dialog)

You define text constants in the C/AL Globals or C/AL Locals window. When you enter a string in the ConstValue field, this value is automatically entered as the ConstValueML value for the currently selected language. You can enter a string for other languages by choosing the AssistEdit button in the ConstValue field. This opens the Multilanguage Editor. For more information, see How to: Enter Text in the Multilanguage Editor.

Text constants are automatically assigned unique IDs according to the number ranges listed in Number Ranges for Text Constants. To see the ID for a text constant, open the C/AL Globals or C/AL Locals window where the text constant is defined, and select the text constant. On the View menu, choose Properties.

When you are working in the C/AL Editor, if you place the cursor on a text constant, then the value of the text constant in the current language is shown in the message line in the language that you have selected as the language.

Caption and CaptionML Properties

Everything that is displayed to the user must have a Caption Property. The Name property must always be English (United States), but you use the Caption property to show the name in the language of the development environment. The Caption property copies the value for the language that you have specified for the development environment from the CaptionML Property.

The CaptionML property allows you to add captions in multiple languages. An example is table 37, field 1, which has the following CaptionML values:

ENU=Document Type;ESM=Tipo documento;FRC=Type de document;ENC=Document Type

These correspond to values for English (United States), Spanish (Mexico), French (Canada), and English (Canada).

If the language in the development environment is English (United States), then the value of the Caption property is Document Type. If the language is Spanish (Mexico), then the value of the Caption field is Tipo documento.

To add captions in different languages, you can either enter values directly in the Value field of the CaptionML property, or you can choose the AssistEdit button to open the Multilanguage Editor. For more information, see How to: Enter Text in the Multilanguage Editor.

Note
You must choose the OK button to save the information when you exit the Multilanguage Editor window.

Note
If you create a new field on a page and you enter a CaptionML value, which is copied to the Caption property, then the value of the Caption property is not shown on the page in Page Designer until you compile, close, and reopen the page. If you enter the caption directly in the Value field of the Caption property, then you do not have to compile, close, and reopen the page to see the Caption property. If you modify the CaptionML property on an existing field in a page, then the new value of the Caption property is shown on the page even in Page Designer.

Option Buttons

The value in the OptionValue field is always in English because this value is used by the corresponding global variable and code must always be in English (United States). You must make sure that the value for English (United States) in the CaptionML field is the same as in the OptionValue field.

Option Strings

For option strings, such as a control in a request page, the Name property must remain the number of the control, such as Control 9.

Option Variables

For option variables, such as in a source expression for a FORMAT, STRSUBSTNO, ERROR, MESSAGE, or CONFIRM statement, create a text constant that contains the options, and then use a SELECTSTR statement to select an option from the text constant.

For example, you have the following text constants and variables.

Text constant name | Value
Text000 | Test %1.

Variable name | Data type | Length
NewStr | Text | 30
OptionVar | Option |

OptionVar has an OptionString value of Option1,Option2. In an application that is not multilanguage-enabled, you can have the following code.

Copy Code
NewStr := STRSUBSTNO(Text000, OptionVar);

In a multilanguage-enabled application, the OptionVar values are not translated. Instead of using the Option variable, create the following text constants and variables.

Text constant name | English (US) value | Croatian (Croatia) value
Text000 | Test %1. | Test %1.
Text001 | Option1,Option2 | Opcija1, Opcija2

Variable name | Data type | Length
NewStr | Text | 30
SelStr | Text | 30

To select an option, you use the SELECTSTR function.

Copy Code
SelStr := SELECTSTR(1,Text001);

When you call the STRSUBSTNO function and use the SelStr variable instead of the OptionVar variable, the result string is in the language of the application.

Copy Code
NewStr := STRSUBSTNO(Text000, SelStr);

Date Formulas

In a multilanguage application, if a table contains a date formula field, then you should verify that the field is of the DateFormula Data Type and not the Text Data Type or Code Data Type. A date formula that is stored as a DateFormula data type is converted to a non-language-dependent format.

Similarly, in a multilanguage application, if you use the CALCDATE Function (Date) and if you use a variable for the DateExpression parameter, then you should verify that the variable is of the DateFormula data type so that it is stored in a non-language-dependent format. If you specify a string for the DateExpression parameter, then you should use angle brackets (< >) around the date formula so that date formula is stored in a non-language dependent format. In this way, the calculation will be the same regardless of which application language the user has selected.

For example, if a user who has the application language set to English (United States) enters a date formula '1W+1D' into a field that is of the DateFormula data type, then to a different user who has the application language set to French (France), that field is displayed as '1S+1J'.

See Also

Tasks

How to: View Names and Captions

Concepts

Multilanguage Development
Multiple Document Languages


How to: Enter Text in the Multilanguage Editor

When you enter captions or text constants for a multilanguage-enabled application, you use the Multilanguage Editor to enter text for multiple languages.

To Enter Text in the Multilanguage Editor

  1. In the Multilanguage Editor, in the Language field, choose the up arrow.

  2. In the Windows Language List window, select the language that you want to add from the list, and then choose the OK button.

    Note
    In the Multilanguage Editor, instead of choosing the AssistEdit button, you can also enter the three-letter code for the language that you want to add and then move the cursor to the Value field. The three-letter code is automatically replaced with the full language description.

  3. In the Multilanguage Editor, in the Value field, enter the text in the language that you entered in the Language field, and then choose the OK button.

  4. (optional) Add a comment by doing the following:

    1. On a blank line in the Multilanguage Editor, in the Language field, choose the up arrow.

    2. In the Windows Language List window, select Comment, and then choose the OK button.

    3. In the Multilanguage Editor, in the Value field of the Comment line, enter your comment.

    Note
    A comment is useful to provide help or instructions for a translator.

See Also

Tasks

How to: Add Translated Strings By Using the Multilanguage Editor
How to: Add a Text Constant to a Codeunit


Number Ranges for Text Constants

Microsoft Dynamics NAV assigns unique IDs to text constants according to number ranges.

Number Ranges

The following table lists the number ranges for text constants.

development environment | From | To
Microsoft Dynamics NAV - W1 version | 000 | 9,999
Microsoft Dynamics NAV - Netherlands | 1,000,000 | 1,009,999
Microsoft Dynamics NAV - Belgium | 1,010,000 | 1,019,999
Microsoft Dynamics NAV - USA | 1,020,000 | 1,029,999
Microsoft Dynamics NAV - Canada | 1,030,000 | 1,039,999
Microsoft Dynamics NAV - United Kingdom | 1,040,000 | 1,049,999
Microsoft Dynamics NAV - Iceland | 1,050,000 | 1,059,999
Microsoft Dynamics NAV - Denmark | 1,060,000 | 1,069,999
Microsoft Dynamics NAV - Sweden | 1,070,000 | 1,079,999
Microsoft Dynamics NAV - Norway | 1,080,000 | 1,089,999
Microsoft Dynamics NAV - Finland | 1,090,000 | 1,099,999
Microsoft Dynamics NAV - Spain | 1,100,000 | 1,109,999
Microsoft Dynamics NAV - Portugal | 1,110,000 | 1,119,999
Microsoft Dynamics NAV - France | 1,120,000 | 1,129,999
Microsoft Dynamics NAV - Italy | 1,130,000 | 1,139,999
Microsoft Dynamics NAV - Germany | 1,140,000 | 1,149,999
Microsoft Dynamics NAV - Switzerland | 1,150,000 | 1,159,999
Microsoft Dynamics NAV - Austria | 1,160,000 | 1,169,999
Microsoft Dynamics NAV - Poland | 1,170,000 | 1,179,999
Microsoft Dynamics NAV - Lithuania | 1,180,000 | 1,189,999
Microsoft Dynamics NAV - Latvia | 1,190,000 | 1,199,999
Microsoft Dynamics NAV - Estonia | 1,200,000 | 1,209,999
Microsoft Dynamics NAV - Russia | 1,210,000 | 1,219,999
Microsoft Dynamics NAV - Czech Republic | 1,220,000 | 1,229,999
Microsoft Dynamics NAV - Slovenia | 1,230,000 | 1,239,999
Microsoft Dynamics NAV - Australia | 1,240,000 | 1,249,999
Microsoft Dynamics NAV - New Zealand | 1,250,000 | 1,259,999
Microsoft Dynamics NAV - Singapore | 1,260,000 | 1,269,999
Microsoft Dynamics NAV - South Africa | 1,270,000 | 1,279,999
Microsoft Dynamics NAV - India | 1,280,000 | 1,289,999
Microsoft Dynamics NAV - Argentina | 1,290,000 | 1,299,999
Microsoft Dynamics NAV - Brazil | 1,300,000 | 1,309,999
Microsoft Dynamics NAV - Mexico | 1,310,000 | 1,319,999
Microsoft Dynamics NAV - Croatia | 1,320,000 | 1,329,999
Microsoft Dynamics NAV - North Africa/Middle East | 1,330,000 | 1,339,999
Microsoft Dynamics NAV - Thailand | 1,340,000 | 1,349,999
Microsoft Dynamics NAV - Malaysia | 1,350,000 | 1,359,999
Microsoft Dynamics NAV - Hungary | 1,360,000 | 1,369,999
Microsoft Dynamics NAV - Iceland | 1,370,000 | 1,379,999
General customer modifications | 1,000,000,000 | 1,000,999,999
Add-on | 1,100,000,000 | 1,199,999,999

See Also

Concepts

Multilanguage Development


How to: View Names and Captions

If you have a multilanguage application, then you need to know how to find the values of both the Name Property of an object, which is in English (United States), and the Caption Property of an object, which is in the local application language.

Viewing Names and Captions in the development environment

Each of the following windows displays both the Name property and the Caption property for the items in the list:

  • Object Designer

  • Table List

  • Page List

  • Field List

  • Object List

  • Field Menu

In each window, there is a column with the object number. The following two columns contain the Name property and the Caption property in the current application language, respectively. The following procedure describes how to view a list in Object Designer.

To view the Table List window when creating a page

  1. In Object Designer, choose Page, and then choose New.

  2. In the New Page window, in the Table field, choose the up arrow.

  3. In the Table List window, the first column contains the table number, the second column contains the Name property, and the third column contains the Caption property in the current application language.

In Object Designer and the Field Menu window, you can show or hide columns, including the Caption column.

To show columns in the Object Designer window

  1. In Object Designer, on the shortcut menu of a column header, choose Show Column.

  2. In the Show Column window, select columns that you want to show, and then choose the OK button.

To hide columns from the Object Designer window

  • In Object Designer, on the shortcut menu of a column header for the column that you want to hide, choose Hide Column.

In the C/AL Editor, the C/AL scanner displays captions for objects, fields, and text constants. When you place the cursor on an object, field, or text constant, the C/AL scanner displays the Caption property for the object, field, or text constant in the status bar at the bottom of the development environment window.

In the C/AL Symbol Menu, if you have selected a field name, then the value of the Name property is displayed in the third column, and the value of the Caption property is displayed in the lower-left corner of the window. If you have selected a caption, then the corresponding Name for that caption is displayed in the lower-left corner of the window and the value of the Caption property is displayed in the third column.

See Also

Concepts

Developing Multilanguage-Enabled Applications


Multiple Document Languages

With a multlanguage-enabled database you can automatically get the languages needed for multiple document language functionality.

Running Multiple Document Languages

If you have documents that you want to print in the language of the recipient rather than in your own working language, you can add a single line of code in the document to handle this. This functionality is already enabled for most reports in the standard Microsoft Dynamics NAV database. The document is printed in the language that is specified in the Language Code field in the Customer Card window.

In reports that need the multiple document languages functionality, you must insert the following C/AL code as the first line in the OnAfterGet Record() trigger:

CurrReport.LANGUAGE := Language.GetLanguageID("Language Code")

For each of these reports, you must create a new variable, Language, with the data type Record pointing to the Language table (table 8). When you have compiled the object, it will no longer print in the user’s working application language if another language has been specified in the Customer Card window.

See Also

Tasks

How to: Add Translated Strings By Using the Multilanguage Editor
How to: Delete Translated Strings

Concepts

Multilanguage Development


Viewing the Application in Different Languages

In a multilanguage-enabled application, you can view the text in any language that has been added to the application. For more information about adding languages, see Language Modules.

Changing the Language from the User Interface

You can change the language in which text is displayed in the Microsoft Dynamics NAV Development Environment and in the RoleTailored client.

When you change the language of the application from the user interface (UI) in either the development environment or the RoleTailored client, you are changing the global language.

For more information, see How to: Change the Language in the User Interface.

Changing the Language from C/AL Code

You can change the global language from C/AL code, which is the same as changing the language from the UI. To change the global language from C/AL code, use the GLOBALLANGUAGE function.

For more information, see Language Functions.

Languages and Primary Languages

If a particular string for the current language cannot be found, then Microsoft Dynamics NAV searches for the text in another related language. Languages in Windows are tagged with a primary language ID. For example, the language with ID 1033, which is English (United States), is the primary language for a group of languages that includes ID 2057, which is English (United Kingdom), and ID 3081, which is English (Australia). Similar relationships exist for languages such as French, Spanish, and German.

Microsoft Dynamics NAV uses the primary language if the text for the current language cannot be found. For example, if you are running the German (Switzerland) localized version and you open a page that contains strings that do not exist with the language ID for German (Switzerland), then Microsoft Dynamics NAV looks for a string with the language ID for German (Germany) because German (Germany) is the primary language for German (Switzerland).

The algorithm searches for the text to use in the following order:

  1. The language of the object, which can be specified by a developer in C/AL code.

  2. The primary language of the object language.

  3. The global language that is either selected by the user or specified by a developer in code.

  4. The primary language of the global language.

  5. The language of the localized version of the application.

  6. The primary language of the localized version of the application.

Text is always displayed, but you can have situations in which different pages or even different controls on a page are displayed in different languages.

To view all language IDs and the associated information, such as primary ID, name, and abbreviated name, you can design a page that is based on the Windows Language virtual table. For more information, see Windows Language Virtual Table.

Maintaining SQL Views for Languages

You can specify that SQL Server creates and maintains a view for each language ID that is added to a table or field in Microsoft Dynamics NAV. If you select this option, then external tools can use these views to access the CaptionML property of the object in the required languages instead of using the name that is supplied in the table.

For more information, see How to: Maintain SQL Views for Each Language.

Help in the RoleTailored Client

In the RoleTailored client, Help displays in the same language as you have selected in Microsoft Dynamics NAV. If the Help Server does not include that language, Help displays in English.

See Also

Concepts

Multilanguage Development
Microsoft Dynamics NAV Help Server


Windows Language Virtual Table

The virtual, read-only Windows Language table displays the languages that Windows supports. You can view its contents by designing a tabular-type page based on the table.

The Table

The Windows Language virtual table contains the following fields.

Field name | Description
Language ID | This field is the primary key. It displays the standard Windows language ID for a specific language. C/AL supports the setting of language using the GLOBALLANGUAGE, WINDOWSLANGUAGE, and object LANGUAGE properties. The values of these properties are taken from this field.
Primary Language ID | Windows languages are grouped. A group consists of a primary language and zero or more secondary languages. The Primary Language ID field contains the Windows Language ID of the primary language.
Name | This field contains the standard Windows name for the language
Abbreviated Name | This field is a secondary key. It contains the standard Windows three-letter code for the language
Enabled | If selected, indicates that the language is globally enabled, page enabled, report enabled, or data port enabled. Your license file determines how a specific language can be used.
Globally Enabled | If selected, indicates that the license file allows you to set the language in question as the global language for the entire application.
Page Enabled | If selected, indicates that the license file allows pages to be shown in a language other than the global language.
Report Enabled | If selected, indicates that the license file allows reports to be printed in a language other than the global language
XMLport Enabled | If selected, indicates that the license file allows data ports to be shown in a language other than the global language.
Primary Code Page | The code page for a language defines the character set available for that language. If you mix text by using multiple code pages, you may not obtain the expected result.
STX File | If selected, indicates that an *.stx file is installed for the language in question. An *.stx file contains general text used in menu labels and system table names.
ETX File | If selected, indicates that an *.etx file is installed for the language in question. An *.etx file contains error messages.
Help File | If selected, indicates that an *.hlp or a *.chm file is installed for the language in question.

See Also

Concepts

Multilanguage Development


How to: Maintain SQL Views for Each Language

The Maintain views option determines whether SQL Server creates and maintains a view for each language ID that is added to a table or field in Microsoft Dynamics NAV.

To maintain views for each language

  1. In the Microsoft Dynamics NAV Development Environment, on the File menu, point to Database, and then choose New or Alter.

  2. In the New Database or Alter Database window, on the Integration tab, select Maintain views, and then choose OK.

See Also

Concepts

Viewing the Application in Different Languages
Multilanguage Development


Testing the Application

Before you release your Microsoft Dynamics NAV application, you must test its functionality. Testing is an iterative process. It is important to create repeatable tests, and it is helpful to create tests that can be automated. This topic describes the features in Microsoft Dynamics NAV 2016 that help you test the business logic in your application and some best practices for testing your Microsoft Dynamics NAV application.

Test Features

Microsoft Dynamics NAV 2016 includes the following features to help you test your application:

  • Test codeunits.

  • Test runner codeunits.

  • Test pages.

  • UI handlers.

  • ASSERTERROR statement.

Test Codeunits

You write test functions as C/AL code in the test codeunits. When a test codeunit runs, it executes the OnRun function, and then executes each test function in the codeunit. By default, each test function runs in a separate database transaction, but you can use the TransactionModel Property on test functions and the TestIsolation Property on test runner codeunits to control the transactional behavior. By default, the results of a test codeunit are displayed in a message window, but you can use the OnAfterTestRun Trigger on a test runner codeunit to capture the results. The outcome of a test function is either SUCCESS or FAILURE. If any error is raised by either the code that is being tested or the test code, then the outcome is FAILURE and the error is included in the results log file.

Even if the outcome of one test function is FAILURE, the next test functions are still executed.

The functions in a test codeunit are one of the following types:

  • Test function.

  • Handler function.

  • Normal function.

For more information, see How to: Create Test Codeunits and Test Functions.

Test Runner Codeunits

You use test runner codeunits to manage the execution of test codeunits and to integrate with other test management, execution, and reporting frameworks. By integrating with a test management framework, you can automate your tests and enable them to run unattended.

Test runner codeunits include the following triggers:

  • OnBeforeTestRun Trigger

  • OnAfterTestRun Trigger

You can use these triggers to perform preprocessing and postprocessing, such as initialization or logging test results. If you implement the OnBeforeTestRun trigger, then it executes before each test function executes. If you implement the OnAfterTestRun trigger, then it executes after each test function executes and also suppresses the automatic display of the results message.

Note
The OnBeforeTestRun and OnAfterTestRun triggers are optional. By default, they are not available on a test runner codeunit. To implement these triggers, you must manually add them as functions and you must specify the correct signature.

Warning
The OnBeforeTestRun and OnAfterTestRun triggers always run in their own transactions, regardless of the value of the TestIsolation Property, the value of the TransactionModel Property, or the outcome of a test function.

For more information, see How to: Create a Test Runner Codeunit.

Test Pages

Test pages mimic actual pages but do not present any UI on a client computer. Test pages let you test the code on a page by using C/AL to simulate user interaction with the page.

There are two types of test pages:

  • TestPage, which is a regular page and can be any kind of page. This includes page parts or subpages.

  • TestRequestPage, which represents the request page on a report.

You can access the fields on a page and the properties of a page or a field by using the dot notation. You can open and close test pages, perform actions on the test page, and navigate around the test page by using C/AL functions. For more information, see Testing Pages.

UI Handlers

To create tests that can be automated, you must handle cases when user interaction is requested by code that is being tested. UI handlers run instead of the requested UI. UI handlers provide the same exit state as the UI. For example, a test function that has a FunctionType of ConfirmHandler handles CONFIRM function calls. If code that is being tested calls the CONFIRM function, then the ConfirmHandler function is called instead of the CONFIRM function. You write code in the ConfirmHandler function to verify that the expected question is displayed by the CONFIRM function and you write C/AL code to return the relevant reply.

The following table describes the available UI handlers.

Function type | Purpose
MessageHandler | Handles MESSAGE statements.
ConfirmHandler | Handles CONFIRM statements.
StrMenuHandler | Handles STRMENU statements.
PageHandler | Handles specific pages that are not run modally.
ModalPageHandler | Handles specific pages that are run modally.
ReportHandler | Handles specific reports.
RequestPageHandler | Handles the request page of a specific report.

You create a specific handler for each page that you want to handle and a specific report handler for each report that you want to handle.

If you run a test codeunit from a test runner codeunit, then any unhandled UI in the test functions of the test codeunit causes a failure of the test. If you do not run the test codeunit from a test runner codeunit, then any unhandled UI is displayed as it typically would.

For more information, see How to: Create Handler Functions.

ASSERTERROR Keyword

When you test your application, you should test that your code performs as expected under both successful and failing conditions. These are called positive and negative tests. To test how your application performs under failing conditions, you can use the ASSERTERROR keyword. The ASSERTERROR keyword specifies that an error is expected at run time in the statement that follows the ASSERTERROR keyword. If a simple or compound statement that follows the ASSERTERROR keyword causes an error, then execution successfully continues to the next statement in the test function. If a statement that follows the ASSERTERROR keyword does not cause an error, then the ASSERTERROR statement itself fails with an error, and the test function that is running produces a FAILURE result.

For more information, see C/AL ASSERTERROR Statements.

Testing Best Practices

We recommend the following best practices for designing your application tests:

  • Test code should be kept separate from the code that is being tested. That way, you can release the tested code to a production environment without releasing the test code.

  • Test code should test that the code being tested works as intended both under successful and failing conditions. These are called positive and negative tests. The positive tests validate that the code being tested works as intended under successful conditions. The negative tests validate that the code being tested work as intended under failing conditions.

    1. In positive tests, the test function should validate the results of application calls, such as return values, state changes, or database transactions.

    2. In negative tests, the test function should validate that the intended errors occur, error messages are presented, and the data has the expected values.

  • Automated tests should not require user intervention.

  • Tests should leave the system in the same well-known state as when the test started so that you can re-run the test or run other tests in any order and always start from the same state.

  • Test execution and reporting should be fast and able to integrate with the test management system so that the tests can be used as check-in tests or other build verification tests, which typically run on unattended servers.

  • Create test functions that follow the same pattern:

    1. Initialize and set up the conditions for the test.

    2. Invoke the business logic that you want to test.

    3. Validate that the business logic performed as expected.

  • Only use hardcoded values in tests when you really need it. For all other data, consider using random data. For example, you want to test the Ext. Doc. No. Mandatory field in the Purchases & Payables Setup table. To do this you need to create and post typical purchase invoice. The typical purchase invoice line specifies an amount. For most tests, it does not matter exactly what amount. For inspiration, see the use of the GenerateRandomCode function in the tests that are included in the TestToolkit folder on the Microsoft Dynamics NAV product media.

  • Monitor code coverage. For more information, see Code Coverage.

See Also

Tasks

How to: Run Automated ApplicationTests
Walkthrough: Testing Purchase Invoice Discounts

Concepts

Application Test Automation
Testing Pages


Application Test Automation

You can write application tests in C/AL and run them individually or collectively. The Microsoft Dynamics NAV product media includes a folder with application objects that form a library of application tests, helper functions, and test runners so you can automate your application tests. For example, use the application test libraries to verify your application after upgrading to the latest release of Microsoft Dynamics NAV.

Application Test Toolkit

The TestToolkit folder on the Microsoft Dynamics NAV product media includes three .fob files:

Name | Description
CALTestCodeunits.W1.fob | Contains codeunits with test functions to test various application areas. The tests in this .fob file depend on the test libraries in the CALTestLibraries.W1.fob file. You must import the objects from all three files in order to use the application tests.
CALTestLibraries.W1.fob | Contains codeunits with generic and application-specific functions to reduce duplication of test code.
CALTestRunner.fob | Contains application objects for running application tests, include the CAL Test Tool page and other objects that support the application tests.
Note
The file names in the table are for the default version of Microsoft Dynamics NAV. The product media for the country-/region specific versions of Microsoft Dynamics NAV contain files that are relevant for that country/region.

Describing Your Tests

To help you design the relevant tests for your functionality, you can write scenarios that outline what you want to test, and you can write test criteria in the GIVEN-WHEN-THEN format. By adding comments based on feature, scenario, and GIVEN-WHEN-THEN, you add structure to your test code and make tests readable.

With this structure, you can analyze your functional coverage, such as which behavior you covered for each feature. When you can parse test code for defined tags, you have a human-readable description (XML or structured text) of the automated scenarios without unnecessary details of test implementation that tells you the purpose of the test. You can provide the owner of the business functionality with this description and include it in a global tree of scenarios supported by your solution.

When you have established the test criteria, you can write the test code itself. If you add the test criteria to the test code as comments, you can always refer to the test criteria, and it is easy to get an overview of what the test does.

The following sections provide an overview of the tags that we recommend that you use.

FEATURE Tag

Copy Code
// [FEATURE] [<FeatureTag1>] [<FeatureTagN>]

FeatureTag represents the name of the feature, application area, functional area, or another aspect of the application.

This list of tags should point to an area of your solution that is touched by the test. Order tags in descending importance. Start with the most important tags referring to the WHEN or THEN steps. Also add tags to important elements of functionality mentioned in GIVEN steps. For example, a test that verifies VAT amounts posted by a sales prepayment invoice can be marked as [VAT] [Prepayment] [Sales].

The [FEATURE] tag can be set for the whole test codeunit if you enter is at the beginning of the Documentation trigger. This means all tests in this codeunit will inherit the list of tags set there. If a test is supposed to have the same list of tags as the codeunit has, you do not have to add the [FEATURE] tag for this test. Add the tags only if the test has something specific to say.

SCENARIO Tag

Copy Code
// [SCENARIO <ScenarioID>] <TestDescription>

ScenarioID links the test to a work item for the functionality. For example, if you use Visual Studio Online or Team Foundation Server, [SCENARIO 12345] represents a work item with the ID 12345.

TestDescription represents a short description of the purpose of the test, such as Annie can apply a deferral template to a purchase order.

The [SCENARIO] tag should be the first line in the test method. Review sets of related tests and make sure that you can recognize the difference between similar tests based on the description. The following example illustrates the use of the [SCENARIO] tag to describe a test:

Copy Code
// [SCENARIO 12345] [Deferral Code] Annie can apply a deferral template to a purchase order.

GIVEN-WHEN-THEN Tags

The GIVEN-WHEN-THEN tags provide a framework for the specific test criteria.

Tag Description

GIVEN

Describes one step in setting up the test. If you feel a need to add an AND, you should probably add a separate GIVEN.

In most of cases, in order to run an action under test, you must prepare the database. Tests can be complex, so you can add more than one GIVEN. They can come in one block or comment particular lines of code. Do not try to repeat code and comment each line. Instead, add information of a higher level that would be valuable when reading without the test code.

WHEN

Describes the action under test.

A test is to test one thing. There should be only one WHEN in a test. It is the line of code that changes state of something that we are going to verify. If you feel a need to add more than one WHEN followed by different verification, you should split this test in two or more tests.

THEN

Describes what is verified by the test.

All tests must have a verification part. If there is no verification, the test does not test anything. You can add more than one THEN tag.

The following example illustrates a use of the GIVEN-WHEN-THEN format:

Copy Code
[GIVEN] The credit limit approval workflow is enabled.
[GIVEN] A sales invoice exists that is not approved and released.
[WHEN] The user wants to post a sales invoice.
[THEN] The user sees an error that they cannot post an invoice that is not approved and released.

Putting It All Together

For an example of how you can use the [FEATURE], [SCENARIO], and GIVEN-WHEN-THEN tags, see Walkthrough: Testing Purchase Invoice Discounts. You can also search for [FEATURE] or [SCENARIO] in the test codeunits that are available on Microsoft Dynamics NAV 2016 product media.

See Also

Tasks

How to: Create a Test Runner Codeunit
Walkthrough: Testing Purchase Invoice Discounts

Reference

Code Coverage

Concepts

Testing the Application


How to: Create Test Codeunits and Test Functions

In Microsoft Dynamics NAV 2016, you can create test codeunits and create test functions in the test codeunits.

When you create a new function in a test codeunit, the FunctionType property is set to Test by default.

To create a test codeunit and test functions

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Codeunit, and then choose New.

  3. On the View menu, choose Properties.

  4. In the Properties window, in the Subtype field, select Test to specify that this is a test codeunit.

  5. On the View menu, choose C/AL Globals.

  6. In the C/AL Globals window, on the Functions tab, enter the names of the test functions in this test codeunit.

  7. For each test function, select the function, choose View, choose Properties, and then verify that the FunctionType property is set to Test.

  8. In the Properties window, choose how you want to commit changes to the database during the test by setting the TransactionModel Property.

  9. If any test functions need UI handlers, then enter the names of the handler functions in the C/AL Globals window. For more information, see How to: Create Handler Functions.

  10. In the C/AL Editor, enter code for each test function and handler function that you defined. You can also enter code in the OnRun function. The OnRun function runs when you execute the codeunit and before the test functions run.

    Note
    Test functions must not have parameters or return values.

  11. On the File menu, choose Save. In the Save window, verify that the Compiled check box is selected, and then choose the OK button to save and compile the test codeunit.

See Also

Tasks

How to: Create a Test Runner Codeunit
How to: Create Handler Functions

Concepts

Testing the Application


Testing Pages

You use test page objects to simulate user interactions with the application. You can:

  • View or change the value of a field on a test page.

  • View the data on page parts.

  • View or change the value of a field on a subpage.

  • Filter the data on a test page.

  • Perform any actions that are available on the page.

  • Navigate to different records.

You must consider how you set the TransactionModel Property to simulate the scenario that you want to test and to return the database to its initial state after the test.

Note
Test functions and code on test pages run on the Microsoft Dynamics NAV Server instance, even though they simulate client interactions.

Accessing Fields on Test Pages

You access the fields on a test page by using the dot notation. For example, if you have a test page variable named CustomerCard that represents the Customer Card page, then to access the Name field on the test page, you write CustomerCard.Name in your code.

To get the value of a field or to write a value in a field, you use the Value property. For example, if you have a test page variable named CustomerCard that represents the Customer Card page, then to assign the value of the No. field to a variable named CustNo, you write CustNo := CustomerCard."No.".Value in your code. To write a value in the Address field of a Customer Card page, you write CustomerCard.Address.Value := '<address>' in your code.

For more information about C/AL functions that you use to access fields on a test page, see TestPage Field Functions.

Accessing Page Parts and Subpages

You access page parts and subpages on a test page by using the dot notation. For example, to compare the value of the No. field on a page to the value of the No. field on a FactBox on the page, you can write the following code.

Copy Code
If CustomerCard."No.".Value <> CustomerCard."Sales Hist. Sell-to FactBox"."No.".Value THEN
  ERROR("Page part data is not updated.");

You can use the Symbol Menu to view page parts and subpages and to access the functions, properties, fields, and actions on page parts and subpages.

Filtering Data on Test Pages

To filter the data that can be accessed on a test page, you use the Filter property and filter functions. For example, to filter the customers on the Customer List page based on a range of values in the No. field, you can write the following code.

Copy Code
CustomerList.Filter.SETFILTER("No.", '20000..30000');

For more information about C/AL functions that you use for filtering, see TestPage Filter Functions.

Invoking Actions on Test Pages

Any action that is available on a page is also available on the test page that mimics that page. You access page actions by using the dot notation and the INVOKE Function (TestPage Action). You can use the Symbol Menu to view the actions that are available on a test page. To view actions that you designed by using Page Designer, select the test page variable in the first column of the symbols, and then select Actions in the second column. To view built-in actions, such as Yes, No, OK, or Cancel, select the test page variable in the first column of the symbols, and then select BuiltInActions in the second column.

Note
The Symbol Menu may include built-in actions that are not available on the page. If you call a built-in action that is not available on the page, then the test fails.

For example, to choose OK after you create a new customer on the Customer Card page, you can write the following code.

Copy Code
CustomerCard.OPENNEW;
CustomerCard.Name.Value := 'Adventure Works';
CustomerCard.OK.INVOKE;

Navigating Among Records

To simulate moving to different items on a list page or moving to different records on a card page, you use one of the following navigation functions:

  • NEXT Function (TestPage)

  • PREVIOUS Function (TestPage)

  • FIRST Function (TestPage)

  • LAST Function (TestPage)

  • GOTORECORD Function (TestPage)

  • GOTOKEY Function (TestPage)

  • FINDFIRSTFIELD Function (TestPage)

  • FINDNEXTFIELD Function (TestPage)

  • FINDPREVIOUSFIELD Function (TestPage)

See Also

Tasks

How to: Create a Test Page

Concepts

Testing the Application


How to: Create a Test Page

You can create and open a test page in the following ways:

  • Declare a test page variable and then write C/AL code to open the test page by using one of the following functions:

    • OPENNEW Function (TestPage)

    • OPENEDIT Function (TestPage)

    • OPENVIEW Function (TestPage)

  • Create a PageHandler or ModalPageHandler function that has a test page parameter. For more information, see How to: Create Handler Functions.

  • Write C/AL code to trap a call to open a test page by using the TRAP Function (TestPage).

The following procedure describes how to declare test page variables. The following code example shows how to use the test page variables to write code to open test pages.

To declare a test page variable

  1. Create a test codeunit. For more information, see How to: Create Test Codeunits and Test Functions.

  2. In Object Designer, on the View menu, choose C/AL Globals.

  3. In the C/AL Globals window, on the Variables tab, enter the following:

    1. In the Name column, enter a name for the test page variable.

    2. In the DataType column, select TestPage from the drop-down list.

    3. In the Subtype column, select the page that you want to test with the test page variable.

Example

This example shows how to use the OPENEDIT function to open a test page. It also shows how to use the TRAP function to trap a call to open a test page so that the opened page is assigned to a variable.

This example requires that you create the following variables.

Variable name | DataType | Subtype
CustomerCard | TestPage | Customer Card
CustomerStatistics | TestPage | Customer Statistics
ShipToAddressList | TestPage | Ship-to Address List
Copy Code
CustomerCard.OPENEDIT;
// Test Customer Card page
CustomerStatistics.TRAP; // The next page that is invoked will be trapped and assigned to the CustomerStatistics variable.
CustomerCard."Page Customer Statistics".INVOKE; // Invokes an action from the Customer Card page.
CustomerStatistics."Balance (LCY)".ASSERTEQUALS(0); // Now that the CustomerStatistics test page is open, you can use the variable to test the page.
ShipToAddressList.TRAP; // The next page that is invoked will be trapped and assigned to the ShipToAddressList variable.
CustomerCard."Page Ship-to Address List".INVOKE; // Invoke an action from the Customer Card page.
// Continue testing

If the Balance (LCY) value for the customer whose card page you opened is 0, then the test result is SUCCESS, and you get a message that is like the following message.

Test Code Unit 50001 TestBalanceLCY

OnRun: SUCCESS

SUCCESS

If the Balance (LCY) value for the customer whose card page you opened is not 0, then the test result is FAILURE, and you get a message that is like the following message.

Test Code Unit 50001 TestBalanceLCY

OnRun: FAILURE

AssertEquals for Field:Balance (LCY) Expected = ‘0,00’, Actual = ‘1.499,02’

FAILURE

See Also

Concepts

Testing the Application


How to: Create Handler Functions

You can create test codeunits, test functions, and test pages to test your application. We recommend that you create tests that can be automated. To create automated tests, you must write code to handle all UI interactions so that the tests do not require user interaction when they are running. To do this, you create special handler functions.

You can use the following handler functions:

  • MessageHandler

  • ConfirmHandler

  • StrMenuHandler

  • PageHandler

  • ModalPageHandler

  • ReportHandler

  • RequestPageHandler

    Note
    If you create a ReportHandler function, then that function replaces all code for running the report, including the request page, and a RequestPageHandler is not called. Only create a RequestPageHandler if you are not using a ReportHandler.

  • FilterPageHandler

    The FilterPageHandler tests the UI that is generated by a FILTERPAGEBUILDER data type. For more information about the FILTERPAGEBUILDER data type, see Creating Filter Pages for Filtering Tables.

  • HyperlinkHandler

Before you begin, you must create a test codeunit and test function. For more information, see How to: Create Test Codeunits and Test Functions.

To create a handler function

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose Codeunit, select your test codeunit, and then choose Design.

  3. On the View menu, choose C/AL Globals.

  4. In the C/AL Globals window, on the Functions tab, enter the name of the new handler function.

  5. On the View menu, choose Properties.

  6. In the Properties window, in the FunctionType property, select the type of handler from the drop-down list.

  7. In the C/AL Globals window, on the Functions tab, choose Locals to specify the signature of the handler functions. The following table describes the signature that is required for each type of handler function.

    FunctionType Signature

    MessageHandler

    <Function name>(<Msg> : Text[1024])

    ConfirmHandler

    <Function name>(<Question> : Text[1024]; VAR <Reply> : Boolean)

    StrMenuHandler

    <Function name>(<Options : Test[1024]; VAR <Choice> : Integer; <Instruction> : Text[1024])

    PageHandler

    <Function name>(VAR <variable name> : Page <page id>)

    <Function name>(VAR <variable name> : TestPage <testpage id>)

    ModalPageHandler

    <Function name>(VAR <variable name> : Page <page id>; VAR <Response> : Action)

    <Function name>(VAR <variable name> : Page <testpage id>)

    ReportHandler

    <Function name>(VAR <report name> : Report <report id>)

    RequestPageHandler

    <Function name>(VAR <TestRequestPage > : TestRequestPage)

    FilterPageHandler

    <Function name>(VAR <RecRef1> : RecordRef)[, VAR <RecRef2> : RecordRef]

    Note
    You must a VAR parameter for each record on the FilterPageBuilder object. For more informatiion about Filter

    HyperlinkHandler

    <Function name>(<Hyperlink> : Text[1024])

    The parameters of the functions that are being handled are passed as parameters to the handler functions. For example, when MESSAGE is called in a test function, the parameter of the MESSAGE function is passed as the parameter of the MessageHandler function. For page and report handlers, the page, report, or request page is passed as the parameter of the PageHandler, ModalPageHandler, ReportHandler, or RequestPageHandler.

    Parameters that are specified as VAR are passed by reference to the handler function. The value of the parameter can be changed by the handler function.

    For example, to specify the signature for a ConfirmHandler function, do the following:

    1. In the C/AL Locals window, on the Parameters tab, enter a name for the <Question> parameter. In the DataType field, select Text. In the Length field, enter 1024. Verify that the Subtype field is blank.

    2. Enter a name for the <Reply> parameter. In the Var field, select the check box. In the DataType field, select Boolean. Verify that the Subtype and Length fields are blank.

    3. In the code of the ConfirmHandler function, set the reply that you want to simulate by setting the value of the Reply parameter.

  8. In the C/AL Globals window, select the test function that requires a handler function. For example, a test function that requires a handler function calls some application code, which then calls the CONFIRM function.

  9. On the View menu, choose Properties.

  10. In the Properties window for the test function, in the HandlerFunctions property, enter the name of the handler function that this test function will use instead of the UI. For example, if the code tested by this test function calls the CONFIRM function, then enter the name of your ConfirmHandler function. To specify more than one handler function, separate the handler function names with a comma.

    Note
    Every handler function that you enter in the HandlerFunctions property of a test function must be called at least one time in the test function. If you run a test function that has a handler function listed that is not called, then the test fails.

  11. In the C/AL Editor, enter code for the handler functions that you defined. The code should simulate in the code that is being tested that the UI was actually raised and some values entered or some actions were taken. For example, the code could verify that the expected text is presented. The code should exit with the same state with which the UI would exit.

  12. On the File menu, choose Save.

  13. In the Save window, verify that the Compiled check box is selected, and then choose the OK button to save and compile the test codeunit.

See Also

Tasks

How to: Create Test Codeunits and Test Functions
How to: Create a Test Runner Codeunit

Concepts

Testing the Application


How to: Create a Test Runner Codeunit

You can create test runner codeunits to manage the execution of test codeunits and to integrate with test management or test reporting frameworks.

To create a test runner codeunit

  1. In the development environment, in Object Designer, create a new codeunit.

  2. In the Properties window for the new codeunit, in the Subtype field, select TestRunner to specify that this is a test runner codeunit.

  3. In the TestIsolation field, specify which changes that you want to roll back. You can choose from the following values:

    • Disabled

    • Codeunit

    • Function

    For more information, see TestIsolation Property.

    Tip
    In the test runners in the automated application test libraries on the Microsoft Dynamics NAV product media, test isolation is set to Codeunit.

  4. In the C/AL Editor, in the OnRun function, enter code to run the test codeunits. For example, the following code in the OnRun function of a test runner codeunit runs three test codeunits in the automated application test libraries.

    Copy Code
    CODEUNIT.RUN(CODEUNIT::”ERM Vendor Statistics”);
CODEUNIT.RUN(CODEUNIT::”ERM Sales Quotes”);
CODEUNIT.RUN(CODEUNIT::”ERM Dimension”);

  5. (optional) You may want to define your test suite in a table and then write code in the OnRun function of the test runner codeunit to iterate through items in the table and run each test codeunit.

    1. In that case, add the following variables to the OnRun function in the test runner codeunit.

      Name DataType Subtype

      EnabledTestCodeunit

      Record

      CAL Test Enabled Codeunit

      Object

      Record

      Object

    2. In the C/AL Editor, in the OnRun function, delete the existing code, and then enter code that iterates through items in the table and runs each test codeunit.

      The following code example illustrates the code that you can add to the test runner.

      Copy Code
      IF EnabledTestCodeunit.FINDSET THEN
  REPEAT
    IF Object.GET(Object.Type::Codeunit,'',EnabledTestCodeunit."Test Codeunit ID") THEN
      CODEUNIT.RUN(EnabledTestCodeunit."Test Codeunit ID");
  UNTIL EnabledTestCodeunit.NEXT = 0

  6. (optional) You may want to save the results of the test execution in the database. This example requires that you add two triggers (steps 7 and 8).

    1. Add the following global variables.

      Name DataType

      StartTime

      Time

      TestRunNo

      Integer

    2. To initialize the TestRunNo trigger, add a local variable to the OnRun function.

      Name DataType Subtype

      TestResult

      Record

      CAL TestResult

    3. Add the following line of code at the beginning of the OnRun function:

      Copy Code
      TestRunNo := TestResult.LastTestRunNo + 1;

  7. To create an OnBeforeTestRun trigger, do the following steps:

    1. In the C/AL Globals window, on the Functions tab, on a new line in the Name field, enter OnBeforeTestRun, and then choose Locals.

    2. In the C/AL Locals window, on the Parameters tab, enter the following.

      Name DataType Length

      CodeunitID

      Integer

      CodeunitName

      Text

      30

      FunctionName

      Text

      128

    3. In the C/AL Locals window, on the Return Value tab, enter the following.

      Name Return type

      OK

      Boolean

    4. In the C/AL Locals window, on the Variables tab, enter the following.

      Name DataType Subtype

      TestResult

      Record

      CAL Test Result

    5. Close the C/AL Locals window.

    6. In the C/AL Editor, in the OnBeforeTestRun trigger, enter code that executes before each test function. Typically, the code in the OnBeforeTestRun function determines if the test function should execute and returns true if it should. Otherwise, the trigger returns false. The OnBeforeTestRun trigger may also initialize logging variables. For example, the following code initializes a logging variable and returns true to indicate that the test function should execute.

      Copy Code
      StartTime := TIME;
IF FunctionName  = '' THEN
  EXIT(TRUE);
CLEARLASTERROR;
TestResult.Create(TestRunNo,CodeunitId,CodeunitName,FunctionName);
EXIT(TRUE)

  8. To create an OnAfterTestRun trigger, do the following steps:

    1. In the C/AL Globals window, on the Functions tab, on a new line in the Name field, enter OnAfterTestRun, and then choose Locals.

    2. In the C/AL Locals window, on the Parameters tab, enter the following.

      Name DataType Length

      CodeunitID

      Integer

      CodeunitName

      Text

      30

      FunctionName

      Text

      128

      Success

      Boolean

    3. In the C/AL Locals window, on the Variables tab, enter the following.

      Name DataType Subtype

      TestResult

      Record

      CAL Test Result

      EndTime

      Time

    4. In the C/AL Editor, in the OnAfterTestRun trigger, enter code that executes after each test function. For example, the following code logs the results of the tests to the test reporting system. This example requires that you create a record variable named log.

      Copy Code
      IF FunctionName  = '' THEN
  EXIT;
EndTime := TIME;
TestResult.FINDLAST;
IF (FunctionName  = 'OnRun') AND Success THEN BEGIN
  TestResult.DELETE;
  EXIT;
END;
TestResult.Update(Success,EndTime - StartTime,FALSE)
      Note
      If you implement the OnAfterTestRun trigger, then it suppresses the automatic display of the results message after the test codeunit runs.

  9. On the File menu, choose Save.

  10. In the Save As window, in the ID field, enter an ID and in the Name field, enter a name for the codeunit. Verify that the Compiled check box is selected, and then choose OK.

See Also

Tasks

How to: Create Test Codeunits and Test Functions
How to: Create Handler Functions

Concepts

Testing the Application
Application Test Automation


How to: Run Automated ApplicationTests

You can run the automated application tests that are included on the Microsoft Dynamics NAV product media, and you can create your own tests suites and run them in the CAL Test Tool window.

To run tests in the CAL Test Tool window, you must import the objects in the .fob files in the TestToolkit folder that is included on the Microsoft Dynamics NAV product media. For more information, see Application Test Automation.

Any changes done to the database by running tests are automatically rolled back using the Test Isolation testability functionality. For more information, see How to: Create a Test Runner Codeunit.

To run an application test suite

  1. Open the CAL Test Tool window.

    From the development environment: In Object Designer, select page ID 130401, and then choose Run.

    From the Microsoft Dynamics NAV Windows client or the Microsoft Dynamics NAV Web client: In the Search field, enter CAL Test Tool, and then choose the relevant link.

    Warning
    Make sure that the application language is English (US). If the language is any other language, the Microsoft-provided tests will fail.

  2. On the Home tab, choose Get Test Codeunits, and then choose All Test Codeunits.

    This adds a number of test codeunits to the lines in the CAL Test Tool window.

  3. To run all loaded tests, on the Home tab, choose Run.

    Note
    If you load all Microsoft-provided tests and run all tests against the CRONUS International Ltd. demonstration database, the process takes approximately 8 hours.

    Alternatively, choose one or more tests, and then, on the Home tab, choose Run Selected.

    If you clear the Run field for a codeunit, the field is also cleared for all functions in that codeunit. You can then select one or more test functions.

When the test run completes, the CAL Test Tool window is updated with the result of the tests. You can the number of tests that were successful, failed, or were not run.

If any test fails, you can attach a debugger session and run the failing test again. The debugger will then break at the line where the test failed, and you will be able to inspect the call stack and examine variables to determine the underlying cause of the failure.

Running Specific Tests

During typical development, it is unacceptable to have to wait hours to get results from tests, which is why we have two additional options for test selection:

  1. Manual test selection.

  2. Test selection based on test coverage maps.

    This is a more advanced test selected that is based on an analysis of the code coverage data from individual test codeunits and comparing the result to the set of objects that have to be tested. Microsoft Dynamics NAV can automatically suggest test codeunits basing on objects where the Modified field is set to Yes in the database. Or you can select objects to be tested from the full list of objects.

You can create several test suites with different set of selected tests. A default test suite is created with the first run of the test tool. You can create an unlimited number of test suites and import and export them in XML format. This helps to move test suites between different databases and machines.

To run specific tests based on manual test selection

  1. Open the CAL Test Tool window.

  2. On the Home tab, choose Get Test Codeunits, and then choose Select Test Codeunits.

  3. In the CAL Test Get Codeunits window, select the codeunits that you want to load, and then choose OK.

The new test codeunits appear at the bottom of the list in the CAL Test Tool window. You can now select them and run them as described in the previous procedure.

To run specific tests based on test coverage maps

  1. Open the CAL Test Tool window.

  2. Choose the test or test suite that you want to generate a test coverage map for, and then choose Generate Test Coverage Map.

    Then, when you run the test, a test coverage map is generated based on the code coverage functionality in Microsoft Dynamics NAV.

When you have generated a test coverage map, you can export it to an XML file and import it into another database, for example.

See Also

Reference

Code Coverage

Concepts

Application Test Automation


Walkthrough: Testing Purchase Invoice Discounts

Before you release a customized Microsoft Dynamics NAV 2016 application to a production environment, you must test the application. This walkthrough demonstrates how to use the test codeunits and test libraries to test an application.

About This Walkthrough

This walkthrough illustrates the following tasks:

  • Creating a test codeunit.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 with a developer license.

  • The CRONUS International Ltd. demo data company.

Story

Isaac is a business application developer working for CRONUS International Ltd. He has modified codeunit 70, Purch-Calc.Discount, which is a codeunit in the CRONUS International Ltd. database. Isaac wants to test the functionality of his customized codeunit before he offers the customized application for sale. He creates a new test codeunit with new test functions to test the Purch-Calc.Discount codeunit. During development, Isaac uses the application test libraries to help him write a test with fewer lines of code.

Creating a Test Codeunit and Test Function

Isaac creates a new codeunit and specifies that it is a test codeunit. He defines the scenario that he wants to verify, adds a test function to tests the Purch-Calc.Discount functionality, and adds a helper function that can be reused if he decides to extend test coverage.

To create the test codeunit and test function

  1. In the development environment, in Object Designer, create a new codeunit.

  2. In the Properties window, in the Subtype field, select Test to specify that this is a test codeunit.

  3. In the C/AL Globals window, on the Variables tab, enter the following variables.

    Name DataType Subtype

    RandomNumberGenerator

    Codeunit

    Random Number Generator

    LibraryPurchase

    Codeunit

    Library - Purchase

    Assert

    Codeunit

    Assert

    This adds 3 codeunits from the application test libraries as global variables so that you can use them in your test code.

  4. In the C/AL Globals window, on the Text Constants tab, in the Name field, enter PurchInvDiscErr. In the ConstValue field, enter The Purchase Invoice Discount Amount was not calculated correctly.

  5. In the C/AL Globals window, on the Functions tab, enter PurchInvDiscCalculationPInvAbove. This is the name of the test function.

    In this example, the name of the test function consists of the tested functionality, Purchase Invoice Discount Calculation, and relevant parameters that affect the test result. We recommend that you follow this naming pattern for your test functions also. In our example, the following parameters are introduced:

    • PInv for the document that is tested, purchase invoices. You can apply the same test to purchase orders or purchase credit memos. Also, we recommend that you have mirrored sets of tests for the sales area.

    • Above. It is a good practice to have tests for positive and negative scenarios. In this test, Isaac wants to check that discount come into effect when the document amount is above a minimum amount. But the amount in the document can be also less than or equal to the minimum amount.

  6. On the Functions tab, choose Locals.

  7. In the C/AL Locals window, on the Variables tab, enter the following variables, which you will use in the PurchInvDiscCalculationPInvAbove test function.

    Name DataType Subtype

    PurchLine

    Record

    Purchase Line

    MinAmount

    Decimal

    DocAmount

    Decimal

    DiscountPct

    Decimal

    PurchCalcDisc

    Codeunit

    Purch.-Calc.Discount

    Important
    Make sure that you add these entries on the Variables tab, not on the Parameters tab. If you create them on the Parameters tab, you get an error when you compile that says the test method signature is invalid.

  8. In the C/AL Editor, in the PurchInvDiscCalculationPInvAbove function, enter the following code:

    Copy Code
    // [SCENARIO] "Inv. Discount Amount" should be calculated on Purchase Invoice (in LCY), where Invoice amount is above the minimal amount required for invoice discount calculation.
// [GIVEN] Vendor with invoice discount percentage "D" for minimal amount "A" in LCY
// [GIVEN] Create purchase invoice with one line and amount >"A"
DiscountPct := RandomNumberGenerator.RandDec(100,5);
MinAmount := RandomNumberGenerator.RandDec(1000,2);
DocAmount := MinAmount + RandomNumberGenerator.RandDec(100,2);
CreatePurchDocument(PurchLine,PurchLine."Document Type"::Invoice,DocAmount,MinAmount,DiscountPct);
// [WHEN] Calculate invoice discount for purchase document (line)
PurchCalcDisc.RUN(PurchLine);
// [THEN] "Inv. Discount Amount" = Amount "A" * discount "D" / 100
PurchLine.FIND;
Assert.AreEqual(ROUND(PurchLine."Line Amount" * DiscountPct / 100),PurchLine."Inv. Discount Amount", PurchInvDiscErr);

    Isaac first defines the test scenario [SCENARIO], then details it with the GIVEN-THEN-WHEN notation. Finally, he adds the C/AL code.The code in this test function prepares the test data by setting a random discount percent, a minimum amount, and a document amount. Then, it creates a purchase document with a line and runs the Purch-Calc.Discount codeunit, which contains the code that is being tested. Finally, it verifies the results of running the Purch-Calc.Discount codeunit and raises an error if the results are not as expected.

    Isaac has created the test function. Next, he creates a helper function that generates data for the test.

Isaac can now create additional test functions in this test codeunit to test other aspects of vendor discounts. These test functions should include negative tests, which validate that the code being tested works as intended under failing conditions.

Adding a Test Helper Function

In the test codeunit, Isaac adds a second function that generates data for the test itself.

To add a test helper function

  1. In the C/AL Globals window, on the Functions tab, in the Name field, enter CreatePurchDocument.

  2. In the Properties window for the new function, set the FunctionType property to Normal and the Local property to Yes.

  3. In the C/AL Locals window for the CreatePurchDocument function, on the Parameters tab, enter the following parameters.

    Var Name DataType Subtype

    Yes

    PurchLine

    Record

    Purchase Line

    DocumentType

    Option

    DocAmount

    Decimal

    MinAmount

    Decimal

    DiscountPct

    Decimal

  4. In the C/AL Locals window, on the Variables tab, enter the following variables.

    Name DataType Subtype Length

    VendorInvoiceDisc

    Record

    Vendor Invoice Disc.

    PurchaseHeader

    Record

    Purchase Header

    VendorNo

    Code

    20

  5. In the C/AL Editor, in the CreatePurchDocument function, enter the following code.

    Copy Code
    // Create vendor
VendorNo := LibraryPurchase.CreateVendorNo;
// Create vendor invoice discount
VendorInvoiceDisc.INIT;
VendorInvoiceDisc.Code := VendorNo;
VendorInvoiceDisc.VALIDATE("Currency Code",'');
VendorInvoiceDisc.VALIDATE("Minimum Amount",MinAmount);
VendorInvoiceDisc.VALIDATE("Discount %", DiscountPct);
VendorInvoiceDisc.INSERT(TRUE);
// Create purchase line
LibraryPurchase.CreatePurchaseDocumentWithItem(PurchaseHeader,PurchaseLine,DocumentType,VendorNo,'',1,'',0D);
PurchaseLine.VALIDATE("Direct Unit Cost",DocAmount);
PurchaseLine.MODIFY(TRUE);

    The code in this helper function prepares data for the test by creating a new vendor, setting up the invoice discount, and creating a purchase document with an item. Because this helper function is not specific to the test itself, Isaac can reuse it for similar tests. For example, he can call it with other parameters and create a purchase credit memo, or set up 0% discount, or create a document where the total amount is less than the minimum amount that is specified in Vendor Invoice Disc. table.

    Note
    This test code does not guarantee that the state of the database after you run the test is the same as the state of the database before you run the test.

  6. On the File menu, choose Save.

  7. In the Save As window, in the ID field, enter 50005. In the Name field, enter ERM Vendor Discount. Verify that the Compiled check box is selected, and then choose the OK button.

Next Steps

The next steps are:

  • Create additional test functions to test different aspects of vendor discounts. These test functions should include negative tests that validate that the code being tested works as intended under failing conditions.

  • Run the test codeunit in the Test Tool page.

See Also

Concepts

Testing the Application


Debugging

The process of finding and correcting errors is called debugging. Microsoft Dynamics NAV 2016 provides an integrated debugger to help you inspect your code to verify that your application can run as expected. The debugger UI runs in the Microsoft Dynamics NAV Windows client or the Microsoft Dynamics NAV Web client. The debugger services run on the computer that is running Microsoft Dynamics NAV Server.

For a tour of the new Microsoft Dynamics NAV Debugger, see Walkthrough: Debugging the Microsoft Dynamics NAV Windows Client.

Note
In Microsoft Dynamics NAV 2009, you used Visual Studio to debug objects on the computer that is running Microsoft Dynamics NAV Server, and you used the Microsoft Dynamics NAV Debugger to debug objects running on the Classic client. You cannot use Visual Studio to debug objects on the computer that is running Microsoft Dynamics NAV Server in Microsoft Dynamics NAV 2016. Instead, you use the new Microsoft Dynamics NAV Debugger.

Business Sessions

To start debugging, you attach the debugger to a business session. The business session that you select can be any of the following:

  • Microsoft Dynamics NAV Windows client session.

  • Microsoft Dynamics NAV Web client session.

  • OData web services session.

  • SOAP web services session.

  • NAS services session.

  • Background session that you start by using the STARTSESSION Function (Sessions).

After you attach the debugger, program flow runs until it reaches a breakpoint.

The remaining unattached business sessions continue to run without interruption.

For more information, see Activating the Debugger.

Breakpoints

The basic concept in debugging is the breakpoint, which is a mark that you set on a statement. When the program flow reaches the breakpoint, the debugger stops execution until you instruct it to continue. Without any breakpoints, the code runs without interruption when the debugger is active. For more information, see Breakpoints.

Debugging Requirements

To use the Microsoft Dynamics NAV debugger, the user who is logged in must be assigned the SUPER permission set for all companies. To assign the permission set for all companies, on the User Card page, under User Permission Sets, leave the Company column blank. If you assign the SUPER permission set for a specific company, then you get an error that you must be a member of the SUPER user role. For more information, see How to: Define Permissions for Users.

Assigning the SUPER permission set for all companies is required because a user who is debugging has access to business data in the debugged session.

Important
If you want to debug code that contains multiple INSERT statements, we recommend that you disable bulk inserts. If a loop with multiple INSERT statements is being buffered for a bulk insert, the Microsoft Dynamics NAV debugger cannot step through that code. If you disable bulk inserts, the debugger will step through the code as expected. For more information, see Bulk Inserts and Configuring Microsoft Dynamics NAV Server.

Disabling Debugging

If you do not want any user to be able to debug sessions on Microsoft Dynamics NAV Server, then you must disable debugging. This is useful if you have concerns about how to allow your data to be seen through the debugger. For more information, see How to: Disable Debugging.

Troubleshooting Protocol Mismatch Errors

We recommend that you do not use the settings parameter when you start a Microsoft Dynamics NAV Windows client if you later want to use that Microsoft Dynamics NAV Windows client to start the debugger. When you start the debugger from Sessions page, it uses some information from the default ClientUserSettings.config file, not the config file that you specified with the settings parameter when you started the Microsoft Dynamics NAV Windows client. There can be differences in the connection properties, which causes a protocol mismatch error.

For more information about the settings parameter, see Starting the Windows Client at the Command Prompt.

See Also

Tasks

Walkthrough: Debugging the Microsoft Dynamics NAV Windows Client

Concepts

Avoiding Run-Time Errors
Using About This Page and About This Report


Activating the Debugger

You can use the Microsoft Dynamics NAV Debugger to debug your application. When you activate the debugger, you start it. When the debugger is activated, it can be in one of the following states:

  • Attached to a session.

  • Waiting to attach to a session.

You can activate the debugger in the following ways:

  • In the development environment, on the Tools menu, point to Debugger, and then choose Debug Session. For more information, see How to: Activate the Debugger from the Development Environment.

  • At the command prompt. For more information, see How to: Activate the Debugger at the Command Prompt.

  • In the RoleTailored client, in the Search box, enter Sessions, and then choose the related link.

You attach the debugger to a session by doing one of the following:

  • Selecting a specific session in the Session List page.

  • Selecting Debug Next in the Session List page and then starting a new session.

Selecting a specific session to debug is useful if you know exactly which session you want to debug or if you want to debug a session that is running in the background.

Selecting Debug Next is useful if you want to debug web services. A web service call exists as a session only for the duration of the web service call, which typically is not long enough for you to select the specific session on the Session List page. To debug a web service, we recommend that you set your breakpoint, select Debug Next, and then make the web service call.

If the session that you want to debug is connected to a different Microsoft Dynamics NAV Server instance than the one that is currently specified in the Options window, then you can change to a different instance, and then activate the debugger in the development environment. For more information, see How to: Change the Microsoft Dynamics NAV Server Instance.

See Also

Concepts

Debugging


How to: Activate the Debugger at the Command Prompt

You can activate the debugger at the command prompt. After you activate the debugger and attach it to a session, program flow in that session continues normally until a breakpoint is hit. For more information, see Breakpoints.

To activate the debugger at the command prompt

  1. At the command prompt, locate the RoleTailored client directory. The default location on a 32-bit computer is C:\Program Files\Microsoft Dynamics NAV\90\RoleTailored Client. The default location on a 64-bit computer is C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client.

  2. Enter the following command:

    Copy Code
    Microsoft.Dynamics.Nav.Client.exe "DynamicsNAV://< Server>[:<port]>/<ServerInstance>/<Company>/debug"

  3. In the Session List window, do one of the following:

    • Choose Debug Next. The debugger is now active and is waiting to attach to a session.

    • Select a session, and then choose Debug. The debugger is now active and attached to the selected session.

In the Debugger window, you can enable and disable breakpoints, step through lines of code, and view variable and call stack information. For more information, see Walkthrough: Debugging the Microsoft Dynamics NAV Windows Client.

See Also

Concepts

Activating the Debugger
Debugging


How to: Activate the Debugger from the Development Environment

You can activate the debugger from the development environment. After you activate the debugger and attach it to a session, program flow in that session continues normally until a breakpoint is hit. For more information, see Breakpoints.

To activate the debugger from the development environment

  1. In the development environment, on the Tools menu, point to Debugger, and then choose Debug Session.

    Note
    You may encounter the following error when activating the debugger.

    Microsoft.Dynamics.Nav.Client has stopped working.

    To fix this error, see Troubleshooting: "Microsoft.Dynamics.Nav.Client has stopped working" error when starting debugger.

  2. On the Session List page, do one of the following:

    • Choose Debug Next. The debugger is now active and is waiting to attach to the next session.

    • Select a session, and then choose Debug. The debugger is now active and attached to the selected session.

In the View - Debugger window, you can enable and disable breakpoints, step through lines of code, and view variable and call stack information. Additionally, you can manage breakpoints on lines of code in the C/AL Editor in the development environment. For more information, see Walkthrough: Debugging the Microsoft Dynamics NAV Windows Client.

See Also

Concepts

Activating the Debugger
Debugging


Walkthrough: Debugging the Microsoft Dynamics NAV Windows Client

This walkthrough demonstrates debugging an action in the Microsoft Dynamics NAV Windows client with the Microsoft Dynamics NAV Debugger. The purpose of this walkthrough is to familiarize you with what you can do with the debugger. It does not describe how to debug and fix a specific error.

About This Walkthrough

This walkthrough illustrates the following tasks:

  • Setting a breakpoint on codeunit 80, Sales-Post, in the development environment.

  • Activating the Microsoft Dynamics NAV Debugger.

  • Posting a sales order so that the debugger breaks in codeunit 80, Sales-Post.

  • Using the debugger to:

    • View the parts of the debugger.

    • View variables and add watches.

    • Step through lines of code.

    • Add another breakpoint from the debugger.

    • Stop the current activity.

Prerequisites

To complete this walkthrough, you will need:

  • Microsoft Dynamics NAV 2016 with a developer license.

  • CRONUS International Ltd. demonstration database.

  • To verify that no other users are connected to the Microsoft Dynamics NAV Server instance. If other users are connected, then you might debug a session other than the one you want.

  • To verify that the user account that you use meets the requirements for setting breakpoints. For more information, see Development Environment (C/SIDE).

Story

Isaac is a business application developer working for CRONUS International Ltd. He has determined that there is an error in his code that posts sales orders. He wants to debug the scenario of posting a sales order. Isaac is not familiar with the Microsoft Dynamics NAV Debugger and wants to try all the functionality that the debugger offers.

Debugging the Post Action on a Sales Order

Isaac starts by setting a breakpoint at the first line of code in the Sales-Post codeunit. Next, he activates the debugger, runs the code so that it breaks at his breakpoint, and then steps through lines of code in this codeunit and other codeunits and examines variables to try to find the error.

To set a breakpoint in the development environment

  1. Open the Microsoft Dynamics NAV Development Environment. In Object Designer, choose Codeunit.

  2. Select codeunit 80, Sales-Post, and then choose Design.

  3. In the C/AL Editor, select the first line in the OnRun trigger.

  4. On the Tools menu, choose Debugger, and then choose Toggle Breakpoint to add a breakpoint to the selected line of code.

    C/AL Editor with a breakpoint set

To activate the debugger

  1. In Object Designer, on the Tools menu, choose Debugger, and then choose Debug Session.

    The Session List page opens.

  2. In the Session List page, on the Home tab, in the Session group, choose Debug Next.

    The Debugger page opens, but no session is currently being debugged, and no code is displayed in the code viewer.

To post a sales order and break in codeunit 80

  1. Open a new Microsoft Dynamics NAV Windows client session.

  2. In the Microsoft Dynamics NAV Windows client, in the Search field, enter Sales Orders, and choose the related link.

  3. In the Sales Orders list, select any sales order for which you want to debug the Post action, such as sales order 101016, and then, on the Actions tab, in the Posting group, choose Post.

  4. In the dialog box, select Ship and Invoice, and then choose the OK button.

    Go to the Debugger window. The code viewer shows the OnRun trigger of codeunit 80. Execution stops on the first line of code in the OnRun trigger, where you set the breakpoint in the development environment.

To use the debugger

  1. Now that you have hit a breakpoint in the code, you can become familiar with the parts of the Debugger page.

    • In the code viewer, the current line is identified by a yellow arrow in the margin. Breakpoints are identified by a red dot in the margin.

      Code Part on Debugger page
    • In the code viewer, you can point to a variable, field, or text constant to inspect the value.

      Code viewer, inspect PostingDateExists variable
    • In the Call Stack FactBox, you can view the function calls that led to the current line of code, starting with the Post action on page 9305.

      Call Stack Part on Debugger page

  2. On the Home tab, choose Variables.

    The Debugger Variables List window displays all variables that are currently in scope, including the Rec variable.

  3. In the Debugger Variables List window, expand Rec, expand Fields, select a field such as Posting Date, choose Add Watch, and then choose the Close button.

    The Posting Date variable is added to the Watches FactBox on the View - Debugger window. This is especially useful if there is a long list of variables in the Debugger Variables List window or if you want to view the value of a field in a record variable while you step through the code. Additionally, if you want to watch how the value of a variable changes, such as if you are in a loop, then it is useful to add the variable to the Watches FactBox.

    Watches Part on Debugger page
    Note
    When adding watches from the Debugger Variables List window, the watches do not appear in the Watches FactBox on the View - Debugger window until you choose the Close button.

    In the Debugger Variables List window, you can also expand and view Keys and Globals on the record variable, and you can view the value of the Filter Group and Filters fields.

  4. On the Home tab, in the Code Tracking group, choose Step Over to step over the current statement and on to the next statement.

  5. Continue stepping over lines of code until the current line is the following.

    Copy Code
    IF GenJnlCheckLine.DateNotAllowed("Posting Date") THEN

  6. Choose Step Into to step into the DateNotAllowed function in codeunit 11. Codeunit 11 is added to the call stack in the Call Stack FactBox. The variable that you added to the Watches FactBox is still listed, but the value is <Out Of Scope>.

  7. Choose Step Into and Step Over to step through the lines of the DateNotAllowed function. To step out of the DateNotAllowed function and go back to the OnRun function of codeunit 80, choose Step Out.

    After you choose Step Out, codeunit 11 is no longer in the call stack. The code viewer displays the OnRun trigger of codeunit 80. The current line is the line that called the DateNotAllowed function.

  8. In the code viewer, scroll down several lines to the following line of code.

    Copy Code
    SalesSetup.GET;

  9. Add a breakpoint to this line of code by doing one of the following:

    • Click in the margin to the left of the line of code.

    • On the Home tab, in the Breakpoints group, choose Toggle.

  10. Scroll back to the current line of code, which is identified by the yellow arrow in the margin.

  11. On the Home tab, in the Running Code group, choose Continue. Execution of code continues until the next breakpoint. The current line of code is now the SalesSetup.GET line.

  12. Choose Step Out to step out of codeunit 80. The call stack and the code viewer display codeunit 81 on the line of code that called codeunit 80.

    Copy Code
    CODEUNIT.RUN(Codeunit::"SalesPost",SalesHeader);

    The variables from codeunit 80 are no longer listed in the Debugger Variables List window. In the Watches FactBox, the value of the Rec.Fields."Posting No." variable is <Out Of Scope>.

  13. On the Home tab, in the Running Code group, choose Stop. This stops execution as if the code hit an error. The following error message is displayed on the session that was being debugged: “The debugger stopped the current activity.” In this example, the sales order that you posted to start debugging is not posted. The error from the debugger when you chose Stop caused the transaction to roll back.

    The Stop action is useful if you have to exit out of an endless loop. It is also useful if you performed several steps to set up data so that you could debug a scenario and do not want to continue executing code to commit and change that setup.

Next Steps

After Isaac is finished debugging, some possible next steps are:

  • Delete or disable all breakpoints. For more information, see How to: Manage Breakpoints from the Debugger Breakpoint List.

  • Delete watches. For more information, see How to: Remove Variables from the Watches FactBox.

Isaac can also keep the breakpoints and watches in his breakpoint list so that he can use them in a future debugging session.

See Also

Concepts

Debugging


Breakpoints

You can break code execution of the session that you are debugging by:

  • Setting a breakpoint on a line of code.

  • Specifying a break on the next statement.

  • Specifying a break on errors.

  • Specifying a break on record changes.

You can set breakpoints before you start a debugging session or when you are debugging. Breakpoints and break rules are applied immediately in the session to which the debugger is attached.

After the breakpoint is hit, you use the debugger to execute C/AL code one line at a time. This procedure is called stepping. The Code Tracking group on the Home tab provides three actions for stepping:

  • Step Into

  • Step Over

  • Step Out

Step Into and Step Over differ in how they handle function calls. Either command instructs the debugger to execute the next line of code. If the line contains a function call, Step Into executes only the call itself and then stops at the first line of code inside the function. Step Over executes the function and then stops at the first line outside the function. Use Step Into if you want to look inside the function call. Use Step Over if you want to avoid stepping into functions.

Use Step Out when you are inside a function call and want to return to the calling function. Step Out resumes execution of your code until the function returns and then breaks at the return point in the calling function.

The Running Code group on the Home tab provides the Continue action. Continue executes code until the next breakpoint or until execution ends.

You can inspect the contents of global variables, local variables, system variables, parameters, and text constants at each step. You can see whether the actual values that are displayed differ from the values that you expected when you designed the application.

For more information about user account requirements for setting breakpoints, see Development Environment (C/SIDE).

Break on Lines of Code

If you set a breakpoint on a line of C/AL code, then execution breaks before the first statement on the line is executed. If you set a breakpoint on a line of code that does not have a C/AL statement, then the breakpoint is automatically set on the next statement. If you set a breakpoint on a line of code that exceeds the number of lines of code in the object, then the breakpoint is set on the last line of code. You can set a condition on a breakpoint on a line of code so that execution breaks only if the condition is met. For more information, see the following topics:

  • How to: Manage Breakpoints from the Debugger Breakpoint List

  • How to: Manage Breakpoints from the Debugger Code Viewer

  • How to: Manage Breakpoints from the Development Environment

Break on Next Statement

If the debugger is attached to a session, then you can specify a break on the next statement that is executed in that session. There are three scenarios for specifying a break on the next statement:

  • The debugger is attached to a session, but no action is running in Microsoft Dynamics NAV. You want to debug a specific task. Before you begin that task, you set the debugger to break on the next statement.

  • The debugger is attached to a session, and Microsoft Dynamics NAV is running some code. You want to debug this code that is currently running. You set the debugger to break on the next statement so that it breaks into this code.

  • You want to debug from the beginning of a session. You activate the debugger and then select Debug Next in the Session List page, and then set the debugger to break on the next statement.

For more information, see How to: Break on the Next Statement.

Break on Errors

You can specify that the debugger breaks execution if it encounters an error. If you specify that the debugger breaks on errors, then it breaks both on unhandled errors and on errors that you handle in C/AL code. For more information about how to handle errors, see Avoiding Run-Time Errors.

When the debugger breaks on an error, you can inspect variables and parameters and you can review the error message for the current error. These inspection steps can help you determine the cause of the error.

For more information, see How to: Break on Errors.

Break on Record Changes

You can specify that the debugger breaks execution before a change to a record occurs. If you specify that the debugger breaks on record changes, then it breaks before creating, updating, or deleting a record. The following table shows each record change and the C/AL functions that cause each change.

Record change | C/AL functions
Create a new record | INSERT Function (Record)
Update an existing record | MODIFY Function (Record), MODIFYALL Function (Record), RENAME Function (Record)
Delete an existing record | DELETE Function (Record), DELETEALL Function (Record)

For more information, see How to: Break on Record Changes.

Conditional Breakpoints

You can specify conditions for breakpoints so that execution breaks only if the condition is true. For example, if an application iterates through a list of customers and you want to break execution at customer 10000, then you can specify the condition "Customer No." = '10000'. For more information, see How to: Set Conditional Breakpoints.

Enabling and Disabling Breakpoints

You can enable or disable the breakpoints in your breakpoint list. When you create a new breakpoint, it is enabled by default. If you disable a breakpoint, then execution does not break at that point in the code, but the breakpoint remains in your breakpoint list so that you can enable it again later. For more information, see the following topics:

  • How to: Manage Breakpoints from the Debugger Breakpoint List

  • How to: Manage Breakpoints from the Debugger Code Viewer

  • How to: Manage Breakpoints from the Development Environment

Storing Breakpoints

Breakpoints are stored immediately when you add or change them. They are stored privately for each user.

Breakpoints on lines of code are preserved in your breakpoint list when you start a new debugging session.

Breakpoints on lines of code are stored in table 2000000100, Debugger Breakpoint.

Breaks on the next statement, breaks on errors, or breaks on record changes are stored in table 2000000073, User Personalization. These breaks are not added to the breakpoint list.

See Also

Concepts

Debugging


How to: Manage Breakpoints from the Debugger Breakpoint List

You use the debugger breakpoint list to view, set, enable, disable, or delete breakpoints.

For more information about how to open the Debugger window, see Activating the Debugger.

Note
If you set a breakpoint from the debugger, then it is not displayed in the C/AL Editor. If you enable, disable, or delete a breakpoint from the debugger, that change is not displayed in the C/AL Editor until you open the editor again.

To view breakpoints in the Debugger Breakpoint List window

  • In the Debugger window, on the Home tab, in the Breakpoints group, choose Breakpoints.

To set a breakpoint in the Debugger Breakpoint List window

  1. In the Debugger Breakpoint List window, in the Object Type column, select the object type from the drop-down list box.

  2. In the Object ID column, select the object ID from the drop-down list box.

  3. In the Line No. column, enter the line number on which you want to set a breakpoint. You can view the line number in the Call Stack FactBox on the Debugger window.

  4. Verify that the Enabled column is selected.

  5. Choose OK.

  6. (optional) In the Condition column, enter a condition for the breakpoint. For more information, see How to: Set Conditional Breakpoints.

To enable or disable a single breakpoint in the Debugger Breakpoint List window

  • In the Debugger Breakpoint List window, do one of the following:

    • In the Enabled column of the breakpoint list, select the check box to enable the breakpoint. Clear the check box to disable the breakpoint.

    • Select the breakpoint, and then on the Home tab, in the Process group, choose Enable or Disable.

To enable all breakpoints in the Debugger Breakpoint List window

  • In the Debugger Breakpoint List window, on the Home tab, in the Process group, choose Enable All.

To disable all breakpoints

  • Do one of the following:

    • In the Debugger Breakpoint List window, on the Home tab, in the Process group, choose Disable All.

    • In the Debugger window, on the Home tab, in the Breakpoints group, choose Disable All.

To delete a single breakpoint

  • Do one of the following:

    • In the Debugger window, in the Code part, place the pointer on the line of code from which you want to delete a breakpoint. On the Home tab, in the Breakpoints group, choose Toggle.

    • In the Debugger Breakpoint List window, select the breakpoint in the list, and then on the Home tab, in the Manage group, choose Delete.

To delete all breakpoints

  1. In the Debugger window, on the Home tab, in the Breakpoints group, choose Breakpoints.

  2. In the Debugger Breakpoint List window, on the Home tab, in the Process group, choose Delete All.

See Also

Tasks

How to: Manage Breakpoints from the Debugger Code Viewer
How to: Manage Breakpoints from the Development Environment
How to: Break on the Next Statement
How to: Break on Errors
How to: Set Conditional Breakpoints

Concepts

Breakpoints


How to: Manage Breakpoints from the Debugger Code Viewer

You can view, set, enable, disable, or delete breakpoints directly in the Code part of the Debugger window.

For more information about how to open the Debugger window, see Activating the Debugger.

Note
If you set a breakpoint from the debugger, then it is not displayed in the C/AL Editor. If you enable, disable, or delete a breakpoint from the debugger, that change is not displayed in the C/AL Editor until you open the editor again.

To view breakpoints in the code viewer

  • In the Debugger window, in the code viewer, breakpoints are displayed in the margin. An enabled breakpoint is identified by a red dot. A disabled breakpoint is identified by an unfilled red circle.

To set a breakpoint in the code viewer

  • In the Debugger window, in the code viewer, do one of the following:

    • Place the cursor on the line of code on which you want to set a breakpoint, and then on the Home tab, in the Breakpoints group, choose Toggle.

      A red dot is displayed in the margin of the code, and the breakpoint is immediately enabled.

    • Choose the margin to the left of the line of code on which you want to set a breakpoint.

      A red dot is displayed in the margin of the code, and the breakpoint is immediately enabled.

To enable a single breakpoint in the code viewer

  • In the Debugger window, in the code viewer, do one of the following:

    • Place the cursor on the line of code that has a disabled breakpoint, and then on the Home tab, in the Breakpoints group, choose Toggle.

      The unfilled red circle changes to a red dot, and the breakpoint is immediately enabled.

    • Choose the unfilled red circle in the margin to the left of the line of code with the disabled breakpoint.

      The unfilled red circle changes to a red dot, and the breakpoint is immediately enabled.

To disable all breakpoints in the code viewer

  • In the Debugger window, on the Home tab, in the Breakpoints group, choose Disable All. All breakpoints, including breakpoints in other codeunits that are not currently displayed in the code viewer, are immediately disabled.

To delete a single breakpoint in the code viewer

  • In the Debugger window, in the code viewer, do one of the following:

    • Place the cursor on the line of code that has an enabled breakpoint, and then on the Home tab, in the Breakpoints group, choose Toggle.

    • Choose the red dot in the margin to the left of the line of code with the enabled breakpoint.

See Also

Tasks

How to: Manage Breakpoints from the Development Environment
How to: Manage Breakpoints from the Debugger Breakpoint List
How to: Break on the Next Statement
How to: Break on Errors

Concepts

Breakpoints


How to: Manage Breakpoints from the Development Environment

You can view, set, enable, disable, or delete breakpoints on lines of code in the C/AL Editor in the development environment. The breakpoints that you set, enable, disable, or delete in the C/AL Editor are displayed in the code viewer in the debugger and in the debugger breakpoint list.

Note
You cannot manage breaks on the next statement, breaks on errors, or breaks on record changes from the development environment. You must manage these breaks from the debugger.

Note
If you set a breakpoint from the debugger, then it is not displayed in the C/AL Editor. If you enable, disable, or delete a breakpoint from the debugger, that change is not displayed in the C/AL Editor until you open the editor again.

To view breakpoints in the development environment

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, select the object that you want to debug, and then choose Design. If the object is not a codeunit, then on the View menu, choose C/AL Code.

    In the C/AL Editor, breakpoints are displayed in the margin. An enabled breakpoint is identified by a red dot. A disabled breakpoint is identified by an unfilled red circle.

To set breakpoints from the development environment

  1. In the C/AL Editor, place the cursor on the line of code on which you want to set a breakpoint.

  2. On the Tools menu, point to Debugger, and then choose Toggle Breakpoint. A red dot is displayed in the margin, and the breakpoint is immediately enabled.

To enable breakpoints from the development environment

  1. In the C/AL Editor, place the cursor on the line of code that has a disabled breakpoint.

  2. On the Tools menu, point to Debugger, and then choose Toggle Breakpoint. The red unfilled circle disappears, and the breakpoint is immediately deleted.

  3. On the Tools menu, point to Debugger, and then choose Toggle Breakpoint again. A red dot is displayed in the margin, and the breakpoint is immediately enabled.

To disable breakpoints from the development environment

  1. In the C/AL Editor, place the cursor on the line of code that has an enabled breakpoint.

  2. On the Tools menu, point to Debugger, and then choose Toggle Breakpoint. The red dot changes to a red unfilled circle, and the breakpoint is immediately disabled.

To delete breakpoints from the development environment

  1. In the C/AL Editor, place the cursor on the line of code that has a disabled breakpoint.

  2. On the Tools menu, point to Debugger, and then choose Toggle Breakpoint. The red unfilled circle disappears, and the breakpoint is immediately deleted.

See Also

Tasks

How to: Manage Breakpoints from the Debugger Code Viewer
How to: Manage Breakpoints from the Debugger Breakpoint List

Concepts

Breakpoints


How to: Break on the Next Statement

If the debugger is attached to a session, then you can specify that the debugger breaks before the next C/AL statement is run in that session.

For more information about how to open the Debugger window, see Activating the Debugger.

To specify a break on the next C/AL statement

  • In the Debugger window, on the Home tab, in the Running Code group, choose Break.

See Also

Tasks

How to: Manage Breakpoints from the Debugger Breakpoint List
How to: Manage Breakpoints from the Development Environment
How to: Break on Errors
How to: Set Conditional Breakpoints

Concepts

Breakpoints


How to: Break on Errors

You can specify if the debugger breaks on the next error. If the debugger is set to break on errors, then it breaks execution both on errors that are handled in code and on unhandled errors. By default, the debugger is set to break on errors.

When the debugger breaks on an error, you can inspect variables and parameters. You can also review the error message in the Debugger window, on the Home tab, in the Show group, by choosing Last Error.

For more information about how to open the Debugger window, see Activating the Debugger.

To break on errors

  1. Activate the debugger. For more information, see How to: Activate the Debugger from the Development Environment or How to: Activate the Debugger at the Command Prompt.

  2. In the Debugger window, on the Home tab, in the Breakpoints group, choose Break Rules.

  3. In the Debugger Break Rules window, select the Break On Error check box, and then choose the OK button.

See Also

Tasks

How to: Manage Breakpoints from the Development Environment
How to: Manage Breakpoints from the Debugger Breakpoint List
How to: Break on the Next Statement
How to: Break on Record Changes
How to: Set Conditional Breakpoints

Concepts

Breakpoints


How to: Break on Record Changes

You can specify if the debugger breaks on record changes. If the debugger is set to break on record changes, then it breaks before creating, modifying, or deleting a record. The following table shows each record change and the C/AL functions that cause each change.

Record change | C/AL functions
Create a new record | INSERT Function (Record)
Update an existing record | MODIFY Function (Record), MODIFYALL Function (Record), RENAME Function (Record)
Delete an existing record | DELETE Function (Record), DELETEALL Function (Record)

By default, the debugger is not set to break on record changes.

For more information about how to open the Debugger window, see Activating the Debugger.

To break on record changes

  1. In the Debugger window, on the Home tab, in the Breakpoints group, choose Break Rules.

  2. In the Debugger Break Rules window, select the Break On Record Changes check box, and then choose the OK button.

See Also

Tasks

How to: Manage Breakpoints from the Development Environment
How to: Manage Breakpoints from the Debugger Breakpoint List
How to: Break on the Next Statement
How to: Break on Errors
How to: Set Conditional Breakpoints

Concepts

Breakpoints


How to: Skip Codeunit 1

Many of the triggers in codeunit 1, Application Management, are not important for debugging a business scenario. Because they are seldom important for debugging and because codeunit 1 triggers are called very often in the application, you can specify that the debugger skips all code in codeunit 1. If you skip codeunit 1, then when you break on the next statement, the debugger does not break on code in codeunit 1. It continues until the first line of code after codeunit 1. In addition, when you step through lines of code, the debugger does not step into code in codeunit 1.

If you skip codeunit 1, then you also implicitly skip all code that is called from codeunit 1.

If you explicitly set a breakpoint in codeunit 1 or in code that is called from codeunit 1, then the debugger breaks execution when it hits the specific breakpoint, regardless of whether you have selected the setting to skip codeunit 1.

By default, the debugger is set to skip codeunit 1.

For more information about how to open the Debugger window, see Activating the Debugger.

To skip codeunit 1

  1. In the Debugger window, on the Home tab, in the Breakpoints group, choose Break Rules.

  2. In the Debugger Break Rules window, select the Skip Codeunit 1 check box, and then choose the OK button.

See Also

Tasks

How to: Break on Errors
How to: Break on Record Changes

Concepts

Breakpoints


How to: Set Conditional Breakpoints

You can define a condition on a breakpoint. If the condition is true, then code execution breaks at the breakpoint. If the condition is false, then code execution continues. The condition can include any variables or fields that are currently in scope. You can compare a variable or a field to another variable or field, or you can compare a variable or field to a literal value. If you compare to a literal value, then the variable or field that you use in the breakpoint condition must be of one of the following data types:

  • BigInteger

  • Boolean

  • Code

  • Decimal

  • Integer

  • Option

  • Text

The following operators are supported in breakpoint conditions:

  • =

  • <>

  • <

  • >

  • <=

  • >=

To set a conditional breakpoint

  1. In the Debugger window, do one of the following:

    • On the Home tab, in the Breakpoints group, choose Set/Clear Condition. In the Debugger Breakpoint Condition window, enter a condition.

    • On the Home tab, in the Breakpoints group, choose List. In the Debugger Breakpoint List window, enter a condition in the Condition column.

  2. Enter any conditional statement that uses variables that are in scope, constants, and supported operators.

    Note
    If you clear an existing condition, then that breakpoint is no longer a conditional breakpoint.

  3. Choose OK to close the Debugger Breakpoint List window. A plus sign is added to the red dot that is displayed in the margin.

Example

In this example, you want to set a breakpoint to debug an application. This application processes invoices in a loop, but it stops responding on a particular invoice. You set a breakpoint on the first line of code in the loop, and then you set the following condition on the breakpoint.

Copy Code
SalesInvoiceHeader."No." = '103007'

See Also

Concepts

Breakpoints


How to: View Variables That Are in Scope

On the Debugger page, if the debugger has broken code execution, then you can view all of the variables that are currently in scope. This allows you to inspect the values of the variables at the point at which you have broken code execution. You can also choose to add variables to the watch list.

To view variables that are in scope

  • In the Debugger window, on the Home tab, in the Show group, choose Variables. The Debugger Variable List opens.

See Also

Tasks

How to: Add Variables to the Watches FactBox
How to: Remove Variables from the Watches FactBox
How to: Show the Last Error When Debugging Code

Concepts

Debugging


How to: Add Variables to the Watches FactBox

You can use the Watches FactBox to view the values of variables. Variables that you add to the Watches FactBox are displayed until you delete them, even if they go out of scope in the currently executing code. This is different from the Debugger Variable List page, which displays only the variables that are currently in scope. If a variable is out of scope, then <Out of Scope> is displayed in the Value column of the Watches FactBox.

Variables that you add to the Watches FactBox are persisted between debugging sessions.

To add a variable to the Watches FactBox

  1. To add a variable from the code viewer, do the following:

    1. On the Debugger page, in the code viewer, pause the mouse pointer over the variable that you want to add to the Watches FactBox.

      A DataTip appears.

    2. In the DataTip, choose the Watch icon to the left of the variable.

  2. To add a variable from the variable list, do the following:

    1. On the Debugger page, choose Variables.

    2. On the Debugger Variable List page, select a variable that you want to add to the Watches FactBox, and then choose Add Watch.

See Also

Tasks

How to: Remove Variables from the Watches FactBox
Walkthrough: Debugging the Microsoft Dynamics NAV Windows Client


How to: Remove Variables from the Watches FactBox

You can remove a variable from the Watches FactBox if you do not want to continue to inspect its value.

To remove a variable from the Watches FactBox

  • On the Debugger window, in the Watches FactBox, select one or more variables that you want to remove from the Watches FactBox, and then choose Delete Watch.

See Also

Tasks

How to: Add Variables to the Watches FactBox
Walkthrough: Debugging the Microsoft Dynamics NAV Windows Client


How to: Show the Last Error When Debugging Code

On the Debugger page, if code execution has paused and an error has occurred in the session that is being debugged, then you can show the last error message. This allows you to see the error that has occurred prior to the break.

To show the last error when debugging code

  • In the Debugger window, on the Home tab, in the Show group, choose Last Error. The last error message is displayed.

See Also

Tasks

How to: View Variables That Are in Scope

Concepts

Debugging


How to: Debug a Background Session

A background session that is started by using the STARTSESSION Function (Sessions) can be difficult to debug because it is called by C/AL code for which you often do not have dedicated control. Therefore, you cannot debug the calling code and step through it to access the background session. To debug a background session, you must first set a breakpoint in the codeunit that runs when the session is started.

Before you begin, you must verify that no breakpoints are currently enabled in the calling code. For more information about how to view and disable breakpoints, see How to: Manage Breakpoints from the Debugger Breakpoint List.

To debug a background session

  1. In the development environment, on the Tools menu, choose Object Designer.

  2. In Object Designer, choose the Codeunit button, select the codeunit that is run when you start the background session, and then choose the Design button. The ID of this codeunit is the value that you pass to the STARTSESSION function in the CodeunitID parameter.

  3. In the C/AL Editor, place the cursor on the first line of the OnRun trigger.

  4. On the Tools menu, choose Debugger, and then choose Toggle Breakpoint. A red dot is displayed in the margin, and the breakpoint is immediately enabled.

  5. On the Tools menu, choose Debugger, and then choose Debug Session. The Session List page opens.

  6. On the Session List page, choose Debug Next. The debugger is now active and is waiting to attach to a session.

  7. Start a new business session. For more information about types of business sessions, see Debugging.

  8. In the new business session, perform the action required to call the STARTSESSION function. The background session starts and calls the codeunit in which you have set a breakpoint. The debugger breaks at the breakpoint in the background session.

See Also

Reference

STARTSESSION Function (Sessions)


How to: Disable Debugging

You can disable debugging for an instance of Microsoft Dynamics NAV Server. If you disable debugging, then you get an error if you choose Debug Next or Debug on the Session List page.

To disable debugging

  1. Configure Microsoft Dynamics NAV Server by doing one of the following:

    • Use the Microsoft Dynamics NAV Server Administration tool. For more information, see Microsoft Dynamics NAV Server Administration Tool.

    • Edit the CustomSettings.config file. For more information, see Configuring Microsoft Dynamics NAV Server.

  2. Set the DebuggingAllowed key to false.

See Also

Concepts

Debugging


Code Changes While Debugging

While you are debugging, you may want to edit code, compile, and save objects. In this case, you must know which version of the code that the debugger executes and displays.

When the debugger loads code to display in the code viewer, it loads code from the newest compiled version of the object. Similarly, when Microsoft Dynamics NAV loads an object into memory to be executed, it loads the newest compiled version of the object. After an object is loaded into memory and is executing, it is not reloaded.

If you change, compile, and save an object that is not currently executing, then when you next execute that object, the changed version of the object is loaded into memory and executed. This behavior is the same if you are debugging a session. If the object that you changed is not currently executing or being debugged, then when you execute the object, the changed version is executed and displayed in the debugger.

If you change, compile, and save an object that is currently executing, then the object is not reloaded. The application continues to execute the original version of the object. This behavior is also the same if you are debugging a session. If the object that you changed is currently being debugged, then the object is not reloaded. The debugger continues to execute the original version of the object and the code viewer displays the original version of the object. However, if you refresh the code in the code viewer, or if the debugger refreshes itself, then the code viewer displays the new version of the code, not the version that is currently executing and being debugged.

See Also

Concepts

Debugging


Debugger Keyboard Shortcuts

The following table describes the keyboard shortcuts that are available from the Debugger window.

Keystroke | Action
F11 | Step into
F10 | Step over
Shift+F11 | Step out
F5 | Continue
Ctrl+Shift+B | Break
Shift+F5 | Stop
F9 | Toggle
Shift+F9 | Open the Debugger Breakpoint Condition window
Ctrl+Shift+V | Open the Debugger Variable List window
Ctrl+Shift+. | Zoom in on the code viewer
Ctrl+Shift+, | Zoom out of the code viewer
Ctrl+Alt+Q | Show the tooltip for the variable on which the cursor is located
Enter (when tooltip is displayed) | Add a variable to the Watches FactBox
Esc (when tooltip is displayed) | Hide tooltip

See Also

Tasks

Walkthrough: Debugging the Microsoft Dynamics NAV Windows Client


Closing the Debugger

When you close the Debugger window, the debugger detaches from the session. The session continues running without the debugger attached.

After you close the Debugger window, you can select a different session to debug. For more information, see Activating the Debugger.


Troubleshooting: "Microsoft.Dynamics.Nav.Client has stopped working" error when starting debugger

When you try start debugger from the Microsoft Dynamics NAV Development Environment, you can get the following error:

Microsoft.Dynamics.Nav.Client has stopped working.

This error indicates that the Microsoft Dynamics NAV Windows client cannot start. The error can occur when the version of development environment is different than the version of the Microsoft Dynamics NAV Windows client that debugger is starting. You can verify the versions by comparing the Application Version for the Microsoft Dynamics NAV Windows client that is shown in details section of the error dialog box with the version of the development environment.

Resolution

By default, the development environment starts the version of the Microsoft Dynamics NAV Windows client that was last installed. The Microsoft Dynamics NAV Windows client that is used by debugger is determined by the path that is specified by a protocol handler in the following registry key on the computer running the development environment:

HKEY_CLASSES_ROOT\DYNAMICSNAV\Shell\Open\Command

To work around this issue, before you start debugger, change the data value of the registry key entry to the path of the Microsoft Dynamics NAV Windows client that you want to use for debugging. For example, to start the Microsoft Dynamics NAV 2016 version of the the Microsoft Dynamics NAV Windows client, set the value to C:\Program Files (x86)\Microsoft Dynamics NAV\90\Microsoft.Dynamics.Nav.Client.exe -protocolhandler "%1".

See Also

Tasks

How to: Activate the Debugger from the Development Environment

Concepts

Debugging


Comparing and Merging Application Object Source Files

When you create or modify application objects, you use the Microsoft Dynamics NAV Development Environment, and you import and export objects as .fob files. But you can also export objects as text files and use other tools, such as the Microsoft Dynamics NAV 2016 Development Shell, to make general changes to the objects. For example, you can use Windows PowerShell cmdlets to merge changes from an upgrade with your Microsoft Dynamics NAV solution.

You can export all application objects to a single text file. Optionally, you can split the large text file into separate text files for each application object. You can also use an external source control system to store the text files, such as Visual Studio Team Foundation Server, but this is not required by the Microsoft Dynamics NAV cmdlets.

The application merge utilities that are available in the Microsoft Dynamics NAV 2016 Development Shell install when you choose the Developer option in Microsoft Dynamics NAV 2016 Setup, or if you add the development environment to another installation option.

Comparing and Merging Application Objects

Microsoft Dynamics NAV includes Windows PowerShell cmdlets that help you apply changes to Microsoft Dynamics NAV solutions. You can use Microsoft Dynamics NAV cmdlets to modify application object source files in the Microsoft Dynamics NAV 2016 Development Shell, or by importing the Microsoft.Dynamics.NAV.Model.Tools.psd1 module into the Windows PowerShell Integrated Scripting Environment (ISE).

When Microsoft releases a new version of Microsoft Dynamics NAV, you want to upgrade your solution. Similarly, you want to update your solution with cumulative updates and other smaller changes to the application. Each time you want to update your solution, you have to compare the original version to the new version, and then you have to apply the difference to your own solution. Or you compare the new version to your own solution and merge the changes into your solution. In both cases, you compare different versions of application objects to calculate and apply the difference. The Merge-NAVApplicationObject cmdlet compares the changes that have been made to application objects between two sets of Microsoft Dynamics NAV application objects, and applies the difference to a third set of application objects, the target of the merge. The result of the application object merge is a fourth set of application objects that make up your new, updated solution.

In the Microsoft Dynamics NAV 2016 Development Shell, you can also use other Windows PowerShell cmdlets that help you with manage application object files. But the recommended way to update your application is to use the Merge-NAVApplicationObject cmdlet. The other option is a two-step process using the Compare-NAVApplicationObject and Update-NAVApplicationObject cmdlets.

You can use the application merge utilities to merge and update the following application object types:

  • Tables

  • Pages

  • Reports

  • Codeunits

  • MenuSuites

  • Queries

  • XMLPorts

You cannot use the cmdlets to modify dataports, forms, or reports with classic report sections. Also, some parts of some object types require special attention from the tool or from you as described in the following list:

  • Application object properties

    Each of the application object properties in the application object files often calls for hands-on handling. The text files specify the Modified, Date, Time, and VersionList properties for each object. When you run the Merge-NAVApplicationObject cmdlet, you can set parameters that are specific for application object properties. But two cmdlets are available specifically for post-processing of object properties: Get-NAVApplicationObjectProperty and Set-NAVApplicationObjectProperty.

    Often handling or setting application object properties is done at a later time than the merge itself. For example, you run the merge, resolve the conflicts, and once you are done, you want to stamp the current date and time on all objects. To do that, use the Set-NAVApplicationObjectProperty cmdlet to change the values of the Version List, Date, Time, or Modified properties in the specified text files. You can use the Set-NAVApplicationObjectProperty cmdlet to extract information about the application objects before you change them.

  • Documentation triggers

    In each object, the documentation trigger is used for many different purposes. Documentation, of course, but also for tracking changes with date or history semantics built into it. You can use the cmdlets to modify the contents of the documentation section. If you want to be explicit about how the content of the documentation triggers is merged, you can set the -DocumentationConflict parameter when you run the Merge-NAVApplicationObject cmdlet. Set this parameter when you are merging objects with the same type of content in the documentation trigger, such as technical descriptions or a version list. By default, conflicting lines of documentation are merged into the result file with the content from the modified object listed first. This is particularly useful when the objects contain version history in the documentation triggers.

  • ControlID

    Sometimes, developers in-house or external partners create objects in the same ID range as you. This surfaces in the merge process as conflicts and hence as work to do. The application merge utilities provide ways to handle that, depending on your needs and requirements. To reduce noise, by default the Merge-NAVApplicationObject cmdlet suppresses conflicting modifications on non-functional incidents such as the ordering of variables and methods that are sometimes referred to as control IDs. If you set the-Strict parameter, these occurrences are treated like any other conflicts and reported accordingly.Significant IDs, such as table and field IDs, are fully considered during compare and merge.

  • CaptionML

    Captions are an integral part of the solution, but when you compare two versions of the same object with two different languages, you will see extensive differences. You can choose to export captions into text files before you compare or merge application objects. For example, you can use the Export-NAVApplicationObjectLanguageWindows PowerShell cmdlet to export specific languages from the objects before you merge them. You can then use the Import-NAVApplicationObjectLanguage cmdlet to import the captions after the merge. Other Windows PowerShell cmdlets support joining and splitting application object language files.

When you merge application changes by running the Merge-NAVApplicationObject cmdlet or the Update-NAVApplicationObject cmdlet, the differences are applied automatically if possible. However, when conflicts are detected, they are captured in CONFLICT files that clearly identify where two parties such as you and Microsoft have changed the same object or parts of it. For more information, see Handling Merge Conflicts.

Scenario: Updating your Solution to the Next Cumulative Update

In the following example, you have built a solution that is based on Microsoft Dynamics NAV 2016, MySolution. Microsoft then releases Microsoft Dynamics NAV 2016 Cumulative Update 1 that includes hotfixes and two regulatory features for your country/region. To help you apply the cumulative update to your solution, you use the Microsoft Dynamics NAV cmdlets. The cmdlets calculate the modifications that Microsoft made between the original release and the cumulative update, and apply these to your solution. Then, you must manually resolve any conflicts, such as both you and Microsoft modified a report object or a table. You must also validate the automatically applied modifications through testing and maybe code review. The following table describes the three versions of the Microsoft Dynamics NAV application that you want to compare and merge.

Version Description

ORIGINAL

The baseline of the application merge. For example, the Microsoft release of Microsoft Dynamics NAV 2016.

MODIFIED

The updated version of the original. For example, this can be Microsoft Dynamics NAV 2016 Cumulative Update 1. Alternatively, it can be a small add-on.

In many cases, the modified application is the version that contains fewer changes to the original than the version that is the target of the merge. This is because you want to apply fewer changes to a large application rather than applying a large change to a small application.

TARGET

The version of the application that you want to apply the difference between the original and the modified application to. For example, this can be your solution that you want to apply a cumulative update to. Alternatively, it can be a new major release from Microsoft that you want to apply your modified solution to.

The Microsoft Dynamics NAV cmdlets calculate the modifications made from ORIGINAL to MODIFIED, capture these, and then apply automatically as many as possible to the TARGET application. The resulting application is stored in a RESULT folder. Some application objects cannot be merged automatically; these conflicts are described in separate text files that you can analyze for further processing.

Tip
The use of TARGET as the name of the folder in the sample scripts and in the -TargetPath cmdlet parameters indicates the most common direction of the merge: You apply external modifications to a target solution. However, there are scenarios where it makes sense to swap the versions that you specify as MODIFIED and TARGET, such as when you upgrade from version to version. Since the processing is so fast, typically just a few minutes, it is recommended that you try out both options. For the smoother experience, place the set of application objects with the fewest modifications in MODIFIED.

See Also

Tasks

How to: Merge Application Changes
How to: Compare and Update Application Object Source Files

Concepts

Handling Merge Conflicts
Merging Application Objects using the Example Scripts
Working with Application Objects as Text Files
Microsoft Dynamics NAV Windows PowerShell Cmdlets


Handling Merge Conflicts

When you merge application changes by running the Merge-NAVApplicationObject cmdlet or the Update-NAVApplicationObject cmdlet, the differences are applied automatically if it is possible. However, when conflicts are detected, they are captured in CONFLICT files. The CONFLICT files clearly identify where two parties such as you and Microsoft have changed the same object or parts of it.You can open a CONFLICT file in Notepad, for example, and see the type of conflict, such as a code conflict or conflicting object property values. By clearly identifying the conflicts in this manner and automatically merging all other changes, you can more easily resolve the conflicts.

Identifying Conflicts

Depending on your application, the merge process often identifies one or more conflicts. The CONFLICT files describe differences that were not automatically merged. This includes conflicting code modifications, property settings, and application code. Each conflict is clearly marked in the corresponding application object text file in the RESULT folder. A copy of the files in ORIGINAL, MODIFIED, or TARGET that caused the conflict is added to subfolders to the RESULT folder.For example, if you run the Merge-NAVApplicationObject cmdlet on three different versions of codeunit 1, and a conflict is found, the RESULT folder will contain the following:

Folder | File name | Description
RESULT | COD1.CONFLICT | Describes the conflict, such as a code modification in a function.
 | COD1.TXT | The merged application object that has the conflicting code clearly marked.
ConflictModified | COD1.TXT | The conflicting application object from the MODIFIED version.
ConflictOriginal | COD1.TXT | The conflicting application object from the ORIGINAL version.
ConflictTarget | COD1.TXT | The conflicting application object from the TARGET version.

Since the CONFLICT files describe the conflicts, you can import the merged text files into the Microsoft Dynamics NAV Development Environment and resolve the conflicts there. Alternatively, you can use an external three-way merge tool to analyze the conflicts.

In most cases, the text files that contain the merged application objects clearly identify where the conflict is. The following code example illustrates an object that has a conflict.

Copy Code
    PROCEDURE ApplicationBuild@3() : Text[80];
    BEGIN
      {>>>>>>>} ORIGINAL
      EXIT('35473-ORIGINAL');
      {=======} MODIFIED
      EXIT('35978');
      {=======} TARGET
      EXIT('35473');
      {<<<<<<<}
    END;

In this example, the ApplicationBuild function is different in all three versions of codeunit 1 that you tried to merge. If you import this file into the development environment, it will not compile. You can resolve the conflict in Notepad, a three-way merge tool, or in the development environment. Use the source files in the subfolders in the RESULT folder to learn how to resolve the conflict.

See Also

Tasks

How to: Merge Application Changes

Concepts

Merging Application Objects using the Example Scripts
Comparing and Merging Application Object Source Files
Microsoft Dynamics NAV Windows PowerShell Cmdlets


Merging Application Objects using the Example Scripts

The Microsoft Dynamics NAV product media includes a folder with examples of how you can use Windows PowerShell cmdlets to compare and merge application objects. In the WindowsPowerShellScripts folder on the product media, the ApplicationMergeUtilities folder contains Windows PowerShell sample scripts and folders that contain demonstration data.

You can run the sample scripts from the Microsoft Dynamics NAV 2016 Development Shell. Alternatively, you can use the Windows PowerShell Integrated Scripting Environment (ISE) as described in the following section.

The individual scripts provide different variations of how you can use the Microsoft Dynamics NAV cmdlets. For example, the HowTo-Merge-N-Conflicts-External-Tools.ps1 script shows different ways of displaying conflicts. By opening the scripts in the Windows PowerShell ISE, you can examine the different variations and decide how you want to use the cmdlets to upgrade and maintain your own application.

Using the Sample Scripts in the Windows PowerShell ISE

If you want to use the Windows PowerShell ISE, you must you must import the Microsoft.Dynamics.Nav.Model.Tools.psd1 module. The module installs to the equivalent of C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client when you choose the Developer option in Microsoft Dynamics NAV 2016 Setup.

For example, you can import the module into the Windows PowerShell ISE by typing a command such as the following:

Copy Code
Import-Module "${env:ProgramFiles(x86)}\Microsoft Dynamics NAV\90\RoleTailored Client\Microsoft.Dynamics.Nav.Model.Tools.psd1" -force

Get-Help "NAV"

Now you can see the Help for the cmdlets and take a closer look at the examples for how to use them.

The ApplicationMergeUtilities folder contains four subfolders that can help you start working with the scripts. The demonstration data in the ORIGINAL, MODIFIED, and TARGET folders illustrate the text files that are the input to the cmdlets. The demonstration data uses separate text files for each application object, but you can configure the text files in the way that works better for you. For example, you can use the Join-NAVApplicationObjectFile cmdlet to combine all the text files in the MODIFIED folder in a single file, for example, before you run the script.

The HowTo-Start-Import-NAV-Module.ps1 script imports the Microsoft.Dynamics.Nav.Model.Tools.psd1 module into the Windows PowerShell ISE. The __Run-Application-Merge-Utilities.ps1 and __Reset-HowTo-Sample.ps1 scripts enable you to run the sample scripts repeatedly.

For Help for a Microsoft Dynamics NAV cmdlet, type Get-Help <cmd name>. For Help for the Windows PowerShell ISE, press F1, or choose the Help menu, and then choose Windows PowerShell ISE Help.

See Also

Tasks

How to: Merge Application Changes

Concepts

Microsoft Dynamics NAV Windows PowerShell Cmdlets
Comparing and Merging Application Object Source Files


How to: Merge Application Changes

Microsoft Dynamics NAV includes Windows PowerShell cmdlets that can help you apply changes to your application by comparing and merging application objects from different versions. For example, you can use the Merge-NAVApplicationObject cmdlet to update your solution when Microsoft releases an update.

The Windows PowerShell cmdlets compare two sets of application objects, calculate the difference, and apply as many of changes as possible to a third version. You can use the cmdlets from the Microsoft Dynamics NAV 2016 Development Shell or from the Windows PowerShell Integrated Scripting Environment (ISE). The sections in this topic illustrate how you can use the Merge-NAVApplicationObject cmdlet to merge application changes into your solution. The sections are based on a scenario you want to apply changes from an update to your version of Microsoft Dynamics NAV. For more information, see Comparing and Merging Application Object Source Files.

The scenario is based on the following three versions of the Microsoft Dynamics NAV application:

Version label | Description
ORIGINAL | The Microsoft release of Microsoft Dynamics NAV.
MODIFIED | The updated version of Microsoft Dynamics NAV, such as Cumulative Update 1.
TARGET | Your solution that is based on Microsoft Dynamics NAV, such as MySolution.

The steps in the following procedures compare the ORIGINAL version to the MODIFIED solution and apply the relevant changes to your TARGET solution. As a result, you have an application that contains your solution with the updates from the MODIFIED application. Alternatively, the MODIFIED solution can be your solution and the TARGET solution can be the new release from Microsoft. The actual versions that you use to set each cmdlet parameter depend on your concrete scenario. However, we recommend that MODIFIED contains the solution with the fewest changes compared to ORIGINAL.

First, you prepare the application object files for the ORIGINAL version. You can do that by exporting the application object from the development environment, or by using the development environment command ExportObjects. The following procedure illustrates how to export the objects by calling finsql.exe file from a command prompt.

To prepare the application object files

  1. In a command prompt, type a command such as the following:

    Copy Code
    finsql.exe command=exportobjects, file=<file name>.txt, servername=<server name>, database=<database name>, ntauthentication=yes

    For example, to export all objects in the original Microsoft-provided version of Microsoft Dynamics NAV to a single text file, type the following:

    Copy Code
    finsql.exe command=exportobjects, file=original_all.txt, servername=MyServer, database="Demo Database NAV (9-0)", ntauthentication=yes

  2. Optionally, split the exported text file into separate files using the Split-NAVApplicationObjectFile cmdlet in the Windows PowerShell ISE or in the Microsoft Dynamics NAV 2016 Development Shell. Alternatively, you can do that as the first step in the next procedure.

  3. Repeat these steps until you have the three sets of text files.

  4. Copy the exported text files to the location where you want to run the merge process. Make sure that the text files are put in folders that reflect the version that they were exported from. The names of the folders are not important, but you must modify any Windows PowerShell command or script to use the folder structure that you have set up.

    For example, create a root folder such as C:\UPGRADE. Then create three subfolders that contain the three sets of application object files, such as ORIGINAL, MODIFIED, and TARGET.

When you have the text files that you need, and you have the folder structure that you need, you can run the Merge-NAVApplicationObject cmdlet to merge the changes between ORIGINAL and MODIFIED into your TARGET application. The cmdlet will put the resulting text files into the folder that you specify in the -ResultPath parameter, such as RESULT.

To run the Merge-NAVApplicationObject cmdlet to merge application objects

  1. Open the Microsoft Dynamics NAV 2016 Development Shell in administrator mode.

  2. Navigate to the location of your folders by typing a command such as the following:

    Copy Code
    cd c:\upgrade

    In this example, the UPGRADE folder on the C drive contains the three folders that you created in the previous procedure, and it contains an empty RESULTS folder. You can now run the cmdlet.

  3. To run the cmdlet and automatically merge as many objects as possible, type the following command:

    Copy Code
    Merge-NAVApplicationObject -OriginalPath .\ORIGINAL -TargetPath .\TARGET -ModifiedPath .\MODIFIED -ResultPath .\RESULT

Depending on the number of objects that you are merging and the number of differences found, this can take a few seconds, a few minutes, or longer. When the process completes, the result is shown. If no conflicts are found, the application merge is complete and you can import the text files from the RESULT folder into the Microsoft Dynamics NAV development environment and compile them. If any conflicts are found, you must resolve them.

Alternatively, you can use the Compare-NAVApplicationObject cmdlet and Update-NAVApplicationObject cmdlet to first compare and the apply the difference. How to: Compare and Update Application Object Source Files

Managing Conflicts

At the end of the previous procedure, the RESULT folder contains text files with merged application objects and zero or more CONFLICT files. Since the CONFLICT files describe the conflicts, you can import the merged text files into the Microsoft Dynamics NAV Development Environment and resolve the conflicts there. Alternatively, you can use an external three-way merge tool to further analyze the conflicts. For more information, see Handling Merge Conflicts.

To resolve merge conflicts in the development environment

  1. Import the text files that contain the merged application objects into the relevant database in the Microsoft Dynamics NAV Development Environment.

    In the previous procedure, the merged objects were stored in the RESULT folder. Optionally, you can choose to run the Join-NAVApplicationObjectFile cmdlet to combine the text files into a single text file for easier file management.

    Important
    You must import the text files that are the result of the previous procedure. You cannot import the CONFLICT files into Microsoft Dynamics NAV. However, you can use the CONFLICT files to identify the conflicts and decide how to resolve them.

  2. Compile all imported objects.

    The application object that contain merge conflicts cannot compile because the conflicts are identified by {>>>>>>>} elements that are not valid C/AL code. The code conflict is clearly marked with the conflicting code from each version.

  3. Resolve each conflict, and then compile the objects.

Resolving conflicts is not completely the end of the process. Even though the application objects compile, the code can still be incorrect. We recommend that you do a final validation of the automatically merged objects. The following list outlines the recommended process for completing an automated application merge:

  1. Review the code.

  2. Compile the objects.

  3. Test the solution.

  4. Optionally, export the objects as text files and check them into an external source control system.

Tip
The Microsoft Dynamics NAV product media contains a folder with Windows PowerShell sample scripts that illustrate how you can use the Merge-NAVApplicationObject cmdlet and other Windows PowerShell cmdlets. For more information, see Merging Application Objects using the Example Scripts.

See Also

Tasks

How to: Compare and Update Application Object Source Files

Reference

ExportObjects

Concepts

Handling Merge Conflicts
Merging Application Objects using the Example Scripts
Comparing and Merging Application Object Source Files
Comparing and Merging Application Object Source Files
Microsoft Dynamics NAV Windows PowerShell Cmdlets


How to: Compare and Update Application Object Source Files

You can use Windows PowerShell cmdlets to compare different sets of Microsoft Dynamics NAV application objects to identify the differences. Then, you can choose to apply all or some of the differences to a target solution.

We recommend that you use the Merge-NAVApplicationObject cmdlet because it is the faster and easier way to merge objects. However, you can choose to use the Compare-NAVApplicationObject cmdlet and Update-NAVApplicationObject cmdlet to identify the differences before you apply them. Or, for example, when you want to apply the same modifications to multiple applications or similar. The following procedures illustrate how you can use these two cmdlets in combination

The scenario is based on the following three versions of the Microsoft Dynamics NAV application:

Version label | Description
ORIGINAL | The Microsoft release of Microsoft Dynamics NAV.
MODIFIED | The updated version of Microsoft Dynamics NAV, such as Cumulative Update 1.
TARGET | Your solution that is based on Microsoft Dynamics NAV, such as MySolution.

The steps in the following procedures compare the ORIGINAL version to the MODIFIED solution and apply the relevant changes to your TARGET solution. As a result, you have an application that contains your solution with the updates from the MODIFIED application. Alternatively, the MODIFIED solution can be your solution and the TARGET solution can be the new release from Microsoft. The actual versions that you use to set each cmdlet parameter depend on your concrete scenario. However, we recommend that MODIFIED contains the solution with the fewest changes compared to ORIGINAL. The Compare-NAVApplicationObject cmdlet compares two sets of application objects and stores the differences in DELTA files in the specified folder.

The following procedure assumes that you have exported the relevant application objects to text files. For an example of how to do that, see the To prepare the application object files section in the How to: Merge Application Changes topic.

To compare two sets of application objects

  1. Open the Microsoft Dynamics NAV 2016 Development Shell in administrator mode.

  2. Navigate to the location of your folders by typing a command such as the following:

    Copy Code
    cd c:\upgrade

    In this example, the UPGRADE folder on the C drive contains five folders: ORIGINAL, MODIFIED, TARGET, DELTA, and RESULT. The DELTA and RESULT folders are empty. The ORIGINAL, MODIFIED, and TARGET folders contains one or more text files that contain application objects. You can now run the cmdlet.

  3. To run the cmdlet to compare all application objects in the ORIGINAL folder to the application objects in the MODIFIED folder, type the following command:

    Copy Code
    Compare-NAVApplicationObject -OriginalPath .\ORIGINAL -ModifiedPath .\MODIFIED -DeltaPath .\DELTA

    This generates a number of DELTA files that describe the difference between ORIGINAL and MODIFIED. You can open the DELTA files in text editors such as Notepad. The following example illustrates how a DELTA file identifies the difference between ORIGINAL and MODIFIED.

    Copy Code
      CHANGES

  {

    { CodeModification  ;Target=ApplicationBuild(PROCEDURE 3);

                         OriginalCode=BEGIN

                                        EXIT('35473-ORIGINAL');

                                      END;

                         ModifiedCode=BEGIN

                                        EXIT('35978');

                                      END;

                                       }

  }

You can apply those differences to TARGET by using the Update-NAVApplicationObject cmdlet.

To apply DELTA files to application objects

  1. Open the Microsoft Dynamics NAV 2016 Development Shell in administrator mode.

  2. Navigate to the location of your folders by typing a command such as the following:

    Copy Code
    cd c:\upgrade

    In this example, the folder structure is the same as described in the previous procedure. You can now run the cmdlet.

  3. To run the cmdlet to apply the differences that are stored in the DELTA folder to the application objects in the TARGET folder, type the following command:

    Copy Code
    Update-NAVApplicationObject -DeltaPath .\DELTA -TargetPath .\TARGET\*.txt -ResultPath .\RESULT

    This merges the difference between ORIGINAL and MODIFIED with the target solution and puts the resulting solution in the RESULT folder.

You can now import the merged objects into a Microsoft Dynamics NAV database. For more information, see How to: Merge Application Changes.

See Also

Tasks

How to: Merge Application Changes

Reference

ExportObjects

Concepts

Handling Merge Conflicts
Merging Application Objects using the Example Scripts
Comparing and Merging Application Object Source Files
Comparing and Merging Application Object Source Files
Microsoft Dynamics NAV Windows PowerShell Cmdlets


Changes in C/AL Behavior and Support from Earlier Versions of Microsoft Dynamics NAV

The following table provides an overview of the new, removed, or changed C/AL data types, functions, properties, and triggers in Microsoft Dynamics NAV 2016 since the previous version of Microsoft Dynamics NAV. For more information about the changes, see the specific topic about the data type, function, property, or trigger.

C/AL Functions

The following table lists the new, removed, or changed functions in Microsoft Dynamics NAV 2016.

Function Description

ADDFIELD Function

New function.

Adds a table field to the filter control for a table on filter page.

ADDFIELDNO Function

New function.

Adds a table field to the filter control for a table as specified by the field number.

ADDRECORD Function

New function.

Adds a filter control for a table to a filter page as specified by a record data type variable.

ADDRECORDREF Function

New function.

Adds filter control for a table to a filter page as specified by a RecordRef variable.

ADDTABLE Function

New function.

Adds filter control for a table to a filter page.

BINDSUBSCRIPTION Function

New function.

Binds event subscribers to the subscriber codeunit instance for handling events.

UNBINDSUBSCRIPTION

New function.

Unbinds event subscribers from the subscriber codeunit instance for handling events.

COUNT Function (FilterPageBuilder)

New function.

Gets the number of filter controls that are specified in the FilterPageBuilder object instance.

CREATEENCRYPTIONKEY

Changed function.

Includes a Boolean return value. The value is true if an encryption key is created successfully; otherwise, it is false.

CURRENTCLIENTTYPE Function

New function.

Gets the Microsoft Dynamics NAV client type that is running on the current session.

CURRENTCOMPANY Function (Record)

New function.

Gets the current company of a database table record.

CURRENTCOMPANY Function (RecordRef)

New function.

Gets the current company of a database table that is referred to by a RecordRef.

DEFAULTCLIENTTYPE Function

New function.

Gets the default Microsoft Dynamics NAV client type that is configured for the Microsoft Dynamics NAV Server instance that is used for the current session.

GETASCENDING Function (Record)

Gets the sort order for the records returned, such as in data from an ODATA web service.

GETURL Function

Changed function. Includes the following changes:

  • Accepts CURRENTCLIENTTYPE and DEFAULTCLIENTTYPE as ClientType parameter.

  • Supports RecordRef variable data type as a parameter to specify the record to open.

  • Includes a Boolean parameter to include filters that are setup on the object in URL.

GETVIEW function (FilterPageBuilder)

New function.

Gets the filter view (which defines the sort order, key, and filters) for the record in the specified filter control of a filter page.

IMPORTENCRYPTIONKEY

Changed function.

Includes a Boolean return value. The value is true if an encryption key is imported successfully; otherwise, it is false.

ISFILTERPAGEBUILDER Function (Variant)

New function.

Indicates whether a C/AL variant contains a FilterPageBuilder variable.

ISTEMPORARY Function (Record)

New function.

Determines whether a record refers to a temporary table.

NAME Function (FilterPageBuilder)

New function.

Gets the name of a table filter control that is included on a filter page based on an index number that is assigned to the filter control.

RECORDID (Record)

New function.

Gets the RecordID of the record that is currently selected in the table.

RUNMODAL Function (FilterPageBuilder)

New function.

Builds and runs the filter page.

SETASCENDING Function (Record)

Sets the sort order for the records returned, such as in data from a ODATA web service.

SETVIEW Function

New function.

Sets the current filter view, which defines the sort order, key, and filters, for a record in a filter control on a filter page.

GETDEFAULTTABLECONNECTION Function (Database), HASTABLECONNECTION Function (Database), REGISTERTABLECONNECTION Function (Database), SETDEFAULTTABLECONNECTION Function (Database), and UNREGISTERTABLECONNECTION Function (Database)

New functions. Registers, sets, gets, and unregister table connections to external tables.

C/AL Properties

The following table lists the new, removed, or changed properties in Microsoft Dynamics NAV 2016.

Function | Description
Event Property | New property. Used for events. Specifies whether a function is a publisher of or subscriber to an event.
EventFunction Property | New property. Used for events. Specifies the event publisher function that an event subscriber function subscribes to.
EventPublisherObject Property | New property. Used for events. Specifies the object that contains the event publisher function that an event subscriber function subscribes to.
EventSubscriberInstance Property | New property. Specifies how event subscriber functions in a codeunit are bound to codeunit instance and events that they subscribe to.
EventType Property | New property. Used for events. Specifies whether an event is a business or integration event.
GlobalVarAccess Property | New property. Used for events. Specifies whether global variables in an event publisher object can be accessed from event subscriber functions.
IncludeSender Property | New property. Used for events. Specifies whether global functions in an event publisher object can be called from event subscriber functions.
Namespaces Property | New property. Specifies one or more namespaces on an XMLport object.
NamespacePrefix Property | New property. Specifies a namespace prefix on an element of an XMLport object.
OnMissingLicense Property | New property. Specifies what happens to the event subscriber function call when the license of the Microsoft Dynamics NAV user account that is running the current session does not include the codeunit that contains the subscriber function.
OnMissingPermission Property | New property. Specifies what happens to the subscriber function call when the Microsoft Dynamics NAV user account that is running the current session does not have permission to the codeunit that contains the subscriber function.
OnValidateEventField Property | New property. Used for events. Specifies the table field that the trigger event pertains to.
Scope Property | New property. Specifies the scope of actions to be either Repeater or Page.
SQL Timestamp Property | New property. Specifies a field to be a timestamp field that contains row version numbers for records.
TableType Property | Specifies whether the table is a normal or external (CRM or ExternalSQL) table.
TryFunction Property | New property. Specifies the function to be try function, which can be used to catch and handle errors and exceptions that occur when code is run.
FunctionType Property (Upgrade Codeunits) | Changed property. Instead of the Upgrade option, there are now two options: UpgradePerCustomer and UpgradePerDatabase. The UpgradePerCustomer option behaves like the Upgrade option in the previous Microsoft Dynamics NAV version.
FunctionType Property (Test Codeunits) | Changed property. Includes the FilterPageHandler and HyperlinkHandler optiions.

C/AL Statements

The following table lists the new, removed, or changed C/AL statements in Microsoft Dynamics NAV 2016.

Statement | Description
FOREACH | New statement. Iterate through a .NET Framework collection or array. For more information, see FOREACH Control Structure.
BREAK | New statement. Terminates the iteration statement in which it used. For more information, see C/AL BREAK Statement.
Important
If your solution has used FOREACH or BREAK as names of variables in earlier versions of Microsoft Dynamics NAV, you must change the names before you upgrade to Microsoft Dynamics NAV 2016. Alternatively, you can enclose the variable names in quotation marks. If you do not, and you import an object that has this code in text format, you cannot compile the object.

See Also

Concepts

Functions Not Supported by Microsoft Dynamics NAV Web Client
Page Properties Not Supported by Microsoft Dynamics NAV Web Client


Administration

Microsoft Dynamics NAV 2016 provides different tools for different administration tasks.

To | See
Learn about the Microsoft Dynamics NAV Server Administration Tool, a Microsoft Management Console snap-in that you use to create and manage Microsoft Dynamics NAV Server instances. | Microsoft Dynamics NAV Server Administration Tool
Perform administration tasks with the Microsoft Dynamics NAV Windows PowerShell cmdlets. | Microsoft Dynamics NAV Windows PowerShell Cmdlets
Use the Microsoft Dynamics NAV Windows client or the Microsoft Dynamics NAV Web client to manage users, permission sets, and profiles. | Administration in the Clients
Use the Microsoft Dynamics NAV Development Environment to manage licenses, databases, and companies. | Administration in the Development Environment
Optimize performance when accessing Microsoft Dynamics NAV data from SQL Server. | Optimizing SQL Server Performance with Microsoft Dynamics NAV
Monitor your Microsoft Dynamics NAV Server instances. | Monitoring Microsoft Dynamics NAV Server
Connect Microsoft Dynamics NAV Windows client to Microsoft Dynamics NAV Server over a wide area network. | Connecting the Microsoft Dynamics NAV Clients over a Wide Area Network

See Also

Concepts

Deployment
Security and Protection


How to: Administer a Remote Microsoft Dynamics NAV Server Computer

You can use the Microsoft Dynamics NAV Server Administration tool to connect to other computers on your network where Microsoft Dynamics NAV 2016 is installed and manage Microsoft Dynamics NAV Server instances on those computers.

Note
In this procedure, you only administer one Microsoft Dynamics NAV Server computer at a time. To administer multiple Microsoft Dynamics NAV Server computers from a single instance of Microsoft Dynamics NAV Server Administration tool, see How to: Administer Multiple Microsoft Dynamics NAV Server Computers.

To connect to a remote Microsoft Dynamics NAV Server computer

  1. Verify that the administrator who will be connecting to the remote computer is a member of that computer’s Administrators group.

  2. On the remote computer, open a Windows PowerShell command prompt with administrative credentials. Choose Start, choose Accessories, right-click Windows PowerShell, and then choose Run as administrator.

    Windows PowerShell is included in Windows 7, Windows 8, Windows Server 2008 R2 and Windows Server 2012, and can be installed on other Windows operating systems. For more information, see Windows PowerShell in the TechNet Library.

  3. At the Windows PowerShell command prompt, type Enable-PSRemoting, and then answer Yes to all prompts.

  4. Close the Windows PowerShell command prompt window.

  5. Start the Microsoft Dynamics NAV Server Administration tool.

    For detailed instructions on starting Microsoft Dynamics NAV Server Administration tool, see "Running the Microsoft Dynamics NAV Server Administration tool" in Microsoft Dynamics NAV Server Administration Tool.

  6. In the tree view pane, choose a Microsoft Dynamics NAV Server computer, and then choose Connect to Another Computer in the right pane.

    Important
    The Connect to Another Computer command is only available when a computer instead of a Microsoft Dynamics NAV Server instance is selected in the tree view pane.

  7. In the Connect to another computer dialog box, type the name of the remote computer in the Server Name box, and then choose OK.

    The tree view changes to show Microsoft Dynamics NAV Server instances on the remote computer.


How to: Administer Multiple Microsoft Dynamics NAV Server Computers

This procedure describes how to administer multiple Microsoft Dynamics NAV Server computers from a single instance of the Microsoft Dynamics NAV Server Administration tool. In this procedure, you start the Microsoft Management Console (MMC) and then configure it to administer multiple Microsoft Dynamics NAV Server computers. If you start the Microsoft Dynamics NAV Server Administration tool from Control Panel or the Start menu, then you can only connect to a single Microsoft Dynamics NAV Server computer at a time. For more information, see How to: Administer a Remote Microsoft Dynamics NAV Server Computer

To configure MMC to connect to multiple Microsoft Dynamics NAV Server computers

  1. Verify that the administrator who will be connecting to the remote computer is a member of that computer’s Administrators group.

  2. On each remote computer, open a Windows PowerShell command prompt with administrative credentials. Choose Start, choose Accessories, right-click Windows PowerShell, and then choose Run as administrator.

    Windows PowerShell is included in Windows 7, Windows 8, Windows Server 2008 R2, and Windows Server 2912 and can be installed on other Windows operating systems. For more information, see Windows PowerShell in the TechNet Library.

  3. On each remote computer, at the Windows PowerShell command prompt, type Enable-PSRemoting, and then answer Yes to all prompts.

  4. On the local Microsoft Dynamics NAV Server computer, choose Start, choose Run, and then enter the following command to run the Microsoft Management Console:

    Copy Code
    mmc

  5. In the Management Console, on the File menu, choose Add/Remove Snap-in to open the Add or remove Snap-ins dialog box.

  6. In the Available snap-ins list, double-click Microsoft Dynamics NAV.

  7. In the Connect to another computer dialog box, type the name of a Microsoft Dynamics NAV Server computer in the Server Name box, and then choose OK.

  8. Double-click Microsoft Dynamics NAV again, and then enter the name of a different Microsoft Dynamics NAV Server computer in the Server Name box. Choose OK.

    You can also accept the default value, which is (Local), if this is one of the Microsoft Dynamics NAV Server computers that you will be administering.

  9. Continue selecting Microsoft Dynamics NAV Server computers as needed. When you are finished selecting computers, choose OK to close the Add or remove Snap-ins dialog box.

    Now you see multiple Microsoft Dynamics NAV Server computers listed in the tree view pane of the Microsoft Dynamics NAV Server Administration tool:

    Tip
    When you close MMC, you are prompted to save your settings to a Microsoft Management Console (.msc) file. If you save your settings, then you can use this file to open MMC with your Microsoft Dynamics NAV Server computers already listed

See Also

Concepts

Microsoft Dynamics NAV Server Administration Tool


How to: Create a Microsoft Dynamics NAV Server Instance

A Microsoft Dynamics NAV Server instance is the service through which the various types of Microsoft Dynamics NAV clients interact with the Microsoft Dynamics NAV SQL Server database. When you install Microsoft Dynamics NAV Server on a computer, there is initially a single default instance. If your organization requires additional instances, then you can either install Microsoft Dynamics NAV Server on additional computers or create additional instances on the original Microsoft Dynamics NAV Server computer. In this procedure, you create a Microsoft Dynamics NAV Server instance in the Microsoft Dynamics NAV Server Administration tool.

To create a Microsoft Dynamics NAV Server instance

  1. Open the Microsoft Dynamics NAV Server Administration tool. Choose Start, and in the Search programs and files box, enter Microsoft Dynamics NAV Administration, and then choose the related link.

  2. In the tree view, which is the left pane, select the Microsoft Dynamics NAV Server computer where you want to add an instance. This is typically the local computer, which is Microsoft Dynamics NAV (local). For more information about remote administration, see How to: Administer a Remote Microsoft Dynamics NAV Server Computer.

  3. Right-click the computer name, and then choose Add Instance.

  4. Supply the required values in the Server instance settings section for the new instance.

    Note
    Each instance on a computer must have unique values for these settings.

  5. Supply the required values in the Log on Account section, and then specify the computer account that will run the instance in the Service Account field. You can select the Network Service account or a domain user account If you select Network Service in the Service Account field, then you do not have to specify values for the User name, Domain, and Password fields.

    Security Note
    Using the Network Service account to run a Microsoft Dynamics NAV Server instance is considered less secure because this account is a shared account that can be used by other unrelated network services. Any user who has rights to the Network Service account also has rights to other services that are running on this account. Running Microsoft Dynamics NAV Server instances under a dedicated domain user account, which is an account that is used only for Microsoft Dynamics NAV components, is more secure but does require a domain administrator to set up and provision the account.

See Also

Concepts

Managing Microsoft Dynamics NAV Server Instances


How to: Mount or Dismount a Tenant on a Microsoft Dynamics Server Instance

If a Microsoft Dynamics NAV Server instance is configured for multitenancy, then you can mount and dismount tenant databases by using the Microsoft Dynamics NAV Server Administration tool or Mount-NAVTenant or Dismount-NAVTenant cmdlets in Microsoft Dynamics NAV 2016 Administration Shell.

Mounting a tenant by using the Microsoft Dynamics NAV Server Administration tool requires that you have a running Microsoft Dynamics NAV Server instance. This is not required when you use the Microsoft Dynamics NAV 2016 Administration Shell. With the Mount-NAVTenant, you can mount a tenant by either specifying the Microsoft Dynamics NAV Server instance, if it is running, or the application database.

This topic describes how to use the Microsoft Dynamics NAV Server Administration tool to mount or dismount a tenant. For more information about how to use the Microsoft Dynamics NAV 2016 Administration Shell, see Mount-NAVTenant and Dismount-NAVTenant.

To mount or dismount a tenant

  1. Open the Microsoft Dynamics NAV Server Administration tool.

    1. Choose Start, and in the Search programs and files box, type Microsoft Dynamics NAV Administration, and then choose the related link.

  2. Verify that the Microsoft Dynamics NAV Server that you want to mount the tenant on is running, and if not, then start it:

    1. In the left pane of Microsoft Dynamics NAV Server Administration tool, choose a Microsoft Dynamics NAV Server computer. Unless you are administering a remote computer, this is Microsoft Dynamics NAV (local).

    2. In the center pane, if the Status of the Microsoft Dynamics NAV Server instance is Stopped, then right-click it, and then choose Start.

  3. In the left pane, expand item for the Microsoft Dynamics NAV Server instance on which you want to mount the tenant, and then choose the Tenants item.

  4. To mount a tenant, in the Actions pane, choose Mount Tenant, fill in the parameters on the Mount Tenant dialog box, and then choose the OK button.

    The following table describes the parameters on the Mount Tenant dialog box.

    Setting Description Required

    ID

    Specifies the ID of the tenant to mount. If the tenant database has not been mounted on a Microsoft Dynamics NAV Server instance before, then you can specify any ID that you want that is not being used. This ID is then assigned to the database. The ID cannot be used by another tenant database and must comply with the following rules:

    • Contains only letters (Aa-Zz), numbers (0-9), or dashes (-).

      Note
      The ID is not case sensitive.

    • Does not start or end with a dash (-).

    • Less than 63 characters.

    Important
    If the database is the first tenant database ever to be mounted on the Microsoft Dynamics NAV Server instance, then you must set the value to default or select the Overwrite Tenant ID in the Database check box, and then specify an ID according to the previous rules.

    If the tenant database has been mounted in a Microsoft Dynamics NAV Server instance before, then you must specify the tenant ID that is assigned to that database or specify another ID and select the Overwrite Tenant ID in the Database check box.

    Yes

    Database Name

    Specifies the name of the Microsoft Dynamics NAV database that you want to mount on the Microsoft Dynamics NAV Server instance. For example, to mount the CRONUS International Ltd. demonstration database, specify Demo Database NAV (9-0).

    Yes

    Database Server

    Specifies the network name of the computer that is running SQL Server and the SQL Server database instance to connect to. You specify the value by using the format ComputerName\SQLServerInstance. The default database instance for Microsoft Dynamics NAV is NAVDEMO.

    No

    Alternate Tenant IDs

    Specifies the alternative IDs for the tenant, such as host names for the Microsoft Dynamics NAV Web client, SOAP web services, OData web services, or the Microsoft Dynamics NAV Windows client.

    If you use alternative IDs for tenant resolution in the Microsoft Dynamics NAV Web client, you must also enable some of the UrlRewrite rules in the web.config file for the Microsoft Dynamics NAV Web Server components.

    No

    Allow Application Database Writes

    Specifies whether the tenant can write to the application database.

    You must create at least one tenant that has write access to the application database.

    No

    Enable NAS Services

    Specifies whether NAV Application Server services are enabled for the tenant. For more information about NAS, see Configuring NAS Services.

    No

    Run NAS Services with Admin Rights

    Specifies whether NAS services run operations with administrator rights instead of the rights that are granted to the Microsoft Dynamics NAV Server service account.

    • If you select this setting, NAS services will have full permissions in Microsoft Dynamics NAV, similar to the permissions that are granted by the SUPER permission set. The Microsoft Dynamics NAV Server service account is not required to be set up as a user in Microsoft Dynamics NAV.

    • If you clear this setting, the Microsoft Dynamics NAV Server service account must be added as a user in Microsoft Dynamics NAV and assigned the permissions that are required to perform the operations.

    No

    Default Company

    Specifies the default Microsoft Dynamics NAV company for the tenant. A tenant can contain several companies. This is the company that opens by default in Microsoft Dynamics NAV client.

    No

    Default Time Zone

    Specifies the default time zone in which web service and NAS services calls on the tenant are run. You can specify the following values:

    • UTC - All business logic for web services and NAS services on the server instance runs in Coordinated Universal Time (UTC). This is how all web services business logic was handled in Microsoft Dynamics NAV 2009 and Microsoft Dynamics NAV 2009 SP1.

    • Server Time Zone - Services use the time zone of the computer that is running Microsoft Dynamics NAV Server.

    • <ID of any time zone recognized by the current version of Windows> - Specifies any Windows time zone as defined in the system registry under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones. For example, Romance Standard Time.

    No

    DatabaseUserName

    You use this setting, together with the ProtectedDatabasePassword setting, to configure SQL Server authentication with the tenant database in SQL Server.

    This setting specifies the login name of the user account in the database that you want to use for authentication.

    No

    ProtectedDatabasePassword

    You use this setting, together with the DatabaseUserName setting, to configure SQL Server authentication with the tenant database in SQL Server.

    This setting specifies the login password of the user account in the database that you want to use for authentication.

    No

    Overwrite Tenant ID in Database

    Specifies whether to overwrite the tenant ID in the database if the database has been mounted as a tenant earlier. Select this check box if you want to use the tenant ID that is specified in the ID parameter instead of the tenant ID in the database that you are mounting to the Microsoft Dynamics NAV Server instance. If you clear this check box, and the tenant database has previously been mounted with a different tenant ID, an error will occur.

    No

    Synchronization Mode

    Specifies how the database schema for the tenant database is synchronized with the database schema that the mounted application database defines. The default value is Synchronize. You can select one of the following values.

    • Synchronize without confirmation - The database schema in the tenant database is updated with the application database schema even if data is lost. For example, if a table or a field has been deleted in the current application, the table or field is removed from the tenant database even if it contains data.

    • Do not allow changes - If the database schema in the tenant database differs from the current application, the tenant cannot be mounted against the Microsoft Dynamics NAV Server instance.

    • Synchronize - The database schema in the tenant database will be updated unless data is lost. For example, if a table or a field has been deleted in the current application, and it contains data in the tenant database, the tenant cannot be mounted against the Microsoft Dynamics NAV Server instance.

    • Check only - Microsoft Dynamics NAV Server tests if a change in the current application will cause data loss in the tenant database if the tenant is mounted with Synchronization Mode set to ForceSync. For example, if a table or a field has been deleted in the current application and it contains data in the tenant database.

    No

  5. To save the changes, choose the OK button.

    If you specified the DatabaseUserName and ProtectedDatabasePassword settings for SQL Server authentication, on the Enable Encryption on SQL Server Connections dialog box, choose the OK button.

    Encryption keys are to secure the login credentials over the connection between the Microsoft Dynamics NAV Server instance and the Microsoft Dynamics NAV database in SQL Server.

  6. Choose the OK button to save the changes.

To dismount a tenant

  • In the center pane, right-click the tenant, and then choose Dismount Tenant.

See Also

Tasks

How to: Start, Stop, Restart, or Remove a Microsoft Dynamics NAV Server Instance

Concepts

Microsoft Dynamics NAV Server Administration Tool
Multitenant Deployment Architecture


Managing Microsoft Dynamics NAV Server Instances

This topic describes how to work with Microsoft Dynamics NAV Server instances in the Microsoft Dynamics NAV Server Administration tool and in the Services MMC snap-in. For more information about how to create a Microsoft Dynamics NAV Server instance, see How to: Create a Microsoft Dynamics NAV Server Instance. For more information about the settings that you can configure in a Microsoft Dynamics NAV Server instance, see Microsoft Dynamics NAV Server Settings.

Each Microsoft Dynamics NAV Server instance on a computer runs as a separate Windows service and can run under a separate computer account, which is the Service Account.

In addition to the Microsoft Dynamics NAV Server Administration tool, you can use the Services snap-in, which is included in Control Panel, to see the Microsoft Dynamics NAV Server instances on the computer. To open the Services snap-in, choose the Start menu, in the Search box type Services, and then choose the related link. Each instance name begins with Microsoft Dynamics NAV Server. The default instance is identified as Microsoft Dynamics NAV Server[DynamicsNAV90]. Any instances that you create are identified by Microsoft Dynamics NAV Server, following by the instance name in brackets. For example, if you create a Microsoft Dynamics NAV Server instance and name it Denmark, the Services snap-in shows the following instances:

  • Microsoft Dynamics NAV Server[DynamicsNAV90]

  • Microsoft Dynamics NAV Server [Denmark]

Tip
You can also administrate your Microsoft Dynamics NAV deployment using Windows PowerShell cmdlets. For more information, see Microsoft Dynamics NAV Windows PowerShell Cmdlets.

Server Instances and Service Types

In Microsoft Dynamics NAV Server Administration tool, settings for a server instance are organized into tabs and then organized by service type.

Setting | Applies to
General | All types of services.
Client Services | Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client.
OData Web Services | OData web services.
SOAP Web Services | SOAP web services
NAS Services | Microsoft Dynamics NAV Application Server (NAS) services.
Management Services | Services for managing Microsoft Dynamics NAV Server on the computer.

For more information about the different service types, see Client Types.

You should recognize and understand the difference between server instances and service types.

A server instance is a distinct service in Windows and is the middle tier in the Microsoft Dynamics NAV three-tier architecture. For more information, see Product and Architecture Overview.

A service type is a category within a Microsoft Dynamics NAV Server instance.

Important
When you modify a permission set or modify permissions for a user, you must restart all Microsoft Dynamics NAV Server instances in the database for those changes to take effect. The exception is for the current instance—that is, the instance that the client (the Microsoft Dynamics NAV Windows client or the Microsoft Dynamics NAV Web client) is using when the changes are made. There is no need to restart this instance. It is also necessary to restart Microsoft Dynamics NAV Server instances if you modify permissions sets or user permissions using the Microsoft Dynamics NAV Windows PowerShell cmdlets.

Managing Different Types of Services from a Single Microsoft Dynamics NAV Server Computer

When you change the value of any setting in any service category, you must restart the Microsoft Dynamics NAV Server instance for the change to take effect. Restarting the instance affects all services types within that instance. For example, Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client users are disconnected, and web service applications are interrupted. Therefore, if you plan to run different types of services on a single computer running Microsoft Dynamics NAV Server, we recommend that you run different services types in separate service instances. Your computer should have sufficient memory to run multiple service instances. For example, if you plan to use both the Client Services and OData Web Services on a single computer running Microsoft Dynamics NAV Server, then you should run the Client Services in one server instance and the OData Web Services in a separate server instance. If you have to change an OData web services setting, then you do not affect Microsoft Dynamics NAV Windows client users when you restart the instance to enable the change.

To disable a service type, clear the Enable property on the relevant tab. The only service type that does not have an Enable property is NAS Services. To disable NAS Services, set Startup Codeunit on the NAS Services tab to 0. For more information, see Configuring NAS Services.

See Also

Tasks

How to: Configure a Microsoft Dynamics NAV Server Instance
How to: Start, Stop, Restart, or Remove a Microsoft Dynamics NAV Server Instance


How to: Configure a Microsoft Dynamics NAV Server Instance

You can configure Microsoft Dynamics NAV Server instances by using the Microsoft Dynamics NAV Server Administration tool. A list of Microsoft Dynamics NAV Server instances is shown in the left pane of the Microsoft Dynamics NAV Server Administration tool.

To configure a Microsoft Dynamics NAV Server instance

  1. In the left pane of the Microsoft Dynamics NAV Server Administration tool, choose an instance.

  2. At the bottom of the center pane, choose Edit.

  3. Modify settings for the instance.

    For more information, see Configuring Microsoft Dynamics NAV Server.

  4. At the bottom of the center pane, choose Save.

  5. Restart the instance. For more information, see How to: Start, Stop, Restart, or Remove a Microsoft Dynamics NAV Server Instance.

See Also

Tasks

How to: Create a Microsoft Dynamics NAV Server Instance
How to: Start, Stop, Restart, or Remove a Microsoft Dynamics NAV Server Instance

Concepts

Managing Microsoft Dynamics NAV Server Instances
Microsoft Dynamics NAV Server Administration Tool


How to: Start, Stop, Restart, or Remove a Microsoft Dynamics NAV Server Instance

You can start, stop, restart, or remove a Microsoft Dynamics NAV Server instance by using the Microsoft Dynamics NAV Server Administration tool. When you select a Microsoft Dynamics NAV Server computer in the left pane of Microsoft Dynamics NAV Server Administration tool, it shows all server instances on that computer in the center pane.

To start, stop, restart, or remove a Microsoft Dynamics NAV Server instance

  1. In the left pane of Microsoft Dynamics NAV Server Administration tool, choose a Microsoft Dynamics NAV Server computer.

    Unless you are administering a remote computer, this is Microsoft Dynamics NAV (local).

  2. In the center pane, right-click an instance, and then choose Start, Stop, Restart, or Remove.

    Choose Restart to stop and then start the instance again.

    Choose Remove to remove a server instance.

See Also

Tasks

How to: Configure a Microsoft Dynamics NAV Server Instance
How to: Create a Microsoft Dynamics NAV Server Instance

Concepts

Managing Microsoft Dynamics NAV Server Instances
Microsoft Dynamics NAV Server Administration Tool


Microsoft Dynamics NAV Server Settings

The center pane in the Microsoft Dynamics NAV Server Administration tool shows settings for the currently selected Microsoft Dynamics NAV Server instance. Settings are grouped into the following tabs, according to service category.

Tab | Description
General | Settings apply to all kinds of services.
Client Services | Settings apply to Microsoft Dynamics NAV Windows clients and Microsoft Dynamics NAV Web clients.
OData Web Services | Settings apply to OData web services.
SOAP Web Services | Settings apply to SOAP web services.
NAS Services | Settings apply to NAV Application Server (NAS) services.
Management Services | Settings apply to the Microsoft Dynamics NAV Server Administration tool.

Settings Information

In the Microsoft Dynamics NAV Server Administration tool, you can view information about the currently selected setting in the information pane at the bottom of the center pane. You can also view complete setting information in Microsoft Dynamics NAV Help. For more information, see Configuring Microsoft Dynamics NAV Server.

Modifying Microsoft Dynamics NAV Server Settings

If you change the value of any setting in any service category, you must restart the Microsoft Dynamics NAV Server instance for the change to take effect. If you plan to run different types of services on a single Microsoft Dynamics NAV Server computer, it is a good idea to run different service types in separate service instances. For example, if you plan to run both Client services and NAS services on a single Microsoft Dynamics NAV Server computer, run the Client services in one server instance and the NAS services in a separate instance. That way, if you want to change one of your NAS services settings, you will not affect Microsoft Dynamics NAV Windows client users when you have to restart the instance to make the change take effect. For performance reasons, it is also a good idea to run different types of Microsoft Dynamics NAV services on a Microsoft Dynamics NAV Server computer in different instances.

See Also

Concepts

Configuring Microsoft Dynamics NAV Server
Microsoft Dynamics NAV Server Administration Tool


Microsoft Dynamics NAV Windows PowerShell Cmdlets

Microsoft Dynamics NAV 2016 includes Windows PowerShell cmdlets for administration and for merging and modifying application object files. The cmdlets are available in two Windows PowerShell modules: Microsoft Dynamics NAV 2016 Administration Shell and Microsoft Dynamics NAV 2016 Development Shell.

  • The Microsoft Dynamics NAV 2016 Administration Shell includes cmdlets for administering the Microsoft Dynamics NAV deployment, such as adding and configuring Microsoft Dynamics NAV server instances, databases, and users. The Microsoft Dynamics NAV 2016 Administration Shell is installed with the Microsoft Dynamics NAV Server.

  • The Microsoft Dynamics NAV 2016 Development Shell includes cmdlets for merging and modifying application object files. The Microsoft Dynamics NAV 2016 Development Shell is installed with the Microsoft Dynamics NAV Development Environment.

The cmdlets are implemented in Windows PowerShell 3.0, which is included with Windows Server 2012 and Windows 8. For other versions of Windows supported for Microsoft Dynamics NAV 2016, you can install it as part of the Windows Management Framework 3.0 on the Microsoft Download Center.

Note
Alternatively to running Microsoft Dynamics NAV 2016 Administration Shell and Microsoft Dynamics NAV 2016 Development Shell from where they are installed, you can import the relevant module into the Windows PowerShell Integrated Scripting Environment (ISE).

Starting a Microsoft Dynamics NAV 2016 Administration Shell Session

You must run the Microsoft Dynamics NAV 2016 Administration Shell as an Administrator. On the computer that is running Microsoft Dynamics NAV Server, choose Start, in the Search box, type Microsoft Dynamics NAV 2016 Administration Shell, right-click the related link, and then choose Run as Administrator.

Important
To run the cmdlets in the Microsoft Dynamics NAV 2016 Administration Shell, you must be a member of the local Administrator group on the computer where the Microsoft Dynamics NAV 2016 Administration Shell is installed.

Starting a Microsoft Dynamics NAV 2016 Development Shell Session

On the computer that is running Microsoft Dynamics NAV Development Environment, choose Start, in the Search box, type Microsoft Dynamics NAV 2016 Development Shell, and then choose the related link.

Getting Help on Microsoft Dynamics NAV Cmdlets

To see the cmdlets that are available for Microsoft Dynamics NAV, type the following at the Windows PowerShell prompt.

Copy Code
Get-Command *NAV*

To get Help about syntax and options for a specific cmdlet, type the following cmdlet.

Copy Code
Get-Help <cmd name>

For example, to get Help about the Get-NAVServerInstance cmdlet, type the following.

Copy Code
Get-Help Get-NAVServerInstance

For more information about Microsoft Dynamics NAV 2016 Administration Shell cmdlets, see Administration Cmdlets for Microsoft Dynamics NAV.

For more information about Microsoft Dynamics NAV 2016 Development Shell cmdlets, see Development Cmdlets for Microsoft Dynamics NAV.

For more information about Windows PowerShell, see Windows PowerShell Getting Started Guide.

See Also

Concepts

Sample Windows PowerShell Scripts for Microsoft Dynamics NAV
Administration
Comparing and Merging Application Object Source Files


Sample Windows PowerShell Scripts for Microsoft Dynamics NAV

The Microsoft Dynamics NAV product media includes a folder that has examples of how you can use the Microsoft Dynamics NAV Windows PowerShell cmdlets to upgrade, deploy, and maintain your Microsoft Dynamics NAV solution.

Microsoft Dynamics NAV Sample Scripts

The sample Windows PowerShell scripts are available in the WindowsPowerShellScripts folder on the Microsoft Dynamics NAV product media.

You can copy the folder to your computer and use the scripts as a starting point for managing your own solution. Depending on your solution, you can then add the sample Windows PowerShell module into the Microsoft Dynamics NAV 2016 Administration Shell or Microsoft Dynamics NAV 2016 Development Shell and then run the scripts.

The current version of Microsoft Dynamics NAV includes the following sample modules.

Parent folder | Module name | Description
ApplicationMergeUtilities |  | Contains sample scripts that illustrate different ways of using Windows PowerShell cmdlets to merge and modify application objects. The sample scripts use the Microsoft.Dynamics.Nav.Model.Tools.psd1 module, which you must import first.
Cloud | HowTo | Contains sample scripts and files for deploying a fully functional end-to-end Microsoft Dynamics NAV solution on Microsoft Azure virtual machines. For more information, see For more information, see Deploying Microsoft Dynamics NAV Using the Example Scripts
 | NAVAdministration | Illustrates how Windows PowerShell can be used to automate the provisioning and management of Microsoft Dynamics NAV installations on a virtual machine (VM).
 | NAVRemoteAdministration | Illustrates how Windows PowerShell can be used to automate the provisioning and management of Microsoft Dynamics NAV installations on Azure VMs.
 | NAVRemoteAdministrationSamples | Provides examples of a fully automated deployment of Microsoft Dynamics NAV on Azure.
Multitenancy | NAVMultitenancySamples | Illustrates how you can automate the steps that are required to migrate to a multitenant deployment architecture. For more information, see Migrating to Multitenancy.
Upgrade | NAVUpgradeModule | Illustrates how you can automate the upgrade of a Microsoft Dynamics NAV 2013 database to Microsoft Dynamics NAV 2016. For more information, see Upgrading to Microsoft Dynamics NAV 2016.

Running the Sample Scripts

The sample scripts are designed to be run from the context of the Windows PowerShell module that is part of each collection of sample scripts. For example, to run the scripts for upgrading to Microsoft Dynamics NAV, import the NAVUpgradeSamples.psm1 module into the Microsoft Dynamics NAV 2016 Administration Shell. Similarly, to run the sample scripts for merging application objects, open the HowTo-Start-Import-NAV-Module.ps1 script in the Windows PowerShell IDE, navigate the command prompt to the folder where you placed the samples, and then run the script.

For more information, see Getting Started with Windows PowerShell in the TechNet Library.

See Also

Concepts

Administration
Deployment
Comparing and Merging Application Object Source Files
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure

Other Resources

Upgrading to Microsoft Dynamics NAV 2016


Changes to Microsoft Dynamics NAV Cmdlets From Previous Release

The following sections provide an overview of the new, changed, and removed cmdlets in the Microsoft Dynamics NAV 2016 Administration Shell and Microsoft Dynamics NAV 2016 Development Shell since the previous release.

Changes to Microsoft Dynamics NAV 2016 Administration Shell Cmdlets

New Cmdlets

The following table includes the new cmdlets in the current release.

Cmdlet | Description
Export-NAVEncryptionKey | Exports an encryption key from a Microsoft Dynamics NAV Server instance to a password protected file.
Get-NAVTableConnection | Gets a list of connections to external database tables from a Microsoft Dynamics NAV application.
Import-NAVEncryptionKey | Imports an encryption key from a password protected file to a Microsoft Dynamics NAV Server instance.
New-NAVEncryptionKey | Creates an encryption key in a password protected file.
New-NAVTableConnection | Registers a connection to an external database table so the table can be used by the Microsoft Dynamics NAV application.
Remove-NAVTableConnection | Removes a connection to an external database table from the Microsoft Dynamics NAV application.
Remove-NAVWebServerInstance | Removes a Microsoft Dynamics NAV Web Server instance on IIS.
Note
A number of other new cmdlets are available in the Microsoft Dynamics NAV 2016 Administration Shell but are not yet listed here. Please see the MSDN Library for a full list.

Changed Cmdlets

The following table includes the cmdlets that have changed in the current release.

Cmdlet | Description
Dismount-NAVTenant | ApplicationDatabaseCredentials parameter added. ApplicationDatabaseName parameter added. ApplicationDatabaseServer parameter added. InputTenantRuntimeSettings parameter added. InputTenantSettings parameter added. InputObject parameter removed and replaced by InputTenantRuntimeSettings and InputTenantSettings parameters. DoNotSaveConfiguration parameter removed.
Export-NAVData | ApplicationDatabaseCredentials parameter added. DatabaseCredentials parameter added.
Get-NAVCompany | FileName parameter changed to FilePath.
Get-NAVDataFile | FileName parameter changed to FilePath.
Get-NAVTenant | ApplicationDatabaseCredentials parameter added. ApplicationDatabaseName parameter added. ApplicationDatabaseServer parameter added.
Import-NAVData | ApplicationDatabaseCredentials parameter added. DatabaseCredentials parameter added.
Mount-NAVApplication | DatabaseCredentials parameter added.
Mount-NAVTenant | ApplicationDatabaseCredentials parameter added. ApplicationDatabaseName parameter added. ApplicationDatabaseServer parameter added. AzureKeyVaultSettings parameter added. DatabaseCredentials parameter added. DefaultTimeZone parameter added. EncryptionProvider parameter added. NasServicesEnabled parameter added. RunNasWithAdminRights parameter added.
New-NAVServerInstance | DatabaseCredentials parameter added. Multitenant parameter added.
Set-NAVServerInstance | DatabaseCredentials parameter added.
New-NAVServerUser | ContactEmail parameter added.
Set-NAVServerUser | ContactEmail parameter added.

Removed Cmdlets

The following table includes the removed cmdlets in the current release.

Cmdlet | Description
Save-NavTenantConfiguration | Saves the current tenant configuration on the specified Microsoft Dynamics NAV Server instance. Tenant information is now stored in the database.

Changes to Microsoft Dynamics NAV 2016 Development Shell Cmdlets

New Cmdlets

The following table includes the new cmdlets in the current release.

Cmdlet | Description
New-NAVCrmTable | Creates Microsoft Dynamics NAV table objects that are based on Microsoft Dynamics CRM entities.
Note
A number of other new cmdlets are available in the Microsoft Dynamics NAV 2016 Development Shell but are not yet listed here. Please see the MSDN Library for a full list.

Changed Cmdlets

The following table includes the cmdlets that have changed in the current release.

Cmdlet | Description
None |

Removed Cmdlets

The following table includes the removed cmdlets in the current release.

Cmdlet | Description
None |

See Also

Concepts

Microsoft Dynamics NAV Windows PowerShell Cmdlets

Other Resources

Administration Cmdlets for Microsoft Dynamics NAV


Managing Users and Permissions

In the following sections, you can read more about how you manage users and permissions in Microsoft Dynamics NAV.

In This Section

Managing Users

Managing Permissions and Permission Sets

Related Sections

Managing Companies

Profiles and Role Centers


Managing Users

You create and manage Microsoft Dynamics NAV users from the Users page.

Microsoft Dynamics NAV Users and Credential Types

Microsoft Dynamics NAV 2016 supports four credential authorization mechanisms for Microsoft Dynamics NAV users. When you create a user, you provide different information depending on the credential type you are using in the current Microsoft Dynamics NAV Server instance.

See Users and Credential Types for details.

In This Section

How to: Create Microsoft Dynamics NAV Users

How to: Set Up User Time Constraints

Related Sections

Managing Permissions and Permission Sets

About Permissions

Profiles and Role Centers

See Also

Concepts

Security and Protection


How to: Create Microsoft Dynamics NAV Users

Before a user can access Microsoft Dynamics NAV, you must have created them as users in Microsoft Dynamics NAV. To create and modify users, you can use the Microsoft Dynamics NAV Windows client, Microsoft Dynamics NAV Web client, or the Microsoft Dynamics NAV Windows PowerShell cmdlets.

Important
You do not create user logins for Microsoft Dynamics NAV user in SQL Server before or after you create Microsoft Dynamics NAV users.

Microsoft Dynamics NAV 2016 supports the following credential authorization mechanisms for Microsoft Dynamics NAV users:

  • Windows

  • UserName

  • NavUserPassword

  • AccessControlService

  • Office 365 Authentication

This topic contains separate procedures for creating users for each credential authentication mechanism. For information about how to configure RoleTailored clients and the Microsoft Dynamics NAV Server instance for a specific authentication scheme, see Users and Credential Types.

Note
The following procedures describe how to create users for a single credential type, but you can create users that are valid for multiple credential types, as long as you configure the appropriate settings for each credential type in the New User page. For example, you could create a user who would automatically be logged on without having to present credentials when the credential type is Windows, but would be prompted for a username (the value of the User Name field) and a password when the credential type is UserName.

Creating a New User

The following procedures describe how to configure users in the Microsoft Dynamics NAV Windows client. Similar steps apply for creating users in the Microsoft Dynamics NAV Web client. For information about how to create users using the Microsoft Dynamics NAV Windows PowerShell cmdlets, see Microsoft Dynamics NAV Windows PowerShell Cmdlets. A Microsoft Dynamics NAV Server instance can either support users with Windows authentication or users with other credentials.

To create a new user

  1. In the Search box, enter Users, and then choose the related link.

  2. In the Users window, on the Home tab, choose New.

  3. In the User Card window, on the General FastTab, fill in the fields as described in the following table.

    Field Description

    User Name

    Specify a unique, short name to identify the user.

    Full Name

    Specify the user’s full name.

    License Type

    Choose one of the available license types. For more information, see License Types.

    State

    Specify if the user’s access is enabled or disabled.

    Expiry Date

    Optionally, to set a time limit on the user’s access, choose a date.

  4. To set up a user for Windows authentication, follow this step:

    • On the Windows Authentication FastTab, in the Windows User Name field, type the name of a valid Active Directory user, using the format domain\username. Or, choose the AssistEdit button, select Allow for the Session, and then, in the Active Directory Select User or Group dialog box, identify a Windows user.

  5. To set up a user for NavUserPassword authentication, follow these steps:

    1. On the NAV Password Authentication FastTab, choose the Password field to specify a password for the user.

    2. If you want to require the user to change the password after they log in for the first time, select User must change password at next login.

      The first time that the user logs on, a prompt will appear prompting the user to change the password.

  6. To set up a user for AccessControlService authentication, follow these steps:

    Note
    The following steps apply to Microsoft Dynamics NAV solutions that are deployed on Azure. For more information, see Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure.

    1. On the Access Control Service Authentication FastTab, next to ACS Access Status, choose the word Disabled.

      This opens the User ACS Setup dialog box.

    2. In the User ACS Setup dialog box, choose the Generate Auth Key button.

      A string value is automatically inserted into the Authentication Key field.

    3. Save the Authentication Key value to a secure location such as a text file, where you can find it later. After you configure your deployment for ACS, and configure your Microsoft Dynamics NAV components for ACS, send this authentication key, and the User Name value, to the actual user and instruct the user to provide these values when they log on to a Microsoft Dynamics NAV client.

    4. Choose the OK button. The ACS Access Status changes to Pending. It will change to Active after the user successfully logs in.

  7. To create a new user for Office 365 authentication, follow this step:

    • On the Office 365 Authentication FastTab, in the Authentication Email field, specify the Microsoft account that this user uses to access Office 365 and SharePoint. The authentication email address must be the organizational email account that the users log in to Office 365 with, such as an account from Azure Active Directory (Azure AD).

      The Microsoft Dynamics NAV Server instance must be configured to accept the relevant credential types that support integration with Office 365, such as Azure AD. For more information, see Users and Credential Types.

      When you specify an email address, the Authentication Status field changes to Inactive. When the user logs in to Office 365, the authentication status changes to Active. For more information, see Authentication Email.

  8. Open the User Permission Sets FastTab to define permission sets for the user. Choose the first row under Permission Sets and then select a permission set. Choose additional permission sets as needed. For more information, see How to: Define Permissions for Users.

  9. Add any Notes or Links for the user in the respective FactBoxes.

  10. Choose the OK button to close the window.

To update the settings for an already existing user in the Users window, select the user and then, on the Home tab, choose Edit.

See Also

How to: Create a Profile

Tasks

How to: Define Permissions for Users

Concepts

Users and Credential Types
License Types


How to: Set Up User Time Constraints

Administrators can define periods of time during which specified users are able to post, and also specify whether Microsoft Dynamics NAV records the amount of time during which specified user are logged on. Administrators can also assign responsibility centers to users.

Setting Up User Time Constraints

To set up user time constraints

  1. In the Search box, enter User Setup, and then choose the related link. The User Setup window opens.

  2. On the Home tab, in the New group, choose New. The New - User Setup window opens.

  3. In the User ID field, enter the ID of a user, or choose the field to see all current Windows users for the current Microsoft Dynamics NAV database.

  4. Enter time constraint data for the user by filling the fields as described in the following table.

    Field Purpose

    Allow Posting From

    Specifies the first date on which the user is able to post.

    Allow Posting To

    Specifies the last date on which the user is able to post.

    Register Time

    To begin registering the amount of time the user spends working on the current company, select this field.

    Sales Resp. Ctr. Filter

    Specifies the code for a responsibility center. The user is then assigned to this responsibility center. Choose the AssistEdit button to the right of the field to see available responsibility centers.

    The Sales responsibility center becomes the default responsibility center when the user creates new sales documents. The user only sees sales orders that are created from their responsibility center.

    If you leave this field blank, the default responsibility center in the Customer Card or Company Information window (in that order of priority) is used.

    Purchase Resp. Ctr. Filter

    Specifies the code for a responsibility center. The user is then assigned to this responsibility center. Choose the AssistEdit button to the right of the field to see available responsibility centers.

    The Purchase responsibility center becomes the default responsibility center when the user creates new purchase documents. The user only sees purchase orders that are created from their responsibility center.

    If you leave this field blank, the default responsibility center in the Customer Card or Company Information window (in that order of priority) is used.

    Service Resp. Ctr. Filter

    Specifies the code for a responsibility center. The user is then assigned to this responsibility center. Choose the AssistEdit button to the right of the field to see available responsibility centers.

    The Service responsibility center becomes the default responsibility center when the user creates new service documents. The user only sees service orders created from their responsibility center.

    If you leave this field blank, the default responsibility center in the Customer Card or Company Information window (in that order of priority) is used.

    Time Sheet Admin.

    Specifies whether the user is a time sheet administrator.

See Also

User Setup
How to: Set Up Time Sheet Administration and Approval

Tasks

How to: Create Microsoft Dynamics NAV Users


Managing Permissions and Permission Sets

A permission set is a set of permissions for a set of objects in the Microsoft Dynamics NAV database that you can assign to one or more users. A number of predefined permission sets are provided by default in the CRONUS International Ltd. demonstration database. You can use these permission sets as defined, modify them, or create your own permission sets.

When you create a new Microsoft Dynamics NAV database, only one permission set is provided automatically: the SUPER permission set.

As you create and define permissions for permission sets in a new database, remember to always add the BASIC permission set, which grants users access to required system tables and other fundamental tables.

The BASIC permission set primarily functions as a prerequisite to open the client and show all pages.

The BASIC permission set is provided in an XML file, UserRoles.xml, which you import into your database using a RoleTailored client. Permissions for the BASIC permission set are provided in a separate XML file, UserRolePermissions.xml, which you also import. For more information, see How to: Work with the BASIC Permission Set.

Note
Another prerequisite permission set is the FOUNDATION permission set.

This permission set, together with other application permission sets, is required to automatically remove UI elements according to user permissions. For more information, see Removing Elements from the User Interface According to Permissions.

Note
Depending on the setting in the UI Elements Removal field in the Microsoft Dynamics NAV Server Administration tool, only UI elements that the user has permissions for will appear in the user interface. For more information, see Removing Elements from the User Interface According to Permissions.

In This Section

First User Is Automatically Assigned the SUPER Permission Set

How to: Create or Modify Permission Sets

Special Permission Sets

Related Sections

Managing Users

See Also

Customize the User Interface

Concepts

About Permissions
Removing Elements from the User Interface According to Permissions


First User Is Automatically Assigned the SUPER Permission Set

When a user creates a Microsoft Dynamics NAV database, that user is automatically assigned the SUPER permission set in the Microsoft Dynamics NAV security system. There are different ways to create a database, such as by performing a Demo install, which creates the CRONUS International Ltd. demonstration database, or by restoring a previously backed-up database. After the database is created, the first user is automatically assigned the SUPER permission set. The SUPER permission set allows the user to read, use, update, and delete all data and all application objects in the scope of the current Microsoft Dynamics NAV license. This user is then responsible for creating additional users and for assigning appropriate permission sets to those users.

The SUPER Permission Set

When you have the SUPER permission set, you can create other users and assign them the SUPER permission set. For example, you can assign the SUPER permission set to one or more users in each company in the Microsoft Dynamics NAV database. Each of these users can then create other users and assign them permission sets in their own company and any other company in that Microsoft Dynamics NAV database. However, a user who has the SUPER permission set for a specific company cannot assign the SUPER permission set to users in other companies.

Note
You cannot modify permissions for the SUPER permission set.

If you want to set up a user who can create other users and assign permission sets, you can choose to assign them the SUPER permission set. Alternatively, you can create a dedicated SECURITY permission set that includes read, insert, modify, and delete permission to the following tables and any other tables that you want to grant access to:

  • User

  • User Property

  • Access Control

The permission set must also include read access to the Permission Set table.

Users who have a SECURITY permission set can create new users and assign them the same permission sets. If you create a SECURITY permission set, users who have this permission set cannot assign themselves or anyone else the SUPER permission set. Also, a user who has the SECURITY permission set for a specific company cannot assign permission sets to users in other companies.

See Also

Tasks

How to: Create Microsoft Dynamics NAV Users
How to: Define Permissions for Users

Concepts

Setting Database Owner and Security Administration Permissions


Special Permission Sets

The following permission sets have special definitions that you should be aware of as you implement permissions and security for Microsoft Dynamics NAV users.

Permission set Definition

SUPER

Can read, use, update, and delete all data and all application objects in the scope of your license. Microsoft Dynamics NAV requires that at least one user be assigned this permission set in each database.

For more information, see First User Is Automatically Assigned the SUPER Permission Set.

You cannot modify permissions for the SUPER permission set.

SUPER (DATA)

Can read, use, update, and delete all data. You typically assign this permission set to an accounting manager who needs to work with all data but does not need to change Microsoft Dynamics NAV.

This permission set does not give access to the Object Designer.

SECURITY

Can create new users and assign them the same permission sets. Must be able to access the User, User Property, Permission Set, and Access Control tables.

For example, you can create a SECURITY permission set that includes the four required tables and any additional permissions that you want to include. You can then assign this permission set to a user who is a department administrator. This user can then administer permissions for other users in their department.

Only a user who has the SUPER permission set can create and modify a SECURITY permission set. Users who have this permission set can assign the same permissions to other users, but they cannot assign themselves the SUPER permission set.

BASIC

Grants Read access to almost all application tables and all system tables.

The main purpose of this permission set is to enable the client to open and show all pages.

When you create a new database, you must import the BASIC permission set from an XML file. For more information, see How to: Work with the BASIC Permission Set.

FOUNDATION

A prerequisite for all other permission sets. The FOUNDATION permission set grants access to system tables and application setup tables that are required for most application features to work.

Note
This permission set is recommended when using the UI Elements Removal feature to automatically remove UI elements according to user permissions. For more information, see Removing Elements from the User Interface According to Permissions.

See Also

Administration Outside of the Clients
Customize the User Interface

Tasks

How to: Remove UI Elements Using the AccessByPermission Property
How to: Specify When UI Elements Are Removed
How to: Try Out the UI Elements Removal Feature Based on Demonstration Permission Sets

Concepts

Security Overview
Removing Elements from the User Interface According to Permissions
About Permissions
First User Is Automatically Assigned the SUPER Permission Set
Removing Elements from the User Interface According to Permissions


About Permissions

Each permission set in Microsoft Dynamics NAV 2013 describes a set of access permissions to tables, reports, functions, and other objects. The types of permissions are:

  • Read

  • Insert

  • Modify

  • Delete

  • Execute

When you assign permissions to permission sets, you should not grant permissions to areas that your license file does not allow you to use. However, granting such permissions does not cause any problems. If you update Microsoft Dynamics NAV or purchase additional application areas, then you must change or add appropriate permissions.

For information on how to define permission sets, see How to: Create or Modify Permission Sets

Note
Depending on the setting in the UI Elements Removal field in the Microsoft Dynamics NAV Server Administration tool, only UI elements that the user has permissions for will appear in the user interface. For more information, see Removing Elements from the User Interface According to Permissions.

Related Sections

Managing Users

Managing Permissions and Permission Sets

How to: Work with the BASIC Permission Set

See Also

Customize the User Interface

Tasks

How to: Define Permissions for Users

Concepts

Security and Protection
Removing Elements from the User Interface According to Permissions


How to: Define Permissions for Users

Microsoft Dynamics NAV provides a set of standard permission sets. A permission set is a collection of permissions for specific objects in the database. All users must be assigned one or more permission sets before they can access Microsoft Dynamics NAV.

Note
Depending on the setting in the UI Elements Removal field in the Microsoft Dynamics NAV Server Administration tool, only UI elements that the user has permissions for will appear in the user interface. For more information, see Removing Elements from the User Interface According to Permissions.

A number of predefined permission sets are provided by default in Microsoft Dynamics NAV. You can use these permission sets as already defined, modify the default permission sets, or create additional permission sets.

Note
A table can contain a FlowField that generates sums based on values that are stored in another table. In this case, users must have permission to read both tables or they will not be able to read the first table.

To define permissions for a user

  1. In the Search box on your Home page in the RoleTailored client, type Users and then choose the associated link in the Results list.

  2. Select a user and choose Edit in the ribbon.

    Any permission sets that are already assigned to the user are displayed in the User Permission Sets area.

  3. To assign a new permission set to the user, click to position the cursor on a blank line in the in the User Permission Sets area and then choose the Assist button in the Permission Set column to display a list of existing permission sets.

  4. Click to select a permission set.

  5. If there is more than one company in your database, you can type or select a company in the Company column to restrict these permissions to that company. If you leave this column blank, the user will have the relevant permissions for the entire database.

  6. Choose the OK button to exit the Edit - User Card page.

See Also

How to: Assign a User to a Profile
Customize the User Interface

Tasks

How to: Create Microsoft Dynamics NAV Users

Concepts

Removing Elements from the User Interface According to Permissions

Other Resources

Managing Permissions and Permission Sets


Managing Companies

In this section, you can read more about how to manage companies in Microsoft Dynamics NAV.

You can create, rename, and delete companies in Microsoft Dynamics NAV Windows client, Microsoft Dynamics NAV Web client, or by using the Microsoft Dynamics NAV 2016 Administration Shell. You can only create, rename, or delete a company if you have the relevant permission for the specified company or for all companies.

In This Section

How to: Create Companies

How to: Rename Companies

How to: Delete Companies

Related Sections

Managing Users and Permissions

Profiles and Role Centers

See Also

Concepts

Microsoft Dynamics NAV Windows PowerShell Cmdlets


How to: Delete Companies

Microsoft Dynamics NAV Documentation
How to: Delete Companies
See Also

You can delete companies in the Microsoft Dynamics NAV Windows client and the Microsoft Dynamics NAV Web client. You can also delete companies by using the Remove-NAVCompany Windows PowerShell cmdlet.

Warning
When you delete a company, the company and all of the data that it contains will be deleted. If you have made reports and customizations, they are not deleted. They are saved in the database.

We recommend that you make a backup before you delete a company.

Before you delete a company, you must make sure that you are the only user who has access to the company.

To make sure that you are the only user who has access to the company

  1. In the Microsoft Dynamics NAV Development Environment, on the File menu, choose Database, and then choose Alter.

  2. Choose the Options tab, select the Single user check box, and then choose the OK button.

You can now delete the company in Microsoft Dynamics NAV Windows client, Microsoft Dynamics NAV Web client, or by using the Remove-NAVCompany Windows PowerShell cmdlet.

You can only delete a company if you have the relevant permission.

To delete a company in Microsoft Dynamics NAV Windows client

  1. In the Microsoft Dynamics NAV Windows client, open a different company than the company that you want to delete. For more information, see How to: Select a Company.

  2. In the Search box, enter Companies, and then choose the related link.

  3. In the Companies window, choose the company that you want to delete, and then, on the Home tab, in the Manage group, choose Delete.

  4. Confirm that you want to delete the company. You must confirm twice that you want to delete the company.

This deletes the company. The action cannot be undone.

See Also

How to: Select a Company
How to: Create a New Company

Concepts

Microsoft Dynamics NAV Windows PowerShell Cmdlets


How to: Create Companies

Microsoft Dynamics NAV Documentation
How to: Create Companies
See Also

You can create as many companies as you want in a database. You can create companies in the Microsoft Dynamics NAV Windows client and the Microsoft Dynamics NAV Web client. You can also create companies by using the New-NAVCompany Windows PowerShell cmdlet.

Important
If the company name starts with CRONUS (in uppercase letters) and you use a CRONUS demonstration database license, the company automatically becomes a demonstration company with all the restrictions that are set in the CRONUS demonstration database. For example, in CRONUS you can only post between November and February.

The following procedure illustrates how you can create a new company in the Microsoft Dynamics NAV Windows client, but similar steps apply to creating companies in the Microsoft Dynamics NAV Web client.

To create a company in the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client

  1. In Microsoft Dynamics NAV, in the Search box, enter Companies, and then choose the related link.

  2. On the Home tab, in the Manage group, choose Edit List.

    You can create a new company, or you can create a copy of an existing company. When you create a new company, data is not included. When you create a copy, the business data is copied to the new company.

    1. To create a new company, choose an empty row, and then, in the Company Name field, enter the name of the new company.

      The company name can have a maximum of 30 characters. If the database collation is case-sensitive, you can have one company called COMPANY and another called Company. However, if the database is case-insensitive, you cannot create companies with names that differ only by case.

    2. To create a copy of an existing company, choose a company, and then, on the Home tab, in the New group, choose Copy.

      Then, in the Copy Company window, in the Company Name field, enter the name of the new company.

      Choose the OK button to create the company.

When you create the company name, remember that it will be written at the top of various reports. Therefore, write it exactly as you want it to appear. You can rename existing companies. For more information, see How to: Rename Companies.

You can create as many companies as your license allows for.

See Also

Companies
How to: Select a Company

Tasks

How to: Rename Companies
How to: Delete Companies

Concepts

Microsoft Dynamics NAV Windows PowerShell Cmdlets


How to: Rename Companies

Microsoft Dynamics NAV Documentation
How to: Rename Companies
See Also

You can rename companies in the Microsoft Dynamics NAV Windows client and the Microsoft Dynamics NAV Web client. You can also rename companies by using the Rename-NAVCompany Windows PowerShell cmdlet.

Before you rename a company, you must make sure that you are the only user who has access to the company.

To make sure that you are the only user who has access to the company

  1. In the Microsoft Dynamics NAV Development Environment, on the File menu, choose Database, and then choose Alter.

  2. Choose the Options tab, select the Single user check box, and then choose the OK button.

You can now rename the company in Microsoft Dynamics NAV Windows client, Microsoft Dynamics NAV Web client, or by using the Rename-NAVCompany Windows PowerShell cmdlet.

You can only rename a company if you have the relevant permission.

To rename a company in the Microsoft Dynamics NAV Windows client

  1. In the Search box, enter Companies, and then choose the related link.

  2. Replace the current company name with the new name that you want to use.

  3. Choose the OK button to accept the new company name.

You can rename a company at any time. You can use this function if you have made a mistake when naming the company, or if you think that a different name will be easier to recognize. However, renaming a company that has been used and already contains data can take some time.

Note
When you work in the CRONUS demonstration database and use the Cronus.flf license file, you can only change the company name to one that starts with CRONUS with uppercase letters.

See Also

How to: Select a Company

Tasks

How to: Delete Companies
How to: Create Companies

Concepts

Microsoft Dynamics NAV Windows PowerShell Cmdlets


Administration in the Development Environment

You can use the development environment to administer certain aspects of Microsoft Dynamics NAV databases and licenses. For more information, see the topics in this section.

For all other aspects of administration, see Microsoft Dynamics NAV Server Administration Tool.

See Also

Concepts

Microsoft Dynamics NAV Server Administration Tool
Window Overviews


How to: Create Databases

You can create new Microsoft Dynamics NAV databases in the development environment and by using the New-NAVDatabaseWindows PowerShell cmdlet.

When you create a database you must specify the SQL Server instance for the database and the authentication type.

To create a database

  1. In the development environment, on the File menu, choose Database, and then choose New.

  2. In the Server Name field, enter the name of the SQL Server instance. You can choose the up arrow to select the server from a list of available servers or you can enter the server name manually.

  3. In the Authentication field, select the type of authentication that you require. Choose the drop-down arrow to select Database Server Authentication or Windows Authentication.

    • If you select Database Server Authentication, then authentication is performed by the SQL Server instance that you have selected.

    • If you select Windows Authentication, then authentication is performed by the Windows domain controller.

  4. In the User ID field, enter your User ID if you have selected Database Server Authentication.

  5. In the Password field, enter your password if you have selected Database Server Authentication.

  6. To set the network type to be used when connecting to the server, choose the Advanced tab and select the net type from the drop down list box in the Net Type field. However, it is not usually necessary to change the network type from the default setting. The Default net type setting allows Microsoft Dynamics NAV to connect to a server using the default client network type assigned by SQL Server. You can change the net type with the Client Network Utility, which is part of the SQL Server Client Utilities, if they have been installed on the client computer.

  7. Choose OK to connect to the server and open the New Database window.

    In the New Database window, enter the information about the database that you want to create. The window contains the same tabs as the Alter Database window. The tabs are the following:

    • Altering Databases - General Tab

    • Altering Databases - Database Files Tab

    • Altering Databases - Transaction Log Files Tab

    • Altering Databases - Collation Tab

    • Altering Databases - Options Tab

    • Altering Databases - Integration Tab

    • Altering Databases - Advanced Tab

Now that you have created a new database, you must configure your Microsoft Dynamics NAV Server instance to access the database and then restart the service. For more information, see How to: Configure a Microsoft Dynamics NAV Server Instance. Next, you must synchronize the table schema. For more information, see Synchronizing Table Schemas.

Warning
You can always enlarge a database later on, but you cannot make it smaller.

After you have created the database, you can enter program objects and company data. Before you can create company data, you must import some basic data from another Microsoft Dynamics NAV database. The imported data must at least include Data Common to All Companies and Application Objects. For more information, see Exporting and Importing Companies and Other Data.

See Also

Tasks

How to: Create Companies
How to: Select the Network Type of the Database
How to: Delete Databases
How to: Export and Import Companies and Other Data in Clients


How to: Open Databases

In order to work in the application, you must always open a database and a company, in that order. After you have done this once, or if the choices are on the command line that starts the program, this will happen automatically when you choose a company. Therefore, you will only need to follow this procedure to open a different database than the one currently open.

To open a database

  1. In the development environment, on the File menu, choose Database, and then choose Open.

  2. In the Server Name field, enter the name of the SQL Server instance. You can choose the up arrow to select the server from a list of available Microsoft SQL Servers, or you can enter the server name manually.

  3. In the Database Name field, enter the name of the database. Choose the up arrow to select from the list of databases that are available on the selected server.

  4. In the Authentication field, enter the type of authentication that you require. Choose the drop-down arrow to select Database Server Authentication or Windows Authentication.

    • If you select Database Server Authentication, then your authentication is performed by the SQL Server instance that you have selected.

    • If you select Windows Authentication, then authentication is performed by the Windows domain controller.

  5. In the User ID field, enter your User ID if you have selected Database Server Authentication.

  6. In the Password field, enter your password if you have selected Database Server Authentication.

  7. To set the network type to be used when connecting to the server, choose the Advanced tab and select the net type from the drop down list box in the Net Type field. However, it is not usually necessary to change the network type from the default setting. The Default net type setting allows Microsoft Dynamics NAV to connect to a server using the default client network type assigned by SQL Server. You can change the net type with the Client Network Utility, which is part of the SQL Server Client Utilities, if they have been installed on the client computer.

  8. If you would like to attach and open a detached database that consists of a single data file, excluding the transaction log file, you must enter the complete path and file name of the database in the Attach File field. This file will typically have the .mdf file name extension. You can give this single file database any name by entering it in the Database Name field on the General tab. If no transaction log file exists alongside the data file, it will be created automatically when you attach the data file. The database file is attached when you open it.

  9. Choose the OK button to open the database.

Note
Microsoft Dynamics NAV will automatically open the database and company that you were last working on when you reopen the program.

See Also

How to: Select a Company

Tasks

How to: Create Databases
How to: Create Companies

Reference

Available Microsoft SQL Servers


How to: Alter Databases

You can change the database property settings that you selected when you created the database.

The Alter Database window gives you access to the same settings as the New Database window.

To alter a database

  1. In the development environment, on the File menu, choose Database, and then choose Alter. The Alter Database window opens. In the Alter Database window you can change database settings.

    The Alter Database window contains the following tabs:

    • Altering Databases - General Tab

    • Altering Databases - Database Files Tab

    • Altering Databases - Transaction Log Files Tab

    • Altering Databases - Collation Tab

    • Altering Databases - Options Tab

    • Altering Databases - Integration Tab

    • Altering Databases - Advanced Tab

  2. Restart the Microsoft Dynamics NAV Server instance.

    The changes will not take effect until you restart the Microsoft Dynamics NAV Server instance. For more information, see How to: Start, Stop, Restart, or Remove a Microsoft Dynamics NAV Server Instance.

Changing Database Collation

You cannot change the collation directly in the current database. To change the collation, you must create a new database that uses the correct collation, and then export the data from the old database and import it to the new database. You can do this by using SQL Server Management Studio and the Microsoft Dynamics NAV Administration Shell as outlined in the following procedure.

To change the collation of a Microsoft Dynamics NAV database

  1. In SQL Server Management Studio, create a new database that uses the desired collation.

    Make sure that the service account of the Microsoft Dynamics NAV Server instance that will connect to the database has proper permission to the database. The service account must be a member of the db_owner role of the database. For more information see Provisioning the Microsoft Dynamics NAV Server Account.

  2. To export the data from the old database to the new database, open the Microsoft Dynamics NAV Administration Shell, and run the Export-NAVData cmdlet as shown in the following example.

    Copy Code
    Export-NAVData -DatabaseServer DatabaseServerName -DatabaseName OldDatabaseName -IncludeApplication -IncludeApplicationData -IncludeGlobalData -AllCompanies -FilePath c:\Files\MyNavDB.navdata

    For more information, see Export-NAVData cmdlet.

  3. To import the data from the old database to the new database, run the Import-NAVData cmdlet as shown in the following example.

    Copy Code
    Import-NAVData -DatabaseServer DatabaseServerName -DatabaseName NewDatabaseName -IncludeApplication -IncludeApplicationData -IncludeGlobalData -AllCompanies -FilePath c:\Files\MyNavDB.navdata

    For more information, see Import-NAVData cmdlet

  4. Connect the new database to the Microsoft Dynamics NAV Server instance.

    For more information, see How to: Connect a Microsoft Dynamics NAV Server Instance to a Database.

  5. Synchronize the table schemas in the database. You can do this from the development environment or Microsoft Dynamics NAV 2016 Administration Shell.

    • From the development environment, on the Tools menu, choose Sync. Schema For All Tables, and then choose With Validation and follow the schema synchronization instructions.

    • From the Microsoft Dynamics NAV 2016 Administration Shell, open the Microsoft Dynamics NAV 2016 Administration Shell as an administrator, and then run the Sync-NavTenant cmdlet. For more information, see How to: Run the Sync-NAVTenant Cmdlet to Synchronize the Tenant Database with the Application Database.

  6. Restart the Microsoft Dynamics NAV Server instance.

    For more information, see How to: Start, Stop, Restart, or Remove a Microsoft Dynamics NAV Server Instance.

See Also

Reference

Alter Database


How to: Select the Network Type of the Database

The default setting allows Microsoft Dynamics NAV to connect to a server using the default client network type assigned by SQL Server. Initially, this is the Named Pipes protocol. However, if the SQL Server Client Utilities have been installed on the client computer, you can change the setting using the Client Network Utility.

To specify the network type

  1. In the development environment, on the File menu, choose Database, and then choose Open. The Open Database window opens.

  2. Choose the Advanced tab.

  3. In the Net Type field, choose the drop-down arrow to select one of the network types: Default, Named Pipes, or TCP/IP Sockets.

  4. Choose the OK button to save your selection and close the window.

See Also

Reference

Open Database

Concepts

Troubleshooting: SQL Server Connection Problems


How to: Change the Microsoft Dynamics NAV Server Instance

In some cases, you may want to change the Microsoft Dynamics NAV Server instance that is being used. For example:

  • When you select an object in Object Designer and then choose the Run button, you may want the selected object to run on a different Microsoft Dynamics NAV Server instance that the one that is currently specified.

  • You may want to debug a session that is connected to a different Microsoft Dynamics NAV Server than the one that is currently specified.

To change the Microsoft Dynamics NAV Server instance by selecting from a list

  1. In the development environment, on the File menu, choose Database, and then choose Information.

    Tip
    If the Information menu item is not available, then you must first open a database.

  2. In the Database Information window, in the Server Instance field, choose the drop-down arrow to open the Available Server Instances window.

  3. Select a server instance, and then choose the OK button.

    Note
    The instance that you select is also displayed in the Options window.

To change the Microsoft Dynamics NAV Server instance by specifying the field in the Database Options window

  1. In the development environment, on the Tools menu, choose Options.

  2. In the Options window, in the Server Instance field, enter the Microsoft Dynamics NAV Server instance. The format is <servername>:<port>/<ServerInstance>.

    Note
    The value that you set is also displayed in the Database Information window.

See Also

Concepts

Running Objects from the Development Environment
Debugging
Managing Microsoft Dynamics NAV Server Instances


How to: Delete Databases

Typically, you take as many precautions as possible to avoid deleting a database, because to do so would usually be a big mistake. But if you really need to delete a database, you can.

You will need this function only in very special circumstances, because when you delete a database, all of the companies, reports, and so on, that are stored in it are deleted as well. If you do choose the function unintentionally, you will get a chance to cancel it before any damage is done, because the database will not be deleted until you have confirmed that you really want to delete it.

To delete the current database

  • In the development environment, on the File menu, choose Database, and then choose Delete.

See Also

Tasks

How to: Open Databases
How to: Close Databases


How to: Close Databases

You may need to close the database from time to time.

To close a database

  • In the development environment, on the File menu, choose Database, and then choose Close.

You can use this function to close an open database, for example, before opening another database. However, it is not necessary to use it because all the data is saved and everything is closed correctly when you choose to open another database or exit the program.

See Also

Tasks

How to: Open Databases
How to: Delete Databases


How to: Increase the Size of Database Files

You can expand your Microsoft Dynamics NAV SQL Server database by increasing the size of one or more of its constituent database files.

Warning
You must always make a backup of your database before expanding it. For more information, see Create a Full Database Backup (SQL Server).

To increase the size of a database file

  1. In the development environment, on the File menu, choose Database, and then choose Alter. The Alter Database window opens.

  2. Choose the Database Files tab.

  3. Select the data file that you want to expand.

  4. Choose the Size (MB) field and enter the new size.

    Note
    If the Unrestricted Growth option is not selected and the database has grown to its maximum size, then you can either select the Unrestricted Growth option or increase the maximum size of one of the secondary data files.

  5. (optional) To increase the maximum size of a data file, in the Maximum Size (MB) field, enter the new maximum size.

You can also delete existing data files that are empty. The first data file that is listed is the primary file, and cannot be deleted.

See Also

Concepts

Altering Databases - Database Files Tab


How to: Add New Database Files

You can expand a database by creating a new database file in the database.

Note
You must always make a backup of the database before you expand it. For more information, see Create a Full Database Backup (SQL Server).

To add a new database file

  1. In the development environment, on the File menu, choose Database, and then choose Alter. The Alter Database window opens.

  2. Choose the Database Files tab.

  3. Select the first empty line in the window.

  4. In the Logical Name field, enter a logical name for each database file.

  5. In the File Name field, enter the full path and name of the database file.

    Note
    We recommend that primary database files have the file name extension .mdf and that secondary database files have the file name extension .ndf. The first data file that is listed is the primary file.

  6. In the Size (MB) field, enter the initial size in megabytes of the database file.

  7. In the File Growth field, enter the amount by which the database file will increase every time that it expands. This can be expressed in kilobytes (KB), megabytes (MB) or as a percentage (%).The default value is MB.

    However, if you enter the value in megabytes, SQL Server will convert it to kilobytes. If you enter the value as a percentage, SQL Server will display it as a percentage.

  8. Select the Unrestricted Growth check box if you want SQL Server to expand the database file when it must.

  9. In the Maximum size (MB) field, enter the maximum size to which the database file can grow.

    You can either allow the database file to grow without restriction or you must specify a maximum file size. If you do not specify a maximum size, SQL Server will expand the database file as often as necessary. This expansion is limited only by the available disk space.

See Also

Tasks

How to: Increase the Size of Database Files


How to: Increase the Size of Transaction Log Files

You can expand your transaction log by increasing the size of one or more of its constituent files.

Note
You must always make a backup of the database before you expand it. For more information, see Create a Full Database Backup (SQL Server).

To increase the size of a transaction log file

  1. In the development environment, on the File menu, choose Database, and then choose Alter. The Alter Database window opens.

  2. Choose the Transaction Log Files tab.

  3. Select the transaction log file that you want to expand.

  4. In the Size (MB) field, enter the new size.

    Note
    If the Unrestricted Growth option is not selected and the transaction log has grown to its maximum size, then you can either select the Unrestricted Growth option or increase the maximum size of one of the transaction log files.

  5. (optional) To increase the maximum size of a data file, in the Maximum Size (MB) field, enter the new maximum size.

See Also

Tasks

How to: Add New Transaction Log Files

Concepts

Altering Databases - Transaction Log Files Tab


How to: Add New Transaction Log Files

You can expand a transaction log by creating a new transaction log file in the database. The transaction log contains the changes that are made to the database and is used for database recovery.

Note
You must always make a backup of the database before you expand it. For more information, see Create a Full Database Backup (SQL Server).

To add a new transaction log file

  1. In the development environment, on the File menu, choose Database, and then choose Alter. The Alter Database window opens.

  2. Choose the Transaction Log Files tab.

  3. Select the first empty line in the window.

  4. In the Logical Name field, enter a logical name for each transaction log file. Logical names make it easier to manage transaction log files.

  5. In the File Name field, enter the full path and name of each transaction log file.

    Note
    We recommend that the transaction log files have the file name extension .ldf.

  6. In the Size (MB) field, enter the initial size in megabytes of the transaction log file.

  7. In the File Growth field, enter the amount by which the transaction log file will increase every time that it expands. This can be expressed in kilobytes (KB), megabytes (MB) or as a percentage (%).The default value is MB.

    However, if you enter the value in megabytes, SQL Server will convert it to kilobytes. If you enter the value as a percentage, SQL Server will display it as a percentage.

  8. Select the Unrestricted Growth field if you want SQL Server to expand the transaction log file when it must.

  9. In the Maximum size (MB) field, enter the maximum size to which the transaction log file can grow.

    You can either allow the transaction log file to grow without restriction or you must specify a maximum file size. If you do not specify a maximum file size, SQL Server will expand the transaction log file as often as necessary. This expansion is limited only by the available disk space.

See Also

Tasks

How to: Alter Databases
How to: Increase the Size of Transaction Log Files

Concepts

Altering Databases - Transaction Log Files Tab


How to: Build Server Application Objects

If you import a .fob file that contains objects that were exported from a native Microsoft Dynamics NAV database, then those objects do not contain the C# and metadata information that is required for Microsoft Dynamics NAV Server. Additionally, if you import a .fob file that contains the C# and metadata information but the information is from an earlier version of Microsoft Dynamics NAV, then the information may be in an incompatible format. In these cases, you must build the server application objects. If you do not build the server application objects, then these objects cannot be run. Building the server application objects does the following:

  • Recompiles the objects.

  • Regenerates the C# and metadata information for the objects.

  • Updates the record in the Object Metadata table for each object.

Note
In Microsoft Dynamics NAV 2009, you used the Enable for Microsoft Dynamics NAV Server option to specify that when you compiled objects, you also wanted to regenerate the C# and metadata information. In Microsoft Dynamics NAV 2016, the Enable for Microsoft Dynamics NAV Server option has been removed from the Options tab in the Alter Database window.

To build server application objects

  1. In the development environment, on the Tools menu, choose Build Server Application Objects.

  2. In the dialog box, choose the Yes button.

    If errors occurred, then the Error List window opens.

See Also

Concepts

Importing and Exporting Objects


Optimizing SQL Server Performance with Microsoft Dynamics NAV

This section describes how to optimize performance in Microsoft Dynamics NAV 2016 when accessing data from the SQL Server database.

See Also

Concepts

Data Access
Table Keys and Performance
Bulk Inserts
C/AL Database Functions and Performance on SQL Server
Query Objects and Performance
Configuring Microsoft SQL Server

Other Resources

Microsoft SQL Server


Data Access

The SQL Server interface from Microsoft Dynamics NAV Server uses ADO.NET instead of ODBC, which was used in Microsoft Dynamics NAV 2009 and earlier. The advantages of the new access layer are described in the following sections.

Simplified Deployment

The new ADO.NET interface is a managed data access layer that supports SQL Server connection pooling, which can dramatically decrease memory consumption by Microsoft Dynamics NAV Server. SQL Server connection pooling also simplifies deployment of the Microsoft Dynamics NAV three-tier architecture for deployments where the three tiers are installed on separate computers. Specifically, administrators are no longer required to manually create SPNs or to set up delegation when the client, Microsoft Dynamics NAV Server, and SQL Server are on separate computers. For more information, see Walkthrough: Installing the Three Tiers on Three Computers.

Collation

SQL Server 2008 is full aligned with the collations in Windows Server 2008. If you upgrade to Microsoft Dynamics NAV from Microsoft Dynamics NAV 2009, the step to convert the database includes upgrading the database to Windows collation. The collation changes provide users with the most up-to-date and linguistically accurate cultural sorting conventions. For more information, see Collation and Unicode Support.

Decreased Resource Consumption

There is no longer a one-to-one correlation between the number of client connections and the number of SQL Server connections. In earlier versions of Microsoft Dynamics NAV, each SQL Server connection could consume up to 40 MB of memory. Additionally, memory allocation is now in managed memory, which is generally more efficient than unmanaged memory.

In Microsoft Dynamics NAV, the data cache is shared by all users who are connected to the same Microsoft Dynamics NAV Server instance. This means that after one user has read a record, a second user who reads the same record gets it from the cache. In earlier versions of Microsoft Dynamics NAV, the data cache was isolated for each user.

Caching

Microsoft Dynamics NAV 2016 uses an improved cache system. The following functions use the cache system:

  • GET

  • FIND

  • FINDFIRST

  • FINDLAST

  • FINDSET

  • COUNT

  • ISEMPTY

  • CALCFIELDS

There are two types of caches:

  • Global cache - for all users connected to a Microsoft Dynamics NAV Server instance.

  • Private cache - per user, per company, in a transactional scope. Data in a private cache for a given table and company are flushed when a transaction ends.

The cache that is used is determined by the lock state of a table. If a table is not locked than the global cache is queried for data; otherwise, the private cache is queried.

Results from query objects are not cached.

For a call to any of the FIND functions, 1024 rows are cached. You can set the size of the cache by using the Data Cache Size setting in the Microsoft Dynamics NAV Server configuration file. The default size is 9, which approximates a cache size of 500 MB. If you increase this number by one, then the cache size doubles.

You can bypass the cache by using the SELECTLATESTVERSION Function (Database).

Microsoft Dynamics NAV synchronizes caching between Microsoft Dynamics NAV Server instances that are connected to the same database. By default, the synchronization occurs every 30 seconds.

You can set the cache synchronization interval by using the CacheSynchronizationPeriod parameter in the CustomSettings.config file. For more information, see Configuring Microsoft Dynamics NAV Server.

Performance

Records are retrieved using multiple active result sets (MARS). Functions such as NEXT, FIND('-'), FIND('+'), FIND('>'), and FIND('<') are generally faster with MARS than the server cursors that earlier versions of Microsoft Dynamics NAV used.

SIFT indexes have also been improved. For example, COUNT and AVERAGE formulas can now use SIFT indexes. For more information, see CALCSUMS Function (Record) and CALCFIELDS Function (Record). MIN and MAX formulas now use SQL Server MIN and MAX functions exclusively.

RecordIds and SQL Variant columns in a table no longer prevent the use of BULK insert inserts. For more information, see Bulk Inserts.

In most cases, filtering on FlowFields issues a single SQL statement. In earlier versions of Microsoft Dynamics NAV, filtering on FlowFields issued an SQL statement for each filtered FlowField and for each record in the table in order to calculate the filtered FlowFields. The exceptions in Microsoft Dynamics NAV in which filtering on FlowFields does not issue a single SQL statement are as follows:

  • You use the ValueIsFilter option on a field and the field has a value. For more information about the ValueIsFilter option, see How to: Create, View, and Edit a Calculation Formula.

  • A second predicate is specified on a source field and the field that is used for the second predicate has a value. For example, when you specify the CalcFormula Property for a FlowField, you can specify table filters in the Calculation Formula window. If you specify two or more filters on the same source field, then filtering does not issue a single SQL statement.

  • You specify Validated for the SecurityFiltering Property on a record. This value for the SecurityFiltering property means that each record that is part of the calculation must be verified for inclusion in the security filter.

In most cases, calling the FIND or NEXT functions after you have set the view to include only marked records issues a single SQL statement. In earlier versions of Microsoft Dynamics NAV, calling FIND or NEXT functions that have marked records issued an SQL statement for each mark. There are some exceptions if many records are marked. For more information, see MARKEDONLY Function (Record).

See Also

Concepts

Changes in C/AL Behavior and Support from Earlier Versions of Microsoft Dynamics NAV
SumIndexField Technology (SIFT)
Query Objects and Performance


Table Keys and Performance

When you write C/AL code that searches through a subset of the records in a table, you must consider what keys are defined for the table and write code that optimizes for the keys. For example, the entries for a specific customer are usually a small subset of a table containing entries for all the customers.

Defining Keys to Improve Performance

The time that it takes to complete a loop through a subset of records depends on the size of the subset. If a subset cannot be located and read efficiently, then performance deteriorates.

To maximize performance, you must define the keys in the table that support the code that you run. You must then specify these keys correctly in your code.

For example, to retrieve the entries for a specific customer, you apply a filter to the Customer No. field in the Cust. Ledger Entry table. To run the code efficiently on Microsoft SQL Server, you must define a key in the table that has Customer No. as the first field.

The table could have the following keys:

  • Entry No.

  • Customer No.,Posting Date

The following is an example of code that finds a subset of records.

Copy Code
SETRANGE("Customer No.",'1000');
IF FIND('-') THEN
REPEAT
UNTIL NEXT = 0;

SQL Server automatically chooses which index to use in order to retrieve data in the most efficient way. SQL Server calculates the cost of retrieving data using different indexes and then chooses the path that has the smallest cost. For Microsoft Dynamics NAV, that calculation is based only on the statistical distribution of values in a column.

For example, if a table contains 1000 rows and a column in the table contains either the value 0 or the value 1, then that column is said to have a low selectivity. If instead a column contained the values ranging from 1 to 500 then the column is said to have a high selectivity. In the following code example, SQL Server chooses an index that contains the HighSelectivityColumn and then sorts the rows by the LowSelectivityColumn.

Copy Code
SETCURRENTKEY("LowSelectivityColumn");
SETFILTER("LowSelectivityColumn",'1');
SETFILTER("HighSelectivityColumn",'777');
FIND('-')

See Also

Concepts

Data Access
Bulk Inserts
C/AL Database Functions and Performance on SQL Server
Query Objects and Performance


Bulk Inserts

By default, Microsoft Dynamics NAV automatically buffers inserts in order to send them to Microsoft SQL Server at one time.

By using bulk inserts, the number of server calls is reduced, thereby improving performance.

Bulk inserts also improve scalability by delaying the actual insert until the last possible moment in the transaction. This reduces the amount of time that tables are locked; especially tables that contain SIFT indexes.

Application developers who want to write high performance code that utilizes this feature should understand the following bulk insert constraints.

Bulk Insert Constraints

If you want to write code that uses the bulk insert functionality, you must be aware of the following constraints.

Records are sent to SQL Server when the following occurs:

  • You call COMMIT to commit the transaction.

  • You call MODIFY or DELETE on the table.

  • You call any FIND or CALC methods on the table.

Records are not buffered if any of the following conditions are met:

  • The application is using the return value from an INSERT call; for example, "IF (GLEntry.INSERT) THEN".

  • The table that you are going to insert the records into contains any of the following:

    • BLOB fields

    • Fields with the AutoIncrement property set to Yes

The following code example cannot use buffered inserts because it contains a FIND call on the GL/Entry table within the loop.

Copy Code
IF (JnlLine.FIND('-')) THEN BEGIN
  GLEntry.LOCKTABLE;
  REPEAT
    IF (GLEntry.FINDLAST) THEN
      GLEntry.NEXT := GLEntry."Entry No." + 1
    ELSE
      GLEntry.NEXT := 1;
    // The FIND call will flush the buffered records.
    GLEntry."Entry No." := GLEntry.NEXT ;
    GLEntry.INSERT;
  UNTIL (JnlLine.FIND('>') = 0)
END;
COMMIT;

If you rewrite the code, as shown in the following example, you can use buffered inserts.

Copy Code
IF (JnlLine.FIND('-')) THEN BEGIN
  GLEntry.LOCKTABLE;
  IF (GLEntry.FINDLAST) THEN
    GLEntry.Next := GLEntry."Entry No." + 1
  ELSE
    GLEntry.Next := 1;
  REPEAT
    GLEntry."Entry No.":= GLEntry.Next;
    GLEntry.Next := GLEntry."Entry No." + 1;
    GLEntry.INSERT;
  UNTIL (JnlLine.FIND('>') = 0)
END;
COMMIT;
// The inserts are performed here.

Disabling Bulk Inserts

Disabling bulk inserts can be helpful when you are troubleshooting failures that occur when inserting records. To disable bulk inserts, you set the BufferedInsertEnabled parameter in the CustomSettings.config file of the Microsoft Dynamics NAV Server to FALSE. For more information, see Configuring Microsoft Dynamics NAV Server.

See Also

Concepts

Data Access
Table Keys and Performance
C/AL Database Functions and Performance on SQL Server
Query Objects and Performance


C/AL Database Functions and Performance on SQL Server

This topic describes the relationship between basic database functions in C/AL and SQL statements.

C/AL and SQL Statements

GET, FIND, and NEXT

The C/AL language offers several methods to retrieve record data. In Microsoft Dynamics NAV 2016, records are retrieved using multiple active result sets (MARS). Generally, retrieving records with MARS is faster than with server-side cursors. Additionally, each function is optimized for a specific purpose. To achieve optimal performance you must use the method that is best suited for a given purpose.

  • Record.GET is optimized for getting a single record based on primary key values.

  • Record.FIND is optimized for getting a single record based on the primary keys in the record and any filter or range that has been set.

  • Record.FIND('-') and Record.FIND('+') are optimized for reading primarily from a single table when the application might not read all records. FIND('-') is implemented by issuing a self-tuning TOP X call, where X can change over time, based on statistics of the number of rows read.

    The following are examples of scenarios in which you should use the FIND('-') function to achieve optimal performance:

    • Before you post a general journal batch, you must check all journal lines for validity and verify that all lines balance. After the first line when an error is found, you do not have to retrieve the rest of the rows.

    • If you want to fulfill multiple outstanding orders from a recent purchase but you do not know how many orders are covered by the purchase.

  • Record.FINDSET(ForUpdate, UpdateKey) is optimized for reading the complete set of records in the specified filter and range. The UpdateKey parameter does not influence the efficiency of this method in Microsoft Dynamics NAV 2016, such as it did in Microsoft Dynamics NAV 2009.

    FINDSET is not implemented by issuing a TOP X call.

  • Record.FINDFIRST and Record.FINDLAST are optimized for finding the single first or last record in the specified filter and range.

  • Record.NEXT can be called at any time. However, if Record.NEXT is not called as part of retrieving a continuous result set, then Microsoft Dynamics NAV calls a separate SQL statement in order to find the next record.

Dynamic Result Sets

Any result set that is returned from a call to the find methods discussed in the previous section is dynamic. That means that the result set is guaranteed to contain any changes that you make further ahead in the result set. However this feature comes at a cost. If any modifications are made to a table which is being traversed, then Microsoft Dynamics NAV might have to issue an extra SQL statement to guarantee that the result set is dynamic.

The following code shows how records are most efficiently retrieved. FINDSET is the most efficient method to use because this example reads all records.

Copy Code
IF FINDSET THEN
  REPEAT
    // Insert statements to repeat.
  UNTIL NEXT = 0;

CALCFIELDS, CALCSUMS, and COUNT

Each call to CALCFIELDS, CALCFIELD, CALCSUMS, or CALCSUM functions that calculates a sum requires a separate SQL statement unless the client has calculated the same sum or another sum that uses the same SumIndexFields or filters in a recent operation, and therefore, the result is cached.

Each CALCFIELDS or CALCSUMS request should be confined to use only one SIFT index. The SIFT index can only be used if:

  • All requested sum-fields are contained in the same SIFT index.

  • The filtered fields are part of the key fields specified in the SIFT index containing all the sum fields.

If neither of these requirements is fulfilled, then the sum will be calculated directly from the base table.

In Microsoft Dynamics NAV 2016, SIFT indexes can be used to count records in a filter provided that a SIFT index exists that contains all filtered fields in the key fields that are defined for the SIFT index.

SETAUTOCALCFIELDS

It is a common task to retrieve data and request calculation of associated FlowFields. The following example traverses customer records, calculates the balance, and marks the customer as blocked if the customer exceeds the maximum credit limit. Note the Customer record and associated fields are imaginary.

Copy Code
IF Customer.FINDSET() THEN REPEAT
  Customer.CALCFIELDS(Customer.Balance)
  IF (Customer.Balance > MaxCreditLimit) THEN BEGIN
    Customer.Blocked = True;
    Customer.MODIFY();
  END
  ELSE IF (Customer.Balance > LargeCredit) THEN BEGIN
    Customer.Caution = True;
    Customer.MODIFY();
  END;
UNTIL Customer.NEXT = 0;

In Microsoft Dynamics NAV 2016, you can do this much faster. First, we set a filter on the customer. This could also be done in Microsoft Dynamics NAV 2009, but behind the scenes the same code as mentioned earlier would be executed. In Microsoft Dynamics NAV 2016, setting a filter on a record is translated into a single SQL statement.

Copy Code
Customer.SETFILTER(Customer.Balance,’>%1’, LargeCredit);
IF Customer.FINDSET() THEN REPEAT
  Customer.CALCFIELDS(Customer.Balance)
  IF (Customer.Balance > MaxCreditLimit) THEN BEGIN
    Customer.Blocked = True;
    Customer.MODIFY();
  END
  ELSE IF (Customer.Balance > LargeCredit) THEN BEGIN
    Customer.Caution = True;
    Customer.MODIFY();
  END;
UNTIL Customer.NEXT = 0;

In the previous example, an extra call to CALCFIELDS still must be issued for the code to be able to check the value of Customer.Balance. In Microsoft Dynamics NAV 2016, you can optimize this further by using the new SETAUTOCALCFIELDS function.

Copy Code
Customer.SETFILTER(Customer.Balance,’>%1’, LargeCredit);
Customer.SETAUTOCALCFIELDS(Customer.Balance)
IF Customer.FINDSET() THEN REPEAT
  IF (Customer.Balance > MaxCreditLimit) THEN BEGIN
    Customer.Blocked = True;
    Customer.MODIFY();
  END
  ELSE IF (Customer.Balance > LargeCredit) THEN BEGIN
    Customer.Caution = True;
    Customer.MODIFY();
  END;
UNTIL Customer.NEXT = 0;

INSERT, MODIFY, DELETE, and LOCKTABLE

Each call to INSERT, MODIFY, or DELETE functions requires a separate SQL statement. If the table that you modify contains SumIndexes, then the operations will be much slower. As a test, select a table that contains SumIndexes and execute one hundred INSERT, MODIFY, or DELETE operations to measure how long it takes to maintain the table and all its SumIndexes.

The LOCKTABLE function does not require any separate SQL statements. It only causes any subsequent reading from the table to lock the table or parts of it.

See Also

Reference

GET Function (Record)
FIND Function (Record)
NEXT Function (Record)
FINDSET Function (Record)
FINDFIRST Function (Record)
FINDLAST Function (Record)
CALCFIELDS Function (Record)
CALCFIELD Function (FieldRef)
CALCSUMS Function (Record)
CALCSUM Function (FieldRef)
SETAUTOCALCFIELDS Function (Record)
INSERT Function (Record)
MODIFY Function (Record)
DELETE Function (Record)
LOCKTABLE Function (Record)

Concepts

Table Keys and Performance
Bulk Inserts


Query Objects and Performance

A query is a new object in Microsoft Dynamics NAV 2016 that you use to specify a set of data that you want to read from the Microsoft Dynamics NAV database. You can query the database to retrieve one or more fields from a single table or multiple tables. You can specify how to join the tables in the query. You can specify totaling methods on fields, such as sums and averages. This topic describes how to design queries and table keys in the most efficient way.

FlowFields in Queries

A sub-query is automatically added to the SQL statement to retrieve each FlowField in a query. This allows Microsoft Dynamics NAV to retrieve all the data in one request.

Important
You cannot use a FlowField on a virtual table in a query because this cannot be converted automatically into a SQL statement.

Covering Indexes

When you use a query to select a subset of fields in a table, you should consider taking advantage of the covering index strategy. A covering index is the index that contains all output fields required by the operation performed on that index. A covering index data access strategy can greatly improve performance because the database must retrieve only data from the index instead of finding data by using the index and then retrieving the data in the clustered index. A covering index data access strategy can be used when the following conditions are true:

  • All columns in a given data item are part of a single Microsoft Dynamics NAV key.

  • All columns that are used in the DataItem table filters are part of the same Microsoft Dynamics NAV key.

  • If two DataItems are linked, then the field on the parent DataItem that links the two DataItems (the Reference Field on the DataItemLink property), must be part of the same Microsoft Dynamics NAV key as the columns in the child DataItem.

The SQL Server optimizer automatically chooses a covering index strategy whenever possible.

For more information about SQL Server covering indexes, see SQL Server Optimization.

For more information about SQL Server clustered and non-clustered indexes, see Types of Indexes.

Covering SIFT Indexes

Similar to how indexes can be used to retrieve data for a query, SIFT indexes can be used to retrieve data for a query that contains totals. SIFT totals are maintained after each insert, modify, or delete call, and so some or all of the totals are already calculated. A SIFT index can be used when the following conditions are true:

  • The query contains at least one aggregated column with Method Type set to Totals and with Method set to either Sum, Count, or Average.

  • If a DataItem contains an aggregated column, then all columns under that DataItem must be aggregated columns, must use either the Sum, Count, or Average method, and must be part of a SumIndexField defined on a single Microsoft Dynamics NAV key.

  • In a query in which you have aggregations but not on all DataItems, then for the DataItems without aggregations, the columns are part of a SumIndexField.

  • All non-aggregated columns under the DataItem that have aggregation are part of the key fields defined for the same SIFT index.

  • All columns that are used in the DataItem table filters are part of the same Microsoft Dynamics NAV key.

  • If two DataItems are linked, then the field on the parent DataItem that links the two DataItems (the Reference Field in the DataItemLink property) must be part of the same Microsoft Dynamics NAV key as the columns in the child DataItem.

Microsoft Dynamics NAV Server automatically use a SIFT index for query objects whenever possible.

Differences Between Query and Record Result Sets

Microsoft Dynamics NAV does not do any caching for query result sets. When you run a query, Microsoft Dynamics NAV always gets the data directly from SQL Server.

Query result sets are not guaranteed to be dynamic, whereas record result sets are always dynamic. This means that if you insert or modify data in result set row that you have not yet looped through, then it is not guaranteed that the query result set includes those changes.

See Also

Concepts

Queries
SumIndexField Technology (SIFT)
Optimizing SQL Server Performance with Microsoft Dynamics NAV


Login Stored Procedure

A login stored procedure is a stored procedure that you can use to perform predefined functions after a user logs on to the Microsoft Dynamics NAV Development Environment. A typical function would be to generate a message that informs the user that the database is currently in single-user mode so that an administrator can perform database maintenance tasks and is therefore inaccessible.

The login stored procedure is run immediately after the user has logged on to SQL Server and opened a database, and before Microsoft Dynamics NAV performs any tasks including executing C/AL triggers.

Note
In Microsoft Dynamics NAV 2016, the Microsoft Dynamics NAV Server instance does not call login stored procedures. The development environment does call login stored procedures.

Creating the Stored Procedure

The stored procedure is created in the database and has a predefined name and a list of parameters.

The stored procedure is called [sp_$ndo$loginproc] and has the following characteristics:

  • It takes two VARCHAR parameters: the name of the application and the Microsoft Dynamics NAV version number. These parameters must be declared as part of the stored procedure but do not have to be used.

  • It can perform transactions. Microsoft Dynamics NAV uses a COMMIT to flush any outstanding transactions after the stored procedure has finished executing.

  • The RAISERROR statement can be used to display an error message in Microsoft Dynamics NAV and prevent the user from accessing the database.

  • The PRINT statement can be used to display a warning in Microsoft Dynamics NAV and let the user access the database.

  • If the stored procedure returns a value, it is ignored.

  • If the stored procedure does not exist, no action is taken by Microsoft Dynamics NAV and the login process continues.

Example 1

The following code example displays a warning message in Microsoft Dynamics NAV and permits the login.

Copy Code
IF EXISTS (SELECT name FROM sysobjects
WHERE name = 'sp_$ndo$loginproc' AND type = 'P')
DROP PROCEDURE [sp_$ndo$loginproc]
GO
CREATE PROCEDURE [sp_$ndo$loginproc]
@appname VARCHAR(64) = NULL,
@appversion VARCHAR(16) = NULL
AS
BEGIN
PRINT 'The system will be unavailable on April 1, 2013.'
END
GO
GRANT EXECUTE ON [sp_$ndo$loginproc] TO public
GO

Example 2

The following code example displays an error message in Microsoft Dynamics NAV and prevents the login.

Copy Code
IF EXISTS (SELECT name FROM sysobjects
WHERE name = 'sp_$ndo$loginproc' AND type = 'P')
DROP PROCEDURE [sp_$ndo$loginproc]
GO
CREATE PROCEDURE [sp_$ndo$loginproc]
@appname VARCHAR(64) = NULL,
@appversion VARCHAR(16) = NULL
AS
BEGIN
IF SUSER_SNAME() IN ('ACCOUNTS\jim', 'SALES\bill')
RAISERROR ('Contact the system administrator.', 11, 1)
END
GO
GRANT EXECUTE ON [sp_$ndo$loginproc] TO public
GO

See Also

Concepts

Table Keys and Performance
Bulk Inserts
C/AL Database Functions and Performance on SQL Server


Monitoring Microsoft Dynamics NAV Server

This section describes the Microsoft Dynamics NAV 2016 features for monitoring Microsoft Dynamics NAV Server.

In this section

  • Tools for Monitoring Performance Counters and Events

  • Monitoring Microsoft Dynamics NAV Server Using Performance Counters

  • Monitoring Microsoft Dynamics NAV Server Events


Tools for Monitoring Performance Counters and Events

This topic lists some of the tools that you can use to monitor Microsoft Dynamics NAV Server.

Microsoft System Center Operations Manager

Microsoft System Center Operations Manager, which is a component of Microsoft System Center 2012, enables you to monitor services and operations on multiple computers from a single console. The System Center Monitoring Pack for Microsoft Dynamics NAV extends Operations Manager for monitoring computers that are running Microsoft Dynamics NAV components and services, including Microsoft Dynamics NAV Server. For more information, see Microsoft Dynamics NAV 2015 Management Pack for System Center Operations Manager.

Windows Performance Monitor

Performance Monitor is available on Windows operating systems. You can use Performance Monitor to collect and view performance data from performance counters and trace events in real-time or from a log file. For more information Windows Performance Monitor.

Windows Event Viewer

Windows Event Viewer is available on Windows operating systems. You can use Event Viewer to collect and view Microsoft Dynamics NAV Server events that are logged in the Microsoft Dynamics NAV Server channel logs in the Applications and Services Logs and Windows Application event log of the Microsoft Dynamics NAV Server computer. For more information, see Monitoring Microsoft Dynamics NAV Server Events in the Windows Event Log.

Windows PowerShell

You can use the Get-WinEvent cmdlet of Windows PowerShell to view Microsoft Dynamics NAV Server instance events that are recorded in the Windows Event Logs. For more information, see Monitoring Microsoft Dynamics NAV Server Events in the Windows Event Log.

PerfView

PerfView is a performance-analysis tool that focuses on Event Tracing for Windows information. PerfView can help you isolate performance issues that are related to Microsoft Dynamics NAV Server. To download and install PerfView, see http://go.microsoft.com/fwlink/?LinkID=313428.


Monitoring Microsoft Dynamics NAV Server Using Performance Counters

Performance counters provide information about how well Microsoft Dynamics NAV Server is operating. By using monitoring tools such as Windows Performance Monitor and System Center Operations Manager, you can use the Microsoft Dynamics NAV performance counters to collect data on Microsoft Dynamics NAV Server instances, and then use the data to identify conditions that are affecting performance and make adjustments.

Microsoft Dynamics NAV also provides a Data Collector Set template that you can use to easily create Data Collector Sets that contain all the Microsoft Dynamics NAV performance counters.

In This Section

  • Microsoft Dynamics NAV Performance Counters

  • How to: Set up Performance Counters in Windows Performance Monitor

  • Working with Data Collector Sets

For information about System Center Operations Manager, see Microsoft Dynamics NAV 2015 Management Pack for System Center Operations Manager.


Microsoft Dynamics NAV Performance Counters

The following table describes the performance counters that are available in Microsoft Dynamics NAV for monitoring Microsoft Dynamics NAV Server instances.

Category Counter Description

Client, NAS, and Web Service sessions

# Active sessions

Number of active sessions on the Microsoft Dynamics NAV Server instance.

An active session is a connection to the Microsoft Dynamics NAV Server instance from a Microsoft Dynamics NAV client, such as the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client, NAS, or Web services.

Server operations/sec

Number of operations that have started on the Microsoft Dynamics NAV Server per second.

An operation is a call to the Microsoft Dynamics NAV Server instance from a Microsoft Dynamics NAV client to run Microsoft Dynamics NAV objects.

Note
OData and SOAP requests are not included.

Average server operation time (ms)

Average duration of server operations in milliseconds.

SQL Server connections

# Mounted tenants

Number of tenants that are mounted on the Microsoft Dynamics NAV Server instance.

For more information about tenants, see Multitenant Deployment Architecture.

# Open connections

Count of the current number of open connections from the Microsoft Dynamics NAV Server instance to Microsoft Dynamics NAV databases on SQL Servers.

% Query repositioning rate

Percentage of queries that are re-executed when fetching the query result.

Heartbeat time (ms)

The time that it takes to complete a single write to a system table. Every 30 seconds, the Microsoft Dynamics NAV Server instance writes a record to indicate that the instance is "alive."

You can use this counter to indicate if there is network latency between the Microsoft Dynamics NAV Server and the SQL Server.

# Preferred connection total requests

Count of the total number of requests to the preferred connection cache. The preferred connection cache contains requests from the SQL connection pool that was last used by a Microsoft Dynamics NAV user.

% Preferred connection cache hit rate

Percentage of hits in the preferred connection cache, compared to the total number of requests.

Data and caching

# Calculated fields cache total requests

Count of the total number of requests to the calculated fields cache. The calculated fields cache contains the results of CALCFIELDS Function (Record) calls.

% Calculated fields cache hit rate

Percentage of hits in the calculated fields cache, compared to the total requests to the calculated fields cache.

# Command cache total requests

Count of the total number of requests to the command cache. The command cache contains the results of all SQL commands.

% Command cache hit rate

Percentage of hits in the command cache, compared to the total requests to the command cache.

# Primary key cache total requests

Count of the total number of requests to the primary key cache. The primary key cache contains the results of requests to get a record by using its primary key.

% Primary key cache hit rate

Percentage of hits in the primary key cache, compared to the total requests to the primary key cache.

# Result set cache total requests

Count of the total number of requests to the result set cache. The result set cache contains result sets that are returned from SQL Server.

% Result set cache hit rate

Percentage of hits in the result set cache, compared to the total requests to the result set cache.

# Rows in all temporary tables

Count of number of rows in all temporary tables.

See Also

Tasks

How to: Set up Performance Counters in Windows Performance Monitor
How to: Create a Data Collector Set From the Microsoft Dynamics NAV Template

Concepts

Optimizing SQL Server Performance with Microsoft Dynamics NAV

Other Resources

Microsoft Dynamics NAV 2013 R2 Management Pack for System Center Operations Manager


How to: Set up Performance Counters in Windows Performance Monitor

This topic describes how to use Windows Performance Monitor to collect and view data from the Microsoft Dynamics NAV performance counters. For a list of Microsoft Dynamics NAV performance counters, see Microsoft Dynamics NAV Performance Counters.

To set up Microsoft Dynamics NAV performance counters

  1. Start Windows Performance Monitor.

    • Choose Start, in the Search box, type perfmon, and then choose the related link.

  2. In the navigation pane, expand Monitoring Tools, and then choose Performance Monitor.

  3. In the console pane toolbar, choose the Add button.

  4. In the Add Counters window, in the Select counters from computer drop-down list, choose the computer that is running Microsoft Dynamics NAV Server.

  5. In the Available counters list, expand Microsoft Dynamics NAV, and select one or more counters.

  6. In the Instances of selected object list, select one or more Microsoft Dynamics NAV Server instances.

  7. Choose the Add button, and then choose the OK button.

  8. Choose the OK button.

    Windows Performance Monitor displays data for the counters that you selected.

For more information about how to use Windows Performance Monitor, see Windows Performance Monitor.

See Also

Concepts

Microsoft Dynamics NAV Performance Counters
Monitoring Microsoft Dynamics NAV Server
Working with Data Collector Sets


Working with Data Collector Sets

A Data Collector Set organizes data collection points, such as performance counters and event trace data, into a single collection. Data Collector Sets enable you to schedule data collection, so that you can analyze the results and view reports later. Data that is collected for performance counters by a Data Collector Set is stored in log files, which you can open and view in Windows Performance Monitor. You can create your own Data Collection Set or you can use the Data Collection Set template that is included with Microsoft Dynamics NAV.

For more information about how to use Data Collector Sets to monitor Microsoft Dynamics NAV Server, see the following topics:

How to: Create a Data Collector for Microsoft Dynamics NAV Performance Counters

How to: Create a Data Collector Set From the Microsoft Dynamics NAV Template

How to: View Performance Counter Data for a Data Collector Set

For general information about Data Collector Sets, see Creating Data Collector Sets.

See Also

Concepts

Microsoft Dynamics NAV Performance Counters


How to: Create a Data Collector for Microsoft Dynamics NAV Performance Counters

This topic describes how to create a Data Collector Set in Performance Monitor that contains Microsoft Dynamics NAV performance counters.

To create a Data Collector Set for Microsoft Dynamics NAV performance counters

  1. On the computer that is running Microsoft Dynamics NAV Server, start Performance Monitor.

    • Choose Start, in the Search box, type perfmon, and then choose the related link.

  2. In the navigation pane, expand Data Collector Sets, right-click User-defined, choose New, and then choose Data Collector Set.

  3. On the Create new Data Collector Set Wizard page, enter a name for the new data collector set. Select Create manually (Advanced), and then choose the Next button.

  4. On the What type of data do you want to include page, select the Performance counter check box, and then choose the Next button.

  5. In the Add Counters window, in the Select counters from computer: drop-down list, choose the computer that is running Microsoft Dynamics NAV Server.

  6. In the Available counters list, expand Microsoft Dynamics NAV, and select one or more counters.

  7. In the Instances of selected object list, select <All instances> to collect data for all Microsoft Dynamics NAV Server instances on the computer or individually select one or more instances from the list.

  8. Choose the Add button, and then choose the OK button

  9. Choose the Next button.

  10. On the Where would you like the data to be saved page page, set Root directory to the location to store the log file that will contain data that is collected by the Data Collector Set.

  11. Choose the Finish button to save the Data Collector Set and exit.

    To see the new Data Collector Set, in the navigation pane, expand Data Collector Sets, and then expand User Defined. You can start to collect data.

To start and stop a Data Collector Set

  • To start to collect data immediately, under Data Collector Sets, expand User Defined, right-click the Data Collector Set, and then choose Start.

  • To stop collecting data, right-click the Data Collector Set, and then choose Stop.

For information about how to schedule a time to start and stop collecting data, see Schedule Data Collection in Windows Performance Monitor.

For information about how to view the data that is collected by the Data Collector Set, see How to: View Performance Counter Data for a Data Collector Set.

See Also

Tasks

How to: Create a Data Collector Set From the Microsoft Dynamics NAV Template

Concepts

Working with Data Collector Sets
Microsoft Dynamics NAV Performance Counters


How to: Create a Data Collector Set From the Microsoft Dynamics NAV Template

Microsoft Dynamics NAV provides a Data Collector Set template that includes the Microsoft Dynamics NAV performance counters and additional performance counters for monitoring components, such as memory, physical disks, and SQL Server. You use the template to create user-defined Data Collection Sets for monitoring all Microsoft Dynamics NAV Server instances on the computer that is running Microsoft Dynamics NAV Server.

The Microsoft Dynamics NAV data collector set template is an XML file that has the name DataCollectorSet.xml and is installed with Microsoft Dynamics NAV Server. By default, the template is located in the C:\Program Files\Microsoft Dynamics NAV\90\Service folder.

Data that is collected by a data collector set is stored in a log file that you can view in Performance Monitor.

For more general information about Data Collector Sets, see Creating Data Collector Sets.

To create a data collection set from the Microsoft Dynamics NAV template

  1. On the computer that is running Microsoft Dynamics NAV Server, start Performance Monitor.

    • Choose Start, in the Search box, type perfmon, and then choose the related link.

  2. In the navigation pane, expand Data Collector Sets, right-click User-defined, choose New, and then choose Data Collector Set.

  3. In the Create new Data Collector Set Wizard page, enter a name for the new data collector set. Select Create from a template (Recommended), and then choose the Next button.

  4. On the Which template would you like to use page, choose the Browse button, locate the DataCollectorSet.xml, and then choose the Open button.

    By default, the template is located in the C:\Program Files\Microsoft Dynamics NAV\90\Service folder.

  5. Choose the Next button, and then follow the instructions to finish creating the data collector set.

    To see the new Data Collector Set, in the navigation pane, expand Data Collector Sets, and then expand User Defined.

For information about how to start the Data Collector Set, see To start and stop a Data Collector Set in Performance Monitor.

See Also

Tasks

How to: View Performance Counter Data for a Data Collector Set

Concepts

Working with Data Collector Sets
Microsoft Dynamics NAV Performance Counters
Microsoft Dynamics NAV Performance Counters


How to: View Performance Counter Data for a Data Collector Set

When you run a Data Collector Set, the data that is collected for performance counters is stored to a log file (.blg) in the location that was defined when the Data Collector Set was created. In Windows Performance Monitor, you can view log files to see a visual representation of performance counter data.

To view the Data Collector Set log file

  1. Start Windows Performance Monitor.

    • Choose Start, in the Search box, type perfmon, and then choose the related link.

  2. In the navigation pane, expand Monitoring Tools, and then choose Performance Monitor.

  3. In the console pane toolbar, choose the View Log Data button.

    The Performance Monitor Properties page opens at the Source tab.

  4. In the Data Source section, select Log files, and then choose the Add button.

  5. Browse to the log file that you want to view, and then choose the Open button.

  6. Choose the OK button.

See Also

Tasks

How to: Create a Data Collector for Microsoft Dynamics NAV Performance Counters
How to: Create a Data Collector Set From the Microsoft Dynamics NAV Template

Concepts

Microsoft Dynamics NAV Performance Counters
Working with Data Collector Sets
Microsoft Dynamics NAV Performance Counters


Monitoring Microsoft Dynamics NAV Server Events

You can monitor events on Microsoft Dynamics NAV Server to diagnose conditions and troubleshoot problems that affect operation and performance.

Event Logging Overview

Microsoft Dynamics NAV uses Event Tracing for Windows (ETW), which is a subsystem of Windows operating systems. ETW provides a tracing mechanism for events that are raised by an application or service. ETW enables you to use industry standard tools such as Windows Performance Monitor, PerfView, Event Viewer, and Windows PowerShell to dynamically collect data on trace events that occur on the Microsoft Dynamics NAV Server.

Events that occur on Microsoft Dynamics NAV Server instances are recorded in Windows Event logs on the Microsoft Dynamics NAV Server computer. Microsoft Dynamics NAV 2016 uses channels on all events. Event channels provide a way to collect and view events from a specific provider, which in this case is Microsoft Dynamics NAV Server, and group the events according to predefined types, such as admin, operational, and debug. For example, in Event Viewer, Microsoft Dynamics NAV Server instance events are collected in the Admin, Operational, and Debug channel logs for Microsoft Dynamics NAV Server in the Applications and Services Logs.

For more general information about ETW and event channels, see Event Tracing for Windows and Event Logs and Channels in Windows Event Log

In This Section

Monitoring Microsoft Dynamics NAV Server Events in the Windows Event Log

Monitoring Microsoft Dynamics NAV Server Event Traces


Monitoring Microsoft Dynamics NAV Server Events in the Windows Event Log

Events that occur on the Microsoft Dynamics NAV Server instances are recorded in event logs on the computer that is running Microsoft Dynamics NAV Server. You can view the events by using Event Viewer or Windows PowerShell as described in this topic.

  • Viewing Microsoft Dynamics NAV Server Events by Using Event Viewer

  • Viewing Microsoft Dynamics NAV Server Events by Using Windows PowerShell

For a list and description of the events that can occur, see Microsoft Dynamics NAV Server Events.

Viewing Microsoft Dynamics NAV Server Events by Using Event Viewer

Events that occur on Microsoft Dynamics NAV Server instances are recorded in the following logs:

  • Microsoft Dynamics NAV Server channel logs in the Applications and Services Logs

    By using event channels, events that occur on a Microsoft Dynamics NAV Server instance are recorded to specific Microsoft Dynamics NAV Server logs in the Applications and Services Logs. Channels provide a way to collect and view events from a specific provider, which in this case, Microsoft Dynamics NAV Server. This differs from the Windows Application log which contains system-wide events from multiple publishers (applications and components).

    To view Microsoft Dynamics NAV Server instance events in Event Viewer, in the console tree, choose Applications and Services Logs, Microsoft, DynamicsNAV, Server. The events are recorded in the following logs, according the event channel to which they belong:

    Log Description

    Admin

    Includes events that target end users and IT administrators. These events typically indicate a problem that requires action to resolve the problem. An example of an admin event is a tenant database failing to mount on the Microsoft Dynamics NAV Server instance.

    Operational

    Includes events that provide information about an operation that occurred on Microsoft Dynamics NAV Server instances. These events are typically ordinary operating events that do not require any action but can be used to analyze and diagnose a problem. An example of an operational event is the shutting down of the Microsoft Dynamics NAV Server instance.

    Debug

    Includes trace events that occur on Microsoft Dynamics NAV Server instances. For more information about the different trace events and others ways to monitor them, see Microsoft Dynamics NAV Server Trace Events and Monitoring Microsoft Dynamics NAV Server Event Traces.

    Note
    In Event Viewer, this log is hidden and disabled by default. For information about how to show and enable this log, see How to: Use Event Viewer to Collect and View Trace Events.

  • Application log in the Windows Logs

    The Windows Application log includes admin and operational type events (errors, warnings, and information messages) that occur on the Microsoft Dynamics NAV Server instance.

    To view the Application log in Event Viewer, in the console tree, choose Windows Logs, Applications.

    The events in this log are the same events that are recorded in the Admin and Operation channel logs for Microsoft Dynamics NAV Server in the Applications and Services Logs. Therefore, you can consider the Windows Application log to be a secondary log for Microsoft Dynamics NAV Server events. Unless you are using System Center Operations Manager to monitor Microsoft Dynamics NAV Server events, you can disable logging Microsoft Dynamics NAV Server events to the Windows Application log and rely on Applications and Services Logs instead. For more information, see How to: Disable Logging Events to the Windows Application Log.

    Note
    Trace events are not included in this log.

For more information about how to use Event Viewer, see Windows Event Viewer.

Filtering Microsoft Dynamics Server Events in Event Viewer

By default, the Microsoft Dynamics NAV Server logs contain events of all levels (error, warning, and information) for all Microsoft Dynamics NAV Server instances. You can use the filtering functionality that is available in Event Viewer to display only Microsoft Dynamics NAV Server instance events that meet specific criteria. For example, if you have several Microsoft Dynamics NAV Server instances, you can filter logs to show only events from a specific Microsoft Dynamics NAV Server instance. For more information, see the following example.

Example

Your Microsoft Dynamics NAV Server is running several instances that are configured with multiple tenants. In Event Viewer, you want to view only errors that occurred in the last 24 hours on the tenant MyTenant1 of the Microsoft Dynamics NAV Server instance MyNavServerInstance1.

To filter the event log

  1. In the console tree of Event Viewer, choose Applications and Services Logs, Microsoft, DynamicsNAV, Server.

  2. Select the Admin log.

  3. In the Action pane, choose Filter Current Log.

    The Filter Current Log window opens.

  4. On the Filter tab, set the Logged drop-down list to Last 24 hours.

  5. In the Error Level section, select the Error check box.

  6. Choose the XML tab.

    XML similar to the following is displayed:

    Copy Code
    <QueryList>
  <Query Id="0" Path="Microsoft-DynamicsNAV-Server/Admin">
    <Select Path="Microsoft-DynamicsNAV-Server/Admin">
      *[System[(Level=2) and TimeCreated[timediff(@SystemTime) &lt;= 604800000]]]
  </Query>
</QueryList>

    Microsoft-DynamicsNAV-Server indicates that Microsoft Dynamics NAV Server is the provider of the events in the log.

  7. Select the Edit query manually check box, and then choose the Yes button.

  8. In the <Select Path="Microsoft-DynamicsNAV-Server/Admin"> element, after *[System[(Level=2) and TimeCreated[timediff(@SystemTime) &lt;= 86400000]]], add the following lines:

    Copy Code
          and
      *[EventData[Data[@Name='tenantId'] and Data  = 'MyTenant1']]
      and
      *[EventData[Data[@Name='serverInstanceName'] and Data='MyNavServerInstance1']]

    The complete XML should look similar to the following XML:

    Copy Code
    <QueryList>
  <Query Id="0" Path="Microsoft-DynamicsNAV-Server/Admin">
    <Select Path="Microsoft-DynamicsNAV-Server/Admin">
      *[System[(Level=2) and TimeCreated[timediff(@SystemTime) &lt;= 604800000]]]
      and
      *[EventData[Data[@Name='tenantId'] and Data  = 'MyTenant1']]
      and
      *[EventData[Data[@Name='serverInstanceName'] and Data='MyNavServerInstance1']]
    </Select>
  </Query>
</QueryList>

  9. Choose the OK button.

The Admin log displays only errors that occurred in the last 24 hours on tenant Tenant1 and Microsoft Dynamics NAV Server instance MyNavServerInstance1. The applied filter can be removed. Alternatively, you can save it as a custom view. For more information about filtering in Event Viewer, see Filter Displayed Events and Advanced XML filtering in the Windows Event Viewer.

Viewing Microsoft Dynamics NAV Server Events by Using Windows PowerShell

You can use the Get-WinEvent cmdlet of Windows PowerShell to view Microsoft Dynamics NAV Server instance events and trace events in the event logs and event tracing log files on the Microsoft Dynamics NAV Server computer. The Get-WinEvent cmdlet retrieves the same events that can be viewed in the Microsoft Dynamics NAV Server logs (Admin, Operational, and Debug) in the Applications and Services Logs of Event Viewer.

The Get-WinEvent cmdlet includes several parameters that enable you to filter the events that you view and specify how the events are displayed. Windows PowerShell enables you can create scripts that perform complex operations for extracting and displaying specific event data. For more information about the Get-WinEvent cmdlet, see Get-WinEvent.

For more information about installing and getting started with Windows PowerShell, see Getting Started with Windows PowerShell.

To use the Get-WinEvent Cmdlet to view Microsoft Dynamics NAV Server events

  1. If you want to view events in the Microsoft Dynamics NAV ServerDebug log, ensure that the log is enabled. The Admin and Operational logs are enabled by default.

    For information, see To enable the Microsoft Dynamics NAV Server Debug Log from Windows PowerShell.

  2. On the computer that is running Microsoft Dynamics NAV Server, start Window PowerShell.

    For more information, see Starting Windows PowerShell.

  3. At the command prompt, enter the Get-WinEvent command. The following table provides some simple example commands.

    To view Command

    Events in the all Microsoft Dynamics NAV Server logs

    Copy Code
    Get-WinEvent -ProviderName Microsoft-DynamicsNav-Server

    Events in the Microsoft Dynamics NAV Server Admin log

    Copy Code
    Get-WinEvent -LogName Microsoft-DynamicsNav-Server/Admin

    Events in the Microsoft Dynamics NAV Server Operational log

    Copy Code
    Get-WinEvent -LogName Microsoft-DynamicsNav-Server/Operational

    Trace events in the Microsoft Dynamics NAV Server Debug log

    Copy Code
    Get-WinEvent -LogName Microsoft-DynamicsNav-Server/Debug -Oldest

To enable the Microsoft Dynamics NAV Server Debug Log from Windows PowerShell

  1. On the computer that is running Microsoft Dynamics NAV Server, start Window PowerShell as an administrator.

  2. At the command prompt, enter the following command:

    Copy Code
    wevtutil.exe set-log “Microsoft-DynamicsNav-Server/<Debug>” /q:true /e:true
Tip
You can also enable the Debug log from Event Viewer. For more information, see Enable Analytic and Debug Logs.

Filtering Microsoft Dynamics NAV Server Events

You can filter the events that you view in a Microsoft Dynamics NAV Server log by setting the FilterXpath parameter of the Get-WinEvent cmdlet. The following examples illustrate how you can use the FilterXpath parameter to filter the Microsoft Dynamics NAV Server events.

Example 1

The following example uses the Get-WinEvent cmdlet to view errors in the Microsoft Dynamics NAV Server Admin log for the tenant MyTenant1 on the server instance MyNavServerInstance1.

Copy Code
Get-WinEvent -LogName 'Microsoft-DynamicsNav-Server/Admin' -FilterXPath "*[System[(Level=2)]] and *[EventData[Data[@Name='tenantId'] and (Data = 'MyTenant1')]] and *[EventData[Data[@Name='serverInstanceName'] and Data='MyNavServerInstance1']]" | Format-List -Property Message-

Example 2

The following is an example of a Windows PowerShell script that you can create and run to view trace events in the Microsoft Dynamics NAV Server Debug log. The script returns the start and stop C/AL function trace events that take more than four seconds to execute on the tenant MyTenant1 of the server instance MyNavServerInstance1.

Copy Code
$maxAllowedSeconds = 4
$xPath = "*[System[(EventID = 400 or EventID = 401)]] and " +
         "*[EventData[Data[@Name='tenantId'] and (Data  = 'MyTenant1')]] and " +
         "*[EventData[Data[@Name='serverInstanceName'] and Data='MyNavServerInstance1']]"

$events = Get-WinEvent -LogName 'Microsoft-DynamicsNav-Server/Debug' -FilterXPath $xPath -Oldest -MaxEvents 10000
Write-Host "List of AL functions that took more than $maxAllowedSeconds  seconds to execute :" -ForegroundColor DarkYellow
for($i = 0; $i -lt  $events.Length; $i+=2)
{
   $seconds = ($events[$i + 1].TimeCreated - $events[$i].TimeCreated).Seconds
   if ($seconds -ge $maxAllowedSeconds )
   {
     Write-Host $events[$i].Message `r`n -ForegroundColor Magenta
   }
}

You can create the script by using, for example, Notepad or Windows PowerShell Integrated Scripting Environment (ISE). You save the script as .ps1 file type, and then run it from the Windows PowerShell.

See Also

Concepts

Monitoring Microsoft Dynamics NAV Server Events
Microsoft Dynamics NAV Server Trace Events
Monitoring Microsoft Dynamics NAV Server
Monitoring Microsoft Dynamics NAV Server Using Performance Counters

Other Resources

Event Viewer


Microsoft Dynamics NAV Server Events

Events have the source MicrosoftDynamicsNAVServer$[ServerInstance]. Each event has a unique ID and is assigned to a task category. The source, IDs, and task categories enable you to filter the events that display in Event Viewer. For a description of the task categories, see Task Categories.

The following table lists the events that are generated by the Microsoft Dynamics NAV Server.

Event ID Level Task category Channel Message Remarks

112

Error

12

Operational

Fatal Sql error. The connection can no longer be used

An error occurred on the connection from the Microsoft Dynamics NAV Server instance to the SQL database and the connection could not been established.

This error could be caused by one of the following reasons:

  • The Microsoft Dynamics NAV Server has been stopped.

  • The SQL server connection settings are incorrect

  • A network failure has occurred.

  • A hardware failure has occurred on the server or on your computer.

To resolve this issue, try to restart the Microsoft Dynamics NAV Server or see Troubleshooting: A fatal error occurred. The connection to SQL server cannot be established.

113

Information

12

Operational

Object Change Listener is listening on SQL Server '{0}'in Database'{1}'.

Occurs when the Microsoft Dynamics NAV Server instance has established a connection to the SQL database. The Change Listener object listens for changes to application objects in the Microsoft Dynamics NAV database.

200

Error

12

Admin

This event ID is used for various errors that occur on Microsoft Dynamics NAV Server instances.

These events indicate that the Microsoft Dynamics NAV Server instance is not operating. View the details of each message to determine the cause of the problem.

201

Information

12

Operational

This event ID is used for various information messages that occur on Microsoft Dynamics NAV Server instances.

These events are typical conditions and are for information only.

202

Warning

12

Admin

This event ID is used for various warning messages that occur on Microsoft Dynamics NAV Server instances.

These events indicate that an unexpected condition occurred on the Microsoft Dynamics NAV Server instance. In most cases, the Microsoft Dynamics NAV Server instance will still be operational.

View the details of each message to determine the cause of the problem.

205

Information

8

Operational

'Microsoft Dynamics NAV Data Service' is listening to requests at net.tcp://[Server]:[Port]/[ServerInstance]/OData

Indicates that the listening port for OData web services has been opened on the Microsoft Dynamics NAV Server instance and it is ready to handle OData requests.

Typically, this condition occurs when the Microsoft Dynamics NAV Server instance starts.

206

Information

11

Operational

'Microsoft Dynamics NAV Data Service' at net.tcp://[Server]:[Port]/[ServerInstance]/OData has stopped.

Indicates that the listening port for OData web services on the Microsoft Dynamics NAV Server instance has been closed.

Typically, this condition occurs when the Microsoft Dynamics NAV Server instance is stopped.

207

Information

8

Operational

'Microsoft Dynamics NAV Business Web Services' is listening to requests at net.tcp://[Server]:[Port]/[ServerInstance]/WS/Service

Indicates that the listening port for SOAP web services has been opened on the Microsoft Dynamics NAV Server instance and it is ready to handle SOAP requests.

Typically, this condition occurs when the Microsoft Dynamics NAV Server instance starts.

208

Information

11

Operational

'Microsoft Dynamics NAV Business Web Services' at net.tcp://[Server]:[Port]/[ServerInstance]/WS/Services has stopped.

Indicates that the listening port for SOAP web services has been closed.

Typically, this condition occurs when the Microsoft Dynamics NAV Server instance is stopped.

209

Information

8

Operational

'Microsoft Dynamics NAV Service' is listening to requests at net.tcp://[Server]:[Port]/[ServerInstance]/Service

Indicates that the listening port for Microsoft Dynamics NAV Windows client has opened and it is ready for Microsoft Dynamics NAV Windows client connections.

Typically, this condition occurs when the Microsoft Dynamics NAV Server instance starts.

210

Information

11

Operational

'Microsoft Dynamics NAV Service' at net.tcp://[Server]:[Port]/[ServerInstance]/Service has stopped.

The listening port for Microsoft Dynamics NAV Windows client has closed.

Typically, this condition occurs when the Microsoft Dynamics NAV Server instance is stopped.

211

Information

12

Operational

This event ID is used for various information messages that are generated by Microsoft Dynamics NAV Application Server (NAS) and background sessions.

Because NAS does not have a user interface, events are used to provide operational information to administrators or developers.

214

Information

8

Operational

'Microsoft Dynamics NAV Service' is listening to requests at net.tcp://[Server]:[Port]/[ServerInstance]/ManagementService.

Indicates that the listening port for Microsoft Dynamics NAV Server Administration tool has been opened on the Microsoft Dynamics NAV Server instance.

Typically, this condition occurs when the Microsoft Dynamics NAV Server instance starts.

215

Information

11

Operational

'Microsoft Dynamics NAV Service' at net.tcp://[Server]:[Port]/[ServerInstance]/ManagementService has stopped.

Indicates that the listening port for the Microsoft Dynamics NAV Server Administration tool has closed.

Typically, this condition occurs when the Microsoft Dynamics NAV Server instance is stopped.

216

Error

13

Admin

This event ID is used for various errors that occur when the Microsoft Dynamics NAV Server cannot start or establish a connection to the Microsoft Dynamics NAV database on SQL Server.

These events are caused by unhandled exceptions that are thrown the Microsoft Dynamics NAV Server instances and indicate that an unrecoverable condition has occurred.

The errors can be caused by an incorrect configuration of the Microsoft Dynamics NAV Server or the Microsoft SQL Server connection.

To resolve errors, verify the Microsoft Dynamics NAV Server and SQL Server configuration. For more information, see Configuring Microsoft Dynamics NAV Server and Configuring Microsoft SQL Server.

217

Information

13

Operational

This event ID is used for various information messages that occur when the Microsoft Dynamics NAV Server starts and establishes a connection to the Microsoft Dynamics NAV database on SQL Server.

These events are caused by exceptions that are thrown by the Microsoft Dynamics NAV Server instances. These events are typical conditions and are for information only.

218

Warning

13

Admin

This event ID is used for various warnings that occur when the Microsoft Dynamics NAV Server starts and establishes a connection to the Microsoft Dynamics NAV database on SQL Server.

These events are caused by handled exceptions that are thrown by the Microsoft Dynamics NAV Server instances.

Typically, the Microsoft Dynamics NAV Server will continue to operate, but you should address the problem that is described in the event message.

219

Information

12

Operational

Microsoft Dynamics NAV Application Server for tenant '[TenantID]' is scheduled to start with the following configuration: Company: [CompanyName], Codeunit: [StartupCodeunitID], Method: [StartupMethod], Arguments: [StartupArguments]

Refers to NAS service only. Indicates that the NAS service is scheduled to start.

220

Information

12

Operational

Microsoft Dynamics NAV Application Server for tenant '[TenantID]' has completed.

Refers to NAS service only. Indicates that the NAS service has started successfully.

221

Error

12

Admin

The Microsoft Dynamics NAV Application Server session for tenant '[TenantID]' has failed and will be restarted. Reason: [Message]

Refers to NAS service only. Indicates that an exception has occurred and NAS service did not start. NAS service will attempt to start again.

222

Error

12

Admin

The Microsoft Dynamics NAV Application Server session for tenant '[TenantID]' has permanently failed and will not be restarted. Reason: [Message]

Refers to NAS service only. Indicates that an exception has occurred and NAS service did not start. The NAS service will not be restarted because the maximum number of times that service can attempt to restart has been met. This value is specified by the NASServicesRetryAttemptsPerDay in the CustomSetting.xml file for the Microsoft Dynamics NAV Server instance. For more information, see Configuring NAS Services.

223

Information

12

Operational

The service is initializing its configuration.

Occurs when the Microsoft Dynamics NAV Server instance has been started but is not ready for use.

The Microsoft Dynamics NAV Server instance is loading the configuration settings that are specified in the CustomSettings.xml file. For more information about the CustomSettings.xml file, see Configuring Microsoft Dynamics NAV Server.

224

Information

12

Operational

The service has completed configuration and is ready.

Occurs when the Microsoft Dynamics NAV Server is started and is ready for use.

225

Information

12

Operational

The service is shutting down.

Occurs when Microsoft Dynamics NAV Server is stopped.

226

Information

12

Operational

The NAV application was mounted from database '[DatabaseName]' on database server '[SQLServerInstance]'.

Refers to Microsoft Dynamics NAV Server instances that are used in a multitenant environment.

Indicates that the Microsoft Dynamics NAV Server instance is connected to the Microsoft Dynamics NAV application in the specified application database.

Typically, this condition occurs when the Microsoft Dynamics NAV Server instance starts or the Mount-NAVApplication cmdlet is run.

227

Error

12

Admin

The NAV application could not be mounted for database '[DatabaseName]' on database server '[SQLServerInstance]' due to the following error: [Message].

Refers to Microsoft Dynamics NAV Server instances that are configured for multitenancy.

Indicates that the Microsoft Dynamics NAV Server instance cannot connect the Microsoft Dynamics NAV application in the specified application database.

Verify that Microsoft Dynamics NAV Server is configured to use the correct application database. For more information, see Migrating to Multitenancy.

228

Information

12

Operational

Tenant '[Tenant]' was mounted from database '[DatabaseName]' on database server '[SQLServerInstance]'.

Refers to the Microsoft Dynamics NAV Server instances that are configured for multitenancy.

Indicates that the Microsoft Dynamics NAV Server is connected to the tenant that is in the specified tenant database.

Typically, this condition occurs when the Microsoft Dynamics NAV Server instance starts or when the Mount-NAVTenantcmdlet is run.

229

Error

12

Admin

Tenant '[TenantID]' could not be mounted due to the following error: [Message]

Refers to Microsoft Dynamics NAV Server instances that are configured for multitenancy.

Occurs when the Microsoft Dynamics NAV Server instance cannot connect to the tenant database.

230

Information

12

Operational

Tenant '[Tenant]' was dismounted.

Refers only to Microsoft Dynamics NAV Server instances that are used in a multitenant environment.

Typically, this condition occurs when the Dismount-NAVTenant cmdlet is run.

231

Error

12

Admin

This event ID is used for various errors that occur when authenticating a Microsoft Dynamics NAV user who is trying to log on to the Microsoft Dynamics NAV Server from a RoleTailored client.

This event is caused by an error in the authentication system.

This event is only relevant when the Microsoft Dynamics NAV Server instance is configured for NavUserPassword or AccessControlService credential types.

232

Information

12

Operational

A user successfully authenticated against the server.

This event occurs when a user successfully logs on to the Microsoft Dynamics NAV Server instance from a RoleTailored client.

This event is only relevant when the Microsoft Dynamics NAV Server instance is configured for NavUserPassword or AccessControlService credential types.

232

Information

12

Operational

A user provided invalid credentials. Authentication was not successful.

This event occurs when a user provides an invalid user name or password when the user logs on to the Microsoft Dynamics NAV Server instance from a RoleTailored client.

This event is only relevant when the Microsoft Dynamics NAV Server instance is configured for NavUserPassword or AccessControlService credential types.

233

Information

12

Admin

The session attempted to write to table '[Table Name]', but the write operation was rejected because it exceeds the optional table limit of the license. The license only permits writing to [Number] optional tables per session. The session has already written to the following tables: '[Table Name]', '[Table Name]', 'and [Table Name]'.

This event pertains to the limited user license that is used on the Microsoft Dynamics NAV solution. A limited user license specifies how many optional tables a session can write to. For more information about licensing for Microsoft Dynamics NAV, see Microsoft Dynamics ERP Licensing Guide.

1000

Error

12

Operational

Certificate monitoring has permanently failed and will not be restarted. Reason: [Message]

An unhandled exception occurred that prevents the certificate from being monitored.

Note
Event IDs 1000 through 1006 refer to the security certificate that is used by the Microsoft Dynamics NAV Server instance to protect communications with client or web services. For more information, see Walkthrough: Implementing Security Certificates in a Test Environment and How to: Implement Security Certificates in a Production Environment.

1001

Information

12

Operational

Configuration setting 'ClientServicesCertificateThumbprint' has been updated. It will not take effect until the service is restarted.

Occurs when the security certificate that is used by Microsoft Dynamics NAV Server has been replaced. The thumbprint is set by the ClientServicesCertificateThumbprint parameter in the CustomSetting.xml file for the Microsoft Dynamics NAV Server.

1002

Error

12

Operational

The service certificate is valid from [Date] to [Date] only.

Occurs when the security certificate that is used by the Microsoft Dynamics NAV Server is not valid for use on the current date.

1003

Warning

12

Operational

The service certificate is close to its expiration date.

Occurs for the first time 30 days before the expiration date of the security certificate that is used on the Microsoft Dynamics NAV Server, and then one time each day until the certificate is replaced or renewed.

1006

Information

12

Operational

Configuration setting 'ClientServicesCertificateThumbprint' has been updated. It will not take effect until the service is restarted.

Occurs when a new security certificate is applied on Microsoft Dynamics NAV Server. The thumbprint is set by the ClientServicesCertificateThumbprint parameter in the CustomSetting.xml file for the Microsoft Dynamics NAV Server.

Task Categories

Task categories logically classify events according to the operations that they perform. In Event Viewer, you can sort, include, or exclude events in the Windows Application log based on the task categories. A task category is defined by a decimal number. The following table lists the task categories that are associated with Microsoft Dynamics NAV Server events.

Task category | Description
8 | Service connects to the Microsoft Dynamics NAV Server instance.
11 | Service disconnects from the Microsoft Dynamics NAV Server instance.
12 | Information, warning, or error message from the Microsoft Dynamics NAV Server instance.
13 | Exception thrown by Microsoft Dynamics NAV Server.

See Also

Concepts

Monitoring Microsoft Dynamics NAV Server Events in the Windows Event Log
Monitoring Microsoft Dynamics NAV Server Event Traces


How to: Disable Logging Events to the Windows Application Log

Because the Microsoft Dynamics NAV Server instance events are always logged to the Application and Services Logs, you can disable logging Microsoft Dynamics NAV Server instance events in the Windows Application log and not lose any data. The Windows Application log contains events from several applications and components. Disabling logging to the Windows Application log enables you to limit the amount of data that is stored.

Important
If you are using System Center Operations Manager to monitor Microsoft Dynamics NAV Server instances, do not disable logging to the Windows Application log. If you do, monitoring will not work.

To disable logging to the Window Applications Log, you can use the Microsoft Dynamics NAV Server Administration tool or modify the Microsoft Dynamics NAV Server instance configuration file (CustomSettings.config).

To disable logging to the Windows Application log by using the Microsoft Dynamics NAV Server Administration tool

  1. To start the Microsoft Dynamics NAV Server Administration tool, choose Start, and in the Search programs and files box, type Microsoft Dynamics NAV Administration, and then choose the related link.

  2. In the left pane, under Console root, select the Microsoft Dynamics NAV Server instance.

  3. In the center pane. choose the Edit button.

  4. Under General, clear the Enable Event Logging to Windows Application Log check box.

  5. Choose the Save button, and then choose the OK button.

    You must restart the Microsoft Dynamics NAV Server instance for the changes to take effect.

  6. To restart, the Microsoft Dynamics NAV Server instance, in the left pane, select the Microsoft Dynamics NAV computer.

    Unless you are administering a remote computer, this is Microsoft Dynamics NAV (local).

  7. In the center pane, right-click an instance, and then choose Restart.

To disable logging to the Windows Application log by modifying the CustomSettings.config file

  1. Open the CustomSettings.config file for the Microsoft Dynamics NAV Server instance in a text editor, such as Notepad.

    By default, the file is located in the C:\Program Files\Microsoft Dynamics NAV\90\Service folder or C:\Program Files\Microsoft Dynamics NAV\90\Service\Instances\<instancename> folder (for multitenant installations).

  2. Set the EnableApplicationChannelLog setting to false.

  3. Save the file, and then restart the Microsoft Dynamics NAV Server instance.

See Also

Concepts

Monitoring Microsoft Dynamics NAV Server Events in the Windows Event Log
Monitoring Microsoft Dynamics NAV Server Event Traces


Monitoring Microsoft Dynamics NAV Server Event Traces

Event tracing provides detailed information about what is occurring on the Microsoft Dynamics NAV Server when users work with Microsoft Dynamics NAV. This can help you identify and analyze problems or conditions that affect performance. Event tracing enables you to dynamically monitor Microsoft Dynamics NAV Server without having to restart the server or Microsoft Dynamics NAV clients. By using industry-standard tools for event tracing, you can start and stop event tracing sessions, and then view the trace event data from a stored log file.

You can use event tracing to track the following operations on Microsoft Dynamics NAV Server instances:

  • Running Microsoft Dynamics NAV reports, queries, and XMLports.

  • Execution of SQL statements by Microsoft Dynamics NAV Server.

  • Execution of C/AL functions.

  • Windows event log events.

Event Trace Monitoring Tools

There are various industry-standard tools that you can use to collect event trace data. The procedures in this section use Windows Performance Monitor, PerfView, Event Viewer, and Windows PowerShell to illustrate how you can collect and view event trace data. For details about how to use these tools and others, refer to the documentation available with the tool.

Getting Started

Task | For more information, see
Review the list of trace events that are available for monitoring Microsoft Dynamics NAV Server instances. | Microsoft Dynamics NAV Server Trace Events
Collect event trace data in an event trace log (.etl) file. Use the event trace monitoring tool to start an event trace session. | How to: Use Performance Monitor to Collect Event Trace Data How to: Use PerfView to Collect Event Trace Data
View event trace data that is contained in an .etl file. | How to: Use PerfView to View Event Trace Data
Use Event Viewer to collect and view event trace data | How to: Use Event Viewer to Collect and View Trace Events
Use Windows PowerShell to view event trace data | Viewing Events by Using Windows PowerShell

See Also

Concepts

Monitoring Microsoft Dynamics NAV Server Events in the Windows Event Log
Monitoring Microsoft Dynamics NAV Server Events
Microsoft Dynamics NAV Server Trace Events


Microsoft Dynamics NAV Server Trace Events

This topic describes the trace events that are generated by Microsoft Dynamics NAV server.

The following list provides useful information about event tracing.

  • The event trace provider is Microsoft-DynamicsNAV-Server. You typically need to provide this name in the monitoring tool that you are using.

  • There are four types of trace events: Windows event log, SQL traces, service calls, and C/AL function calls. Trace event types are identified by a keyword with a corresponding decimal and hexadecimal value. The keywords and values enable you to collect data on specific trace events. Some tools support the hexadecimal values only and other tools support both hexadecimal and decimal.

  • For most trace events, there is separate event for when an operation starts and when it stops. This enables you to determine the duration of the operation. Some monitoring tools, such as PerfView, will automatically return the duration in the stop event.

  • Some monitoring tools might interpret and display the collected event trace differently than others. For more information, see Event Trace Data.

Windows Event Log Trace Events

Windows Event Log trace events track errors, warnings, and information messages that provide information about the condition or state of Microsoft Dynamics NAV Server instances. These events are also logged in the Windows Application event log of the computer that is running Microsoft Dynamics NAV Server. For a complete list of the events, see Monitoring Microsoft Dynamics NAV Server Events in the Windows Event Log.

Keyword | Decimal value | Hexadecimal value
EventViewer | 1 | 0x1

SQL Trace Events

SQL trace events track a specific set of SQL statements that are executed from the Microsoft Dynamics NAV Server instance against the Microsoft Dynamics NAV database on SQL Server.

Keyword | Decimal value | Hexadecimal value
SQLTracing | 2 | 0x2

The event data that is collected includes: session ID, tenant ID, the Microsoft Dynamics NAV user, and the SQL statement. For more information, see Event Trace Data.

The following table lists the SQL trace events.

ID | Event (task/opcode) | What is traced
1 | ExecuteScalar/Start | SQL statements that query a database table and return a single field from a row in the query result.
2 | ExecuteScalar/Stop
3 | ExecuteNonQuery/Start | SQL statements that return a number of rows from a database table
4 | ExecuteNonQuery/Stop
5 | ExecuteReader/Start | SQL statements that return a set of rows from a database table.
6 | ExecuteReader/Stop
7 | ReadNextResult/Start | SQL statements that return the next result from a database query.
8 | ReadNextResult/Stop
9 | ReadNextRow/Start | SQL statements that return the next row in database table.
10 | ReadNextRow/Stop
11 | BeginTransaction/Start | SQL statements that start a database transaction.
12 | BeginTransaction/Stop
13 | Prepare/Start | SQL statements that create a prepared version of the command on an instance of SQL Server.
14 | Prepare/Stop
15 | OpenConnection/Start | SQL statements that open connection to the database from the connection pool.
16 | OpenConnection/Stop
17 | Commit/Start | SQL statements that commit a database transaction.
18 | Commit/Stop
19 | Rollback/Start | SQL statements that cancel the changes in a pending database transaction.
20 | Rollback/Stop

Service Call Trace Events

Service call trace events track when Microsoft Dynamics NAV clients run the Microsoft Dynamics NAV objects: Queries, Reports, and XMLports.

Keyword | Decimal value | Hexadecimal value
ServiceCall | 4 | 0x4

The event data that is collected includes: session ID, tenant ID, Microsoft Dynamics NAV user, and the Microsoft Dynamics NAV object ID. For more information, see Event Trace Data.

The following table lists the service call trace events.

ID | Event (task/opcode) | What is traced
300 | RunQuery/Start | Microsoft Dynamics NAV Query objects that are opened and closed.
301 | RunQuery/Stop
302 | RunReport/Start | Microsoft Dynamics NAV Report objects that are opened and closed.
303 | RunReport/Stop
310 | RunXmlPort/Start | Microsoft Dynamics NAV XMLport objects that are opened and closed.
311 | RunXmlPort/Stop
500 | OpenSession | Microsoft Dynamics NAV Windows clients and Microsoft Dynamics NAV Web clients establish a connection to the Microsoft Dynamics NAV Server instance.
501 | CloseSession

C/AL Function Trace Events

C/AL function tracing events track the execution of C/AL functions and statements on the Microsoft Dynamics NAV Server instance.

Keyword | Decimal value | Hexadecimal value
ALTracing | 8 | 0x8

The event data that is collected includes: session ID, tenant ID, Microsoft Dynamics NAV user, C/ALC/AL function, C/AL statements, and line number. For more information, see Event Trace Data.

Important
If the Microsoft Dynamics NAV Server instance is not configured for full C/AL function tracing, then only root-level C/AL function will be traced. Statements and C/AL functions that are called from functions will not be traced. By default, the Microsoft Dynamics NAV Server instance is not configured for full C/AL functionf tracing. For information about how to specify full C/AL function tracing, see Configuring Microsoft Dynamics NAV Server.

The following table lists the C/AL function tracing events.

ID Event (task/opcode) What is traced

400

ExecuteALFunction/Start

C/AL functions that are called.

401

ExecuteALFunction/Stop

402

ExecuteALFunctionFailed

Errors that occur when executing C/AL functions. The errors can be caused by exceptions or ERROR Function (Dialog) calls.

403

ExecuteALFunction

C/AL statements that are executed.

Important
This trace event is only traced when the Microsoft Dynamics NAV Server is configured to full C/AL function tracing.

Event Trace Data

The following table lists the arguments that make up the data collected for trace events. When viewing event trace data, the way that the arguments are interpreted and displayed can vary depending on the tool that you use.

Argument | Description | Trace event type
connectionType | Specifies the RoleTailored client that has established the connection to the Microsoft Dynamics NAV server instance. Values include Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client. | Service calls
failureMessage | Includes the error message that is returned when a C/AL function fails. | C/AL function trace events
functionName | Specifies the C/AL function that was executed. | C/AL function trace events
lineNumber | Specifies the line number of the statement in the C/AL code of the Microsoft Dynamics NAV object that was executed. | C/AL function trace events
message | Specifies the error, warning, or information message text that was issued for a Windows event log trace on the Microsoft Dynamics NAV Server. | Windows event log trace events
objectId | Specifies the ID of the Microsoft Dynamics NAV object that was executed in the session. | Service calls trace events C/AL function trace events
objectType | Specifies the Microsoft Dynamics NAV object type that executed by a C/AL function or statement. Values include the following: CodeUnit, Page, Query, Report, Table, and XMLport. | C/AL function trace events
sessionId | Specifies the ID that is assigned to the session that is used by the operation. Each operation establishes a session with the Microsoft Dynamics NAV Server instance from a connection in the Microsoft Dynamics NAV Server's connection pool. | All
sqlStatement | Specifies the SQL statement that was executed on the session. | SQL trace events
statement | Specifies the C/AL statement that was executed on the session. | C/AL function trace events
tenantId | Specifies the ID of the tenant database that is mounted on the Microsoft Dynamics NAV Server instance. If the Microsoft Dynamics NAV Server instance is not configured for multitenancy, then the value is empty. For more information about multinenancy, see Multitenant Deployment Architecture. | All
userName | Specifies the Microsoft Dynamics NAV user account that is logged on to the session. | All

See Also

Concepts

Monitoring Microsoft Dynamics NAV Server Event Traces
Monitoring Microsoft Dynamics NAV Server Events


How to: Use Performance Monitor to Collect Event Trace Data

This topic describes how to use Windows Performance Monitor to collect event trace data for Microsoft Dynamics NAV Server. To collect trace event data, you create a Data Collector Set, and then start the Data Collector Set.

To create a Data Collector Set for collecting Microsoft Dynamics NAV trace event data

  1. Start Windows Performance Monitor.

    • Choose Start, in the Search box, type perfmon, and then choose the related link.

  2. In the navigation tree, expand Data Collector Sets, right-click User-defined, choose New, and then choose Data Collector Set.

  3. On the Create new Data Collector Set Wizard page, enter a name for the new data collector set, select Create manually (Advanced), and then choose the Next button.

  4. On the What type of data do you want to include page, select the Event trace data check box, and then choose the Next button.

  5. On the Which event trace providers would you like to enable page, choose the Add button to add a provider.

  6. In the Event Trace Providers list, select Microsoft-DynamicsNav-Server, and then choose the OK button.

  7. If you want to collect data for all trace events, choose the Next button. If you want to collect data on specific trace events, do the following:

    1. In the Properties list, select Keywords (Any), and then choose the Edit button.

    2. On the Property page, in the Manual box, type the keyword decimal value for the trace event. For a list of keyword values for trace events, see Microsoft Dynamics NAV Server Trace Events.

      For example, if you want to collect data on service call trace events, then type 4. If you want to collect data on more than one trace event, add the keyword values for each trace event and then use the sum in the Manual box. For example, if you want to collect data on service calls (keyword decimal value = 4) and C/AL functions (keyword decimal value = 8), then use the value 12.

      Note
      Performance Monitor will automatically convert the value to hexadecimal, such as 0x4 or 0xC. You can also enter the keyword hexadecimal values directly.

    3. Choose the OK button, and then Next button.

  8. On the Where would you like the data to be stored page, set the Root directory box to the folder where you want to save the event trace log file that is generated when you run the Data Collector Set.

  9. Choose the Finish button to complete the wizard

    The new Data Collector Set appears under User Defined in the navigation pane.

Complete the next procedure to increase trace buffer settings to make sure that events are not dropped when collecting trace event data.

To change the Data Collector Set trace buffers

  1. In the navigation pane, select the new Data Collector Set.

  2. In the main pane, right-click the DataCollector01 item, and then choose Properties.

  3. In the Properties dialog box, choose the Trace Buffers tab.

  4. Set the following properties.

    Property Recommended minimum values

    Buffer size

    128

    Minimum buffers

    50

    Maximum buffers

    50

    You might have to adjust these properties based on the monitoring sessions and expected number of events that will be collected. If a large number of events are collected, then the trace buffer size and count might have to be increased.

  5. Choose the OK button to save and close the Properties dialog box.

To start and stop a Data Collector Set

  • To start to collect data, right-click the Data Collector Set, and then choose Start.

  • To stop collecting data, right-click the Data Collector Set, and then choose Stop.

For information about how to schedule a time to start and stop collecting data, see Schedule Data Collection in Windows Performance Monitor.

The collected event trace data is stored in an event trace log (.etl) file in the location that you specified. You can view the data in the log file by using various industry-standard tools, such as PerfView. For information about how to use PerfView to view the event trace data, see How to: Use PerfView to View Event Trace Data.

See Also

Tasks

How to: Use PerfView to View Event Trace Data

Concepts

Monitoring Microsoft Dynamics NAV Server Event Traces


How to: Use PerfView to Collect Event Trace Data

This topic describes how to use PerfView to collect event trace data for Microsoft Dynamics NAV Server. When you collect event trace data, the data is stored in an event trace log (.etl) file in a location that you choose.

To install PerfView

  • Go to http://go.microsoft.com/fwlink/?LinkID=313428, and then follow the instructions to download and install PerfView.

To collect event trace data

  1. Open PerfView.exe.

  2. On the Collect menu, choose Collect.

    The Collecting data over a user specified interval dialog box appears.

  3. Set the Data file field to the path and name of the log file in which to store the trace event data. The file name must have the .etl file name extension.

  4. Choose Advanced options.

    The upper part of the Advanced options area includes check boxes and fields that specify the providers from which to collect event trace data.

  5. In the Additional providers field, type Microsoft-DynamicsNav-Server.

    • If you want to filter on a specific trace event, include a colon after Microsoft-DynamicsNav-Server, followed by the hexadecimal keyword value for the trace event. For example, to collect trace events data on service call trace events only, then type Microsoft-DynamicsNav-Server:0x4.

    • If you want to collect data on more than one trace event, add the keyword values for each trace event and then use the sum in the field. For example, if you want to collect data on service calls (keyword value = 0x4) and C/AL function traces (keyword value = 0x8), then type Microsoft-DynamicsNav-Server:0xC in the field. In hexadecimal, the sum of 0x4 and 0x8 is 0xC.

  6. Clear the check boxes above the Additional providers field for any providers that you do not want to collect data for.

  7. To start recording data, choose the Start Collection button.

  8. To stop recording data, choose the Stop Collection button.

The collected event trace data is stored in an event trace log (.etl) file in the location that you specified. You can view the data in the log file by using various industry-standard tools, such as PerfView. For information about how to use PerfView to view the event trace data, see How to: Use PerfView to View Event Trace Data.

To view event trace data from an event trace log file

  1. Open PerfView.exe.

  2. In PerfView, use the left pane to locate the .etl file that you want to view.

    The left pane displays the current directory and the files that PerfView is set up to browse. To change a directory, choose a subdirectory from the list or type the directory (for example, c:\PerfLogs) in the text box at the top of the pane.

  3. Double-click the .etl file that you want to view.

    Several items appear in the left pane under the .etl file that you selected.

  4. To view the event traces, double-click Events.

    The Events window opens to display the contents of the .etl file. Trace events are listed in the left pane.

  5. To view details about a trace event, double-click the trace event.

See Also

Concepts

Monitoring Microsoft Dynamics NAV Server Event Traces
Microsoft Dynamics NAV Server Trace Events


How to: Use PerfView to View Event Trace Data

This topic describes how to use PerfView to view Microsoft Dynamics NAV Server event trace data that is stored in an event trace log (.etl) file.

To install PerfView

  • Go to http://go.microsoft.com/fwlink/?LinkID=313428, and then follow the instructions to download and install PerfView.

To view event trace data from an event trace log file

  1. Open PerfView.exe.

  2. In PerfView, use the left pane to locate the .etl file that you want to view.

    The left pane displays the current directory and the files that PerfView is set up to browse. To change a directory, choose a subdirectory from the list or type the directory (for example, c:\PerfLogs) in the text box at the top of the pane.

  3. Double-click the .etl file that you want to view.

    Several items appear in the left pane under the .etl file that you selected.

  4. To view the event traces, double-click Events.

    The Events window opens to display the contents of the .etl file. Trace events are listed in the left pane.

  5. To view details about a trace event, double-click the trace event.

See Also

Tasks

How to: Use PerfView to Collect Event Trace Data
How to: Use Performance Monitor to Collect Event Trace Data

Concepts

Monitoring Microsoft Dynamics NAV Server Event Traces
Microsoft Dynamics NAV Server Trace Events


How to: Use Event Viewer to Collect and View Trace Events

This topic describes how to collect and view Microsoft Dynamics NAV Server event trace data in Event Viewer. Trace events are recorded in a Debug log for Microsoft Dynamics NAV Server in the Applications and Services Logs. By default the Debug log is disabled and may also be hidden in the Event Viewer. To collect trace event data, you must enable the Debug log.

To collect and view trace events in Event Viewer

  1. On the computer that is running Microsoft Dynamics NAV Server, start Event Viewer.

    For more information, see How to Start Event Viewer.

  2. In the console tree, choose Applications and Services Logs, Microsoft, DynamicsNAV, and then Server.

  3. If the Debug log is not shown under Server, then on the View menu, select Show Analytic and Debug Logs.

  4. Select the Debug log, and then on the Actions menu, choose Enable Log.

    Note
    Depending on the number of events, you might have to increase the maximum size of the log. The default value is 1028 KB. For more information, see Set Maximum Log Size.

Microsoft Dynamics NAV Server trace events will now be recorded in the Debug log. For a list and description of trace events, see Microsoft Dynamics NAV Server Trace Events.

See Also

Concepts

Monitoring Microsoft Dynamics NAV Server Event Traces

Other Resources

Show or Hide Analytic and Debug
Enable Analytic and Debug Logs


Understanding and Configuring Session Timeouts

When you start the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client, a connection is established with the Microsoft Dynamics NAV Server instance and a corresponding session is added on Microsoft Dynamics NAV Server.

Microsoft Dynamics NAV Server includes several timeout settings that determine when a session closes as a result of inactivity over the client connection, lost client connection, or closing of the client. This document provides an overview of how the session timeouts work, how to configure them, and answers some basic questions about session behavior.

The topic includes the following sections:

  • Session Timeout Settings Overview

  • Configuring How Long a Session Remains Open When the Client Connection is Inactive

  • Configuring How Long a Session Remains Open after the Client Connection is Lost

  • FAQ

Session Timeout Settings Overview

This section provides an overview of the settings that are available in Microsoft Dynamics NAV to control when a Microsoft Dynamics NAV Server session for a Microsoft Dynamics NAV client connection times out and closes. Some of the settings are set on Microsoft Dynamics NAV Server and others are set for the Microsoft Dynamics NAV Windows client or for the Microsoft Dynamics NAV Web client. For more details about using these settings, see the other sections in this topic.

Microsoft Dynamics NAV Server timeout settings

The following table describes the session timeout settings that are used by Microsoft Dynamics NAV Server.

Setting | Description | Remarks
ClientServicesReconnectPeriod | The amount of time during which a client can reconnect to an existing session on Microsoft Dynamics NAV Server before a session closes. | For more information, see Configuring How Long a Session Remains Open after the Client Connection is Lost.
ClientServicesIdleClientTimeout | The interval of time that a Microsoft Dynamics NAV client connection can remain inactive before the session is closed. | For more information, see Configuring How Long a Session Remains Open When the Client Connection is Inactive.

These settings are available in the CustomSettings.config file of Microsoft Dynamics NAV Server. For more information about this file, see Configuring Microsoft Dynamics NAV Server.

Microsoft Dynamics NAV Windows client timeout settings

The following table describes the session timeout settings that are used by the Microsoft Dynamics NAV Windows client.

Setting Description Remarks

ClientServicesKeepAliveInterval

Specifies the interval (in seconds) between keep-alive messages that are sent from the Microsoft Dynamics NAV Windows client to Microsoft Dynamics NAV Server.

Note
This setting is also used, in part, to define the reconnect period when a connection is lost.

For more information, see Keeping inactive sessions alive.

This setting is available in the ClientSettings.config file of the Microsoft Dynamics NAV Windows client. For more information about this file, see Configuring the Windows Client.

Microsoft Dynamics NAV Web client timeout settings

The following table describes the session timeout settings that are used by the Microsoft Dynamics NAV Web client.

Setting | Description | Remarks
SessionTimeout | Specifies the amount of time that session remains open when there is no activity over the connection from the Microsoft Dynamics NAV Web client to Microsoft Dynamics NAV Server. | For more information, see Configuring How Long a Session Remains Open When the Client Connection is Inactive.

This setting is available in the web.config file of Microsoft Dynamics Web Server for the client. For more information about this file, see Configuring the Microsoft Dynamics NAV Web Server and Client.

Configuring How Long a Session Remains Open When the Client Connection is Inactive

Inactivity on a connection is when the Microsoft Dynamics NAV client is not sending messages to Microsoft Dynamics NAV Server. Controlling when a session will timeout and close because of inactivity is different for the Microsoft Dynamics NAV Windows client and the Microsoft Dynamics NAV Web client.

Configuring the inactive session timeout for the Microsoft Dynamics NAV Windows client

When the Microsoft Dynamics NAV Windows client is inactive, the session will remain open until the time period that is specified by the ClientServicesIdleClientTimeout setting has passed, provided that the client has not been stopped or the connection to Microsoft Dynamics NAV Server has not been lost. The default value of the ClientServicesIdleClientTimeout setting is MaxValue, which means that there is no time limit so the session will remain active indefinitely.

Configuring the inactive session timeout for the Microsoft Dynamics NAV Web client

There are two settings that control when a Web client session closes because of inactivity on a connection:

  • ClientServicesIdleClientTimeout setting on Microsoft Dynamics NAV Server.

  • SessionTimeout setting on the Microsoft Dynamics NAV Web Server.

The session closes according to the setting that has the shortest time period. By default, the ClientServicesIdleClientTimeout setting is set to MaxValue, which means no time limit, and the SessionTimout setting is 00:20:00 (20 minutes). This means that when client connection is inactive, a session will close after 20 minutes. The following figure illustrates the timeout behavior:

Inactiviy session timeout for NAV 2013 R2

The SessionTimeout setting enables you to set the Microsoft Dynamics NAV Web client inactive session timeout different than for the Microsoft Dynamics NAV Windows client, which is only controlled by the ClientServicesIdleClientTimeout setting. Typically, you will set the inactive session timeout period on Microsoft Dynamics NAV Web client connections shorter than for the Microsoft Dynamics NAV Windows client.

Keeping inactive sessions alive

To keep an inactive session alive, the Microsoft Dynamics NAV Windows client uses the Windows Communication Framework (WCF) reliable sessions feature. When the Microsoft Dynamics NAV Windows client is inactive, reliable sessions automatically sends messages from the Microsoft Dynamics NAV Windows client to Microsoft Dynamics NAV Server. You control the interval of the keep-alive messages by setting the ClientServicesKeepAliveInterval setting on the Microsoft Dynamics NAV Windows client. The default value of the ClientServicesKeepAliveInterval setting is 120 seconds (2 minutes).

For most installations, the ClientServicesKeepAliveInterval setting default value sufficient for keeping sessions open until the ClientServicesIdleClientTimeout setting period elapses. However, when Microsoft Dynamics NAV Server is installed behind a load balancer, which is the case on Microsoft Azure, you might have to adjust the value the ClientServicesKeepAliveInterval setting to prevent sessions from closing before the expected session timeout. A load balancer typically has an idle timeout setting that it uses to determine whether to redirect connections. However, you want a stable connection between the Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Server. If there is no activity on the client connection for duration of the load balancer's idle timeout setting, then the load balancer might redirect the client connection to another server. To avoid this condition, we recommend that you set the ClientServicesKeepAliveInterval to half the value of the load balancer’s idle timeout setting.

Note
The idle timeout on Azure is around 4 minutes, so the default setting of ClientServicesKeepAliveInterval (2 minutes) should be sufficient.

Configuring How Long a Session Remains Open after the Client Connection is Lost

Occasionally, a Microsoft Dynamics NAV client can lose the network connection to Microsoft Dynamics NAV Server. You can use ClientServicesReconnectPeriod setting on Microsoft Dynamics NAV Server to control how long a session remains open after the connection is lost to allow time for the client to reconnect to the session.

The time a session remains open actually depends two settings: ClientServiceKeepAliveInterval and ClientServicesReconnectPeriod. The ClientServiceKeepAliveInterval setting is used to specify an initial inactivity period. The initial inactivity period is equal to two times the ClientServiceKeepAliveInterval setting value. After this initial inactivity period, the session remains open for the time period that is specified ClientServicesReconnectPeriod setting. By default, the ClientServiceKeepAliveInterval setting is 120 seconds (2 minutes) and the ClientServicesReconnectPeriod setting is 10 minutes. This means that Microsoft Dynamics NAV Server waits approximately 14 minutes for the client to reconnect before closing the session.

The following figure illustrates the reconnect session timeout behavior.

Reconnect session timeout

The process that occurs when a client does not reconnect to the session is explained as follows:

  1. The connection is lost and the initial inactivity period starts (default is 4 minutes).

  2. After the initial inactivity period, the service channel enters a faulted state.

    When the service channel is in the faulted state, Microsoft Dynamics NAV Server considers the session with the client as orphaned and waits for it to reconnect.

  3. If the client does not reconnect within the time period that is specified by the ClientServicesReconnectPeriod setting (default is 10 minutes), then Microsoft Dynamics NAV Server closes the session.

  4. The session is then removed from the Active Session table in the Microsoft Dynamics NAV.

FAQ

This section answers some typical questions about session timeout.

How long does Microsoft Dynamics NAV Server wait when the Microsoft Dynamics NAV Windows client is inactive before closing a session??

With Microsoft Dynamics NAV Windows client, by default, Microsoft Dynamics NAV Server will wait indefinitely as long as the client has not been stopped or the connection to Microsoft Dynamics NAV Server has not been lost. With the Microsoft Dynamics NAV Web client, the session will remain active for 20 minutes. The Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client include configuration settings that you can use to change the inactivity timeout period. For more information, see Configuring How Long a Session Remains Open When the Client Connection is Inactive.

What happens to the session if I end the Microsoft Dynamics NAV Windows client by using Task Manager?

If the Microsoft Dynamics NAV Windows clientis waiting for a response from Microsoft Dynamics NAV Server, as is the case with a modal dialog, then the session remains open until the time period that is specified by the ClientServicesReconnectPeriod setting expires. When the Window Client process is ended, the service channel will enter a faulted state. Microsoft Dynamics NAV Server considers the session with the Microsoft Dynamics NAV client as orphaned and waits for it to reconnect.

What happens to the session if the client loses the connection to Microsoft Dynamics NAV Server?

By default, it will take approximately 14 minutes for the Microsoft Dynamics NAV Server to close the current session. The time it takes to close the session is in part determined by the ClientServicesReconnectPeriod setting on Microsoft Dynamics NAV Server plus an initial 10 minute inactivity period. For more information, see Configuring How Long a Session Remains Open after the Client Connection is Lost.

What happens if the session is still active when Microsoft Dynamics NAV Server tries to close it?

  1. The server stops any executing threads when the next statement is to be executed and the current call stack is aborted so any uncommitted transactions will be rolled back.

  2. The server cancels any callbacks to the client (similar to waiting for the response to a Confirm dialog).

  3. The session is closed, and then removed from the Active Session table.

See Also

Concepts

Configuring Microsoft Dynamics NAV


Connecting the Microsoft Dynamics NAV Clients over a Wide Area Network

This topic contains information about how to implement a secure Microsoft Dynamics NAV Windows client connection to Microsoft Dynamics NAV Server over a wide area network (WAN). The Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Server computers can be in the same or separate Active Directory domains.

For additional information about hosting and WAN connections, see the Microsoft Dynamics NAV Team Blog and search for the terms hosting and performance.

Assumptions

The implementation that is used in these topics assumes the following:

  • User accounts are provisioned in an Active Directory domain. SQL Server and Microsoft Dynamics NAV Server are installed on a computer in this domain.

  • The administrator who is creating this implementation is a member of the domain administrator group in this domain.

  • On the computer that is running Microsoft Dynamics NAV Server, a DNS entry that resolves to the published server port on the computer’s firewall exists for Microsoft Dynamics NAV Server.

  • If the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Server is behind a firewall, then you must open a port to communicate with Microsoft Dynamics NAV Server on the Microsoft Dynamics NAV Windows client computer and publish the port on the Microsoft Dynamics NAV Server computer. The default port number is 7046.

  • The Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Server are configured as described in the Walkthrough: Installing the Three Tiers on Three Computers topic in the MSDN Library.

Implementing the Windows Client over a Wide Area Network

The implementation that is shown in these topics includes instructions for protecting your WAN connections with security certificates. We recommend that you do not implement remote access without security certificates.

To | See
Read about the certificate security implementation that is presented in this implementation. | Using Certificates to Secure a Remote Client Connection
Follow a detailed demonstration of how to set up an environment for testing secure connections over a WAN by using the chain trust configuration. | Walkthrough: Implementing Security Certificates in a Test Environment
Learn how to implement security certificates in a production environment. | How to: Implement Security Certificates in a Production Environment


Using Certificates to Secure a Remote Client Connection

You can use service certificates to help secure RoleTailored client connections over a wide area network (WAN). Microsoft Dynamics NAV 2016 can support the following configurations:

  • Chain trust, which specifies that each certificate must belong to a hierarchy of certificates that ends in a root authority at the top of the chain.

  • Peer trust, which specifies that both self-issued certificates and certificates in a trusted chain are accepted.

This implementation describes the chain trust configuration, which is the more secure option.

In a production environment, you implement chain trust by obtaining X.509 service certificates from a trusted provider. These certificates and their root certification authority (CA) certificates must be installed in the certificates store on the computer that is running Microsoft Dynamics NAV Server. The CA certificate must also be installed in the certificate store on computers that are running the RoleTailored client so that clients can validate the server.

Note
This implementation does not use Secure Sockets Layer (SSL). Although these implementations do use the public and private key infrastructure of SSL and SSL certificates, they use Windows Communication Foundation (WCF) transport-level security (TLS) over the TCP/IP protocol instead of https. This means that these are not strict SSL implementations.


Walkthrough: Implementing Security Certificates in a Test Environment

In this walkthrough, you set up an environment to test integrating certificates into a configuration for connecting computers running the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web Server components to Microsoft Dynamics NAV Server instances over a wide area network (WAN) with the chain trust configuration.

Prerequisites

To complete this walkthrough, you will need:

  • The Certificates snap-in for Microsoft Management Console (MMC). If you do not already have this snap-in installed, then follow these steps:

    1. Choose Start, choose Run, and then type Mmc.exe.

    2. In the console, on the File menu, choose Add/Remove Snap-in.

    3. In the Add Standalone Snap-in dialog box, select Certificates, choose Computer Account, choose Local Computer, and then choose Add.

  • The makecert.exe utility.

    The makecert.exe utility is installed with Microsoft Visual Studio and Microsoft Windows SDK. For more information, see Certificate Creation Tool (Makecert.exe) in the MSDN Library.

Configuring Microsoft Dynamics NAV Server

You create and install a root certification authority (CA) and a server certificate on the computer running Microsoft Dynamics NAV Server.

To create a root CA and a private key file by using the makecert.exe utility

  1. On the computer running Microsoft Dynamics NAV Server, create a temporary folder to use when you work with certificates.

  2. Open the command prompt as follows:

    • If you have Visual Studio installed on your computer, choose Start, choose All Programs, choose Microsoft Visual Studio 2012, choose Visual Studio Tools, and then right-click Visual Studio Command Prompt and choose Run as Administrator.

    • If you have the Windows SDK installed on your computer, choose Start, choose All Programs, choose Microsoft Windows SDK, and then right-click Windows SDK Command Prompt (2010) (or CMD Shell) and choose Run as Administrator.

  3. At the command prompt, locate the temporary directory.

  4. Type the following command.

    Copy Code
    makecert -n "CN=RootNavServiceCA" -r -sv RootNavServiceCA.pvk RootNavServiceCA.cer

  5. When you are prompted, enter a password.

    You need this password to create the service certificate.

  6. The RootNavServiceCA.cer certificate file and the RootNavServiceCA.pvk private key are saved in your temporary folder.

To use the Certificates snap-in to install the root CA on the computer running Microsoft Dynamics NAV Server

  1. Start the Certificates snap-in for MMC on the computer running Microsoft Dynamics NAV Server, and then add the Certificates snap-in.

  2. In the Certificates snap-in dialog box, choose Computer account, and then choose Next.

  3. In the Select Computer pane, choose Local computer: (the computer this console is running on), and then choose Finish.

  4. Choose OK to close the Add or Remove Snap-ins dialog box.

  5. In the left pane of MMC, expand the Certificates (Local Computer) node.

  6. Expand the Trusted Root Certification Authorities node, right-click the Certificates subfolder, select All Tasks, and then choose Import.

  7. In the Certificate Import Wizard, on the Welcome page, choose Next.

  8. On the File to Import page, choose Browse.

  9. Browse to the location of the RootNavServiceCA.cer certificate file, select the file, and then choose Open.

  10. On the File to Import page, choose Next.

  11. On the Certificate Store page, accept the default selection, and then choose Next.

  12. On the Completing the Certificate Import Wizard page, choose Finish.

The RootNavServiceCA certificate is now visible in the list of trusted root CAs.

You now create a certificate revocation list for the root certification authority and then install the certificate revocation list on the computer running Microsoft Dynamics NAV Server. A certificate revocation list is required because WCF applications check the revocation list when validating certificates.

To create a certificate revocation list for the root certification authority

  1. At the command prompt, type the following command:

    Copy Code
    makecert -crl -n "CN=RootNavServiceCA" -r -sv RootNavServiceCA.pvk RootNavServiceCA.crl

  2. When you are prompted, enter the password that you used to create the root CA.

To install the certificate revocation list on the computer running Microsoft Dynamics NAV Server

  1. In the Certificates snap-in, in the left pane of MMC, expand the Certificates (Local Computer) node.

  2. Expand the Trusted Root Certification Authorities node, right-click the Certificates subfolder, select All Tasks, and then choose Import.

  3. In the Certificate Import Wizard, on the Welcome page, choose Next.

  4. On the File to Import page, choose Browse.

  5. In the File Type field, select Certificate Revocation List (*.crl).

  6. Browse to the location of the RootNavServiceCA.crl file, select the file, and then choose Open.

  7. On the File to Import page, choose Next.

  8. On the Certificate Store page, accept the default selection, and then choose Next.

  9. On the Completing the Certificate Import Wizard page, choose Finish.

  10. Select the Trusted Root Certificate Authorities node, and then refresh the snap-in.

    A Certificate Revocation List folder that contains the RootNavServiceCA.crl file has been created.

To create and install a test certificate for the Microsoft Dynamics NAV Server computer

  1. At the command prompt, type the following command:

    Copy Code
    makecert -sk NavServiceCert -iv RootNavServiceCA.pvk -n "CN=NavServiceCert" -ic RootNavServiceCA.cer -sr localmachine -ss my -sky exchange -pe NavServiceCert.cer
    Note
    This command specifies the subject’s certificate name as NavServiceCert. You need this certificate name when you configure the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web Server components.

  2. When you are prompted, enter the password that you used to create the root CA.

  3. Select the Trusted Root Certificate Authorities node, and then refresh the snap-in.

You now have the NavServiceCert.cer certificate file in your temporary folder. The certificate is installed under the Personal node in the Certificates Snap-in.

To grant access to the certificate’s private key to the service account for Microsoft Dynamics NAV Server

  1. In the left pane of MMC, expand the Certificates (Local Computer) node, expand the Personal node, and then select the Certificates subfolder.

  2. In the right pane, right-click the NavServiceCert certificate, choose All Tasks, and then choose Manage Private Keys.

  3. In the Permissions for NavServiceCert private keys dialog box, choose Add.

  4. In the Select Users, Computers, Service Accounts, or Groups dialog box, enter the name of the service account that is used by Microsoft Dynamics NAV Server By default, the service account is NETWORK SERVICE. Choose OK when done.

    Security Note
    In a production environment, you run Microsoft Dynamics NAV Server under a dedicated domain user account instead of the less secure NETWORK SERVICE account. Because this is a test implementation, the NETWORK SERVICE account is acceptable.

  5. In the Permissions for NavServiceCert private keys dialog box, select the account, and then select the Allow check box next to Full Control. Choose OK when done.

  6. In the right pane, double-click the NavServiceCert certificate.

  7. In the Certificate dialog box, choose the Details tab, and then select the Thumbprint field.

  8. Copy or note the value of the Thumbprint field.

To modify the Microsoft Dynamics NAV Server configuration file to support login over a WAN

  1. Start the Microsoft Dynamics NAV Server Administration tool. For more information, see Microsoft Dynamics NAV Server Administration Tool.

  2. Stop the Microsoft Dynamics NAV Server instance. For more information, see Managing Microsoft Dynamics NAV Server Instances.

  3. Modify the following settings for the Microsoft Dynamics NAV Server instance. For more information, see Configuring Microsoft Dynamics NAV Server.

  4. Modify the following settings in the Microsoft Dynamics NAV Server Administration tool.

    Key New value Description

    ClientServicesCredentialType

    (General tab)

    NavUserPassword or Username

    This parameter is on the General tab in the Microsoft Dynamics NAV Server Administration tool. The default value is Windows. When you change it to NavUserPassword or Username, client users who connect to the server are prompted for user name and password credentials. For more information on authentication mechanisms for Microsoft Dynamics NAV 2016, see Users and Credential Types. For information on how to provision users with initial username and password values, see How to: Create Microsoft Dynamics NAV Users.

    CertificateThumbprint

    (Client Services tab)

    Value of the Thumbprint field in the previous procedure

    The default value is <key>. Remove any leading or trailing spaces in the thumbprint.

  5. Choose Save.

  6. Restart the Microsoft Dynamics NAV Server instance.

    If there is a problem, see Windows Event Viewer.

If you get an error, see the Windows Event Viewer.

Configuring the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client

With the chain trust configuration, only the root CA and the certificate revocation list must be installed for the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web Server components. To do this, complete these procedures on the computer running the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web Server components.

To install the root CA

  1. Start the Certificates snap-in for MMC on the computer running the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web Server components, and then add the Certificates snap-in.

    Note
    This procedure is identical to the one that you followed for installing the root CA on the computer running Microsoft Dynamics NAV Server.

  2. In the Certificates snap-in dialog box, choose Computer account, and then choose Next.

  3. In the Select Computer pane, choose Local computer: (the computer this console is running on), and then choose Finish.

  4. Choose OK to close the Add or Remove Snap-ins dialog box.

  5. In the left pane of MMC, expand the Certificates (Local Computer) node.

  6. Expand the Trusted Root Certification Authorities node, right-click the Certificates subfolder, select All Tasks, and then choose Import.

  7. In the Certificate Import Wizard, on the Welcome page, choose Next.

  8. On the File to Import page, choose Browse.

  9. Browse to the location of the RootNavServiceCA.cer certificate file, select the file, and then choose Open.

  10. On the File to Import page, choose Next.

  11. On the Certificate Store page, accept the default selection, and then choose Next.

  12. On the Completing the Certificate Import Wizard page, choose Finish.

To install the certificate revocation list

  1. Start the Certificates snap-in for MMC on the computer running the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client, and then add the Certificates snap-in.

  2. In the Certificates snap-in dialog box, choose Computer account, and then choose Next.

  3. In the Select Computer pane, choose Local computer: (the computer this console is running on), and then choose Finish.

  4. Choose OK to close the Add or Remove Snap-ins dialog box.

  5. In the left pane of MMC, expand the Certificates (Local Computer) node.

  6. Expand the Trusted Root Certification Authorities node, right-click the Certificates subfolder, select All Tasks, and then choose Import.

  7. In the Certificate Import Wizard, on the Welcome page, choose Next.

  8. On the File to Import page, choose Browse.

  9. In the File Type field, select Certificate Revocation List (*.crl).

  10. Browse to the location of the RootNavServiceCA.crl file, select the file, and then choose Open.

  11. On the File to Import page, choose Next.

  12. On the Certificate Store page, accept the default selection, and then choose Next.

  13. On the Completing the Certificate Import Wizard page, choose Finish.

To modify the Microsoft Dynamics NAV Windows client configuration file to add certificate information

  1. Open the ClientUserSettings.config configuration file.

    The location of this file is Users\<username>\AppData\Roaming\Microsoft\Microsoft Dynamics NAV.

    By default, this file is hidden. Therefore, you may have to change your folder options in Windows Explorer to view hidden files.

  2. Modify the following settings.

    Key New value Description

    ClientServicesCredentialType

    NavUserPassword or Username

    The default value is Windows. When you change it to NavUserPassword or Username, client users who connect to the server are prompted for user name and password credentials. For more information on authentication mechanisms for Microsoft Dynamics NAV 2016, see Users and Credential Types. For information on how to provision users with initial username and password values, see How to: Create Microsoft Dynamics NAV Users.

    DnsIdentity

    The subject name of the service certificate

    The default value is <identity>.

    For this walkthrough, set the key to NavServiceCert.

  3. Save and close the ClientUserSettings.config file.

When you start the client, you are prompted for a valid user name and password for the server domain.

To modify the Microsoft Dynamics NAV Web client configuration file to add certificate information

  1. On the Microsoft Dynamics NAV web server instance, open the Microsoft Dynamics NAV Web client folder. By default, the folder is C:\inetpub\wwwroot\DynamicsNAV90.

  2. Open the web.config file in a text editor, such as Notepad.

  3. Find the <DynamicsNavSettings> element, and then change the following settings:

    Key New value Description

    ClientServicesCredentialType

    NavUserPassword or Username

    The default value is Windows. When you change it to NavUserPassword or Username, client users who connect to the server are prompted for user name and password credentials. For more information on authentication mechanisms for Microsoft Dynamics NAV 2016, see Users and Credential Types. For information on how to provision users with initial username and password values, see How to: Create Microsoft Dynamics NAV Users.

    DnsIdentity

    The subject name of the service certificate

    For this walkthrough, set the key to NavServiceCert.

  4. Save the web.config file.

    For more information about configuring the credential type for the Microsoft Dynamics NAV Web client, see How to: Configure User Authentication for the Microsoft Dynamics NAV Web Client.


How to: Implement Security Certificates in a Production Environment

After you have installed and configured Microsoft Dynamics NAV Server and obtained a service certificate and a root certification authority (CA) from a trusted provider, you must install the certificates on the computer running Microsoft Dynamics NAV Server. Complete instructions are available from your certificate provider.

The root CA certificate and the service certificate are used in the configuration, but client certificates are not. The root CA must be installed on the computer running Microsoft Dynamics NAV Server and all computers running the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web Server components. The service certificate must only be installed on the computer running Microsoft Dynamics NAV Server.

Most enterprises and hosting providers have their own infrastructure for issuing and managing certificates. You can also use these certificate infrastructures. The only requirement is that the service certificates must be set up for key exchange and therefore must contain both private and public keys.

Note
An instance of Microsoft Dynamics NAV Server that has been configured for secure WAN communication always prompts Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client users for authentication when they start the client, even when the client computer is in the same domain as Microsoft Dynamics NAV Server.

The following procedures use the Certificates snap-in for Microsoft Management Console (MMC). If you do not already have this snap-in installed, then follow these steps:

  1. From the Windows Start menu, choose Run, and then type Mmc.exe.

  2. In the console, on the File menu, choose Add/Remove Snap-in.

  3. In the Add Standalone Snap-in dialog box, select Certificates, and then choose Add.

Configuring Microsoft Dynamics NAV Server

After you have installed the root CA and the service certificate on the computer running Microsoft Dynamics NAV Server, you must grant access to the service account that is associated with the server so that the service account can access the service certificate’s private key. You must also change the configuration settings for Microsoft Dynamics NAV Server to enable remote logins.

To configure the computer running Microsoft Dynamics NAV Server

  1. In the left pane of MMC, expand the Certificates (Local Computer) node, expand the Personal node, and then select the Certificates subfolder.

  2. In the right pane, right-click the certificate, select All Tasks, and then choose Manage Private Keys.

  3. In the Permissions dialog box for the certificate, choose Add.

  4. In the Select Users, Computers, Service Accounts, or Groups dialog box, enter the name of the dedicated domain user account that is associated with Microsoft Dynamics NAV Server, and then choose the OK button.

  5. In the Full Control field, select Allow, and then choose the OK button.

  6. In the right pane, select the certificate.

  7. In the Certificate dialog box, choose the Details tab, and then select the Thumbprint field.

  8. Copy or note the value of the Thumbprint field.

  9. Start the Microsoft Dynamics NAV Server Administration tool. For more information, see Microsoft Dynamics NAV Server Administration Tool.

  10. Stop the Microsoft Dynamics NAV Server instance. For more information, see Managing Microsoft Dynamics NAV Server Instances.

  11. Modify the following settings for the Microsoft Dynamics NAV Server instance. For more information, see Configuring Microsoft Dynamics NAV Server.

    Key New value Description

    Credential Type

    NavUserPassword or Username

    This parameter is on the General tab in the Microsoft Dynamics NAV Server Administration tool. The default value is Windows. When you change it to NavUserPassword or Username, client users who connect to the server are prompted for user name and password credentials. For more information on authentication mechanisms for Microsoft Dynamics NAV 2016, see Users and Credential Types. For information on how to provision users with initial username and password values, see How to: Create Microsoft Dynamics NAV Users.

    Certificate Thumbprint

    Value of the Thumbprint field in the previous procedure.

    This parameter is on the Client Services tab in the Microsoft Dynamics NAV Server Administration tool. The default value is <key>. Remove any leading or trailing spaces in the thumbprint.

  12. Save and the new values for the server instance.

  13. Restart the Microsoft Dynamics NAV Server instance.

    If there is a problem, see Windows Event Viewer.

Configuring the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web Server components

The chain trust configuration allows all users of the Microsoft Dynamics NAV Windows client on a computer to log on to one or more instances of Microsoft Dynamics NAV Server as long as their login credentials have been associated with user accounts in Microsoft Dynamics NAV. The client validates that the server certificate is signed with the root CA.

After you have installed the root CA on the computer running the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web Server components, you must modify the client configuration file.

To modify the Microsoft Dynamics NAV Windows client configuration file

  1. Open the ClientUserSettings.config configuration file.

    In Windows 7 or Windows Server 2008, the location of this file is Users\<username>\AppData\Local\Microsoft\Microsoft Dynamics NAV.

    By default, this file is hidden. Therefore, you may have to change your folder options in Windows Explorer to view hidden files.

    Note
    If you want to change default Microsoft Dynamics NAV Windows client settings for all future users, edit the default ClientUserSettings.config file—that is, the one in C:\Program Files\Microsoft Dynamics NAV\90. Be sure that you run your text editor with Administrator privileges when you do so.

  2. Modify the following settings.

    Key New value Description

    ClientServicesCredentialType

    NavUserPassword or Username

    The default value is Windows. When you change it to NavUserPassword or Username, client users are prompted for user name and password credentials. For more information on authentication mechanisms for Microsoft Dynamics NAV 2016, see Users and Credential Types. For information on how to provision users with initial username and password values, see How to: Create Microsoft Dynamics NAV Users.

    DnsIdentity

    The subject name of the service certificate.

    The default value is <identity>. Replace this with the subject name or common name (CN) of the certificate that is used on the computer that is running Microsoft Dynamics NAV Server.

  3. Save and close the ClientUserSettings.config file.

When you starting the Microsoft Dynamics NAV Windows client, users are prompted for a valid user name and password.

To modify the Microsoft Dynamics NAV Web client configuration file

  1. On the computer that is installed the Microsoft Dynamics NAV Web Server components, open the installation folder for the Microsoft Dynamics NAV Web client. By default, the folder is C:\Program Files\Microsoft Dynamics NAV\90\Web Client.

  2. Open the web.config file in a text editor, such as Notepad.

  3. Find the <DynamicsNavSettings> element, and then change the following settings:

    Key New value Description

    ClientServicesCredentialType

    NavUserPassword

    The default value is Windows. When you change it to NavUserPassword or Username, client users who connect to the server are prompted for user name and password credentials. For more information on authentication mechanisms for Microsoft Dynamics NAV 2016, see Users and Credential Types. For information on how to provision users with initial username and password values, see How to: Create Microsoft Dynamics NAV Users.

    DnsIdentity

    The subject name of the service certificate

    The default value is <identity>. Replace this with the subject name or common name (CN) of the certificate that is used on the computer that is running Microsoft Dynamics NAV Server.

  4. Save the web.config file.

    For more information about configuring the credential type for the Microsoft Dynamics NAV Web client, see How to: Configure User Authentication for the Microsoft Dynamics NAV Web Client.


How to: Create a Self-signed Security Certificate Using PowerShell Script

With the New-NavSelfSignedCertificate PowerShell cmdlet, you can create a self-signed certificate to help secure the communication between the Microsoft Dynamics NAV Server and the Microsoft Dynamics NAV Web client.

Running the New-NavSelfSignedCertificate takes several parameters. One of these parameters is MakeCertExePath. This parameter must be filled in with the file path of the Windows SDK MakeCert.exe file. Typically, this file can be found under C:\Program Files (x86)\Windows Kits\8.1\bin\x86\makecert.exe. If you do not have a Windows 7.1 or 8.1 SDK on the Microsoft Dynamics NAV Server computer, you can download this from MSDN.

To create a self-signed security certificate using the PowerShell script

  1. On the computer or virtual machine that is running Microsoft Dynamics NAV Server, run Microsoft Dynamics NAV Administration Shell as an Administrator.

  2. Choose Start, in the Search box, type Microsoft Dynamics NAV Administration Shell.

  3. Right-click the related link, and then choose Run as Administrator.

  4. At the command prompt, import the PowerShell module by typing the following command: Import-Module <dvddir>\\WindowsPowerShellScripts\NAVCertificateAdministration\NAVCertificateAdministration.psm1 or a path equivalent to where your PowerShell module is located.

  5. Next, at the command prompt, type the following command: New-NavSelfSignedCertificate <parameters>

    The following table describes the parameters you can specify:

    Parameter name Type Description

    -TestCertificateName

    Type:String

    The name that identifies your test certificate. The default value is TestCertificate. This parameter is optional.

    -TestCertificateServerAddress

    Type:String

    The authority/entity that this certificate is issued for. Default is the computer host name. Specify this value if the Microsoft Dynamics NAV Server is accessed by using an address that differs from the computer name. This parameter is optional.

    -TestCertificateRootCertificateAuthorityName

    Type:String

    The root certificate authority name. The name will identify the root certificate issuer. The default value is the TestCertificate parameter value prefixed RootCA. This parameter is optional.

    -Outputfolder

    Type:String

    Specifies the output folder for the certificates. Default is the location where the script was executed from. This parameter is optional.

    -MakeCertExePath

    Type:String

    The path of the Windows SDK MakeCert.exe tool. Default is the specified Outputfolder. This parameter is optional.

    -NavServiceIdentity

    Type:String

    Username for the identity running the Microsoft Dynamics NAV Server. Default is NTAUTHORITY\Network Service. This parameter is optional.

    -Import

    Type:String

    Imports the certificates after creation. If not specified, the user will be prompted for a reply. This parameter is optional.

    -SkipImport

    Type:Boolean

    false will import certificates and true will skip the import of certificates.

The New-NavSelfSignedCertificate PowerShell cmdlet has now generated a self-signed security certificate with an accompanying root certificate and root revocation list, which is put under the specified output folder. Once the cmdlet is run, you have the option to import the security certificate, root certificate, and root revocation list to the local computer.

See Also

Tasks

Walkthrough: Implementing Security Certificates in a Test Environment

Concepts

Using Certificates to Secure a Remote Client Connection


Exporting and Importing Companies and Other Data

You can export a company from a Microsoft Dynamics NAV database and import it into another database, and you can export and import other types of data such as global data, application data, and application objects.

In earlier versions of Microsoft Dynamics NAV, you exported and imported this type of data as part of backing up and restoring databases. In Microsoft Dynamics NAV 2016, you can do this by using the Export-NAVData and Import-NAVData Windows PowerShell cmdlets. You can also import and export data in the Microsoft Dynamics NAV Windows client and the Microsoft Dynamics NAV Web client.

Important
If you want to back up data, we recommend that you use the SQL Server management tools.

Reuse of Companies, Data, and Applications

You can back up and restore databases using the SQL Server management tools, but sometimes you want to move only part of the data in a database to another database. For example, you can set up a test environment in a Microsoft Dynamics NAV database with a demonstration company. You can then export that demonstration company and import it in other databases so you can train users in your solution. In other cases, you want to export application objects and metadata in order to solve a problem in an existing customer's database without taking the customer offline, for example. In those cases, you can export the relevant data to a file and share the data that way.

When you export data from a Microsoft Dynamics NAV database, the data is stored in a file with the extension .navdata. This file cannot be modified in external tools. The data that you export is not deleted from the original database.

Warning
When you export data to a .navdata file, you must import the data into a database that is compatible with the data in the .navdata file. For example, you cannot import a company into a database that has a different database schema, and you cannot import Microsoft Dynamics NAV 2013 data into a Microsoft Dynamics NAV 2016 database. Also, you must import a company into a database that contains the data and application that the company's data depends on.

This means that you must import a company into a database that is based on the same application as in the database that the company was exported from.

Important
If you export companies and other data that is secured by data encryption, then remember to also export the encryption key so that you can access the data after you import it into another database, for example when you restore a backup. For more information, see Manage Data Encryption.

What to Export

You can export specific sets of data, such as a company or other data. The following table describes what is exported depending on your choices.

Type of data | Description
Company | Exports the specified company or companies, or all companies in the database. This includes the company-specific business data but no other data.
Global data | Exports data that is common to all companies in the database. This includes the report list, user IDs, and printer selections, but no company-specific business data.
Application data | Exports the data that defines the application in the database. This includes the permissions, permission sets, profiles, and style sheets.
Application | Exports all application objects. Data is not included. This is similar to exporting all objects to an .fob file.

What to Import

You can import all data from a .navdata file, or you can choose the data that you want to import. For example, if the file contains four companies, you can choose to import only one company. Similarly, if the file contains all data, you can choose to import only global data, for example. To import applications, you must use the Import-NAVData Windows PowerShell cmdlet. You can import other data, such as companies, in the Microsoft Dynamics NAV Windows client and the Microsoft Dynamics NAV Web client.

You can export and import the four types of data in different combinations. However, you must maintain database integrity and not leave databases in a state when you cannot open Microsoft Dynamics NAV.

Important
If you import application data but not the application, you cannot access the database from Microsoft Dynamics NAV. Similarly, if you import global data into a database that does not contain a company, you cannot open Microsoft Dynamics NAV.

Also, we recommend that you do not import an application into a database that users are accessing. A new application often defines a new database schema that changes the structure of the business data.

Windows PowerShell Cmdlets

You can import and export data in the Microsoft Dynamics NAV 2016 Administration Shell. The following table describes the available Windows PowerShell cmdlets. For more information, see Administration Cmdlets for Microsoft Dynamics NAV.

Name | Description
Export-NAVData | Exports data from a Microsoft Dynamics NAV database. You can export company-specific data, and you can choose to include global data, application data, or application objects.
Import-NAVData | Imports data into a Microsoft Dynamics NAV database from a file. You can import all data in the file, or you can choose to include specific companies, global data, application data, or application objects. You can only import an application into an empty database.
Get-NAVDataFile | Gets information from a file that has been exported from a Microsoft Dynamics NAV database. The extracted information includes the types of data that the file contains and any company names.

The cmdlets take different parameter sets depending on how you connect to the database that you want to export data from or import data into. You can access the database through the Microsoft Dynamics NAV Server instance, or you can access the database directly as described in the following table.

Access Description

Through the Microsoft Dynamics NAV Server instance.

Use parameter sets that include -ServerInstance when the database that you want to access is mounted against a Microsoft Dynamics NAV Server instance.

The user account for the Microsoft Dynamics NAV Server instance must have access to write to the location that is specified by the -FilePath parameter.

Through a direct connection to the database.

Use parameter sets that include -DatabaseServer and -DatabaseName when the Microsoft Dynamics NAV Server instance is stopped or not available. For example, if you want to import an updated application into a database, you stop the service so that users cannot access the database.

You must have access to write to the location that is specified by the -FilePath parameter.

In multitenant deployments of Microsoft Dynamics NAV, if you export or import business data, you must specify the ID of the tenant database. If you export or import applications, you must specify the application database and database server. You can only import application data if the specified tenant is mounted with the -AllowAppDatabaseWrite parameter.

C/AL Functions

You can use the following C/AL functions to handle export and import of data programmatically:

  • EXPORTDATA Function (Database)

  • IMPORTDATA Function (Database)

  • DATAFILEINFORMATION Function (Database)

For examples of how to use these functions, see page 9900 and 9901 in the CRONUS International Ltd. demonstration database.

See Also

Tasks

How to: Export and Import Companies and Other Data using Windows PowerShell Cmdlets
How to: Export and Import Companies and Other Data in Clients

Concepts

Microsoft Dynamics NAV Windows PowerShell Cmdlets


How to: Export and Import Companies and Other Data using Windows PowerShell Cmdlets

You can export data such as a company or an application from a Microsoft Dynamics NAV database from the Microsoft Dynamics NAV 2016 Administration Shell. You can also use Windows PowerShell cmdlets to import data into a Microsoft Dynamics NAV database.

The cmdlets take different parameter sets depending on how you connect to the database that you want to export data from or import data into. You can access the database through the Microsoft Dynamics NAV Server instance, or you can access the database directly. The procedures in this topic illustrate both approaches. For more information, see Exporting and Importing Companies and Other Data.

To export data using Windows PowerShell cmdlets

  1. Open the Microsoft Dynamics NAV 2016 Administration Shell.

    Important
    You must run the program as administrator. Also, you must ensure that scripting is enabled on the computer. You must also have write access to the location that you specify in the -FilePath parameter.

  2. For an overview of the cmdlet, type the following command:

    Copy Code
    get-help Export-NAVData

  3. To export a single company from a tenant database that is mounted against a Microsoft Dynamics NAV Server instance, type the following command:

    Copy Code
    Export-NAVData -ServerInstance <service name> -Tenant <tenant ID> -CompanyName "<Company name>" -FilePath <location>

    For example, to run the cmdlet against the CRONUS International Ltd. demonstration database, type the following command:

    Copy Code
    Export-NAVData -ServerInstance DynamicsNAV90 -Tenant Tenant1 -CompanyName "CRONUS International Ltd." -FilePath c:\Data\mytenantcompany.navdata

    In the example, the Microsoft Dynamics NAV Server instance is DynamicsNAV90, the tenant database is Tenant1, and the company name is CRONUS International Ltd.. The example is based on a multitenant deployment where you want to export a specific company from the specified tenant database. In a single-tenant deployment, you do not specify the tenant, and the example will export the company from the database that the specified Microsoft Dynamics NAV Server instance is configured for.

    For an example of how to export data directly from a database that is not mounted against a Microsoft Dynamics NAV Server instance, see the next step.

  4. To export global data, application data, and application objects directly from a database, type the following command:

    Copy Code
    Export-NAVData -DatabaseServer <service name> -Database <database name> -IncludeGlobalData -IncludeApplicationData -IncludeApplication -FilePath <location>

    For example, to run the cmdlet against the CRONUS International Ltd. demonstration database, type the following command:

    Copy Code
    Export-NAVData - DatabaseServer localhost -DatabaseName 'Demo Database NAV (9-0)' -AllCompanies -IncludeGlobalData -IncludeApplicationData -IncludeApplication -FilePath c:\Data\myappanddata.navdata

    In the example, the database server is the local computer, the database is the demonstration database, and the export includes global data, application data, and the application objects, and all companies in the database. The example is based on a single-tenant deployment where you have chosen to specify the -DatabaseServer and -DatabaseName parameters. Alternatively, you can specify the -ServerInstance parameter as illustrated in the previous step. In a multitenant deployment, you must also specify the tenant database.

For another example of how to export companies and other data, see the Example section.

You have exported a Microsoft Dynamics NAV company into a file. Now, you can import the company into another Microsoft Dynamics NAV database.

To import data using Windows PowerShell cmdlets

  1. Open the Microsoft Dynamics NAV 2016 Administration Shell.

    Important
    You must run the program as administrator. Also, you must ensure that scripting is enabled on the computer.

  2. To see what a .navdata file contains, type the following command:

    Copy Code
    Get-NAVDataFile -FilePath <location>

    For example, to run the cmdlet against one of the files that were exported in the previous procedure, type the following command:

    Copy Code
    Get-NAVDataFile -FilePath c:\Data\myappanddata.navdata

    In the example, the command returns the following information:

    Copy Code
    ExportVersion               : 1

DatabaseVersion                  : 70730

Description                      : All companies and all other data from a database.

IncludeApplication               : True

IncludeApplicationData           : True

TenantId                         :

IncludeGlobalData                : True

CompanyName                      : {CRONUS International Ltd.}

ExportDateTime                   : 28-08-2014 11:17:16

  3. To import a single company into a tenant database that is mounted against a Microsoft Dynamics NAV Server instance, type the following command:

    Copy Code
    Import-NAVData -ServerInstance <server name> -Tenant <tenant ID> -CompanyName "<Company name>" -FilePath <location>

    For example, to run the cmdlet based on the data that you exported in the previous procedure, type the following command:

    Copy Code
    Export-NAVData -ServerInstance DynamicsNAV90 -Tenant Tenant2 -CompanyName "CRONUS International Ltd." -FilePath c:\Data\mytenantcompany.navdata

    In the example, the Microsoft Dynamics NAV Server instance is DynamicsNAV90, the tenant database is Tenant2, and the company name is CRONUS International Ltd.. The example is based on a multitenant deployment where you want to move a company from one tenant database to another tenant database. In a single-tenant deployment, you do not specify the tenant, and the example will import the company into the database that the specified Microsoft Dynamics NAV Server instance is configured for.

    For an example of how to import data directly into a database, see the next step.

    Important
    To import an application, you must use the Import-NAVData cmdlet using the -DatabaseServer and -Database parameters, and you must make sure no users are accessing the database. Also, the database must be empty.

  4. To import an application directly into a Microsoft Dynamics NAV database, type the following command:

    Copy Code
    Import-NAVData -DatabaseServer <server name> -Database <database name> -IncludeApplication -FilePath <location>

    For example, to run the cmdlet based on the data that you exported in the previous procedure, type the following command:

    Copy Code
    Import-NAVData - DatabaseServer localhost -DatabaseName 'My Application Database' -IncludeApplication -FilePath c:\Data\myappanddata.navdata

    In the example, the database server is the local computer, the database is My Application Database, and the command imports the application objects that you exported from the CRONUS International Ltd. demonstration database. Because you want to import an application, you specify the -DatabaseServer and -DatabaseName parameters. If you want to import other types of data, you can choose to specify the -ServerInstance parameter as illustrated in the previous step. In a multitenant deployment, you must also specify the tenant database.

For another example of how to import companies and data, see the Example section.

Example

The following code example illustrates a Windows PowerShell script that you can use to export data from a Microsoft Dynamics NAV database and import data into another database.

Copy Code
Export-NAVData -ServerInstance ProductionServer -AllCompanies -FilePath MyFile.navdata |

Import-NAVData -ServerInstance TestServer -AllCompanies

In the example, you export all companies from the database in a production environment. You then import the companies into a database in a test environment. This example illustrates how you can use the Windows PowerShell cmdlets to copy data to a database for debugging or maintenance, for example.

See Also

Tasks

How to: Export and Import Companies and Other Data in Clients

Concepts

Exporting and Importing Companies and Other Data
Microsoft Dynamics NAV Windows PowerShell Cmdlets


How to: Export and Import Companies and Other Data in Clients

You can export data such as a company or an application from a Microsoft Dynamics NAV database in the Microsoft Dynamics NAV Windows client and the Microsoft Dynamics NAV Web client. You can also import data into a Microsoft Dynamics NAV database.

Important
To export or import data from a Microsoft Dynamics NAV database, you must be a user in the Microsoft Dynamics NAV database, and your user account must have a permission set that enables you to export or import data, such as the SUPER permission set. We recommend that you define a specific permission set such as DATA-EXPORTIMPORT and add system permissions 5410, Export Data to Data File, and 5420, Import Data from Data file. Optionally, add other permissions, and then assign the permission set to the users that you want to be able to export and import data.

When you export data from the Microsoft Dynamics NAV Windows client or the Microsoft Dynamics NAV Web client, data is exported from the database that your current company uses. Similarly, when you import data, data is imported into your current database.

The following procedures assume that you have the relevant permissions as described above.

To export data

  1. In the Search box, enter Export to a Data File, and then choose the related link.

  2. In the Export Data window, fill in the fields as described in the following table.

    Field Description

    Description

    Optionally, specifies a description of the data that you want to export, such as Company A data.

    The text that you specify is used as a suggested file name when you start the export.

    All Companies

    Specifies if you want to export all companies in the current database.

    If you do not choose this field, and you want to export one or more companies, you must you must select the relevant companies from the list of available companies.

    Global Data

    Specifies if you want to export data that is common to all companies in the database. This includes the report list, permission sets, user IDs, and printer selections, but no company-specific business data.

    Application Data

    Specifies if you want to export the data that defines the application in the database.

    Application

    Specifies if you want to export all application objects. Application data is not included.

  3. Optionally, if you did not choose the All Companies field, select one or more companies to export.

  4. Choose the OK button, and then, in the window that appears, specify the location and name of the file that the data is exported to, and then choose the Save button.

    The data is exported to a file with the extension .navdata.

You have exported data from a Microsoft Dynamics NAV database into a file. Now, you can import the data into another Microsoft Dynamics NAV database.

Before you import data from a navdata file, you can choose to use the Get-NAVDataFile Windows PowerShell cmdlet to see what the file contains. For more information, see How to: Export and Import Companies and Other Data using Windows PowerShell Cmdlets.

To import data

  1. In the Search box, enter Import Data, and then choose the related link.

  2. In the Import Data window, fill in the fields as described in the following table.

    Field Description

    File Name

    Specifies the name and location of the .navdata file that you want to import data from.

    All Companies

    Specifies if you want to import all companies in the current database.

    If you do not choose this field, and you want to import one or more companies, you must select the relevant companies from the list of available companies.

    Company Name

    Specifies the name of the company that you want to import. You can specify more than one company.

    Global Data

    Specifies if you want to import data that is common to all companies in the database. This includes the report list, permission sets, user IDs, and printer selections, but no company-specific business data.

    Application Data

    Specifies if you want to import the data that defines the application in the database.

    Warning
    If you choose to import application data, you must make sure that the application in the current database supports the application data.

  3. Optionally, if you did not choose the All Companies field, select one or more companies to import.

  4. Choose the OK button.

    Warning
    If you choose to import data of a type that already exists in the database, you risk overwriting the data. You will be asked to confirm that you want to overwrite the existing data.

  5. The data that you specified is now imported into your current database.

See Also

Tasks

How to: Export and Import Companies and Other Data using Windows PowerShell Cmdlets

Concepts

Exporting and Importing Companies and Other Data


Integrating Microsoft Dynamics NAV in SharePoint Sites

You can set up Microsoft Dynamics NAV to be available as an app for SharePoint. This means that Microsoft Dynamics NAV data can be shown in a SharePoint site, and that you can modify the data on the SharePoint site through the Microsoft Dynamics NAV Web client.

You can deploy Microsoft Dynamics NAV as an app for SharePoint Online and SharePoint on-premises.

SharePoint and Microsoft Dynamics NAV

If you set up a SharePoint site, you can add Microsoft Dynamics NAV as an app to the site so that the Microsoft Dynamics NAV Web client opens when the user chooses an icon. Then, you can add web parts that show Microsoft Dynamics NAV data, such as a list of sales invoices with overdue payments. Users can drill down into the data and the web parts will open the relevant page in the Microsoft Dynamics NAV Web client when the user chooses an icon or a link.

For example, if you provide financial services to several subscribers, you want your subscribers to be able to see their data in a SharePoint site. In that case, you can create separate subsites for each subscriber so that they have access to only their data. Their data is stored in dedicated business databases, because you have deployed your Microsoft Dynamics NAV solution in a multitenant deployment architecture. You add Microsoft Dynamics NAV as an app so that users can open the Microsoft Dynamics NAV Web client when they choose an icon, and they are signed in to Microsoft Dynamics NAV automatically. Then, you add parts to show the subscriber’s list of unpaid sales invoices, or a chart that reflects top sales. When the user chooses the list of unpaid sales invoices, the underlying page from Microsoft Dynamics NAV Web client opens as a seamless part of the SharePoint site. The user can filter and modify the data without having to sign in to a new site.

Warning
The users' access to Microsoft Dynamics NAV is not restricted to the page that you expose in SharePoint. You must assign the relevant permissions to each user in Microsoft Dynamics NAV.

You can set up a site collection with a site for each subscriber to your services, or you can set up a single site with general information. In this scenario, your Microsoft Dynamics NAV implementation is most likely to be a multitenant deployment with a tenant for each of your subscribers. But you can choose other deployment scenarios, such as using Microsoft Dynamics NAV companies in shared databases for your subscribers. Similarly, you can deploy Microsoft Dynamics NAV as an app for SharePoint that is used internally exclusively by users in your own organization. In general, the configuration of the app and how Microsoft Dynamics NAV and SharePoint interact are the same in both scenarios.

Deploying Microsoft Dynamics NAV for Integration with SharePoint

To integrate with SharePoint, you must have a Microsoft Dynamics NAV Server and Microsoft Dynamics NAV Web Server instance. These components can be deployed on-premise or on a cloud service, such as Microsoft Azure.

  • The Microsoft Dynamics NAV Server instance that you want your app for SharePoint to access must be configured for multitenancy and configured with AccessControlService as the credential type. For more information, see Authenticating Users with Azure Active Directory.

  • The Microsoft Dynamics NAV Web Server components instance that you want to use for your app for SharePoint must be configured to be able to run in the SharePoint site. The default configuration prevents the Microsoft Dynamics NAV Web client from running inside an iframe in an external website. If you want to show Microsoft Dynamics NAV data in app parts, you must remove the X-FRAME-OPTIONS setting in the web.config file. For more information, see Embedding Microsoft Dynamics NAV Web Client Pages in Other Websites.

    The Microsoft Dynamics NAV Web Server components instance must be configured to use secure authentication and SSL. For more information, see How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client.

  • Each user who will access Microsoft Dynamics NAV from your app for SharePoint must be set up in Microsoft Dynamics NAV. For example, create the users with Windows authentication or with user name/password authentication, depending on your deployment scenario. But you must also specify an authentication email address on the Office 365 Authentication FastTab in the User Card window. The authentication email address must be the same account that the users log on to Office 365 or SharePoint Online with. If you set up this account in your Microsoft Azure AD tenant, you achieve a deeper integration between SharePoint and Microsoft Dynamics NAV. By creating the users of the SharePoint site as users in Microsoft Dynamics NAV with this authentication email address, they achieve single sign-on when they access Microsoft Dynamics NAV Web client from the SharePoint site, for example. For more information, see How to: Create Microsoft Dynamics NAV Users.

Building an App for SharePoint

In order to add Microsoft Dynamics NAV as an app to a SharePoint site, you must create a provider-hosted app for SharePoint in Visual Studio. This includes configuring an appManifest.xml file, so that the app can be added to a site. The app manifest describes metadata such as the title, the publisher, and the URL of start page for the Microsoft Dynamics NAV Web client so that the app will open the relevant Microsoft Dynamics NAV Web client address. Also, you can add one or more client web parts for the Microsoft Dynamics NAV pages that you want to show on the SharePoint site. You can choose to use an already existing page, or you can create specific pages that are only used for SharePoint. For example, you can create a part that is based on page ID 9305, Sales Order List. Then, you deploy the app to your SharePoint site, and you add the part as an app part that will show the page in the Microsoft Dynamics NAV Web client as a list of sales orders without navigation elements. The list resembles any other list in SharePoint, but it is the Microsoft Dynamics NAV Web client, and the data is current. For more information, see Embedding Microsoft Dynamics NAV Web Client Pages in Other Websites and Developing and Installing a Microsoft Dynamics NAV Apps for SharePoint.

Apps for SharePoint and Multitenant Deployments of Microsoft Dynamics NAV

You can deploy Microsoft Dynamics NAV in a multitenant deployment architecture. When you create an app for SharePoint that will access the Microsoft Dynamics NAV Web client, you must decide if you want to deploy the app for a specific tenant, or if the app can be used by all tenants that are mounted against a Microsoft Dynamics NAV Server instance. Then, in the app manifest for the app, you include a tenant parameter in start page URL according to the following:

  • If you want the app to apply to a specific tenant only, then set the tenant parameter to the tenant ID, such as https://www.solutions.com/DynamicsNAV/WebClient/?tenant=tenant1. In this example, the tenant ID is tenant1. The value of the tenant parameter must be included in tenants list of alternative IDs.

    Alternatively, if you have configured the Microsoft Dynamics NAV Web Server components to accept host names, you can specify the host name in the URL in the app manifest. For more information, see How to: Configure the Microsoft Dynamics NAV Web client to Accept Host Names for Tenants.

  • If you want the app to apply to all tenants, then set the tenant parameter to {HostUrl}, such as https://www.solutions.com/DynamicsNAV/WebClient/?tenant={HostUrl}.

    When the app accesses the Microsoft Dynamics NAV Web client, HostUrl is automatically replaced by the SharePoint site address where the app is installed. Because the SharePoint site is tenant-specific, this parameter identifies the tenant.

    You must include all SharePoint site addresses that can access a tenant in the tenant's list of alternative IDs.

Note
For more information about how to set alternate IDs for tenants, see How to: Mount or Dismount a Tenant on a Microsoft Dynamics Server Instance.

Installing Microsoft Dynamics NAV as an App

When you have built your app for SharePoint in Visual Studio, you must publish it in order to create the deployment package. Depending on your scenario, you can deploy the app to SharePoint in different ways.

For example, you can publish the app to the SharePoint store so that it is accessible for others to install on their SharePoint sites.

If you want to install the app only on your own SharePoint sites, you can upload it to your SharePoint app catalog from where you can install it to the relevant SharePoint sites. For example, if you have a SharePoint site collection with a site that is used internally and a site that is publicly available. Then, you can add different parts to the two sites, such as a read-only part on the public site, and an editable part on the internal site. For more information, see Developing and Installing a Microsoft Dynamics NAV Apps for SharePoint.

See Also

Tasks

Troubleshooting: Microsoft Dynamics NAV and SharePoint

Concepts

Multitenant Deployment Architecture
Developing and Installing a Microsoft Dynamics NAV Apps for SharePoint
Authenticating Users with Azure Active Directory
Configuring Authentication and Single Sign-On Between Microsoft Dynamics NAV and SharePoint


Configuring Authentication and Single Sign-On Between Microsoft Dynamics NAV and SharePoint

This topic provides an overview of how to configure user authentication with SharePoint.

Configuring User Authentication for SharePoint Online and SharePoint On-Premises

SharePoint Online and SharePoint on-premises support different authentication methods. This means that depending on your SharePoint deployment, you must configure Microsoft Dynamics NAV differently. The configuration applies to the Microsoft Dynamics NAV Server instances, the user setup, and the Microsoft Dynamics NAV clients that users can use.

SharePoint Online

For SharePoint Online, the following Microsoft Dynamics NAV configurations are available:

Client Type Microsoft Dynamics NAV Server Credential Type Authentication Mechanism

Microsoft Dynamics NAV Web client

AccessControlService

Microsoft Azure Active Directory (Azure AD)

Microsoft Dynamics NAV Windows client

AccessControlService

Azure AD added to an Access Control service (ACS) namespace.

Important
The Microsoft Dynamics NAV Windows client is currently not supported if the Microsoft Dynamics NAV deployment must be accessed by more than on Azure AD tenant.

SharePoint On-Premise

When you want to deploy apps to SharePoint on-premises, you must configure the SharePoint sites first. For more information, see Configure an environment for apps for SharePoint and Plan for apps for SharePoint 2013 on TechNet.

For SharePoint on-premises that must be accessible from the internet so that SharePoint and Microsoft Dynamics NAV are publicly accessible, the following Microsoft Dynamics NAV configurations are available:

Client Type | Microsoft Dynamics NAV Server Credential Type | Authentication Mechanism
Microsoft Dynamics NAV Web client | AccessControlService | Azure AD -Or- Azure AD added to an Access Control service (ACS) namespace.
Microsoft Dynamics NAV Windows client | AccessControlService | Azure AD added to an Access Control service (ACS) namespace.
Important
If you use Azure AD as the authentication mechanism, your app for SharePoint must open the Microsoft Dynamics NAV Web client in full screen mode in SharePoint on-premises deployments. For more information, see Troubleshooting: Microsoft Dynamics NAV and SharePoint.

For SharePoint on-premises that must be accessible from an intranet so that SharePoint and Microsoft Dynamics NAV are accessed only on-premises, the following Microsoft Dynamics NAV configurations are available:

Client Type | Microsoft Dynamics NAV Server Credential Type | Authentication Mechanism
Microsoft Dynamics NAV Web client | Windows -Or- AccessControlService | Windows authentication -Or- Azure AD
Microsoft Dynamics NAV Windows client | Windows | Windows authentication
Note
The security zones that the security mechanisms in Internet Explorer rely on can lead to unexpected behavior when users access the Microsoft Dynamics NAV Web client from SharePoint. For more information, see Troubleshooting: Microsoft Dynamics NAV and SharePoint.

Configuring Single Sign-on

As part of a SharePoint Online subscription, you also get an Azure AD tenant. The Azure AD tenant handles user authentication when users sign in to SharePoint Online. To enable a seamless integration between SharePoint Online and Microsoft Dynamics NAV, you must configure Microsoft Dynamics NAV to authenticate users against the same Azure AD tenant. This will enable single sign-on between the two applications, so that users will only have to sign in once. Also, Microsoft Dynamics NAV web parts that are embedded on SharePoint pages will work. You can work with Azure AD management in the Azure management portal, or you can use Azure AD Module for Windows PowerShell cmdlets. For more information, see Authenticating Users with Azure Active Directory.

For more information about how to achieve single sign-on between Microsoft Dynamics NAV and SharePoint based on Azure AD, see Authenticating Users with Azure Active Directory.

See Also

Tasks

Troubleshooting: Microsoft Dynamics NAV and SharePoint

Concepts

Multitenant Deployment Architecture
Developing and Installing a Microsoft Dynamics NAV Apps for SharePoint
Authenticating Users with Azure Active Directory


Developing and Installing a Microsoft Dynamics NAV Apps for SharePoint

If you set up a SharePoint site using SharePoint Online or SharePoint on-premises, you can embed Microsoft Dynamics NAV in an app on the site. You can create an app that opens Microsoft Dynamics NAV Web client in a new browser tab, and you can display Microsoft Dynamics NAV data in hosted app parts in the SharePoint site. Building and deploying apps for SharePoint requires that you create the app in Visual Studio and add it to the SharePoint site. After you have built your app, you can make it available to other sites, such as subsites in your site collection. For example, if you provide financial services to several customers, you can set up a site collection with a subsite for each subscriber. You can then create and deploy an app for SharePoint that displays each subscriber’s Microsoft Dynamics NAV data in their SharePoint site. You can create an app for SharePoint that will display different pages in Microsoft Dynamics NAV Web client as hosted app parts.

This topic describes the overall configuration of an app for SharePoint that uses Microsoft Dynamics NAV data with examples of what you are likely to have to do.

Getting Started

If you already have a site available on SharePoint Online, you can deploy your first app to that. Alternatively, sign up for a free trial Office 365 plan. We recommend that you use a plan such as Office 365 Enterprise E1 as your test site, or that you sign up for a trial developer plan. A trial plan includes an administrative account which you will use to set up the app in the SharePoint site. For example, if your Office 365 site is Solutions.onmicrosoft.com, your administrative account can be admin@solutions.onmicrosoft.com. For more information, see Select an Office 365 plan for business.

If you want to use your app in a SharePoint on-premises deployment, you must choose a solution that meets your requirements. For example, the App Catalog is not available in all SharePoint 2013 on-premises solutions.

You will also need tools to create the actual app. We recommend that you use the latest version of Visual Studio 2012 with the Microsoft Office Developer Tools for Visual Studio 2012. You do not have to write code to create the app, but Visual Studio 2012 includes project templates for creating apps for SharePoint, which makes it less complex. For more information, see Microsoft Office Developer Tools for Visual Studio 2012 online.

Registering the App in SharePoint

Before you can install the app on a SharePoint site, the app must be registered in SharePoint. Registering an app generates an app identity, which includes the following information: client ID, display name of the app, app domain where the app is hosted, and in some cases, a redirect URI associated with the app. You will use some of the app identity information when you create the app.

There are five ways that you can register an app. The way that you choose to register your app depends on your scenario and environment. For more information, see Guidelines for registering apps for SharePoint 2013 in the MSDN Library.

For example, with the deployment scenario that is discussed in this guide, you will only install your apps on your own SharePoint sites. Therefore, you can manually register the app by using appregnew.aspx. To do this, you must access the appregnew.aspx page for your subscription, as described in the following procedure.

To register an app using the appregnew.aspx

  1. Go to the appregnew.aspx page for your subscription, such as https://MyTenant.sharhepoint.com/_layouts/15/appregnew.aspx, where https://MyTenant.sharhepoint.com is the URL of your SharePoint site.

  2. Fill out the fields as described in the following table.

    Field Description

    App Id

    A GUID, such as 2de23703-bbb9-4542-970d-84b6e5597f53. This is also referred to as the client ID.

    This is generated when you choose the Generate button.

    App Secret

    A base-64 encoded string, such as xvVpG0AgVIJfch6ldu4dLUlcZyysmGqBRbpFDu6AfJw=. This is also referred to as the client secret.

    This is generated when you choose the Generate button.

    Title

    The name of the app, which will be shown to users of your site, such as Financial App by Solutions.

    App Domain

    The host name for your Microsoft Dynamics NAV Web Server components, such as www.solutions.com. If you have deployed the Microsoft Dynamics NAV Web client on a local machine, you can also enter the machine name.

    Redirect URI

    The URI for signing in to your Microsoft Dynamics NAV Web Server components, such as https://www.solutions.com/DynamicsNAV or https://MyComputer/DynamicsNAV.

  3. Choose the Create button to register the app.

Developing the App in Visual Studio

With Visual Studio 2012 and the Microsoft Office Developer Tools, you can create an app for SharePoint. This topic provides the general instructions for creating a provider-hosted app. For more information, see How to: Create a basic provider-hosted app and Build apps for SharePoint in the MSDN Library.

Create the App in Visual Studio

You create an app for SharePoint using the App for SharePoint 2013 project template in Visual Studio. The app that you create must be a provider-hosted app for SharePoint.

To create a provider-hosted app in Visual Studio

  1. In Visual Studio, create a new App for SharePoint 2013 project.

  2. When you create the project, specify the name and location of the SharePoint site as described in the following table.

    Field Description

    What is the name of your app for SharePoint?

    Specify a name, such as NAVSharePointApp.

    The name that you specify here is not the name that displays to users of the SharePoint site.

    What SharePoint site do you want to use for debugging your app?

    Specify the developer site that is part of your Office 365 plan. For example, if your Office 365 plan is Solutions.onmicrosoft.com, your developer site can be Solution.sharepoint.com.

    Note
    This must be a developer site in order for Visual Studio’s F5 deployment to work. F5 depends on the side-loading feature in SharePoint, which is only available on developer sites.

    How do you want to host your app for SharePoint?

    Choose Provider-Hosted.

  3. When you are done, a new solution is created in Visual Studio, which you can see in Solution Explorer. The solution contains two projects: a SharePoint App project called <project name> and an ASP .NET Web project called <project name>Web, where <project name> is the project name that you specified when you created the project.

    1. The SharePoint App project will be used to generate the app package that you will upload to SharePoint. The project contains the following files:

      • AppIcon.png

        You can replace this file to use an image that is more relevant for your app.

      • AppManifest.xml

        The app manifest describes the app.

    2. The ASP .NET Web project will not be used because it is not required to build an app that uses Microsoft Dynamics NAV data. Therefore, you can delete this project.

Modify the App Manifest

After you create the app, you modify settings in the app manifest for the app, which includes setting the app ID and start page URL. The start page URL specifies the URL of the Microsoft Dynamics NAV Web client but it is also used in multitenant Microsoft Dynamics NAV Server deployments to specify whether the app can be used by a specific tenant only or by all tenants that are mounted against a Microsoft Dynamics NAV Server instance.

To modify the appmanifest.xml

  1. In Visual Studio, open the AppManifext.xml file to view the code.

  2. To set up the app, set the StartPage element and RemoteWebApplication element as described in the following table.

    Element Description

    StartPage

    Set this element to the URL of the Microsoft Dynamics NAV Web client and append the URL with the {StandardTokens} parameter. For example, if the URL of the Microsoft Dynamics NAV Web client is https://www.solutions.com/DynamicsNAV/WebClient, then set the element to https://www.solutions.com/DynamicsNAV/WebClient/?{StandardTokens}.

    If the Microsoft Dynamics NAV Web client is deployed in a multitenant environment, then include the tenant parameter in the URL to specify which tenants the app applies to. You can configure that app to apply to a specific tenant or all tenants as follows:

    • To apply the app to a specific tenant only, set the tenant parameter to the ID of the tenant, such as https://www.solutions.com/DynamicsNAV/WebClient/?tenant=tenant1. In this example, the tenant ID is tenant1. The value of the tenant parameter must be included in tenant's list of alternative IDs.

      Alternatively, if you have configured the Microsoft Dynamics NAV Web Server components to accept host names, you can specify the host name in the URL. For more information, see How to: Configure the Microsoft Dynamics NAV Web client to Accept Host Names for Tenants.

    • To apply the app to all tenants, set the tenant parameter to {HostUrl}, such as https://www.solutions.com/DynamicsNAV/WebClient/?tenant={HostUrl} .

      When the app accesses the Microsoft Dynamics NAV Web client, HostUrl is automatically replaced by the SharePoint site address where the app is installed. Because the SharePoint site is tenant-specific, this parameter identifies the tenant.

      You must include all SharePoint site addresses that can access a tenant in the tenant's list of alternative IDs.

    Note
    For more information about how to set alternate IDs for tenants, see How to: Mount or Dismount a Tenant on a Microsoft Dynamics Server Instance.

    RemoteWebApplication

    Set the value of the ClientId parameter to App ID that was assigned when you registered the app.

    The following code example illustrates the content of an AppManifest.xml file:

    Copy Code
    <?xml version="1.0" encoding="utf-8" ?>
<App xmlns="http://schemas.microsoft.com/sharepoint/2012/app/manifest"
     Name="NAVSharePointApp"
     ProductID="{335df4e8-93b1-4205-8504-001aa934b01e}"
     Version="1.0.0.0"
     SharePointMinVersion="15.0.0.0"
>
  <Properties>
    <Title>Financial App by Solutions</Title>
    <StartPage>https://www.solutions.com/DynamicsNAV/WebClient/?{StandardTokens}</StartPage>
  </Properties>
  <AppPrincipal>
    <RemoteWebApplication ClientId="2de23703-bbb9-4542-970d-84b6e5597f53" />
  </AppPrincipal>
</App>

    We recommend that you do not set up permissions that your app for SharePoint will request from the user at installation time.

Adding Web Parts to the App

Optionally, you can add client web parts to the project and configure them to show specific Microsoft Dynamics NAV pages in Microsoft Dynamics NAV Web client. This means that the Microsoft Dynamics NAV pages will display inside the SharePoint pages. When you create a client web part, you can specify URLs that display a page without displaying the ribbon or UI parts. As a result, the page will appear to be just another app part on the SharePoint site, but it is the Microsoft Dynamics NAV Web client. For more information, see Embedding Microsoft Dynamics NAV Web Client Pages in Other Websites

To add web parts to the app, add an item of type Client Web Part (Host Web) to the project in Visual Studio. Specify that it must use an existing web page, and then specify use a URL such as https://www.solutions.com/DynamicsNAV/WebClient/default.aspx?mode=View&isembedded=1&page=9301&shownavigation=0&showribbon=0&showuiparts=0&pagesize=7&SPHostUrl={HostUrl}.

You can choose to convert the query parameters of the URL into properties on the web part, which will enable you to configure the same web part differently when inserting it on different SharePoint pages. To do this, you modify the Elements.xml file for the web part. In the Elements.xml file, the Src attribute of the Content element specifies the URL of the page of the Microsoft Dynamics NAV Web client. For each parameter of the URL that you want to make a property, replace its value with a property name that has the format _PropertyName_, and then add a corresponding Property element in the Properties element. For example, the following code illustrates the content of the Elements.xml file for a web part for page 9301 of the Microsoft Dynamics NAV Web client.

Copy Code
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <ClientWebPart Name="ListPart" Title="Microsoft Dynamics NAV List Part" Description="List from Microsoft Dynamics NAV" DefaultWidth="800" DefaultHeight="300" >
    <Content Type="html" Src="https://www.solutions.com/DynamicsNAV/WebClient/default.aspx?mode=View&isembedded=1&page=9301&shownavigation=0&showribbon=0&showuiparts=0&pagesize=7&SPHostUrl={HostUrl}" />
    <Properties>
    </Properties>
  </ClientWebPart>
</Elements>

The following code illustrates how to change the Elements.xml file to include properties for the page and pagesize parameters.

Copy Code
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <ClientWebPart Name="ListPart" Title="Microsoft Dynamics NAV List Part" Description="List from Microsoft Dynamics NAV" DefaultWidth="800" DefaultHeight="300" >
    <Content Type="html" Src="https://www.solutions.com/DynamicsNAV/WebClient/default.aspx?mode=View&amp;isembedded=1&amp;page=_PageId_&amp;shownavigation=0&amp;&amp;pagesize=_PageSize_&amp;SPHostUrl={HostUrl}" />
    <Properties>
        <Property
               Name="PageId"
               Type="int"
               RequiresDesignerPermission="true"
               DefaultValue="9301"
               WebCategory="Microsoft Dynamics NAV"
               WebDisplayName="Page number.">
        </Property>
        <Property
               Name="PageSize"
               Type="int"
               RequiresDesignerPermission="true"
               DefaultValue="7"
               WebCategory="Microsoft Dynamics NAV"
               WebDisplayName="Number of rows to show.">
        </Property>
    </Properties>
  </ClientWebPart>
</Elements>

Installing the App on your SharePoint Site

When you have created app in Visual Studio, you can press F5, and Visual Studio will deploy the app to SharePoint and install it on the SharePoint site that you chose for the project.

Important
In this scenario, you must use a developer subscription of SharePoint Online. Visual Studio makes use of the SharePoint side-loading feature for uploading and installing the app, and this feature is only available in developer subscriptions.

You must sign in to <site name>.sharepoint.com as the administrator for the site. For example, the URL for the team site for an Office 365 developer site is https://<site name>.sharepoint.com/_layouts/15/start.aspx#/SitePages/DevHome.aspx. The .app file that was built by Visual Studio is added to the Apps in Testing section. When you choose the app, you are directed to the Microsoft Dynamics NAV Web client, and you are signed in automatically.

Adding an App from the App Catalog

You can also choose to only publish the project in Visual Studio. Then, you must manually deploy the app file that that Visual Studio builds to SharePoint’s App Catalog. From the app catalog, the app can be added to any site that is part of your SharePoint organization.

If the SharePoint site has subsites, you can deploy the app to the subsites, or you can let users add the app manually, provided they have permission to add apps to their site. If you upload the Microsoft Dynamics NAV app to the App Catalog, it is automatically available for users to install when they browse apps under From Your Organization. When the app has been installed, users can choose the app and be directed to the Microsoft Dynamics NAV Web client where they are signed in automatically.

If you want to preconfigure your users’ sites, you can deploy the app to one or more site templates. For more information, see the Deploy a custom app section in Use the App Catalog to make custom business apps available for the SharePoint Online environment in the SharePoint Online admin center.

In both cases, you can provide the users with SharePoint sites that give them access to view and modify Microsoft Dynamics NAV data and any other information that you want them to have access to. You can choose to combine this with the document library functionality in SharePoint so that documents that are exported from Microsoft Dynamics NAV are stored on the SharePoint site. For more information, see Integrating with Office 365 and SharePoint Online.

See Also

Integrating with Office 365 and SharePoint Online

Tasks

How to: Configure SSL to Secure the Connection to Microsoft Dynamics NAV Web Client
Troubleshooting: Microsoft Dynamics NAV and SharePoint

Concepts

Authenticating Users with Azure Active Directory
Integrating Microsoft Dynamics NAV in SharePoint Sites
Embedding Microsoft Dynamics NAV Web Client Pages in Other Websites

Other Resources

Select an Office 365 plan for business
How to: Create a basic provider-hosted app
Use the App Catalog to make custom business apps available for your SharePoint Online environment


Troubleshooting: Microsoft Dynamics NAV and SharePoint

When you deploy a solution where Microsoft Dynamics NAV is embedded in web parts in SharePoint, users can experience unexpected problems when they access the Microsoft Dynamics NAV Web client. This topic describes some common problems that you may encounter.

Multiple sessions used when a user accesses the Microsoft Dynamics NAV Web client in full-screen mode and in embedded mode

The Microsoft Dynamics NAV Web client uses cookies to store session-related information on the client machine. In some scenarios, Internet Explorer assigns different security zones to the Microsoft Dynamics NAV Web client depending on how the Microsoft Dynamics NAV Web client is accessed, which impacts how the cookies are stored.

If you deploy the Microsoft Dynamics NAV Web client on an intranet machine, and you access the Microsoft Dynamics NAV Web client in full-screen mode, such as if you open the Microsoft Dynamics NAV Web client directly in a browser, Internet Explorer applies the Local Intranet security zone to the website and stores the cookie at a more trusted integrity level. In contrast, if the Microsoft Dynamics NAV Web client is embedded in an IFRAME element in a web part in SharePoint Online, Internet Explorer considers both SharePoint Online and the Microsoft Dynamics NAV Web client to be in the Internet zone. The two security zones, Internet and Local Intranet, do not share the same cookie store, and as a result, the Microsoft Dynamics NAV Web client will initiate two separate sessions.

For example, a user opens a SharePoint Online site, such as https://Fabrikam.SharePoint.com/Financials, in Internet Explorer. This website has the Microsoft Dynamics NAV Web client embedded in web parts with IFRAME elements that access the Microsoft Dynamics NAV Web client at https://MyLocalServer/NAV. When the user accesses the page with the web part, the Microsoft Dynamics NAV Web client starts a new session. Then, when the user chooses one of the web parts to access the Microsoft Dynamics NAV Web client in full-screen mode, the Microsoft Dynamics NAV Web client starts a new session.

Resolution

Make sure all websites that the user accesses as part of your Microsoft Dynamics NAV deployment are placed in the same security zone by Internet Explorer.

For example, configure your deployment to always use public domain names for Microsoft Dynamics NAV Web Server components and SharePoint. Alternatively, if your deployment uses SharePoint on-premises, you can choose to configure the deployment to use local names.

However, if you work in a mixed environment where a local Microsoft Dynamics NAV Web Server components instance is used with SharePoint Online, you may experience problems with multiple Microsoft Dynamics NAV sessions starting for the same user. This is caused by the security zones and integrity levels that Internet Explorer applies to websites and web applications.

Modal dialog windows do not display when the Microsoft Dynamics NAV Web client is embedded in a web part

When the Microsoft Dynamics NAV Web client is embedded in a SharePoint site, modal dialog windows do not display. In some scenarios, Internet Explorer will attempt to open the modal dialog window in a new session.

Resolution

If you are going to embed a page in a SharePoint site, make sure that it does not open modal dialog windows.

Note
If you use the CRONUS International Ltd. demonstration database for test purposes, you must disable the modal dialog window that displays when the CRONUS International Ltd. company opens.

Users cannot access the Microsoft Dynamics NAV Web Client from SharePoint web parts with Microsoft Azure Active Directory or Azure Access Control services authentication for SharePoint on-premises

In SharePoint on-premises deployments, if you use Azure AD or Access Control services (ACS) as the authentication mechanism, users cannot access an embedded Microsoft Dynamics NAV Web client. If the Microsoft Dynamics NAV Web client is embedded in an IFRAME element in a web part, the authentication requires a login dialog to open inside the IFRAME element in the web part. This is not possible.

Resolution

If your app for SharePoint embeds the Microsoft Dynamics NAV Web client in a web part, use Windows authentication for SharePoint on-premises deployments.

Alternatively, if you must deploy to SharePoint on-premises and cannot use Windows authentication, design your app for SharePoint so that it opens the Microsoft Dynamics NAV Web client in full screen mode.

See Also

Concepts

Integrating Microsoft Dynamics NAV in SharePoint Sites
Developing and Installing a Microsoft Dynamics NAV Apps for SharePoint


Security and Protection

Microsoft Dynamics NAV Documentation
Security and Protection

An enterprise business solution must have a built-in security system that helps protect your database and the information that it contains from unauthorized access. It must also allow you to specify what authorized users are allowed to do in the database, such as what data they can read and modify.

Microsoft Dynamics NAV 2016 provides a security system that allows administrators to manage user access to the objects and data in the Microsoft Dynamics NAV database. Because the Microsoft Dynamics NAV database is on SQL Server, the Microsoft Dynamics NAV security system and SQL Server security system work together to help ensure that only authorized users can gain access to the Microsoft Dynamics NAV database.

Much additional information relating to security can be found in the Administration in the Clients node under Administration. See in particular:

  • Managing Users

  • About Permissions

  • Managing Permissions and Permission Sets

  • Profiles and Role Centers

In This Section

Security Overview

Enhancing Microsoft Dynamics NAV Server Security

Security Considerations

Microsoft Dynamics Online Connect

Customizing Security

Data Security

Business Areas and Granules


Security Overview

Microsoft Dynamics NAV Documentation
Security Overview
See Also

You can use the following table as a checklist to help set up a more secure Microsoft Dynamics NAV environment.

To | See
Install Microsoft Dynamics NAV software. | You must make decisions about where you install Microsoft Dynamics NAV components. Working with Microsoft Dynamics NAV Setup
Activate your Microsoft Dynamics NAV license. | How to: Upload the License File
Create users. | How to: Create Microsoft Dynamics NAV Users
Assign users to permission sets. | How to: Define Permissions for Users
Configure Role Centers. | Working with Role Centers
Assign users to profiles. | How to: Assign a User to a Profile

See Also

Concepts

Security and Protection
Enhancing Microsoft Dynamics NAV Server Security


Enhancing Microsoft Dynamics NAV Server Security

Microsoft Dynamics NAV Documentation
Enhancing Microsoft Dynamics NAV Server Security
See Also

Microsoft Dynamics NAV Server is a .NET-based Windows Service application that works exclusively with SQL Server databases. Microsoft Dynamics NAV Server provides an additional layer of security between clients and the database. It leverages the authentication features of the Windows Communications Framework to provide another layer of user authentication and uses impersonation to ensure that business logic is executed in a process that has been instantiated by the user who submitted the request. This means that authorization and logging of user requests are performed on a per-user basis.

Login Account

After you install Microsoft Dynamics NAV Server, the default configuration is for the service to log on using the NT Authority\Network Service account. If Microsoft Dynamics NAV Server and SQL Server are on different computers, then we recommend that you configure Microsoft Dynamics NAV Server to log on using a dedicated Windows domain user account instead. This account should not be an administrator either in the domain or on any local computer. A dedicated domain user account is considered more secure because no other services and therefore no other users have permissions for this account.

Disk Quotas

Client users can send files to be stored on Microsoft Dynamics NAV Server, so we recommend that administrators set up disk quotas on all computers running Microsoft Dynamics NAV Server. This can prevent users from uploading too many files, which can make the server unstable. Disk quotas track and control disk space usage for NTFS volumes, which allows administrators to control the amount of data that each user can store on a specific NTFS volume. For more information about disk quotas, see the Disk Quotas Technical Reference on Microsoft TechNet.

Limiting Port Access

The Microsoft Dynamics NAV Setup program opens a port in the firewall on the computer where you install Microsoft Dynamics NAV Server. By default, this is port 7046. To improve security, you can consider limiting access to this port to a specific subnet. One way is to use netsh, which is a command-line tool for configuring and monitoring Windows-based computers at a command prompt. The specific version of this command that you would use is netsh firewall set portopening. For example, the following command limits access to port 7046 to the specified addresses and subnets:

Copy Code
netsh firewall set portopening protocol=TCP port=7046 scope=subnet addresses=LocalSubnet

See Also

Tasks

Walkthrough: Installing the Three Tiers on Three Computers

Concepts

Configuring Microsoft Dynamics NAV Server
Security Overview

Other Resources

How to Use the Netsh.exe Tool and Command-Line Switches


Security Considerations

Microsoft Dynamics NAV Documentation
Security Considerations
See Also

The following list contains some important things to consider when setting up your Microsoft Dynamics NAV security system.

  • The Microsoft Dynamics NAV security system is initiated when you create the first login. Until you create the first login, any user can have full access to carry out any transaction in a Microsoft Dynamics NAV database. Therefore, the first login that you create must be a superuser (that is, should be assigned the SUPER permission set). The superuser must own and administer all access to the database from within Microsoft Dynamics NAV. We recommend that the user who administers security in Microsoft Dynamics NAV be a superuser.

  • One of the first things that the superuser should do is create logins for the other users that will have access to the database and grant them the appropriate permissions.

  • In Microsoft Dynamics NAV, a table can contain a FlowField, which generates sums based on values that are stored in another table. When using a FlowField, a user must have permission to read both tables or they will not be allowed to read the first table.

See Also

Concepts

Security and Protection
Security Overview


Microsoft Dynamics Online Connect

Microsoft Dynamics NAV Documentation
Microsoft Dynamics Online Connect
See Also

If your installation includes both the Microsoft Dynamics NAV Windows client and the CRONUS International Ltd. demonstration database, then you have the option of offering Microsoft Dynamics Online Connect to client users. Microsoft Dynamics Online Connect is a Web service that displays Microsoft Dynamics product and business information from online sources such as CustomerSource and the Microsoft Dynamics online community and provides links into those online sources. The actual list of links is customized for each Role Center.

Microsoft Dynamics Online Connect is displayed by default on some Role Centers, can be configured to be displayed on most other Role Centers, and is unavailable on a few Role Centers. See How to: Include Microsoft Dynamics Online Connect on Role Centers for information on which Role Centers offer Microsoft Dynamics Online Connect, and for information on how to configure Role Centers to either include or exclude Microsoft Dynamics Online Connect.

Security Consideration for Microsoft Dynamics Online Connect

Microsoft Dynamics Online Connect sends the following information about the Microsoft Dynamics NAV software over the Internet to Microsoft:

  • Product name

  • Product version

  • Some license information, but not the license number

  • Country/region version

  • Language

  • Profile, which is based on the Role Center ID

No other information is sent.

Internet Access

If you decide to make Microsoft Dynamics Online Connect available to users, then they will require Internet access to use the service. If you have not previously offered Internet access to users, then you should consider the security implications before implementing Microsoft Dynamics Online Connect.

See Also

Concepts

Security and Protection


Customizing Security

Microsoft Dynamics NAV Documentation
Customizing Security
See Also

Microsoft Dynamics NAV 2016 provides options for limiting and monitoring user access to the database.

Security Customization Options

Use the following options to limit user access beyond the permission level:

Limiting Access to Specific Database Entries

You can specify that each individual user or group can only access specific entries in the database. For example, you can limit access to the entries that relate to a specific department or project. This level of access control is known as record level security.

Time-Limited Passwords

Passwords in Microsoft Dynamics NAV do not have time limits, but you can put time limits on user IDs.

If you have the required permissions, then you can delete a user ID from the system or cancel all permissions. If deleting a user ID is too drastic a step to take, then you can specify a limited time period during which a particular user ID is allowed to post in the system. You set up this limitation in the User Setup window. For more information, see How to: Set Up User Time Constraints.

Customizing Password Requirements

Codeunit 9801, Identity Management, contains a function ValidateKeyStrength that you can modify to customize the requirements for user passwords. You can, for example, change the minimum length required (the default is eight characters) or specify whether uppercase, lowercase, or numeric characters are required.

Registering User Time

You can specify that you want Microsoft Dynamics NAV to register the amount of time that each user works with a company in the database.

To register user time, use the User Setup window. In the RoleTailored client, search for or navigate to the User Setup page.

To see the time use that has been registered, search for or navigate to the Time Registers page.

Default and Fixed Printer Selections

You can specify which printer that each individual user can use. In the RoleTailored client, search for or navigate to the Printer Selections page.

See Also

Administration in the Clients

Tasks

How to: Set Up User Time Constraints


Data Security

Microsoft Dynamics NAV Documentation
Data Security
See Also

The Microsoft Dynamics NAV security system allows you to control which objects or tables a user can access within each database. You can specify the type of access that each user has to these objects and tables, whether they are able to read, modify, or enter data.

The Microsoft Dynamics NAV Security System

You can specify which records are stored in the tables that each user is allowed to access. This means that permissions can be allocated at both the table level and the record level.

The security system contains information about the permissions that have been granted to each user who can access a particular database.

This information includes the roles that the users have been assigned, as well as any permissions that they have been granted to individual users.

There are four different levels of security:

  • Database

  • Company

  • Object

  • Record

Graphically, these can be represented as the layers, where the central layer is the records in the database.

See Also

Concepts

Database-Level Security
Users and Credential Types
Database Logins
Company-Level Security
Object-Level Security
Permissions on Database Objects
Record-Level Security
Security Considerations


Database-Level Security

The first layer of security when you open Microsoft Dynamics NAV is database security.

Database-Level Security

After you start Microsoft Dynamics NAV and attempt to open the database, your credentials are checked. If you have not been granted permission to open the database then the database is not listed in the Available Databases window. For more information about granting a user permission to create or work with a Microsoft Dynamics NAV database, see Setting Database Owner and Security Administration Permissions.

For more information about how to open a database, see How to: Open Databases.

See Also

Tasks

How to: Create Databases

Reference

Open Database
New Database

Concepts

Data Security


Company-Level Security

Microsoft Dynamics NAV Documentation
Company-Level Security
See Also

After you have gained access to the database, you can open the company that you want to work with.

Opening a Company

Use the Microsoft Dynamics NAV Windows client to open a company. For more information, see How to: Select a Company. The Select Company window lists all of the companies that have been created in the current database and that you have been given permission to access. A Microsoft Dynamics NAV database can contain several companies. Each company can use its own tables and can also share tables with other companies.

Select the company that you want to open, choose OK, and the company opens. If there are companies in the database that you have not been given permissions to access, you will not be able to see them in this window.

Managing User Access to Companies

When you assign a permission set to a user, you can specify a company to restrict the user’s access for that permission set to that specific company. For more information, see How to: Define Permissions for Users.

See Also

Concepts

Data Security
Business Areas and Granules
Object-Level Security


Object-Level Security

When you open a company in Microsoft Dynamics NAV, your ability to access information is determined by the security system.

Object-Level Security

Object-level security is the set of permissions on Microsoft Dynamics NAV objects that constitute a permission set. Permission sets determine the access that users have and the tasks that users can perform on objects in the database.

Security System Database Objects

You can define permissions for all types of objects in a Microsoft Dynamics NAV database.

Object Type | Description
Table Data | The actual data that is stored in the tables.
Table | The tables themselves.
Pages | The pages that are used to view and enter data.
Report | The reports that are used to present the data.
Codeunit | The codeunits that are used in the database.
XMLport | The XMLports that are used to import and export data.
MenuSuite | The object that contains the menus that are displayed in the navigation pane.
Query | The object that you use to specify a dataset from the database.
System | The system tables in the database that allow the user to make backups, change license files, and so on.

The various permission sets that exist in Microsoft Dynamics NAV determine the actions that you can perform on these objects. For more information about permissions, see Permissions on Database Objects.

See Also

Concepts

Data Security
Business Areas and Granules
Permissions on Database Objects


Record-Level Security

Microsoft Dynamics NAV Documentation
Record-Level Security
See Also

Record-level security lets you limit the access that a user has to the data in a table.

You implement record-level security in Microsoft Dynamics NAV by creating security filters on table data. A security filter describes a set of records in a table that a user has permission to access. You can specify, for example, that a user can only read the records that contain information about a particular customer. This means that the user cannot access the records that contain information about other customers. For more information, see How to: Set Security Filters.

Setting Security Filtering Modes

When you create security filters, you limit a user's access to data in a table. Therefore, code that requires access to all data in a table fails and the user receives an error message.

You can resolve potential conflicts with security filters and specify the desired behavior by setting the security filtering mode on Record variables to determine how the security filters are applied. For more information, see Security Filter Modes.

Performance

Record-level security filters are handled by SQL Server just like other filters that are applied by the user. They do not adversely affect performance unless the security filtering mode is Validated. When the security filtering mode for a record is Validated, then Microsoft Dynamics NAV must validate whether each record is in the filter expression.

See Also

Concepts

Data Security


How to: Set Security Filters

Microsoft Dynamics NAV Documentation
How to: Set Security Filters
See Also

You set security filters to limit the access that a user has to data in a table. You set security filters on permission sets, which you assign to users. For more information, see Managing Permissions and Permission Sets.

To set a security filter

  1. In the Search box, enter Permission Sets, and then choose the related link.

  2. On the Permission Sets page, select the permission set to which you want to add a security filter, and then choose Permissions.

  3. On the Permissions page, on the row for the table data to which you want to add a security filter, in the Security Filter column, choose the AssistEdit button.

    The Table Filter page opens.

  4. In the Table Filter page, in the Field Number column, select the field on which you want to limit a user's access. For example, if you want to create a security filter so that a user can view only sales with a specific salesperson code, then choose the field number for the Salesperson Code field.

    The Field Caption column in the Table Filter page is filled in automatically after you select the field number.

  5. In the Field Filter column, enter the value of field that you want to use to limit access. For example, to limit a user's access to only Annette Hill's sales, enter AH, which is the salesperson code for Annette Hill, in the Field Filter column.

    Note
    Record level security filters do not support wildcard characters. This means that you cannot use * and ? in the filters. You can use other symbols, delimiters and, operators, such as, <, >, |, &, .., and =. If you do not enter an operator, then the default operator = is used.

    Note
    Security filters support Unicode characters. The maximum length of a security filter is 200 characters, including all field names, delimiters, symbols, and operators that used in the filter.

    Note
    When multiple permission sets that refer to the same table data are assigned to a user, they are combined so that the least restrictive filter is used. You should not repeat a table in multiple permission sets if you plan to combine those permissions sets for one user.

See Also

Concepts

Record-Level Security
Security Filter Modes


Security Filter Modes

Microsoft Dynamics NAV Documentation
Security Filter Modes
See Also

Query objects and Record objects, including both explicit record variables and implicit records on pages, reports, or XMLports, have a property named SecurityFiltering, which describes how security filters are applied. The possible values of the SecurityFiltering property are:

  • Filtered

  • Validated

  • Ignored

  • Disallowed

Filtered

If a record is set to Filtered, then any security filters that have been set are respected for this instance of the record. To the user, it is as if records outside the security filters that do not exist.

An example scenario in which you use the Filtered value is that one salesperson is not allowed to view customers, sales quotes, or sales orders that belong to another salesperson. When the salesperson opens a list of customers or sales documents, or runs reports such as the Customer - Top 10 List report, he sees his filtered view of customers, sales quotes, and sales orders.

Validated

If a record is set to Validated, then any security filters that have been set are respected for this instance of the record, and an error occurs if the code attempts to access a record that is outside the range of the security filters.

An example scenario in which you use the Validated value is that one parts purchaser in a warehouse is responsible for only one location and can view and create purchase orders for only that location. However, some purchase orders have lines for multiple locations. Only a parts purchaser who has access to all locations should be allowed to post these purchase orders that have lines for multiple locations. All other purchasers receive an error.

If security filters have been set, then the Validated value decreases performance. For more information, see Performance Impact of Security Filtering Mode.

The Validated value is used mainly for compatibility with the security model in earlier versions of Microsoft Dynamics NAV. We recommend that you use the other modes when you implement your security model.

Ignored

If a record is set to Ignored, then any security filters that have been set are ignored for this instance of the record.

An example scenario in which you use the Ignored value is that one salesperson is not allowed to view customers, sales quotes, or sales orders that belong to another salesperson. However, to post her sales orders, the salesperson must have access to all entries in the Customer Ledger Entry table so that the posting algorithm can find the last sales order entry number and generate the correct number for the next entry. In the code that posts sales orders, you set the SecurityFiltering property of the record variable to Ignored, but for record variables in other parts of the code, you set the SecurityFiltering property to either Filtered or Validated.

When you set the SecurityFiltering property on a record to Ignored, the administrator who sets a security filter is not informed that the security filter will be ignored. You must be careful when you set the SecurityFiltering property that it does not cause unintended information disclosure.

Disallowed

If a record is set to Disallowed, then setting any security filter on the record causes an error.

An example scenario in which you use the Disallowed value is that you have batch jobs that must be run only by users who have access to all records in the related tables, otherwise the batch jobs can cause incorrect and potentially harmful results. The partner developer sets record variables on these batch jobs to Disallowed so that a user who does not have access to all records in the related tables receives an error.

Default Values

The following table shows the default values of the SecurityFiltering property.

 | Explicit record variables | Explicit query variables | Implicit records on pages, reports, and XMLports
Upgraded from Microsoft Dynamics NAV 2009 | Validated | N/A | Filtered
New | Validated | Filtered | Filtered
Important
It is not supported to change the default Filtered value of the SecurityFiltering property on implicit records on pages.

If you keep the default values after you upgrade from Microsoft Dynamics NAV 2009 to Microsoft Dynamics NAV 2016, then the behavior is the same in all cases except the following:

  • In earlier versions, the COUNT Function (Record) ignored security filters and always returned the total number of records unless you called the SETPERMISSIONFILTER function to get a filtered count. In Microsoft Dynamics NAV 2016, the COUNT function adheres to the SecurityFiltering property.

  • In earlier versions, on a page, you could modify or insert a record outside of the range of your security filters but in Microsoft Dynamics NAV 2016, you cannot.

Note
For Query variables, the Validated value of the SecurityFiltering property is not allowed.

Security Filters and FlowFields

If you set a security filter on a table that is used in a FlowField calculation, then the calculated value of the FlowField is filtered, based on the security filter and the security filter mode of the record variable for the record in the table. For example, if you set a security filter so that a user can only view sales with a specific salesperson code, and if the security filter mode is Filtered, then when the user views a FlowField that calculates total sales, the user can see the total of only those sales that have the specific salesperson code. In earlier versions of Microsoft Dynamics NAV, the security filter mode value was Validated and in this example, the user received an error.

Programming Examples

For these examples, you have a table that has 100 records. Each record has an ID field that is the primary key of the table. The values of the ID field that are currently in the database range from 1 to 100. In this example, you set a security filter on the table data for ID=1..50. Then, in a codeunit you create a record variable for the table.

Security filter mode Example

Filtered

If you set the SecurityFiltering property on the record variable to Filtered, then the code behaves as if records with ID values from 1 to 50 are the only records that exist. If you call the FIND, FINDFIRST, FINDLAST, or FINDSET function on the record variable without any additional filters besides the security filter, then the function only finds records with ID values from 1 to 50. If you call the DELETEALL function, then it successfully deletes records with ID values from 1 to 50. It does not delete records with ID values greater than 50, and it does not return an error. If you modify a record, for example, by calling the MODIFY function on a record with an ID value less than 50, then the function succeeds. If you call the MODIFY function on a record with an ID value greater than 50, then it fails because you do not have access to the record. If you insert a record with an ID less than 50 and the record does not already exist, the INSERT function succeeds. If you insert a record with an ID greater than 50 and the record does not already exist, it fails because you do not have access to the record. If you call the GET function on a record with an ID value less than 50, then the function succeeds. If you call the GET function on a record with an ID value greater than 50, then it fails.

Validated

If you set the SecurityFiltering property on the record variable to Validated, then the code behaves as if records with ID values from 1 to 100 exist, but you only have access to the records that are specified by the security filter. If you call the FIND, FINDFIRST, FINDLAST, or FINDSET function on the record variable without additional filters, it finds all 100 records, but a NEXT function call to the record with ID value 51 fails because you do not have access to it. If you call the DELETEALL function, it fails because it finds all 100 records but you do not have access to all of them. If you modify a record with an ID value less than 50, it succeeds. If you modify a record with an ID value greater than 50, it fails. If you insert a record with an ID less than 50 and the record does not already exist, it succeeds. If you insert a record with an ID greater than 50 and the record does not already exist, it fails.

Ignored

If you set the SecurityFiltering property on the record variable to Ignored, then the code behaves as if all security filters that are set do not exist for that instance of the record. Any of the FIND functions find all 100 records. The DELETEALL function deletes all 100 records. You can insert and modify records in any range, regardless of security filters.

Disallowed

If you set the SecurityFiltering property on the record variable to Disallowed, then as long as a security filter is set on the record, any code that uses the record variable causes an error.

Performance Impact of Security Filtering Mode

If security filters are set on a table, then setting the SecurityFiltering property to Validated on a record instance of that table causes a decrease in performance. The Microsoft Dynamics NAV Server must go through every record in the table to validate the record instead of adding the filters to the query that is sent to SQL Server.

If security filters are not set, then setting the SecurityFiltering property to Validated has no performance impact.

Note
We recommend that you change commonly used record variables from the default value of Validated to either Filtered or Ignored to improve performance.

See Also

Tasks

How to: Set Security Filters

Reference

SecurityFiltering Property

Concepts

Record-Level Security


Database Logins

Microsoft Dynamics NAV Documentation
Database Logins
See Also

Users are given a database login when they have their own user ID and password in Microsoft Dynamics NAV. The user must enter the user ID and password to access the database.

Note
Database logins are only valid for connecting to the database from the Microsoft Dynamics NAV Development Environment.

How Database Logins Work

Users must also have a login on SQL Server. SQL Server has its own authentication of the user’s ID and password. SQL Server does this by checking whether a SQL Server login with this user’s ID and password has been created.

This login must first be created by a SQL Server administrator, with a SQL Server tool. If a SQL Server login has not been set up, authentication fails and the user receives an error. For more information, see Setting Database Owner and Security Administration Permissions.

The user is granted access to the server after his login has been authenticated. Database security then validates the user’s permissions by checking the database user accounts on the server. The permissions that the user has been granted to the various objects within the database, such as tables, are determined by the information contained in the user’s database user account. This account also contains information about any additional permissions that the user may have been granted to alter the database itself.

See Also

Concepts

Security and Protection
Users and Credential Types
Company-Level Security


Permissions on Database Objects

Microsoft Dynamics NAV Documentation
Permissions on Database Objects
See Also

This section provides an overview of permissions and permission sets in Microsoft Dynamics NAV 2016

Permissions

If you have been granted permission to read a page, then you can open the page and view the data that it displays. If, however, you do not have write permission, you are not allowed to enter data into this page.

Sometimes, when you open a page it displays information from several tables. To access this page, you must have permission to view all the data displayed by the page. You might not have permission to read directly from all the tables that the page uses. In this case, you must have indirect permission to read from the tables in question. Having indirect permission to a table means that you cannot open the table and read from it but can only view the data it contains indirectly through another object, such as a page or report, that you have direct permission to access.

Microsoft Dynamics NAV has a number of standard predefined security permission sets. You can use these permission sets as defined or you can change a permission sets to suit your particular needs. You can also create your own permission sets and assign them the permissions that you want.

Permissions on Objects

Permission | Description
Read | You can read this object.
Insert | You can insert data into this object.
Modify | You can modify data in this object.
Delete | You can delete data from this object.
Execute | You can run this object.

See Also

Concepts

Data Security
Business Areas and Granules
Record-Level Security


Business Areas and Granules

Microsoft Dynamics NAV contains business areas. You can control how the license file controls the access that you have to these business areas and the functionality that they contain.

Business Areas and Granules

The standard Microsoft Dynamics NAV application is divided into several business areas. Each business area consists of a number of functional areas. These functional areas contain functionality; however different customers might only need some of the functionality that is provided. To facilitate this, a Microsoft Dynamics NAV license file contains a number of granules. Each granule represents a small area of functionality.

This system makes it possible for each customer to purchase a license that only gives the company and the company's employees access to exactly the functionality needed.

See Also

Concepts

Business Areas and Functional Areas
Granules Available in the General Ledger


Business Areas and Functional Areas

Microsoft Dynamics NAV is divided into several business areas. Each business area consists of a number of functional areas.

Business Areas and Functional Areas

The following table shows all of the business areas and functional areas. Each functional area represents an important field of activity.

Business areas | Functional areas
Finance Management | Cash Management Fixed Assets General Ledger Inventory Payables Receivables
Sales & Marketing Sales | Analysis & Reporting History Inventory & Pricing Marketing Order Processing
Purchase | Analysis & Reporting History Inventory & Costing Order Processing Planning
Warehouse | Goods Handling History Inventory Orders & Contacts Planning & Education
Manufacturing | Capacities Costing Execution History Planning Product Design
Jobs | History Jobs Periodic Activities Reports
Resource Planning | History Periodic Activities Reports Resources
Service | Contact Management History Order Processing Planning & Dispatching
Human Resources | Absence Registration Employees Reports
IT Administrator | Application Setup IT Administration

See Also

Concepts

Granules Available in the General Ledger


Granules Available in the General Ledger

This topic contains a list of granules that are available in the General Ledger. The information in the table below does not necessarily correspond with the granule definition that is currently enforced by Microsoft Dynamics NAV.

Each of the other functional areas can be similarly broken down into areas of more specific functionality. This means that your license file and the way that it is configured have an important influence on the functionality that is available to you in Microsoft Dynamics NAV. Your license file and the granules that it contains determine which functional areas you have access to and which functions you can perform in these areas. The advantage of this system is that the customer does not pay for a general license to run the product but only pays for the granules that they need to run their business.

Granules Available in the General Ledger

The following table lists the granules that are available in the General Ledger.

Granule name and number Description

Basic General Ledger (3,010)

You use this granule to set up a company and post to the general ledger.

This granule provides you with the basic features necessary for setting up a company and posting to the general ledger, chart of accounts, general journals, VAT facilities, recurring journals, and source codes. It also includes features for internal and external reporting.

This granule allows you to post and report in the company's base currency. If you also purchase the Multiple Currencies granule, you can post and report in an additional currency.

This granule allows you to use two languages—the U.S. English language and the native language for the particular country/region.

This granule must always be included as part of the initial purchase of Microsoft Dynamics NAV because it includes one session and the first company.

Requirements: Microsoft Dynamics NAV Version 3.XX

Budgets (3,030)

This granule allows you to work with budgets in general ledger accounts.

After you have created a budget, you can print a balance compared to the budget, which shows variances by percentages. Budgets are normally entered per period for the relevant general ledger accounts. You can create, copy, and work with any number of budgets at the same time. You can work with, for example, a 100% budget, a 110% budget, and so on.

Requirements: Basic General Ledger

Account Schedules (3,040)

You use this granule for financial reporting. You can arrange reports based on the figures in the chart of accounts and budgets, but with a different arrangement for financial figures, text, or details than in the chart of accounts. The Account Schedules granule is like a filter for the chart of accounts that enables you to choose the accounts that you want to include. You can also use it to change the order of the accounts or combine the figures in various ways, and set up which columns to print. In addition, it is possible to make simple calculations.

Requirements: Basic General Ledger

Consolidation (3,050)

This granule enables you to consolidate companies in Microsoft Dynamics NAV.

The companies can come from one or from several different Microsoft Dynamics NAV databases or from another type of file. You can import and export financial information in this granule. If the data is retrieved from several Microsoft Dynamics NAV solutions, the granule is only used in the parent company itself.

Requirements: Basic General Ledger

Allocations (3,020)

This granule allows you to allocate general ledger entries so you can have combinations of accounts, departments, and projects using allocation keys.

The allocation keys can be based on amount, percentage, or quantity.

Allocations can be used for many purposes, for example, to allocate overhead, such as rent, to company profit centers.

Requirements: Basic General Ledger

Responsibility Centers (3,060)

With this granule you can setup profit centers and cost centers. A company can sell items with specific prices and related to a responsibility center. This granule enables you to associate a user to a responsibility center so that only sales and purchase documents related to the particular user are displayed. In addition, users get assistance when entering extra data, such as dimensions and location codes.

Requirements: Multiple Locations

Basic XBRL (3,070)

With this granule you can export documents from Microsoft Dynamics NAV in XBRL format and import XBRL taxonomies into Microsoft Dynamics NAV from the Internet, e-mail, or from other systems. XBRL is an XML-based specification that uses accepted financial reporting standards based on standardized, underlying data tags. It is possible to map your general ledger to XBRL taxonomies, meaning that the same XBRL instance document can be used for various purposes, independent of the format required by the receiver of the document.

Requirements: Basic General Ledger

Change Log (3,080)

This granule enables you to log user changes made to Microsoft Dynamics NAV master data.

It is possible to log all direct modifications that a user makes to the data in the database, except changes to 'working documents' such as journals, sales orders, and purchase orders. The change log functionality makes it possible to get a chronological list of all changes to any field in any table and to see who (what user ID) made the changes.

Requirements: Basic General Ledger

See Also

Concepts

Business Areas and Functional Areas


Technical Reference

This section provides reference information for Microsoft Dynamics NAV objects. For more reference information, see C/SIDE Reference Guide.

See Also

Reference

Object Specifications and Limitations

Concepts

C/SIDE Reference Guide
Development Environment (C/SIDE)
Development Environment Commands
Window Overviews

Other Resources

Special Tables


C/SIDE Reference Guide

The topics in this section contain help on all functions, data types, properties, and triggers in Microsoft Dynamics NAV. They also provide general descriptions of some of the features and functionality that Microsoft Dynamics NAV supports.

In the Table of Contents, all C/AL Functions are grouped alphabetically according to the data type that they support or according to a category. Each data type topic contains a description of the data type.

Properties and Triggers are also listed alphabetically.

For more information about the Microsoft Dynamics NAV Development Environment, see Development.

To ensure that you are reading the latest information and to find additional Microsoft Dynamics NAV 2016 documentation, see the MSDN Library. To download the latest version of the C/SIDE Reference Guide, see the Microsoft Download Center.

In This Section

  • C/AL Functions

  • Properties

  • Triggers

See Also

Concepts

Window Overviews
Development Environment Commands
Technical Reference


C/AL Functions

The C/AL functions in this section are grouped alphabetically according to the data type that they support or according to a category. Each data type topic contains a description of the data type.

See Also

Concepts

Properties
Triggers
Essential C/AL Functions
Programming in C/AL


Functions Not Supported by Microsoft Dynamics NAV Web Client

This topic lists the C/AL functions and data types that are not supported or partially supported by Microsoft Dynamics NAV Web client. For more information about partially supported functions, see the function topic in the reference section.

Unsupported Functions

This section lists the functions that are not supported by the Microsoft Dynamics NAV Web client. If you use a function that is not supported, an error occurs at runtime.

  • CREATE Function (Automation)

  • ISCLEAR Function (Automation)

  • ACTIVATE Function (Debugger)

  • UPDATE Function (Dialog)

Partially Supported Functions

This topic lists the functions that either do not have all the capabilities in the Microsoft Dynamics NAV Web client as they do in the Microsoft Dynamics NAV Windows client or they behave differently than in the Microsoft Dynamics NAV Windows client.

  • DOWNLOAD Function (File)

  • DOWNLOADFROMSTREAM Function (File)

  • HYPERLINK Function

  • PREVIEW Function (Report)

  • PRINTONLYIFDETAIL Function (Report)

  • REPORT.RUN Function

  • REPORT.RUNMODAL Function

  • UPLOAD Function (File)

  • UPLOADINTOSTREAM Function (File)


Automation Data Type

Use the Automation data type to reference an automation server.

To use an automation server in Microsoft Dynamics NAV

  1. Define a variable of type Automation and give it a name.

  2. Select the Subtype field, and in the Automation Object List window that opens, in the Automation Server field, get a list of available automation servers.

  3. Select a server and then choose the OK button.

    In the Automation Object List the interfaces of the selected automation server are displayed.

  4. Select an interface and then choose the OK button.

This procedure has selected the GUID of the automation server, the version number, and the GUID of the interface. It is immediately evaluated into a name such as <name of server>.<name of interface>, as in the following:

Copy Code
'Microsoft Excel X.0 Object Library'.Application

When you have defined an automation server as a variable, you must use CREATE Function (Automation) to create an instance of the server. After that, you can use the server through the variable. You can browse its methods and properties in the Symbol menu.

When you are using a server, you should know that there is not a one-to-one relationship between C/AL data types and COM data types. For an overview of the data type mapping, see Using COM Technologies in Microsoft Dynamics NAV.

If you use a variable of type Automation to automate Microsoft Excel and you run an English (United States) version of Excel but the regional settings for the computer are configured for a non-English language, then you will receive the following error:

Copy Code
Error: 0x80028018 (-2147647512)
Description: Old Format or Invalid Type Library

For more information, see Microsoft Help and Support article 320369: BUG: "Old format or invalid type library" error when automating Excel.

Limitations

  • Automation is not supported by Microsoft Dynamics NAV Web client.

  • Automation objects cannot run on Microsoft Dynamics NAV Server.

See Also

Reference

CREATE Function (Automation)
ISCLEAR Function (Automation)
Variant Data Type


CREATE Function (Automation)

Creates an Automation object.

[Ok :=] CREATE(Automation [,NewServer] [,OnClient])

Parameters

Automation

Type: Automation

A variable that has previously been declared.

NewServer

Type: Boolean

If NewServer is false, which is the default value, then the CREATE function tries to reuse an already running instance of the Automation server that is referenced by Automation before creating a new instance. If NewServer is true, then the CREATE function always creates a new instance of the Automation server.

OnClient

Type: Boolean

OnClient must evaluate to true. You can either set the parameter to true or define a Boolean type variable that evaluates to true. If variable evaluates to false, then you will see a run-time error.

Property Value/Return Value

Type: Boolean

true if the Automation object could be created; otherwise, false.

If the return value is not tested, then execution will end with a run-time error.

Supported Display Targets

Microsoft Dynamics NAV Windows client only

Remarks

Important
This function is not supported by the Microsoft Dynamics NAV Web client.

The CREATE function instantiates, or creates, the Automation server that is referenced by the Automation variable. An OCX, or a custom control, is instantiated implicitly, but Automation variables must be created explicitly.

If you have an array of OCXs, then each control is created when its first member is accessed.

If you have an array of Automation servers, then you have to call the CREATE function on each element individually. The NewServer variable can be used independently on each element.

The Automation object that is created can be explicitly destroyed by the CLEAR Function. The object is implicitly destroyed when the Automation variable goes out of scope.

An Automation variable can only be created one time. You will get a run-time error if you try to create an Automation variable again and do not call CLEAR first. You also get a run-time error if you try to create an OCX variable.

Example

The following example shows how you can use the CREATE function. This example requires that you create the following variables.

Name | DataType | Subtype
Document | Automation | 'Microsoft XML, V3.0'.DOMDocument
ReturnValue | Boolean | Not applicable
Copy Code
ReturnValue := CREATE(Document, FALSE, TRUE);

See Also

Reference

Automation Data Type


ISCLEAR Function (Automation)

Checks whether an Automation object has been created or cleared.

Ok := ISCLEAR(Automation)

Parameters

Automation

Type: Automation

A variable that has previously been declared.

Property Value/Return Value

Type: Boolean

true if any of the following is true; otherwise, false:

  • The Automation variable has not been created. See CREATE Function (Automation).

  • The Automation variable has been cleared. See CLEAR Function.

  • The Automation variable has been assigned NULL by an Automation server.

Remarks

This function is not supported in the Microsoft Dynamics NAV Web client.

Example

The following example shows how you can use the ISCLEAR function. This example requires that you create the following variables.

Name | DataType | Subtype
Document | Automation | 'Microsoft XML, V3.0'.DOMDocument
ReturnValue | Boolean | Not applicable
Copy Code
ReturnValue := ISCLEAR(Document);
// ReturnValue will be TRUE.
CREATE(Document);
ReturnValue := ISCLEAR(Document);
// ReturnValue will be FALSE.
CLEAR(Document);
ReturnValue := ISCLEAR(Document);
// ReturnValue will be TRUE.

See Also

Reference

Automation Data Type


BLOB Data Type

A binary large object (BLOB) is a complex data type. Variables of this data type differ from normal numeric and string variables in that BLOBs have a variable length.

The maximum size of a BLOB is 2 GB.

Remarks

Use BLOBs to store memos (text), pictures (bitmaps), or user-defined types.

Note
You cannot view text that is stored in BLOBs from the development environment.

You can read from and write to BLOBs by creating input and output streams, respectively. To do so, use CREATEINSTREAM Function (BLOB) and CREATEOUTSTREAM Function (BLOB).

For more information, see InStream and OutStream Data Types.

To optimize performance, when you access a record that has a BLOB field, the data in the BLOB is not always read into memory. You must call the CALCFIELDS Function (Record) to read the BLOB into memory and calculate it. Then you can use the BLOB in C/AL code or display it in the application.

It is not supported to insert a BLOB field into a Variant.

It is not supported for a page to access a BLOB field from a table other than the SourceTable of the page.

Differences Between Microsoft Dynamics NAV 2016 and Previous Versions

In previous versions of Microsoft Dynamics NAV, if you wrote to a BLOB OutStream but did not insert or modify the record in the database, and then called the CALCFIELDS function on the BLOB field, you would get the value of the BLOB based on what you wrote to the OutStream, not based on what was currently in the database. In Microsoft Dynamics NAV 2016 in the same scenario, you get the value of the BLOB that is in the database. Similarly, in Microsoft Dynamics NAV 2016 if you call the CALCFIELDS Function on a new record that has not been inserted into the database, then you clear the BLOB field from the record.

See Also

Reference

CREATEINSTREAM Function (BLOB)
CREATEOUTSTREAM Function (BLOB)
HASVALUE Function (BLOB)
Variant Data Type


CREATEINSTREAM Function (BLOB)

Creates an InStream object for a binary large object (BLOB). This enables you to read data from the BLOB.

Blob.CreateInStream(Stream[,TextEncoding.value])

Parameters

Blob

Type: Variable

The BLOB variable for which you are creating the InStream object.

Stream

Type: InStream

The InStream object type that has been created.

TextEncoding

Value: MsDos, UTF8, UTF16, or Windows

Optionally, you can specify the encoding on the stream. By specifying the text encoding, you ensure that all the language-specific characters are represented correctly in Microsoft Dynamics NAV when you read data and write data. The following example illustrates how you can set the encoding to Windows when you create a stream for a BLOB field.

Copy Code
MyTable.MyBLOBfield.CREATEINSTREAM(MyStream, TextEncoding.WINDOWS)
For more information, see Text Encoding.

See Also

Reference

BLOB Data Type
InStream and OutStream Data Types

Concepts

Text Encoding


CREATEOUTSTREAM Function (BLOB)

Creates an OutStream object for a binary large object (BLOB). This enables you to write data to the BLOB.

Blob.CreateOutStream(Stream [,TextEncoding.value])

Parameters

Blob

Type: Variable

The BLOB variable for which you are creating the OutStream object.

Stream

Type: OutStream

The OutStream object type that has been created.

TextEncoding

Value: MsDos, UTF8, UTF16, or Windows

Optionally, you can specify the encoding on the stream. By specifying the text encoding, you ensure that all the language-specific characters are represented correctly in Microsoft Dynamics NAV when you read data and write data. The following example illustrates how you can set the encoding to Windows when you create a stream for a BLOB field.

Copy Code
MyTable.MyBLOBfield.CREATEOUTSTREAM(MyStream, TextEncoding.WINDOWS)
For more information, see Text Encoding.

See Also

Tasks

How to: Use Streams to Write to Text Files

Reference

BLOB Data Type
InStream and OutStream Data Types

Concepts

Text Encoding


EXPORT Function (BLOB)

Exports a binary large object (BLOB).

[ExportName] := Blob.EXPORT([Name [, CommonDialog]])

Parameters

Blob

Type: Variable

The BLOB that you want to export.

Name

Type: Text or code

The path and name of the BLOB that you want to export.

When you enter the path, consider these shortcuts:

  • You can omit the drive letter if the command is located on the current drive.

  • You can omit the full path if the command is located in the current directory.

  • You can enter only the subdirectory name if the command is located in a subdirectory of the current directory.

CommonDialog

Type: Boolean

Specifies whether you want to display a dialog box before the BLOB is exported. This dialog box lets you select the file that you want to export. Based on the SubType Property (BLOB) property, only the appropriate file types are listed, such as bitmap files (*.bmp), memo files (*.txt), or all files (*.*).

If the CommonDialog parameter is true, Microsoft Dynamics NAV will display the confirmation dialog box. If the CommonDialog parameter is false (default), Microsoft Dynamics NAV will not display the confirmation dialog box.

Property Value/Return Value

Type: text

The name and path of the exported file.

If the return value is the file's name and path, then the BLOB was exported.

If the return value is an empty string, then the BLOB was not exported.

See Also

Reference

BLOB Data Type


HASVALUE Function (BLOB)

Determines whether a binary large object (BLOB) has a value.

HasValue := Blob.HASVALUE

Parameters

Blob

Type: BLOB

The BLOB that you want to check.

Property Value/Return Value

Type: Boolean

true if the BLOB has a value; otherwise, false.

See Also

Reference

BLOB Data Type


IMPORT Function (BLOB)

Imports a binary large object (BLOB).

[ImportName] := Blob.IMPORT([Name [, CommonDialog]])

Parameters

Blob

Type: Variable

The BLOB that you want to import.

Name

Type: Text or code

The path and name of the BLOB that you want to import.

When you enter the path, consider the following shortcuts:

  • You can omit the drive letter if the command is located on the current drive.

  • You can omit the full path if the command is located in the current directory.

  • You can enter only the subdirectory name if the command is located in a subdirectory of the current directory.

CommonDialog

Type: Boolean

Specifies whether you want to display an import dialog box before the BLOB is imported. This dialog box lets you select the file that you want to import. Based on the SubType Property (BLOB), only the relevant file types are listed, such as bitmap files (*.bmp), memo files (*.txt), or all files (*.*).

If the CommonDialog parameter is true, then Microsoft Dynamics NAV displays the import dialog box. If the CommonDialog parameter is false (default), then Microsoft Dynamics NAV does not display the import dialog box.

Property Value/Return Value

Type: text

The name and path of the imported file.

If the return value is the file's name and path, then the BLOB was imported.

If the return value is an empty string, then the BLOB was not imported.

See Also

Reference

BLOB Data Type


Boolean Data Type

Indicates true or false.

For usability reasons, Boolean values are sometimes shown as Yes or No. For example, the two possible values for the InsertAllowed page property are Yes and No.

Note
The values that are shown are based on the regional format that is set on the computer. For example, on a computer that has the regional format set to Danish (Denmark), the Boolean values are shown as Ja and Nej instead of Yes and No.

You can use the FORMAT Function (Code, Text) to specify how Boolean values are shown.


Byte Data Type

Use this simple data type to store a single, 8-bit character as a value in the range 0 to 255. You can easily convert this data type from a number to a character and vice versa. This means you can use mathematical operators on Byte variables.

Example

The following example assumes that you have a Byte variable named B and a Text variable named S.

You can assign a constant string of the length 1 to a Byte variable, as shown in the first line of the following code example.

You can assign a single character in a Text or Code variable to a Byte variable, as shown in the second line of the following code example.

You can assign a numeric value to a Byte variable, as shown in the third line of the following code example. This causes the Byte variable to contain the character from the ASCII character set that corresponds to the numeric ASCII code.

Copy Code
B := 'A';
B := S[2];
B := 65;

You cannot assign a character to a position greater than the position of the null terminator. For example, if the value of the text variable MyText is 'abc', then the null terminator is at position 4 and the following assignment causes a run-time error to occur.

Copy Code
MyText[5] := 'e';

See Also

Reference

Text Data Type
Code Data Type
Byte Data Type


Char Data Type

Use this simple data type to store a single, 16-bit character as a value in the range 0 to 65535. You can convert this data type from a number to a character and vice versa. This means you can use mathematical operators on Char variables.

Example

The following example assumes that you have a Char variable named C and a Text or Code variable named S.

You can assign a constant string of the length 1 to a Char variable, as shown in the first line of the following code example.

You can assign a single Char in a Text or Code variable to a Char variable, as shown in the second line of the following code example.

You can assign a numeric value to a Char variable, as shown in the third line of the following code example.

A Char variable represents Unicode characters in the same way as the .NET Framework Char structure. For more information about the .NET Framework Char structure, see Char Structure.

Copy Code
C := 'A';
C := S[2];
C := 65;

You cannot assign a Char to a position greater than the position of the null terminator. For example, if the value of the Text variable MyText is 'abc', then the null terminator is at position 4 and the following assignment causes a run-time error to occur.

Copy Code
MyText[5] := 'e';

See Also

Reference

Text Data Type
Code Data Type
Byte Data Type


Codeunit Data Type

Use this complex data type to store units of C/AL code. Codeunits contain a number of user-defined functions.

See Also

Reference

Codeunit.RUN Function (Codeunit)
RUN Function (Codeunit)


Codeunit.RUN Function (Codeunit)

Loads and executes the unit of C/AL code that you specify. See also RUN Function (Codeunit).

[Ok :=] Codeunit.RUN(Number[, Record])

Parameters

Number

Type: Integer

The ID of the codeunit to run. You can use the Symbols option on the View menu to select from a list.

You can specify the codeunit by name instead of by ID by using the following syntax:

Codeunit.RUN(CODEUNIT::"<codeunit name>", RecVariable)

If the codeunit that you specify does not exist, then a run-time error occurs.

If you run the codeunit with a record from a table other than the one it is associated with in the TableNo Property of the codeunit, then a run-time error occurs.

Record

Type: Record

Specifies a record from the table that is associated with the codeunit in the TableNo property.

Property Value/Return Value

Type: Boolean

If you do not include the optional return value and an error occurs when the codeunit is running, then the C/AL code that called this codeunit will end.

If you include the return value and an error occurs, then the calling C/AL code continues to run. This means that you must handle any errors.

true if no errors occurred; otherwise, false.

Example

The following example runs codeunit 15, Gen. Jnl.-Show Card by specifying the ID. This codeunit is associated with the Gen. Journal Line table. This example requires that you create the following variable in the C/AL Globals window.

Variable name | DataType | Subtype
GenJournalLine | Record | Gen. Journal Line
Copy Code
CODEUNIT.RUN(15,GenJournalLine);

Example

The following example runs codeunit 15, Gen. Jnl.-Show Card by specifying the name of the codeunit instead of the ID. This example requires that you create the following variable in the C/AL Globals window.

Variable name | DataType | Subtype
GenJournalLine | Record | Gen. Journal Line
Copy Code
CODEUNIT.RUN(CODEUNIT::"Gen. Jnl.-Show Card",GenJournalLine);

See Also

Reference

Codeunit Data Type


RUN Function (Codeunit)

Loads and executes the unit of C/AL code you specify. To use this function, you can specify a table associated with the codeunit when you defined the codeunit properties. This allows you to pass a variable with the function. The transaction that the codeunit contains is always committed due to the Boolean return value.

[Ok :=] Codeunit.RUN(VAR Record)

Parameters

Codeunit

Type: Codeunit

Identifies the codeunit that you want to run.

VAR Record

Type: Record

This parameter is not always optional. If you specify a table associated with the codeunit, then you can select a record. If you do not specify a table, then you cannot specify a record. However, you must use this parameter to select a record if you attached a record to the codeunit when you defined its properties.

This parameter is a record data type.

Property Value/Return Value

Type: Boolean

If you do not include the optional return value and an error occurs while the codeunit is running, then the C/AL code that called this codeunit will terminate.

If you include the return value and an error occurs, then the calling C/AL code continues to run. This means that you must handle any errors. If you include the return value, the variables used in the codeunit will be cleared before and after the codeunit runs.

true if no errors occurred; otherwise, false.

Example

This example runs two codeunits. The first uses a record parameter. The second is defined without a source table. This example requires that you create the following variables.

Variable name | DataType | Subtype
FiscalYearCloseInstance | Codeunit | Fiscal Year-Close
AppMgmtInstance | Codeunit | ApplicationManagement
AccountRecord | Record | Accounting Period
Copy Code
AccountRecord.INIT;
IF NOT FiscalYearCloseInstance.RUN(AccountRecord) THEN
  ERROR('Codeunit run failed (with record).');
IF NOT AppMgmtInstance.RUN THEN
  ERROR('Codeunit run failed.');

See Also

Reference

Codeunit Data Type


Database

This section contains the following topics:

  • CHECKLICENSEFILE Function (Database)

  • COMMIT Function (Database)

  • COMPANYNAME Function (Database)

  • COPYCOMPANY Function (Database)

  • CURRENTTRANSACTIONTYPE Function (Database)

  • DATAFILEINFORMATION Function (Database)

  • EXPORTDATA Function (Database)

  • GETDEFAULTTABLECONNECTION Function (Database)

  • HASTABLECONNECTION Function (Database)

  • IMPORTDATA Function (Database)

  • LOCKTIMEOUT Function (Database)

  • REGISTERTABLECONNECTION Function (Database)

  • SELECTLATESTVERSION Function (Database)

  • SERIALNUMBER Function (Database)

  • SETDEFAULTTABLECONNECTION Function (Database)

  • SID Function (Database)

  • TableConnectionType Data Type

  • TENANTID Function (Database)

  • TransactionType Data Type

  • UNREGISTERTABLECONNECTION Function (Database)

  • USERID Function (Sessions)

See Also

Concepts

C/AL Functions
C/SIDE Reference Guide
Development


CHECKLICENSEFILE Function (Database)

Checks a key in the license file of the system.

CHECKLICENSEFILE(KeyNumber)

Parameters

KeyNumber

Type: Integer

The number of the key you want to check.

Remarks

The license file turns on or off different system capabilities. Use this function to check a key in the file for the current user. If the user has no access rights to the object, a message is displayed and the process is terminated.

If you omit this function, the user will have the ability to continue regardless of whether the appropriate license file is open.

See Also

Concepts

Database


COMMIT Function (Database)

Ends the current write transaction.

COMMIT

Remarks

When a C/AL codeunit begins, it automatically enables write transactions to be performed. When a C/AL code module completes, it automatically ends the write transaction by committing the updates made by the C/AL code.

This means that if you want the C/AL codeunit to perform a single write transaction, it is automatically handled for you. However, if you want the C/AL codeunit to perform multiple write transactions, you must use the COMMIT function to end one write transaction before you can start the next. The COMMIT function separates write transactions in a C/AL code module.

Example

The following pseudo-code example contains two write transactions. When it begins, a write transaction is automatically started. Using the COMMIT function, you end the first write transaction and prepare for the second. When the code completes, the second write transaction automatically ends.

Copy Code
BeginWriteTransactions
(C/AL Statements) // Transaction 1
COMMIT
(C/AL Statements) // Transaction 2
EndWriteTransactions

See Also

Concepts

Database


COMPANYNAME Function (Database)

Gets the current company name.

Name := COMPANYNAME

Property Value/Return Value

Type: Text constant or code

The name of the company, or an empty string if no company has been selected.

Example

This example requires that you create the following variables and text constants.

Variable name | DataType | Length
CompName | Text | 1024

Name | ConstValue
Text000 | The name is %1.
Copy Code
CompName := COMPANYNAME;
MESSAGE(Text000, CompName);

See Also

Concepts

Database


COPYCOMPANY Function (Database)

Creates a new company and copies all data from an existing company in the same database.

[Ok:=] COPYCOMPANY(SourceName, DestinationName)

Parameters

SourceName

Type: Text

The name of the company that you want to copy data from.

DestinationName

Type: Text

The name of the company that you want to create and copy data to.

The company name can have a maximum of 30 characters. If the database collation is case-sensitive, you can have one company called COMPANY and another called Company. However, if the database is case-insensitive, you cannot create companies with names that differ only by case.

Example

The following example is based on the Copy Company batch job, which is part of the CRONUS International Ltd. demonstration database. The batch job takes the Company system table as a data item and uses the Name field as the value of the SourceName parameter. The value of the DestinationName parameter is specified in the New Company Name field in the request page, which is represented by the NewCompanyName variable.

Copy Code
COPYCOMPANY(Name, NewCompanyName);

See Also

Copy Company

Concepts

Database


CURRENTTRANSACTIONTYPE Function (Database)

Gets the current transaction type and sets a new type to be assigned.

[TransactionType :=] CURRENTTRANSACTIONTYPE([TransactionType])

Property Value/Return Value

Type: TransactionType

The type of transaction to be set or retrieved for the next transaction.

Remarks

This function sets the transaction type for the next transaction that starts when you are using Microsoft SQL Server. The transaction type determines the extent of locking that is performed on data in SQL Server tables and indexes. It also determines whether modifications to data can occur within the transaction. The following basic transaction types are available:

  • Browse

  • Snapshot

  • UpdateNoLocks

  • Update

  • Report

The Report transaction type maps to one of the other basic transaction types. For more information about the behavior of the transaction types, see TransactionType Property.

Using CURRENTTRANSACTIONTYPE to set a transaction type from within a currently active transaction does not affect the transaction type. You must set the transaction type before a transaction starts, which occurs at the first database call in a trigger or in a codeunit. If you set the current transaction type to a less isolated transaction behavior, for example, if you try to change an Update transaction to a Browse transaction, the function call is ignored. If you try to change the current transaction type to a more isolated transaction behavior, for example, from Browse to Update, you will receive an error message.

Example

In Example 1, CURRENTTRANSACTIONTYPE is used to set the required behavior of the next transaction in the database.

Copy Code
//Example 1
CURRENTTRANSACTIONTYPE := TRANSACTIONTYPE::UpdateNoLocks;

In Example 2, CURRENTTRANSACTIONTYPE is used to return the transaction type setting for the current transaction.

Copy Code
//Example 2
IF CURRENTTRANSACTIONTYPE = TRANSACTIONTYPE::UpdateNoLocks THEN...

Examples 3 and 4 show how to use the CURRENTTRANSACTIONTYPE function to set the transaction type for two separate transactions.

When you set the transaction type as in Example 3, you will get an update (or write) transaction using SERIALIZABLE behavior, which means that modifications are allowed within this transaction. SQL Server will guarantee the serializability of the transaction by placing the appropriate locks when you read from the table in the database.

Copy Code
//Example 3
CURRENTTRANSACTIONTYPE := TRANSACTIONTYPE::Update;

Examples 3 and 4 show how to use the CURRENTTRANSACTIONTYPE function to set the transaction type for two separate transactions.

When you set the transaction type as in Example 4, you will get a read-only, non-locking transaction. This means that no modifications are allowed within this transaction and that SQL Server does not add any locks. It is also possible to read any uncommitted data.

Copy Code
//Example 4
CURRENTTRANSACTIONTYPE := TRANSACTIONTYPE::Browse;

In Example 5, the initial transaction type is UpdateNoLocks. This is usually the default transaction type for a trigger. When you try to change the transaction type from UpdateNoLocks to Browse, which is a less isolated transaction type, the function call is ignored. The current transaction type remains UpdateNoLocks. After the first Table.GET line, again, when you try to change the transaction type from UpdateNoLocks to Browse, the function call is ignored. The current transaction type remains UpdateNoLocks. Next, when you try to change the transaction type from UpdateNoLocks to Update, which is a more isolated transaction type, the function call causes an error message to be generated. The current transaction type remains UpdateNoLocks. After the COMMIT, you can set a new transaction type and change it again if it is required. After the second Table.GET line, the CURRENTTRANSACTIONTYPE call is ignored. The transaction type remains Update.

Copy Code
//Example 5
OnInsert
CURRENTTRANSACTIONTYPE := TRANSACTIONTYPE::Browse;
Table.GET;
CURRENTTRANSACTIONTYPE := TRANSACTIONTYPE::Browse;
CURRENTTRANSACTIONTYPE := TRANSACTIONTYPE::Update;
COMMIT;
CURRENTTRANSACTIONTYPE := TRANSACTIONTYPE::Browse;
CURRENTTRANSACTIONTYPE := TRANSACTIONTYPE::Update;
Table.GET;
CURRENTTRANSACTIONTYPE := TRANSACTIONTYPE::Browse;
OnInsert.RETURN
COMMIT;

In Example 6, the initial transaction type is UpdateNoLocks. The first two times that you try to change to a less isolated transaction type, the function call is ignored. Finally, when you try to change to a more isolated transaction type, the function call causes an error message to be generated.

Copy Code
//Example 6
CODEUNIT
CURRENTTRANSACTIONTYPE := TRANSACTIONTYPE::Snapshot;
Report 1
CURRENTTRANSACTIONTYPE := TRANSACTIONTYPE::Browse;
Report 2
CURRENTTRANSACTIONTYPE := TRANSACTIONTYPE::Update;

See Also

Concepts

Database


DATAFILEINFORMATION Function (Database)

Specifies data from a file that has been exported from a Microsoft Dynamics NAV database.

For an example of how to use this function, see page 9900, Import Data, in the CRONUS International Ltd. demonstration database.

[Ok:=] DATAFILEINFORMATION(ShowDialog, FileName, Description, HasApplication, HasApplicationData, HasGlobalData, tenantId, exportDate, CompanyRecord)

Parameters

ShowDialog

Type: Boolean

Specifies if you want to display a dialog box where the user can confirm the action.

FileName

Type: Text

Specifies the name and location of the file that you want to read information from. The file must have been exported from a Microsoft Dynamics NAV database.

HasApplication

Type: Variable

Specifies if the file contains application objects.

Create a variable of type Boolean to specify this parameter.

HasApplicationData

Type: Variable

Specifies if the file contains the data that defines the application in the database. This includes the permissions, permission sets, profiles, and style sheets.

Create a variable of type Boolean to specify this parameter.

HasGlobalData

Type: Variable

Specifies if the file contains global, non-company specific data.

Create a variable of type Boolean to specify this parameter.

tenantId

Type: Variable

Specifies the tenant ID of the database that the data was exported from.

Create a variable of type Text to specify this parameter.

exportDate

Type: Variable

Specifies the date and time when the data was exported.

Create a variable of type DateTime to specify this parameter.

CompanyRecord

Type: Record

Specifies the company or companies in the file.

See Also

Concepts

Exporting and Importing Companies and Other Data


EXPORTDATA Function (Database)

Exports data from the Microsoft Dynamics NAV database to a file. The data is not deleted from the database.

For an example of how to use this function, see page 9901, Export Data, in the CRONUS International Ltd. demonstration database.

[Ok:=] EXPORTDATA(ShowDialog, FileName[, Description][, IncludeApplication][, IncludeApplicationData][, IncludeGlobalData][, CompanyRecord])

Parameters

ShowDialog

Type: Boolean

Specifies if you want to display a dialog box where the user can confirm the action.

FileName

Type: Text

Specifies the name and location of the file that the data must be exported to. The file must have the .navdata extension.

Description

Type: Text

Specifies a description for the exported data.

IncludeApplication

Type: Variable

Specifies if you want to export the application objects.

Create a variable of type Boolean to specify this parameter.

IncludeApplicationData

Type: Variable

Specifies if you want to export the data that defines the application in the database. This includes the permissions, permission sets, profiles, and style sheets.

Create a variable of type Boolean to specify this parameter.

IncludeGlobalData

Type: Variable

Specifies if you want to export global, non-company specific data.

Create a variable of type Boolean to specify this parameter.

CompanyRecord

Type: Record

Specifies the company or companies that must be imported.

See Also

Reference

IMPORTDATA Function (Database)

Concepts

Exporting and Importing Companies and Other Data


GETDEFAULTTABLECONNECTION Function (Database)

Gets the default table connection based on the specified connection type. You must already have registered a table connection of this type.

Name:= GETDEFAULTCONNECTIONTYPE(Type)

Parameters

Type

Type: TableConnectionType

The type of table connection as defined in the TableType property.

See Also

Reference

TableType Property
TableConnectionType Data Type
REGISTERTABLECONNECTION Function (Database)
SETDEFAULTTABLECONNECTION Function (Database)

Concepts

External Tables


HASTABLECONNECTION Function (Database)

Verifies if a connection to an external database exists based on the specified name.

Ok := HASCONNECTIONTYPE(ConnectionType, Name)

Parameters

ConnectionType

Type: TableConnectionType

Specifies the type of table connection as defined in the TableType property.

Name

Type: Text

The name of the external table connection. You must already have registered a table connection with this name.

Return Value

Type: Boolean

true if a table connection of the specified name exists; otherwise false.

See Also

Reference

TableType Property
TableConnectionType Data Type
GETDEFAULTTABLECONNECTION Function (Database)
REGISTERTABLECONNECTION Function (Database)
UNREGISTERTABLECONNECTION Function (Database)

Concepts

External Tables


IMPORTDATA Function (Database)

Imports data from a file that has been exported from a Microsoft Dynamics NAV database.

For an example of how to use this function, see page 9900, Import Data, in the CRONUS International Ltd. demonstration database.

[Ok:=] IMPORTDATA(ShowDialog, FileName[, IncludeApplicationData][, IncludeGlobalData][, CompanyRecord])

Parameters

ShowDialog

Type: Boolean

Specifies if you want to display a dialog box where the user can confirm the action.

FileName

Type: Text

Specifies the name and location of the file that must be imported. The file must have been exported from a Microsoft Dynamics NAV database.

IncludeApplicationData

Type: Variable

Specifies if you want to import the data that defines the application in the database. This includes the permissions, permission sets, profiles, and style sheets.

Create a variable of type Boolean to specify this parameter.

Important
To import application objects, you must use the Import-NAVData Windows PowerShell cmdlet. For more information, see Exporting and Importing Companies and Other Data.

IncludeGlobalData

Type: Variable

Specifies if you want to import global, non-company specific data.

Create a variable of type Boolean to specify this parameter.

CompanyRecord

Type: Record

Specifies the company or companies that must be imported.

See Also

Concepts

Exporting and Importing Companies and Other Data


LOCKTIMEOUT Function (Database)

Determines whether the lock time-out setting is set to On. You can also use this function to override the default setting.

[LockTimeout :=] LOCKTIMEOUT([LockTimeout])

Parameters

LockTimeout

Type: Boolean

The new setting for whether the lock time-out is on.

Property Value/Return Value

Type: Boolean

This value shows whether to use a lock time-out.

Remarks

This function has been designed specifically for use in long-running processes that should not be terminated because of a lock time-out, for example batch jobs that run overnight.

When the C/AL code has finished running, the default setting is used again. This function does not change the duration of a lock time-out.

To change the default setting in the Microsoft Dynamics NAVdevelopment environment, on the File menu, choose Database, and then choose Alter to open the Alter Database window. Choose the Advanced tab and select or clear the Lock time-out field.

See Also

Concepts

Database


REGISTERTABLECONNECTION Function (Database)

Registers a table connection between Microsoft Dynamics NAV and an external database.

REGISTERTABLECONNECTION(Type, Name, Connection)

Parameters

Type

Type: TableConnectionType

Specifies the type of table connection as defined in the TableType property.

Name

Type: Text

Specifies the name of the connection in your code, or the name of the primary key field on the table.

Connection

Type: Text

Specifies the connection to the external database, such as 'Data Source=ProdServer1;Initial Catalog=ProdDb1;User ID=sqladmin;Password=p@ssword'). Alternatively, define the connection in a separate function.

See Also

Reference

TableConnectionType Data Type
UNREGISTERTABLECONNECTION Function (Database)

Concepts

External Tables


SELECTLATESTVERSION Function (Database)

Forces the latest version of the database to be used.

SELECTLATESTVERSION

Remarks

This function makes sure that the data displayed is the most current data in the database. The function clears all non-locked records from the client cache, thereby ensuring that you read the most recent data. The function also clears the current client session's cache for the CaptionClassTranslate strings. The strings will then be reevaluated by the CaptionClassTranslate function trigger (ID 15) in codeunit 1.

Warning
Clearing the cache and reading data directly from the database adversely affects performance.

See Also

Concepts

Database
CaptionClass Functionality


SERIALNUMBER Function (Database)

Gets a string that contains the serial number of the license file for your Microsoft Dynamics NAV system.

String := SERIALNUMBER;

Property Value/Return Value

Type: Text or Code

This string contains the serial number.

Example

This example requires that you create the following text constants and variables in the C/AL Globals window.

Text constant name | ENU value
Text000 | The serial number for this software package is:\%1

Name | DataType | Length
SN | Text | 30
Copy Code
SN := SERIALNUMBER;
MESSAGE(Text000, SN);

The output of this example is as follows:

The serial number for this software package is:

W1-ZA-002-6R75A-7

Note
The serial number depends on your licensed version of Microsoft Dynamics NAV. The serial number shown here is an example.


SETDEFAULTTABLECONNECTION Function (Database)

Establishes a connection to an external database based on a previously registered connection of the specified type.

SETDEFAULTCONNECTIONTYPE(Type, Name, Scope)

Parameters

Type

Type: TableConnectionType

The type of table connection as defined in the TableType property.

Name

Type: Text

The name of the external table connection. You must already have registered a table connection with this name.

Scope

Type: Boolean

If true, when the function ends where you have used SETDEFAULTTABLECONNECTION, the default table connection returns to the value it had before. Use the Scope parameter when you want to use a specific table connection for a specific task and then return to the normal configuration.

See Also

Reference

TableType Property
TableConnectionType Data Type
GETDEFAULTTABLECONNECTION Function (Database)
REGISTERTABLECONNECTION Function (Database)
UNREGISTERTABLECONNECTION Function (Database)

Concepts

External Tables


SID Function (Database)

Retrieves the security identifier (SID) of a Windows user account.

Sid := SID(UserAccount);

Parameters

UserAccount

Type: Text

The Windows user account for which you want to get the SID. You must specify a domain and user name, such as 'cronus\simon'.

Property Value/Return Value

Type: Text

The SID of the specified Windows user account.

Remarks

If you create a page for adding Windows logins, then you must use the SID function to retrieve the SID for the user account so that you can enter the new login into the Windows Login table.

This function runs only on the computer that is running Microsoft Dynamics NAV Server. If you call this function from the client computer, then no action occurs.

Example

This example assigns the SID for Simon's Windows user account to a variable. This example requires that you create the following variables.

Name | DataType | Length
NewSID | Text | 119
UserAccount | Text | 132
Copy Code
UserAccount := 'cronus\simon';
NewSID := SID(UserAccount);


TableConnectionType Data Type

Use variables of this data type to specify the type of connection to an external database.

You can specify tables as external by setting the TableType property. For more information, see External Tables.

  See Also
Reference
TableType Property
REGISTERTABLECONNECTION Function (Database)
UNREGISTERTABLECONNECTION Function (Database)
SETDEFAULTTABLECONNECTION Function (Database)
GETDEFAULTTABLECONNECTION Function (Database)
HASTABLECONNECTION Function (Database)
Concepts
External Tables


TENANTID Function (Database)

Gets the ID of the tenant that has started the current session.

Use this function when your code must be specific about which tenant database to access in a multitenant deployment. For example, if your code imports data into a cache, you can make a cache tenant-specific by using the tenant ID as a key. Also, if you want to write code that saves documents, you can include the tenant ID in the file name or location, for example. In those cases, you can use the TENANTID function in combination with the COMPANYNAME function to identify the company and the tenant database.

ID := TENANTID

Property Value/Return Value

Type: Text

The ID of the tenant that has started the current session.

See Also

Reference

COMPANYNAME Function (Database)

Concepts

Multitenant Deployment Architecture
Database


TransactionType Data Type

Use variables of this complex data type to store the current transaction type. You can then use the value to set the transaction type. You can only change the transaction type when there is no current transaction (immediately after a commit).

For more information about transaction types, see TransactionType Property.

For more information about the rules governing transaction types, see CURRENTTRANSACTIONTYPE Function (Database).


UNREGISTERTABLECONNECTION Function (Database)

Unregisters a table connection between Microsoft Dynamics NAV and an external database.

UNREGISTERTABLECONNECTION(Type, Name)

Parameters

Type

Type: TableConnectionType

Specifies the type of table connection as defined in the TableType property. If the table is of type ExternalSQL, UNREGISTERTABLECONNECTION rolls back the current transaction.

Name

Type: Text

Specifies the name of the connection in your code, or the name of the primary key field on the table.

See Also

Reference

TableConnectionType Data Type
REGISTERTABLECONNECTION Function (Database)

Concepts

External Tables


USERID Function (Sessions)

Gets the ID of the user that is logged on to the current session.

ID := USERID

Property Value/Return Value

Type: Text or Code

This string contains the value of the User Name field in table 2000000120, the User table, for the current user.

Example

This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
User | Text

Text constant name | ConstValue
Text000 | The client was started by %1.
Copy Code
User := USERID;
MESSAGE(Text000, User);

The following is an example of the output of the previous code:

The system was started by cronus\simon.

See Also

Concepts

Database


DateFormula Data Type

Use this data type to contain a date formula that has the same capabilities as an ordinary input string for the CALCDATE Function (Date). The DateFormula data type is used to provide multilanguage capabilities to the CALCDATE Function (Date).

Remarks

When a date calculation formula is stored in a DateFormula field, it is converted to a generic, non-language dependent format. When a date calculation formula is retrieved from a DateFormula field, it is converted to a valid date conversion string for the currently selected language.

To assign a value to a DateFormula data type, whether it is a field or a variable, you must use the EVALUATE Function.

Example

This example requires that you create a DateFormulaVariable variable that is a DateFormula data type.

Copy Code
IF FORMAT(DateFormulaVariable) = ' ' THEN
  EVALUATE(DateFormulaVariable, '1W');

You must use the FORMAT Function (Code, Text) to make a comparison with a text string. If you do not use this function, then the IF statement will fail because you cannot compare a DateFormula data type with a Text data type.

See Also

Reference

DateFormula Property

Concepts

Developing Multilanguage-Enabled Applications


Dates and Times

This section contains the following topics:

  • Date Data Type

  • DateTime Data Type

  • Duration Data Type

  • Time Data Type

  • Date and Time Functions

  • DateTime Functions


Date Data Type

Denotes a date ranging from January 1, 1753 to December 31, 9999.

The displayed text format of the date is determined by your Region and Language Format setting in Windows.

Undefined Dates

An undefined or blank date is specified by 0D. The undefined date is considered to be before all other dates.

Normal Dates and Closing Dates

All normal dates have a corresponding closing date. The closing date for a given date is defined as a period of time that follows a given normal date and precedes the next normal date.

To assign a normal date to a variable, use the following format: <MMDDYY>D

To assign a closing date to a variable, use the CLOSINGDATE Function (Date).

Year Format

If the year is defined by two digits and is between 30 and 99, then it is considered to be in the 1900s. If it is between 00 and 29, then it is considered to be in the 2000s.

Storing Dates in the SQL Server Database

SQL Server stores information about both date and time in columns of the DATETIME types. For date fields, Microsoft Dynamics NAV uses only the date and uses a constant value for the time. For a normal date, this constant value contains 00:00:00:000. For a closing date, it contains 23:59:59:000.

The Microsoft Dynamics NAV undefined date is represented by the earliest valid date in SQL Server. The earliest valid date in SQL Server for a DATETIME is 01-01-1753 00:00:00:000.

If you store a date in the database that is outside the valid range for a SQL DATETIME, a run-time error occurs.

Example

This example shows valid assignments of Dates. It requires that you define the following variable.

Variable | DataType
Date1 | Date

This example is compiled and run on a computer with the regional format set to English (United States).

Copy Code
Date1 := 0D;
Date1 := 112710D;
MESSAGE(FORMAT(Date1));
Date1 := 11271810D;
MESSAGE(FORMAT(Date1));

The message window displays the following:

11/27/10

11/27/1810

Note
When you assign a value to a date variable, the value that you assign must be in the correct format for the regional setting of the computer. For example, if the computer is set to English (United States), then Date1 := 271108D; results in a compiler error.

Changes from Previous Versions of Microsoft Dynamics NAV

This topic has been updated to specify the SQL Server requirement for the earliest DateTime rather than the internal Microsoft Dynamics NAV date. In SQL Server, the earliest DateTime is January 1, 1753, 00:00:00.000. Microsoft Dynamics NAV can handle dates as early as January 3, 0001, but such dates cannot be stored in the database.

See Also

Reference

CALCDATE Function (Date)
CLOSINGDATE Function (Date)
DATE2DMY Function (Date)
DATE2DWY Function (Date)
DATI2VARIANT Function (Date, Variant)
DMY2DATE Function (Date)
DWY2DATE Function (Date)
NORMALDATE Function (Date)
TODAY Function (Date)
VARIANT2DATE Function (Date, Variant)
WORKDATE Function (Date)


DateTime Data Type

Denotes a date and time ranging from January 1, 1753, 00:00:00.000 to December 31, 9999, 23:59:59.999. An undefined or blank DateTime is specified by 0DT.

The displayed text format of a DateTime is determined by your Regional and Language Options in Windows.

Remarks

A DateTime is stored in the database as Coordinated Universal Time (UTC). UTC is the international time standard (formerly Greenwich Mean Time, or GMT). Zero hours UTC is midnight at 0 degrees longitude.

The DateTime is always displayed as local time in Microsoft Dynamics NAV. Local time is determined by the time zone regional settings used by your computer. You must always enter DateTimes as local time. When you enter a DateTime as local time, it is converted to UTC using the current settings for the time zone and daylight savings time.

The DateTime data type does not support closing dates.

By default, DateTimes are displayed using the standard display format. When you use the standard display format, seconds and milliseconds are not displayed until you select the DateTime field. Furthermore, if you export your data using an XMLport or by writing it to a file, the seconds and milliseconds are not exported unless you specify that DateTime fields use another format and display this information. For more information about how DateTime objects are displayed and the formats that are available, see Format Property.

The only constant available when you use the DateTime data type is the undefined DateTime, 0DT. To assign a constant value to a DateTime variable you must use the CREATEDATETIME Function (DateTime).

If you use a date that is outside the valid date range, a run-time error occurs.

SQL Server

In SQL Server, the earliest permitted DateTime is January 1, 1753, 00:00:00.000. The latest permitted DateTime is December 31, 9999, 23:59:59.999.

If you store a date in the database that is outside the valid range for a SQL DATETIME, a run-time error run-time occurs.

Changes from Previous Versions of Microsoft Dynamics NAV

In versions earlier than Microsoft Dynamics NAV 2009, the DateTime data type denotes DateTimes ranging from January 1, 0000, 00:00:00.000 to December 31, 9999, 23:59:59.999, and includes the undefined DateTime, 0DT. Microsoft Dynamics NAV 2016 supports DateTimes with date January 1, 0000 as a special case for compatibility with previous versions.

This topic has been updated to specify the SQL Server requirement for the earliest DateTime rather than the internal Microsoft Dynamics NAV DateTime. In SQL Server, the earliest DateTime is January 1, 1753, 00:00:00.000. Microsoft Dynamics NAV can handle dates as early as January 3, 0001, but such dates cannot be stored in the database.

See Also

Reference

CREATEDATETIME Function (DateTime)
CURRENTDATETIME Function (DateTime)
DT2DATE Function (DateTime)
DT2TIME Function (DateTime)
ROUNDDATETIME Function (DateTime)


Duration Data Type

Represents the difference between two DateTimes. This value can be negative. It is stored as a 64-bit integer. The integer value is the number of milliseconds during the duration.

The following are examples of durations:

DATETIME-DATETIME=DURATION

DATETIME-DURATION=DATETIME

DATETIME+DURATION=DATETIME

Example

This example shows how to calculate the difference between two DateTimes. It requires that you define the following variables.

Variable | DataType
DateTime1 | DateTime
Datetime2 | DateTime
Duration | Duration

This example is run on a computer with the Current Format in the Regional and Language Options set to English (United States).

Copy Code
DateTime1 := CREATEDATETIME(010109D, 080000T); // January 1, 2009 at 08:00:00 AM
DateTime2 := CREATEDATETIME(050509D, 133001T); // May 5, 2009 at 1:30:01 PM
Duration := DateTime2 - DateTime1;
MESSAGE(FORMAT(Duration));

The message window displays the following:

124 days 4 hours 30 minutes 1 second

See Also

Reference

DateTime Data Type


Time Data Type

Denotes a time ranging from 00:00:00.000 to 23:59:59.999. An undefined or blank time is specified by 0T.

The displayed text format of the time is determined by your Regional and Language Options in Windows.

The following are examples of valid assignments of times to a Time variable MyTime.

Copy Code
MyTime := 0T;
MyTime := 1159T;
MESSAGE(FORMAT(MyTime));
MyTime := 115934T;
MESSAGE(FORMAT(MyTime));
MyTime := 115934.444T;
MESSAGE(FORMAT(MyTime));
MyTime := 0300T;
MESSAGE(FORMAT(MyTime));

The following shows what the message windows display on a computer with the regional format set to English (United States).

11:59:00 AM

11:59:34 AM

11:59:34.444 AM

3:00:00 AM

SQL Server

Microsoft SQL Server stores information about both date and time in columns of the DATETIME type. Microsoft Dynamics NAV uses only the time part and inserts a constant value for the date: 01-01-1754.

The Microsoft Dynamics NAV undefined time is represented by the same value as an undefined date. The undefined date is represented by the earliest valid DATETIME in SQL Server, which is 01-01-1753 00:00:00:000.

See Also

Reference

TIME Function (Time)
VARIANT2TIME Function (Date, Variant)
CREATEDATETIME Function (DateTime)
DT2TIME Function (DateTime)


Date and Time Functions

This section contains the following topics:

  • CALCDATE Function (Date)

  • CLOSINGDATE Function (Date)

  • DATE2DMY Function (Date)

  • DATE2DWY Function (Date)

  • DATI2VARIANT Function (Date, Variant)

  • DMY2DATE Function (Date)

  • DWY2DATE Function (Date)

  • NORMALDATE Function (Date)

  • TIME Function (Time)

  • TODAY Function (Date)

  • VARIANT2DATE Function (Date, Variant)

  • VARIANT2TIME Function (Date, Variant)

  • WORKDATE Function (Date)


CALCDATE Function (Date)

Calculates a new date that is based on a date expression and a reference date.

NewDate := CALCDATE(DateExpression [, Date])

Parameters

DateExpression

Type: Text, Code, or DateFormula

The date expression can be any length. The string is interpreted from left to right with one subexpression at a time. The following rules describe the valid syntax of date expressions:

  • DateExpression = [<SubExpression>][<SubExpression>][<SubExpression>]

  • <SubExpression> = [<Sign>] <Term>

  • <Sign> = + | -

  • <Term> = <Number><Unit> | <Unit><Number> | <Prefix><Unit>

  • <Number> = Positive integer

  • <Unit> = D | WD | W | M | Q | Y (D=day, WD=weekday, W=week, M=month, Q=quarter, Y=year)

  • <Prefix> = C (C=current)

These production rules show that date expressions consist of zero, one, two, or three subexpressions. Each subexpression consists of an optional sign and a term. The following are some typical examples of terms:

  • 30D (30 days; corresponds to <Number><Unit>)

  • WD2 (weekday number 2; corresponds to <Unit><Number>)

  • CW (current week; corresponds to <Prefix><Unit>)

The internal calendar of Microsoft Dynamics NAV starts on Monday and ends on Sunday. This means that Monday is weekday 1 and Sunday is weekday 7.

A run-time error occurs if the syntax of DateExpression is incorrect.

Date

Type: Date

Use this optional parameter to define a reference date. The default is the current system date.

If you omit this optional value, the current system date is used.

Property Value/Return Value

Type: Date

The date that is computed from the reference date and the date expression.

Remarks

DateExpression can be a field or variable of type Text or Code, and it can be a field or variable of type DATEFORMULA. The benefit of using a DateFormula field or variable is that the date formula becomes language independent.

The user can enter formulas in the currently selected language. The formula is stored in a generic format in a field or variable. When the formula must be displayed, the actual string that is displayed is converted to the currently selected language.

For example, if a user who has language set to ENG (English) enters the date formula "1W+1D" for one week and one day, then a user who has the language set to FRA (French) sees "1S+1J," and a user who has the language set to ESP (Spanish) sees "1S+1D".

If a date formula is entered with < > delimiters surrounding it, then the date formula is stored in a generic, nonlanguage-dependent format. This makes it possible to develop date formulas that are not dependent on the currently selected language.

For more information about how to calculate the duration between two DateTimes, see Duration Data Type.

Example

This code example shows how to use the production rules that were previously described.

Copy Code
<CQ+1M-10D>

This should be interpreted as the following: current quarter + 1 month - 10 days.

The DateExpression is composed of the following:

<Prefix><Unit><Sign><Number><Unit><Sign><Number><Unit>

Note
The angle brackets (< >) specify that the expression is not translated, regardless of the application language. For more information about multilanguage capabilities with date formulas, see Developing Multilanguage-Enabled Applications.

Example

This example shows how to use the CALCDATE function.

This code example requires that you create the following variables and text constants in the C/AL Globals window.

Variable Name | DataType | Length
Expr1 | Text | 30
Expr2 | Text | 30
Expr3 | Text | 30
RefDate | Date | Not applicable
Date1 | Date | Not applicable
Date2 | Date | Not applicable
Date3 | Date | Not applicable

Text constant | ENU value
Text000 | 'The reference date is: %1 \'
Text001 | 'The expression: %2 returns %3\'
Text002 | 'The expression: %4 returns %5\'
Text003 | 'The expression: %6 returns %7'
Copy Code
Expr1 := '<CQ+1M-10D>'; // Current quarter + 1 month - 10 days
Expr2 := '<-WD2>'; // The last weekday no.2, (last Tuesday)
Expr3 := '<CM+30D>'; // Current month + 30 days
RefDate := 052196D;
Date1 := CALCDATE(Expr1, RefDate);
Date2 := CALCDATE(Expr2, RefDate);
Date3 := CALCDATE(Expr3, RefDate);
MESSAGE(Text000 + Text001 + Text002 + Text003,
  RefDate, Expr1, Date1, Expr2, Date2, Expr3, Date3);

The message window displays the following text:

The reference date is: 05/21/96

The expression: CQ+1M-10D returns 07/20/96

The expression: -WD2 returns 05/14/96

The expression: CM+30D returns 06/30/96

See Also

Concepts

Date and Time Functions
Developing Multilanguage-Enabled Applications


CLOSINGDATE Function (Date)

Gets the closing date for a Date Data Type.

ClosingDate := CLOSINGDATE(Date)

Parameters

Date

Type: Date

The input date.

Property Value/Return Value

Type: Date

The corresponding closing date for the input date.

Remarks

All dates have a corresponding closing date. A closing date is a period in time following the given date but before the next regular date. Closing dates are sorted immediately after the corresponding regular date but before the next regular date.

xxxxxxD: Regular date

xxxxxxC: Closing date

The compiler cannot convert the expression xxxxxxC to a Date data type. Therefore, you must use the CLOSINGDATE function to create a closing date.

Example

The first example shows how to use the CLOSINGDATE function. A regular date is given as input. This code example requires that you create the following variables and text constants in the C/AL Globals window.

Name | DataType
Date1 | Date
CloDate | Date

Name | ConstValue
Text000 | The closing date for %1 is %2.
Copy Code
Date1 := 040414D;
CloDate := CLOSINGDATE(Date1);
MESSAGE(Text000, Date1, CloDate);

The following message is displayed:

The closing date for 04/04/14 is C04/04/14.

Example

The second example shows some statements that do not work and explains why they do not work. This example requires that you create the following variables and text constants in the C/AL Globals window.

Name | DataType
Date1 | Date
CloDate1 | Date
CloDate2 | Date

Name | ConstValue
Text001 | The closing date for %1 is %2.
Copy Code
// Date1 := 040414C;
// The previous statement does not compile because the compiler
// cannot convert '040414C' to a Date data type.
Date1 := 040414D;
// The previous statement compiles.
// The compiler converts '040414D' to a Date data type.
// CloDate1 := CLOSINGDATE(050514C);
// The previous statement does not compile because the compiler
// cannot convert '050514C' to a Date data type and the CLOSINGDATE
// function requires a Date data type for its parameter.
CloDate1 := CLOSINGDATE(Date1);
// The previous statement compiles.
// Date1 is a Date data type.
CloDate2 := CLOSINGDATE(CloDate1);
// The previous statement compiles.
// CloDate1 is a Date data type.
MESSAGE(Text001, CloDate1, CloDate2);

The following message is displayed:

The closing date for C04/04/14 is C04/04/14.

See Also

Concepts

Date and Time Functions


DATE2DMY Function (Date)

Gets the day, month, or year of a Date Data Type.

Number := DATE2DMY(Date, What)

Parameters

Date

Type: Date

The input date.

What

Type: Integer

Specifies what the function should return. The valid options are 1, 2, and 3.

The value 1 corresponds to Day (1-31).

The value 2 corresponds to Month (1-12).

The value 3 corresponds to Year.

Property Value/Return Value

Type: Integer

The day, month, or year of the Date parameter.

Example

This example shows how to use the DATE2DMY function. This code example requires that you create the following variables and text constants in the C/AL Globals window.

Name | DataType
InputDate | Date
Day | Integer
Month | Integer
Year | Integer

Name | ConstValue
Text000 | Today is day %1 of month %2 of the year %3.
Copy Code
InputDate := TODAY;
Day := DATE2DMY(InputDate,1);
Month := DATE2DMY(InputDate,2);
Year := DATE2DMY(InputDate,3);
MESSAGE(Text000,Day,Month,Year);

The message window displays the following:

Today is day 16 of month 2 of the year 2014.

See Also

Concepts

Date and Time Functions


DATE2DWY Function (Date)

Gets the day of the week, week number, or year of a Date Data Type.

Number := DATE2DWY(Date, What)

Parameters

Date

Type: Date

The input date.

What

Type: Integer

Specifies what the function returns. The valid options are 1, 2, and 3.

The value 1 corresponds to day of the week (1-7, Monday = 1).

The value 2 corresponds to week number (1-53).

The value 3 corresponds to year.

Property Value/Return Value

Type: Integer

The resulting day of the week, week number, or year.

Remarks

If the input date to the DATE2DWY function is in a week which spans two years, then the DATE2DWY function computes the output year as the year that has more days of the given week. For example, if the input date is 010114, then the date is in a week that starts on Monday, December 29, 2013, and ends Sunday, January 4, 2014. This week has three days in 2008 and four days in 2014. Therefore, the output year is 2014.

Example

This example shows a special case that occurs when you use the DATE2DWY function in a week which spans two years. This code example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
InputDate | Date
DayOfWeek | Integer
WeekNumber | Integer
Year | Integer

Text constant name | ENU value
Text000 | The date %1 corresponds to:\
Text001 | The day of the week: %2\
Text002 | The week number: %3\
Text003 | The year: %4
Copy Code
InputDate := 010114D;
DayOfWeek := DATE2DWY(InputDate, 1);
WeekNumber := DATE2DWY(InputDate, 2);
Year := DATE2DWY(InputDate, 3);
MESSAGE(Text000 + Text001 + Text002 + Text003, InputDate, DayOfWeek, WeekNumber, Year);

The message window displays the following:

The date 01/01/14 corresponds to:

The day of the week: 4

The week number: 1

The year: 2014

This example shows that the date 01/01/14 is regarded as day number 4 (Thursday) in week number 1 in the year 2014.

See Also

Concepts

Date and Time Functions


DATI2VARIANT Function (Date, Variant)

Creates a variant that contains an encapsulation of a COM VT_DATE.

Variant := DATI2VARIANT(Date, Time)

Parameters

Date

Type: Date

The input date.

Time

Type: Time

The input time.

Property Value/Return Value

Type: Variant

Example

This example requires that you create the following variables.

Name | DataType
TestDate | Date
TestTime | Time
Variant1 | Variant
Copy Code
TestDate := TODAY;
TestTime := TIME;
Variant1 := DATI2VARIANT(TestDate, TestTime);

See Also

Reference

Variant Data Type

Concepts

Date and Time Functions
Using COM Technologies in Microsoft Dynamics NAV


DMY2DATE Function (Date)

Gets a Date object based on a day, month, and year.

Date := DMY2DATE(Day [, Month] [, Year])

Parameters

Day

Type: Integer

The number of the day in the month (1-31)

Month

Type: Integer

The number of the month in the year (1-12). If you omit this optional parameter, the current month will be used as the default.

Year

Type: Integer

The four-digit number of the year. If you omit this optional parameter, the current year is used as the default.

Property Value/Return Value

Type: Date

The resulting date.

Example

This code example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
Day | Integer
Month | Integer
Year | Integer
OutputDate | Date

Text constant name | ConstValue
Text000 | Day number %1, month number %2, and year number %3 corresponds to the date %4.
Copy Code
Day := 17;
Month := 2;
Year := 2014;
OutputDate := DMY2DATE(Day, Month, Year);
MESSAGE(Text000, Day, Month, Year, OutputDate);

On a computer that has the regional format set to English (United States), the message window displays the following:

Day number 17, month number 2, and year number 2014 corresponds to the date 02/17/14.

See Also

Reference

Date Data Type

Concepts

Date and Time Functions


DWY2DATE Function (Date)

Gets a Date that is based on a week day, a week, and a year.

Date := DWY2DATE(WeekDay [, Week] [, Year]))

Parameters

Weekday

Type: Integer

The number of the day in the week (1-7). Monday is day number 1.

Week

Type: Integer

The number of the week. Week 1 is the first week of the year that has four or more days in the year. If you omit this optional parameter, the current week is used as the default.

Year

Type: Integer

The four-digit number of the year. If you omit this optional parameter, the year of the current week is used as the default.

Property Value/Return Value

Type: Date

The resulting date.

Remarks

A special situation occurs if the week (Week) that is input into DWY2DATE spans two years. Depending on Weekday, the year of the output Date can differ from the input year. This scenario is shown in the following code example.

Example

The input week in this example spans two years. This code example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
DayOfWeek | Integer
Week | Integer
Year | Integer
OutputDate | Date

Text constant name | ENU value
Text000 | Day %1 of week %2 in the year %3 is the date %4.
Copy Code
DayOfWeek := 1;
Week := 1;
Year := 2014;
OutputDate := DWY2DATE(DayOfWeek, Week, Year);
MESSAGE(Text000, DayOfWeek, Week, Year, OutputDate);

On a computer that has the regional format set to English (United States), the message window displays the following:

Day 1 of week 1 in the year 2014 is the date: 12/30/13.

The example shows that the first day of the week in the first week of the year 2014 is regarded as the date December 30, 2013. The first week of the year 2014 is the first week that has four or more days in the year 2014. That week starts on Monday, December 30, 2013, and ends on Sunday, January 5, 2014.

Example

The input week in this example spans two years. This code example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | Data type
DayOfWeek | Integer
Week | Integer
Year | Integer
OutputDate | Date

Text constant | ENU value
Text000 | Day %1 of week %2 in the year %3 is the date %4.
Copy Code
DayOfWeek := 1;
Week := 1;
Year := 2016;
OutputDate := DWY2DATE(DayOfWeek, Week, Year);
MESSAGE(Text000, DayOfWeek, Week, Year, OutputDate);

On a computer that has the regional format set to English (United States), the message window displays the following:

Day 1 of week 1 in the year 2016 is the date: 01/04/16.

The example shows that the first day of the week in the first week of the year 2016 is regarded as the date January 4, 2016. The first week of the year 2016 is the first week that has four or more days in the year 2016. That week starts on Monday, January 4, 2016, and ends on Sunday, January 11, 2015.

Example

This example shows how to use the DWY2DATE function without specifying the optional Year parameter. The output in this example depends on the day on which you run the code. This code example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
DayOfWeek | Integer
Week | Integer
OutputDate | Date

Text constant | ENU value
Text000 | Day %1 of week %2 is the date %3.
Copy Code
DayOfWeek := 1;
Week := 1;
OutputDate := DWY2DATE(DayOfWeek, Week);
MESSAGE(Text000, DayOfWeek, Week, OutputDate);

On a computer that has the regional format set to English (United States), if you ran the code on January 1, 2014, then the message window displays the following:

Day 1 of week 1 is the date: 12/30/13.

If you do not specify the year, then the year of the current week is used. On January 1, 2014, the current week is the week that starts on December 30, 2013 and ends on January 5, 2014. This week has four days in 2014 so the year of the current week is 2014. The first day of the first week of 2014 is 12/30/13.

On a computer that has the regional format set to English (United States), if you ran the code on January 1, 2016, then the message window displays the following:

Day 1 of week 1 is the date: 12/29/14.

On January 1, 2016, the current week is the week that starts on December 28, 2015 and ends on January 3, 2016. This week has four days in 2015 so the year of the current week is 2015. The first day of the first week of 2015 is 12/29/14.

See Also

Concepts

Date and Time Functions


NORMALDATE Function (Date)

Gets the regular date (instead of the closing date) for the argument Date.

NormalDate := NORMALDATE(Date)

Parameters

Date

Type: Date

The input date. You can enter a closing date or a normal date. A run-time error occurs if the value of Date is set to the undefined date (0D).

Property Value/Return Value

Type: Date

The resulting date. If the input date is either a normal date or a closing date, then the return value is a normal date.

Remarks

All dates have a corresponding closing date. A closing date is a period of time that follows the given date but comes before the next date. Closing dates are sorted immediately after the corresponding date and before the next date.

xxxxxxD: regular date

xxxxxxC: closing date

Example

The input date is a regular date. This code example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
InputDate | Date
OutputDate | Date

Text constant name | ENU value
Text000 | The normal date for %1 is %2.
Copy Code
InputDate := 040414D;
OutputDate := NORMALDATE(InputDate);
MESSAGE(Text000, InputDate, OutputDate);

On a computer that has the regional format set to English (United States), the message window displays the following:

The normal date for 04/04/14 is 04/04/14.

Example

The input date is a closing date. This code example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
InputDate | Date
OutputDate | Date

Text constant name | ENU value
Text001 | The normal date for %1 is %2.
Copy Code
InputDate := CLOSINGDATE(040414C);
OutputDate := NORMALDATE(InputDate);
MESSAGE(Text001, InputDate, OutputDate);

On a computer that has the regional format set to English (United States), the message window displays the following:

The normal date for C04/04/14 is 04/04/14.

See Also

Concepts

Date and Time Functions


TIME Function (Time)

Gets the current time from the operating system.

Time := TIME

Property Value/Return Value

Type: Time

The current time.

Remarks

You can only use the TIME function to retrieve the time from the operating system. You cannot use it to set the time in the operating system.

Example

This example requires that you create the following text constant in the C/AL Globals window.

Name | ConstValue
Text000 | The current system time is %1.
Copy Code
MESSAGE(Text000, TIME);

On a computer that has the regional format set to English (United States), the message window could display the following:

The current system time is 11:15:46 AM.

See Also

Reference

Time Data Type

Concepts

Date and Time Functions


TODAY Function (Date)

Gets the current date set in the operating system.

Date := TODAY

Property Value/Return Value

Type: Date

The current date defined by the operating system.

Remarks

You can only use the TODAY function to retrieve the current date from the operating system. You cannot use it to set the date in the operating system.

Example

This example shows how to use the TODAY function. This example requires that you create the following text constant in the C/AL Globals window.

Name | ConstValue
Text000 | The current date is: %1
Copy Code
MESSAGE(Text000, TODAY);

The message window could display the following:

The current date is: 05/27/08

See Also

Concepts

Date and Time Functions


VARIANT2DATE Function (Date, Variant)

Gets a date from a variant.

Date := VARIANT2DATE(Variant)

Parameters

Variant

Type: Variant

The input variant.

Property Value/Return Value

Type: Date

The resulting date.

Example

This example requires that you create the following variables.

Name | DataType
TestDate | Date
variant1 | Variant
Copy Code
variant1 := TODAY;
TestDate := VARIANT2DATE(variant1);

See Also

Reference

Variant Data Type

Concepts

Date and Time Functions
Using COM Technologies in Microsoft Dynamics NAV


VARIANT2TIME Function (Date, Variant)

Gets a time from a variant.

Time := VARIANT2TIME(Variant)

Parameters

Variant

Type: Variant

The input variant.

Property Value/Return Value

Type: Time

The resulting time.

Example

This example requires that you create the following variables.

Name | DataType
TestTime | Time
variant1 | Variant
Copy Code
variant1 := TIME;
TestTime := VARIANT2TIME(variant1);

See Also

Reference

Variant Data Type

Concepts

Date and Time Functions
Using COM Technologies in Microsoft Dynamics NAV


WORKDATE Function (Date)

Gets and sets the work date for the current session.

[WorkDate]:= WORKDATE([NewDate])

Parameters

NewDate

Type: Date

The new work date you want to set.

Property Value/Return Value

Type: Date

The current work date.

Remarks

If you do not set a value for the NewDate parameter, then the function returns the work date that is specified by the Set Work Date option on the Application menu Application Menu button in menu bar in the Microsoft Dynamics NAV Windows client. If there is no work date selected, then the current system date is returned.

To set the work date to follow the calendar day so that the work date is always the current date, set NewDate to TODAY or 0D. If you explicitly set NewDate to the current date, then the work date will also follow the calendar day.

Example

This example shows how to use the WORKDATE function. This example requires that you create the following text constant in the C/AL Globals window.

Name | ConstValue
Text000 | The work date is: %1
Copy Code
WORKDATE(010114D);
MESSAGE(Text000, WORKDATE);

The first line of code sets the work date to January 1, 2014. In the second line of code, the WORKDATE function returns the current work date. On a computer that has the regional format set to English (United States), the message window displays the following:

The work date is: 01/01/14

See Also

Concepts

Date and Time Functions


DateTime Functions

This section contains the following topics:

  • CREATEDATETIME Function (DateTime)

  • CURRENTDATETIME Function (DateTime)

  • DT2DATE Function (DateTime)

  • DT2TIME Function (DateTime)

  • ROUNDDATETIME Function (DateTime)


CREATEDATETIME Function (DateTime)

Creates a DateTime object from a date and a time.

DateTime := CREATEDATETIME(Date, Time)

Parameters

Date

Type: Date

The date that you want to use to create a DateTime.

You cannot use an undefined date to create a DateTime.

Time

Type: Time

The time that you want to use to create a DateTime.

You cannot use an undefined time to create a DateTime.

Property Value/Return Value

Type: DateTime

The concatenated DateTime.

Example

These examples of using the CREATEDATETIME function require that you create the following variables.

Name | DataType
TestDate | Date
TestTime | Time
TestDateTime | DateTime
Copy Code
TestDate := TODAY;
TestTime := TIME;
TestDateTime := CREATEDATETIME(TestDate,TestTime);
…
TestDateTime := CREATEDATETIME(081111D,020000T);
…
TestDateTime := CREATEDATETIME(010101D,0T);

See Also

Concepts

DateTime Functions


CURRENTDATETIME Function (DateTime)

Gets the current DateTime.

DateTime := CURRENTDATETIME

Property Value/Return Value

Type: DateTime

The current DateTime.

Example

This example requires that you create a DateTime variable named TestDateTime.

Copy Code
TestDateTime := CURRENTDATETIME;
MESSAGE(Format(TestDateTime));

The message window displays the current date and time.

See Also

Concepts

DateTime Functions


DT2DATE Function (DateTime)

Gets the date part of a DateTime object.

Date := DT2DATE(Datetime)

Parameters

Datetime

Type: DateTime

The DateTime of which to return the date part.

Property Value/Return Value

Type: Date

The date part of the DateTime object.

Remarks

If Datetime is undefined, then this function returns an undefined date.

See Also

Concepts

DateTime Functions


DT2TIME Function (DateTime)

Gets the time part of a DateTime object.

Time := DT2TIME(Datetime)

Parameters

Datetime

Type: DateTime

The DateTime of which to return the time part.

Property Value/Return Value

Type: Time

The time part of the DateTime object.

Remarks

If Datetime is undefined, then this function returns an undefined time.

See Also

Concepts

DateTime Functions


ROUNDDATETIME Function (DateTime)

Rounds a DateTime.

NewDateTime := ROUNDDATETIME(Datetime [, Precision][, Direction])

Parameters

Datetime

Type: DateTime

The DateTime that you want to round.

Precision

Type: BigInteger

This optional parameter determines the precision used when rounding. The default value is 1000, which rounds to the nearest second.

You can only use positive BigIntegers.

Direction

Type: Text or Code

This optional parameter specifies how to round the DateTime. The default rounding method is '='. You can change the method by using the following options:

  • '=' rounds up or down to the nearest value (default). Values of 5 or greater are rounded up. Values less than 5 are rounded down.

  • '>' rounds up

  • '<' rounds down

Property Value/Return Value

Type: DateTime

The rounded result.

Remarks

A variable of type DateTime is stored as a 64 bit integer. The integer value is the number of milliseconds since year 0. When you call ROUNDDATETIME, the DateTime integer value is rounded as a numeric variable.

If you use 1 for the Precision parameter, then the resulting DateTime is rounded to the nearest millisecond. If you use 1000 for the Precision parameter, which is the default value, then the resulting DateTime will be rounded to the nearest second.

We recommend that you do not use a value greater than 60*60*1000, which is the number of milliseconds in an hour, for the Precision parameter. The Regional and Language Options in Windows affect how the hour and date parts of a DateTime are rounded. To display a DateTime in a specific format, we recommend that you use the FORMAT Function (Code, Text) instead of the ROUNDDATETIME function.

Example

This example shows how to use the ROUNDDATETIME function to round to the nearest second. This example requires that you create the following text constant in the C/AL Globals window.

Text constant name | ENU value
Text000 | ROUNDDATETIME(%1, %2) returns %3.
Copy Code
DateToRound := 112708D;
TimeToRound := 093524.567T;
DateTimeToRound := CREATEDATETIME(DateToRound, TimeToRound);
Precision := 1000L;
FormatString := '<Month,2>/<Day,2>/<Year> <Hours24,2>:<Minutes,2>:<Seconds,2>.<Thousands,3>';
Result := ROUNDDATETIME(DateTimeToRound, Precision);
MESSAGE(TEXT000, Format(DateTimeToRound,0,FormatString), Precision, Format(Result,0,FormatString));

The message window displays the following:

ROUNDDATETIME(11/27/08 09:35:24.567, 1000) returns 11/27/08 09:35:25.000.

See Also

Reference

FORMAT Function (Code, Text)
Format Property

Concepts

DateTime Functions


Debugger

Use the debugger functions to implement a debugger for C/AL code. The Microsoft Dynamics NAV 2016 Debugger is an example of a debugger application that is built using tables, pages, codeunits, and the C/AL debugger functions.


ACTIVATE Function (Debugger)

Activates the debugger and attaches the debugger to the next session that is started.

[Ok :=] ACTIVATE

Property Value/Return Value

Type: Boolean

true if the debugger is started successfully; otherwise, false.

If you omit this optional return value and if the break is not set successfully, then a run-time error occurs. If you include the return value, then you must handle any errors.

Remarks

The ACTIVATE function behaves like the Debug Next action on the Sessions page.

You can call either the ACTIVATE function or the ATTACH Function (Debugger) to activate the debugger.

The ACTIVATE function is not supported by the Microsoft Dynamics NAV Web client. If the ACTIVATE function is called from a page in the Microsoft Dynamics NAV Web client, you receive a runtime error with a message that is similar to the following:

The Ribbon Tab with id: "MBSCC.1A7.1A7" has not been made available for this page or does not exist. Use Ribbon.MakeTabAvailable().

See Also

Reference

DEACTIVATE Function (Debugger)

Concepts

Activating the Debugger


ATTACH Function (Debugger)

Activates the debugger and attaches it to the specified session.

[Ok :=] ATTACH(SessionID)

Parameters

SessionID

Type: Integer

The ID of the session that you want to attach the debugger to.

The session can be any of the following:

  • Microsoft Dynamics NAV Windows client

  • Microsoft Dynamics NAV Web client

  • NAS services session

  • SOAP web services client session

  • OData web services client session

  • Background session

Property Value/Return Value

Type: Boolean

true if the debugger is attached to a session; otherwise, false.

If you omit this optional return value and if the break is not set successfully, then a run-time error occurs. If you include the return value, then you must handle any errors.

Remarks

The ATTACH function behaves like the Debug action on the Sessions page.

You can call either the ATTACH function or the ACTIVATE Function (Debugger) to activate the debugger.

See Also

Concepts

Activating the Debugger


BREAK Function (Debugger)

Breaks code execution of a debugging session.

[Ok :=] BREAK

Property Value/Return Value

Type: Boolean

true if a breakpoint is set in the debugging session; otherwise, false.

If you omit this optional return value and if the break is not set successfully, then a run-time error occurs. If you include the return value, then you must handle any errors.

See Also

Tasks

How to: Break on the Next Statement
How to: Manage Breakpoints from the Development Environment

Concepts

Breakpoints


BREAKONERROR Function (Debugger)

Sets whether the debugger breaks on errors.

[Ok :=] BREAKONERROR(SetBreakOnError)

Parameters

SetBreakOnError

Type: Boolean

Specifies whether the debugger breaks on errors.

Property Value/Return Value

Type: Boolean

true if the break on errors is set successfully; otherwise, false.

If you omit this optional return value and if the break is not set successfully, then a run-time error occurs. If you include the return value, then you must handle any errors.

Remarks

The debugger must be attached to a session when you run the BREAKONERROR function.

Example

This example shows how to implement the code for an action on a page that sets the break on error setting to true. You can use this code example in the OnAction trigger of that action. This code example requires that you create a Boolean variable named Value.

Copy Code
Value := true;
DEBUGGER.BREAKONERROR(Value);

See Also

Tasks

How to: Break on Errors


BREAKONRECORDCHANGES Function (Debugger)

Breaks execution before a change to a record occurs.

[Ok :=] BREAKONRECORDCHANGES(Ok)

Parameters

Ok

Type: Boolean

Specifies whether the debugger should break execution when a change to a record occurs.

If Ok is true, then the debugger breaks before creating, updating, or deleting a record.

Property Value/Return Value

Type: Boolean

true if the debugger breaks when a change occurs in a record; otherwise, false.

If you omit this optional return value and if the break is not set successfully, then a run-time error occurs. If you include the return value, then you must handle any errors.

See Also

Reference

BREAK Function (Debugger)

Concepts

Breakpoints


CONTINUE Function (Debugger)

Executes code until the next breakpoint or until execution ends.

[Ok :=] CONTINUE

Property Value/Return Value

Type: Boolean

true if code executes until the next breakpoint or until execution ends; otherwise, false.

If you omit this optional return value and if the break is not set successfully, then a run-time error occurs. If you include the return value, then you must handle any errors.

See Also

Concepts

Breakpoints


DEACTIVATE Function (Debugger)

Deactivates the debugger.

[Ok :=] DEACTIVATE

Property Value/Return Value

Type: Boolean

true if the debugger is deactivated successfully; otherwise, false.

If you omit this optional return value and if the break is not set successfully, then a run-time error occurs. If you include the return value, then you must handle any errors.

See Also

Reference

ACTIVATE Function (Debugger)

Concepts

Activating the Debugger


DEBUGGEDSESSIONID Function (Debugger)

Gets the ID of the previous session that the debugger was attached to.

SessionID := DEBUGGEDSESSIONID

Property Value/Return Value

Type: Integer

The session ID of the session that the debugger was previously attached to.

See Also

Reference

DEBUGGINGSESSIONID Function (Debugger)


DEBUGGINGSESSIONID Function (Debugger)

Gets the ID of the session that the debugger is currently attached to.

SessionID := DEBUGGINGSESSIONID

Property Value/Return Value

Type: Integer

The session ID that the debugger is currently attached to.

See Also

Reference

DEBUGGEDSESSIONID Function (Debugger)

Concepts

Debugging


ENABLESQLTRACE Function (Debugger)

Enables or verifies SQL tracing. If you enable SQL tracing, then SQL Server events for selected sessions on the Microsoft Dynamics NAV Server instance are collected.

[IsEnabled :=] ENABLESQLTRACE(SessionID [,NewIsEnabled])

Parameters

SessionID

Type: Integer

The ID of the session for which you want to enable the SQL trace, or for which you want to verify if tracing is enabled.

If you specify 0 and you specify the NewIsEnabled parameter, then tracing is enabled for all existing sessions and all new sessions on the current Microsoft Dynamics NAV Server instance. If you specify 0 and you omit the NewIsEnabled parameter, then the function returns true if tracing is enabled for new sessions on the current Microsoft Dynamics NAV Server instance.

If the session ID that you specify does not exist and you specify the NewIsEnabled parameter, then a run-time error occurs. If the session ID that you specify does not exist and you do not specify the NewIsEnabled parameter, then the function returns false.

NewIsEnabled

Type: Boolean

If you specify the optional NewIsEnabled parameter, then the function sets whether tracing is enabled. true if you want to enable tracing for the specified session; false if you want to disable tracing. If you omit the NewIsEnabled parameter, then the function verifies if tracing is enabled.

Property Value/Return Value

Type: Boolean

true if SQL tracing is enabled; otherwise, false.

Remarks

You use Microsoft SQL Server Profiler to view traces. For more information, see Using SQL Server Profiler. To start SQL Server Profiler, in SQL Server Management Studio, on the Tools menu, choose SQL Server Profiler.

You can also enable and disable SQL tracing by using the Start Full SQL Tracing and Stop Full SQL Tracing buttons on the Session List page.

See Also

Concepts

Debugging


GETLASTERRORTEXT Function (Debugger)

Gets the last error that occurred in the debugger.

String := GETLASTERRORTEXT

Property Value/Return Value

Type: Text

A text that represents the last error that occurred.

See Also

Reference

BREAKONERROR Function (Debugger)

Concepts

Debugging


ISACTIVE Function (Debugger)

Indicates whether the debugger is active.

Ok := ISACTIVE

Property Value/Return Value

Type: Boolean

true if the debugger is active; otherwise, false.

Remarks

When the debugger is activated, it is in one of the following states:

  • Attached to a session.

  • Waiting to attach to a session.

See Also

Tasks

How to: Activate the Debugger from the Development Environment

Concepts

Activating the Debugger


ISATTACHED Function (Debugger)

Specifies if the debugger is attached to a session.

Ok := ISATTACHED

Property Value/Return Value

Type: Boolean

true if the debugger is attached to a session; otherwise, false.

See Also

Tasks

How to: Activate the Debugger from the Development Environment

Reference

ATTACH Function (Debugger)


ISBREAKPOINTHIT Function (Debugger)

Specifies if a breakpoint is hit in a debugging session.

Ok := ISBREAKPOINTHIT

Property Value/Return Value

Type: Boolean

true if a breakpoint is hit in a debugging session; otherwise, false.

See Also

Concepts

Breakpoints


SKIPSYSTEMTRIGGERS Function (Debugger)

Enables the debugger to skip code that is inside system triggers.

[Ok :=] SKIPSYSTEMTRIGGERS(Ok)

Parameters

Ok

Type: Boolean

Specifies if the debugger should skip system triggers.

Property Value/Return Value

Type: Boolean

true if the debugger skips system triggers; otherwise, false.

If you omit this optional return value and if the break is not set successfully, then a run-time error occurs. If you include the return value, then you must handle any errors.

See Also

Reference

Debugger


STEPINTO Function (Debugger)

Executes a function call and then stops at the first line of code inside the function.

[Ok :=] STEPINTO

Property Value/Return Value

Type: Boolean

true if the debugger executes a function call; otherwise, false.

If you omit this optional return value and if the break is not set successfully, then a run-time error occurs. If you include the return value, then you must handle any errors.

See Also

Reference

STEPOVER Function (Debugger)
STEPOUT Function (Debugger)

Concepts

Breakpoints


STEPOUT Function (Debugger)

Enables debugging to return to the calling function after it steps into a function call.

[Ok :=] STEPOUT

Property Value/Return Value

Type: Boolean

true if the debugger returns to the calling function; otherwise, false.

If you omit this optional return value and if the break is not set successfully, then a run-time error occurs. If you include the return value, then you must handle any errors.

See Also

Reference

STEPOVER Function (Debugger)
STEPINTO Function (Debugger)

Concepts

Breakpoints


STEPOVER Function (Debugger)

Executes a function call and then stops at the first line outside the function call.

[Ok :=] STEPOVER

Property Value/Return Value

Type: Boolean

true if the debugger steps over a function call; otherwise, false.

If you omit this optional return value and if the break is not set successfully, then a run-time error occurs. If you include the return value, then you must handle any errors.

See Also

Reference

STEPINTO Function (Debugger)
STEPOUT Function (Debugger)

Concepts

Breakpoints


STOP Function (Debugger)

Stops execution as if the code hits an error.

[Ok :=] STOP

Property Value/Return Value

Type: Boolean

true if the debugger stops execution; otherwise, false.

If you omit this optional return value and if the break is not set successfully, then a run-time error occurs. If you include the return value, then you must handle any errors.

See Also

Tasks

Walkthrough: Debugging the Microsoft Dynamics NAV Windows Client

Reference

Debugger


Dialog Data Type

Variables of this complex data type store dialog windows. These variables also give you access to a number of dialog functions, such as OPEN Function (Dialog), CLOSE Function (Dialog), and so on.

Dialog Functions

CLOSE Function (Dialog)

CONFIRM Function (Dialog)

ERROR Function (Dialog)

MESSAGE Function (Dialog)

OPEN Function (Dialog)

STRMENU Function (Dialog)

UPDATE Function (Dialog)


CLOSE Function (Dialog)

Closes a dialog window that has been opened by OPEN Function (Dialog).

Dialog.CLOSE

Parameters

Dialog

Type: Dialog

The Dialog variable that you are closing.

Remarks

If CLOSE is used on a dialog window that is not open, a run-time error will occur.

The dialog windows of an object are automatically closed when the object terminates.

See Also

Reference

Dialog Data Type


CONFIRM Function (Dialog)

Creates a dialog box that prompts the user for a yes or no answer. The dialog box is centered on the screen.

Ok := Dialog.CONFIRM(String [, Default] [, Value1] ,...)

Parameters

String

Type: Code or text constant

Specifies the string that is displayed in the dialog box. Use a backslash (\) to indicate a new line. The string can be a text constant that is enabled for multilanguage functionality. For more information, see Multilanguage Development.

Default

Type: Boolean

Specifies the default button. If you do not specify a default button, then No is used as the default button.

Value1, …

Type: Any

Any type of constant or C/AL variable that you want to insert into String. You can insert up to 10 values.

Property Value/Return Value

Type: Boolean

true if you entered Yes; otherwise, false.

This return parameter reflects the user's selection.

Remarks

The message window is automatically sized. The height of the window corresponds to the number of lines and the width corresponds to the length of the longest line.

We recommend that you always end CONFIRM messages with a question mark. For more information about best practices for end-user messages, see Progress Windows, MESSAGE, ERROR, and CONFIRM Functions.

Example

In the following example, the Dialog.CONFIRM function prompts the user for a Yes or No answer. This code example requires that you create the following variables.

Name | DataType
Question | Text
Answer | Boolean
CustomerNo | Integer

This code example requires that you create the following text constants in the C/AL Globals window.

Name | ConstValue
Text000 | Exit without saving changes to customer %1?
Text001 | You selected %1.
Copy Code
CustomerNo := 01121212;
Question := Text000;
Answer := Dialog.CONFIRM(Question, TRUE, CustomerNo);
MESSAGE(Text001, Answer);

The first dialog box shows:

Exit without saving changes to customer 1121212?

If you select the default Yes value, then the second dialog box is shown:

You selected Yes.

See Also

Reference

Dialog Data Type


ERROR Function (Dialog)

Displays an error message and ends the execution of C/AL code.

ERROR(String [, Value1, …])

Parameters

String

Type: Text constant or code

This string contains the text of the error message you want to display to the user. Use percent signs (%) or number signs (#) to insert variable values into the string. Place the percent or number signs where you want to substitute the variable value. The string can be a text constant that is enabled for multilanguage functionality. For more information, see Multilanguage Development.

Value1, …

Type: Any

Any variable or expression to be inserted in String. You can insert up to 10 values.

For '#'-type fields, the value is truncated according to the total number of number-sign characters in String. For '%'-type fields, the full length of the value is printed.

Remarks

The window is automatically sized to hold the longest line of text and total number of lines.

Programming Guidelines

We recommend the following guidelines for error messages:

  • Describe what is wrong and how to solve the problem.

  • Write a short descriptive message. Do not use more words than necessary.

  • Always end the error message with a period.

  • Use a text constant for the text of the message.

For more information, see Progress Windows, MESSAGE, ERROR, and CONFIRM Functions.

Example

This example shows how to use the ERROR function. The code example requires that you create the following variables and text constants in the C/AL Globals window.

Name | DataType
AccountNo | Integer

Name | ConstValue
Text000 | Finance Account #1#### must not be blocked.
Text001 | Placeholder message.
Copy Code
AccountNo := 1230;
// The execution stops when the error statement is executed
// and all following statements will never be executed.
ERROR(Text000, AccountNo);
MESSAGE(Text001); // This line is not executed.

The error window displays the following:

Finance Account 1230 must not be blocked.

The ERROR function causes execution of C/AL code to stop. The MESSAGE function is never executed.

See Also

Reference

Dialog Data Type
MESSAGE Function (Dialog)

Concepts

Progress Windows, MESSAGE, ERROR, and CONFIRM Functions
Error Handling


MESSAGE Function (Dialog)

Displays a text string in a message window.

MESSAGE(String [, Value1, …])

Parameters

String

Type: Code or text constant

This string contains the text you want the system to display in the message window. Use a backslash (\) to start a new line. Use percent signs (%) to insert variable values into the string. Place the percent where you want the system to substitute the variable value. The string can be a text constant that is enabled for multilanguage functionality. For more information, see Multilanguage Development.

Value1, …

Type: Any

Any type of C/AL variable you want to insert into String. You can insert up to 10 values.

Remarks

When a message statement in the C/AL code is executed, the message is not immediately displayed. Instead, it is displayed after the C/AL code is finished executing or after the C/AL code pauses to wait for user interaction.

The window is automatically sized to hold the longest line of text and the total number of lines.

For NAS sessions or Microsoft Dynamics NAV sessions (including NAS) that are started by the STARTSESSION Function (Sessions), messages are recorded in the event log of the computer that is running Microsoft Dynamics NAV Server. The message entries have the ID 100 and type Information.

Programming Guidelines

We recommend the following guidelines for messages:

  • Always end a message with a period.

  • Supply the user with a message when the system has finished performing a task.

  • Write the message in past tense.

For more information, see Progress Windows, MESSAGE, ERROR, and CONFIRM Functions.

Example

This example shows how to use the MESSAGE function.

This code requires you to create the following variables.

Variable | DataType
Text | Text
Number | Decimal

This code requires you to create the following text constants.

Text constant | ENU value
Text000 | You can use message windows to display text and numbers: \
Text001 | The number:
Text002 | The text:
Copy Code
Text := 'ABCDE';
Number := 12345.678;
// The backslash indicates a new line.
// You can concatenate strings using the + operator.
// You can insert variable values using the % symbol.
MESSAGE(Text000 + Text001 + '%1\' +Text002 + '%2', Number, Text);

The message window reads:

You can use message windows to display text and numbers:

The number: 12,345.678

The text: ABCDE

See Also

Reference

Dialog Data Type

Concepts

Configuring NAS Services


OPEN Function (Dialog)

Opens a dialog window.

Dialog.OPEN(String [, Variable1],...)

Parameters

Dialog

Type: Dialog

After you define this variable, you can open the dialog and then use other dialog functions.

String

Type: Text constant or code

This string contains the text that you want to display in the window. Use a backslash (\) to start a new line. Use number signs (#) to insert variable values into the string. Place the number signs where you want to substitute the variable value. Place a number in the part of the string where a variable value will be substituted (for example, #1####) to be able to reference this field for updating.

If you use @ characters instead of # characters, then the variable value is used as a percentage and both the percentage and a progress indicator are displayed. The percentage value that is displayed is the percentage of the variable value from 0 to 9999.

The number of # or @ characters in the string indicates the length of the field or progress indicator.

You can update the fields using the UPDATE Function (Dialog) or by letting the user edit the values.

Variable1

Type: Any

Use these optional parameters to specify variables for field1, field2, and so on in the String.

Remarks

Dialog windows that are opened by an object are closed when the object terminates.

Dialog windows are automatically sized to hold the longest line of text and the total number of lines.

We recommend the following guidelines:

  • Enter messages as text constants.

  • Write messages using active voice. For example, write “Processing items” instead of writing “Items are being processed.”

  • Align the # and @ fields to the left with at least one space character between the text and the variable.

Example

This example shows how to use the dialog.OPEN function.

This code example requires that you create the following variables and text constants.

Name | DataType
MyDialog | Dialog
MyNext | Integer

Text constant name | Constant value
Text000 | Counting to 4 #1
Copy Code
MyNext := 0;
MyDialog.OPEN(Text000,MyNext);
REPEAT
  // Do some processing.
  SLEEP(1000);
  MyNext := MyNext + 1;
  MyDialog.UPDATE(); // Update the field in the dialog.
UNTIL MyNext = 4;
SLEEP(1000);
MyDialog.CLOSE()

The dialog window opens and displays this text:

Counting to 4: 0

Every one second, the dialog window updates with the new value of MyNext until it reaches 4, then the dialog window closes.

Example

This example shows how to use the dialog.OPEN function to display a progress indicator.

This code example requires that you create the following variables and text constants.

Name | Datatype
MyDialog | Dialog
MyNext | Integer

Text constant name | Constant value
Text000 | Progress from 0 to 9999 @1@@@@@
Copy Code
MyNext := 0;
MyDialog.OPEN(Text000,MyNext);
REPEAT
  // Do some processing.
  MyNext := MyNext + 1;
  MyDialog.UPDATE(); // Update the field in the dialog.
UNTIL MyNext = 9999;
SLEEP(1000);
MyDialog.CLOSE()

The dialog window opens and displays the progress indicator and percentage.

Dialog window progress indicator

See Also

Reference

Dialog Data Type


STRMENU Function (Dialog)

Creates a menu window that displays a series of options.

OptionNumber := Dialog.STRMENU(OptionString [, DefaultNumber] [, Instruction])

Parameters

OptionString

Type: Code or text constant

A comma-separated string. Each substring in OptionString specifies an option on the menu. The string can be a text constant that is enabled for multilanguage functionality. For more information, see Multilanguage Development.

DefaultNumber

Type: Integer

Use this optional parameter to determine a default option, which is highlighted. The options are numbered 1, 2, 3, 4, and so on.

If you omit this optional parameter, the first option (1) is used as the default.

Instruction

Type: Code or text constant

Use this optional parameter to add a description to the option values.

Property Value/Return Value

Type: Integer

The number of the menu option that the user selected. If the user presses the Esc key to exit the menu, zero (0) is returned.

Example

This example shows how to use the Dialog.STRMENU function.

This code example requires that you create the following text constants and variables in the C/AL Globals window.

Name | ConstValue
Text000 | 'Save,Delete,Exit,Find'
Text001 | 'You selected option%1.'
Text002 | 'Choose one of the following options:'

Name | DataType | Length
Options | Text | 30
Selected | Integer | Not applicable
Copy Code
Options := Text000
// Sets the default to option 3
Selected := Dialog.STRMENU(Options, 3, Text002);
MESSAGE(Text001, Selected);

The menu window displays the following text:

Choose one of the following options:

Save

Delete

Exit

Find

Option 3, Exit, is highlighted. The option that the user selects is stored in the variable Selected. The user receives following message:

You selected option 3.

See Also

Reference

Dialog Data Type


UPDATE Function (Dialog)

Updates the value of a '#'-or '@' field in the active window.

Dialog.UPDATE([Number] [, Value1])

Parameters

Dialog

Type: Dialog

The dialog box that you want to update.

Number

Type: Integer

Each '#' or '@' field has a specific number. The Number argument tells into which field the Value should be inserted. If you omit this parameter, then all '#' or '@' fields in the active window are updated.

Value

Type: Any

This value or expression can be any simple C/AL data type such as Boolean, Option, Integer, Decimal, Date, Time, Text, and Code. If you omit this value, then the value from the variable in the OPEN Function (Dialog) call is used.

Remarks

This function is not supported by Microsoft Dynamics NAV Web client.

When you have a function that contains Dialog.UPDATE(Number,Value) and the value is a variant, you must format the text constant to make sure that the variant type can consume the text constant.

In Microsoft Dynamics NAV, the text constant is read as type AL_TEXTCONST, which cannot be interpreted by the variant.

You can use the FORMAT Function (Code, Text) to convert the text constant to a string type, which can be interpreted and displayed by the variant.

Example

The following example shows how to update '#' fields in a window.

This code example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Length
AccountInfo | Text | 1024
AccountNo | Integer | Not applicable
TotalSum | Decimal | Not applicable
MyDialog | Dialog | Not applicable

Text constant name | Constant value
Text000 | Account no. #1######\
Text001 | shows a total of $ #2######
Copy Code
AccountInfo := Text000 + Text001;
AccountNo := 5634;
TotalSum := 1000;
MyDialog.OPEN(AccountInfo); // Opens a window with '#'-fields.
SLEEP(5000);
MyDialog.UPDATE(1, AccountNo); // Fills in field 1.
SLEEP(5000);
MyDialog.UPDATE(2, TotalSum); // Fills in field 2.
SLEEP(5000);

When the dialog box first opens, the following information is displayed:

Account no. . . . . shows a total of $. . . . . . .

After the first SLEEP call, the value of the AccountNo variable is inserted. After the second SLEEP call, the value of the TotalSum variable is inserted.

See Also

Reference

Dialog Data Type
OPEN Function (Dialog)


FieldRef Data Type

This complex data type identifies a field in a table and gives you access to this field. The FieldRef object can refer to any field in any table in the database.

See Also

Reference

ACTIVE Function (FieldRef)
CALCFIELD Function (FieldRef)
CALCSUM Function (FieldRef)
CAPTION Function (FieldRef, TestPage Field)
CLASS Function (FieldRef)
FIELDERROR Function (FieldRef)
GETFILTER Function (FieldRef)
GETRANGEMAX Function (FieldRef)
GETRANGEMIN Function (FieldRef)
LENGTH Function (FieldRef)
NAME Function (FieldRef)
NUMBER Function (FieldRef)
OPTIONCAPTION Function (FieldRef)
OPTIONSTRING Function (FieldRef)
RECORD Function (FieldRef)
RELATION Function (FieldRef)
SETFILTER Function (FieldRef)
SETRANGE Function (FieldRef)
TESTFIELD Function (FieldRef)
TYPE Function (FieldRef)
VALIDATE Function (FieldRef)
VALUE Function (FieldRef, TestPage Field)


ACTIVE Function (FieldRef)

Checks whether the field that is currently selected is enabled.

Ok := FieldRef.ACTIVE

Parameters

FieldRef

Type: FieldRef

Refers to the current field.

Property Value/Return Value

Type: Boolean

true if the field is enabled; otherwise, false.

Remarks

Each field in a record can be set as enabled or disabled in the table description.

You cannot use a disabled field because disabled fields cannot contain data.

This function is like the FIELDACTIVE Function (Record) function.

Example

The following example opens table 18 (Customer) as a RecordRef variable that is named Recref. The FIELD Function (RecordRef) uses Recref to create a FieldRef variable that is named MyFieldRef. MyFieldRef sets a reference to the first field (field 1) in the table. The SETRANGE Function (FieldRef) sets a filter that selects record 30000. The FIND Function (RecordRef) selects the record and then loops through fields1 through 6. For each field, the ACTIVE function determines whether the field is enabled. If the field is enabled, a message that states that the field is enabled is displayed. Otherwise, a message that states that the field is not enabled is displayed.

Note
You can use the name of the table instead of the table number to open the table by using the following syntax: Recref.OPEN(DATABASE::Customer).

This example requires that you create the following variables and text constants in the C/AL Globals windows.

Variable name | DataType
Recref | RecordRef
MyFieldRef | FieldRef
i | Integer

Text constant | ENU value
Text000 | Field %1 is enabled.
Text001 | Field %1 is not enabled.
Copy Code
Recref.OPEN(18);
MyFieldRef := Recref.FIELD(1);
MyFieldRef.SETRANGE('30000');
Recref.FIND('-');
FOR i := 1 TO 5 DO BEGIN
  MyFieldRef := Recref.FIELDINDEX(i);
  IF MyFieldRef.ACTIVE THEN
    MESSAGE(Text000, i)
  ELSE BEGIN
    MESSAGE(Text001, i)
  END;
END;

See Also

Reference

FieldRef Data Type


CALCFIELD Function (FieldRef)

Updates FlowFields in a record.

[Ok :=] FieldRef.CALCFIELD

Parameters

FieldRef

Type: FieldRef

The FieldRef of the FlowField that you want to update.

Property Value/Return Value

Type: Boolean

true if FlowField has been calculated; otherwise, false.

Remarks

FlowFields are virtual fields. The values in these fields are not saved in the table.

This means that you must use the CALCFIELDS function to update them. For example, if you retrieve a record using the FIND Function (RecordRef) and NEXT Function (RecordRef) functions, the FlowFields in those records are set to zero (0). Then, you can call FieldRef.CALCFIELD, to calculate the value in one of the FlowFields.

When a FlowField is a direct source expression of a control on a page or a report, the calculation is automatically performed.

You can also use the CALCFIELDS function to calculate binary large objects (BLOBs). For more information, see BLOB Data Type.

This function is similar to the CALCFIELDS Function (Record) function.

Example

The following example opens table 18 (Customer) as a RecordRef variable that is named CustRecordref. The FIND Function (RecordRef) selects the first record in the table and then loops through all the records until no records could be found. For each record, the FIELD Function (RecordRef) creates a FieldRef variable that is named MyFieldref for the Balance Due field (field 66), which is a flow field. The CALCFIELD function is called to update the field before the customer ID and the balance due are displayed. Otherwise, the balance due for every record will be set to 0. This example requires that you create the following variables and text constants in the C/AL Globals windows.

Variable name | DataType
CustRecordref | RecordRef
MyFieldRef | FieldRef
Count | Integer

Text constant | ENU value
Text000 | %1: \Balance Due: %2
Copy Code
Count := 0;
CustRecordref.OPEN(18);
IF CustRecordref.FIND('-') THEN
  REPEAT
    MyFieldRef := CustRecordref.FIELD(66);
    MyFieldRef.CALCFIELD;
    MESSAGE(Text000, CustRecordref.RECORDID, MyFieldRef);
    Count := Count + 1;
  UNTIL CustRecordref.NEXT = 0;

See Also

Reference

FieldRef Data Type

Concepts

FlowFields


CALCSUM Function (FieldRef)

Calculates the total of all values of a SumIndexField in a table.

[Ok :=] FieldRef.CALCSUM

Parameters

FieldRef

Type: FieldRef

Refers to the SumIndexField for which you want to calculate a sum.

Property Value/Return Value

Type: Boolean

If you omit this optional return value and if the field is not SumIndexField Technology (SIFT), then a run-time error occurs. If you include a return value, you must handle any errors.

Remarks

This function is like the CALCSUMS Function (Record) function.

This function operates only on records that meet the conditions of any filters associated with the record.

If possible, the CALCSUM function uses SumIndexField Technology (SIFT). SIFT is used only if the following conditions are true:

  • The Microsoft Dynamics NAV key contains the fields that are used in the filters that are defined for the FlowField.

  • The SumIndexFields on the Microsoft Dynamics NAV key contain the field to which the FieldRef parameter refers.

  • The MaintainSIFTIndex Property is set to Yes.

    Note
    By default this property is set to Yes for all keys.

For Microsoft Dynamics NAV 2016, CALCSUM execution is decoupled from Microsoft Dynamics NAV SIFT index definitions. This means that if any of the conditions for using SIFT indexes are not true, then Microsoft Dynamics NAV traverses all records in the base table to perform the calculation instead of using SIFT. This can reduce the number of required SIFT indexes, which can improve performance. In earlier versions of Microsoft Dynamics NAV, if the conditions for using SIFT indexes were not true and the MaintainSIFTIndex property was enabled, then you received an error when you called the CALCSUM function. This provided a degree of protection in earlier versions against accidentally requesting a sorting for which no index existed. In Microsoft Dynamics NAV 2016, an index is not required to support a certain sorting, but sorting without an index could lead to bad performance if a search returns a large result set, which would then have to be sorted before the first row is returned.

The CALCSUM function adheres to the SecurityFiltering Property. For more information about security filters, see Record-Level Security.

Example

This example sets a RecordRef variable to refer to table 21, the Cust. Ledger Entry table. Next, it creates a reference to field 18, the Sales (LCY) field, in the Cust. Ledger Entry table and assigns the field reference to a FieldRef variable. The Sales (LCY) field is a decimal field and is one of the SumIndexFields on a Microsoft Dynamics NAV key in the Cust. Ledger Entry table. The code displays the original value of the FieldRef variable, then calls the CALCSUM function and displays the calculated value of the field.

This example requires that you create the following variables.

Variable name | DataType
MyFieldRef | FieldRef
MyRecRef | RecordRef
Copy Code
MyRecRef.OPEN(21);
MyFieldRef := MyRecRef.FIELD(18);
MESSAGE('Before CALCSUM, Sales (LCY) is %1.', MyFieldRef.VALUE);
MyFieldRef.CALCSUM;
MESSAGE('After CALCSUM, Sales (LCY) is %1.', MyFieldRef.VALUE);

On a computer that has the regional format set to English (United States), the first message window displays the following:

Before CALCSUM, Sales (LCY) is 0.

The second message window displays the following:

After CALCSUM, Sales (LCY) is 55,162.67.

See Also

Reference

CALCSUMS Function (Record)


CAPTION Function (FieldRef, TestPage Field)

Gets the current caption of a field as a String.

Caption := FieldRef.CAPTION
Caption := TestPageField.CAPTION

Parameters

FieldRef

Type: FieldRef

Refers to the current field.

TestPageField

The current field on a TestPage.

Property Value/Return Value

Type: Text or Code

CaptionML or Name property as Text or Code.

Remarks

CAPTION returns the caption of a field. CAPTION first looks for a CaptionML Property.

If it does not find one, it will use the Name Property. This means that CAPTION is enabled for multilanguage functionality.

This function is similar to the FIELDCAPTION Function (Record) function.

Example

The following example opens table 18 (Customer) as a RecordRef variable that is named CustomerRecref. The code uses the FIELD Function (RecordRef) to loop through field 1 through 9 and creates a FieldRef variable that is named MyFieldRef. For each field, the CAPTION function retrieves the caption of the field, stores it in the varCaption variable and displays it in a message box. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
CustomerRecref | RecordRef
MyFieldRef | FieldRef
varCaption | Text
i | Integer

Text constant | ENU value
Text000 | The caption for field %1 is "%2".
Copy Code
CustomerRecref.OPEN(18);
FOR i := 1 TO 9 DO BEGIN
  MyFieldRef := CustomerRecref.FIELD(i);
  varCaption := MyFieldRef.CAPTION;
  MESSAGE(Text000, i, varCaption);
END;
CustomerRecref.CLOSE;

See Also

Reference

FieldRef Data Type

Concepts

Multilanguage Development


CLASS Function (FieldRef)

Gets the value of the FieldClass Property of the field that is currently selected.

This function returns an error if no field is selected.

Class := FieldRef.CLASS

Parameters

FieldRef

Type: FieldRef

Refers to the current field.

Property Value/Return Value

Type: Option

The field class of the field.

Remarks

The FieldRef refers to the field that you are interested in.

The CLASS function returns the class as an Option. However, you cannot assign the class to an Option variable directly. Instead, you must use the EVALUATE Function. The EVALUATE function has a variable parameter to which the value is assigned and a string parameter. You use the FORMAT function to convert the result of the FieldRef.CLASS function to Text, and then use the EVALUATE function to convert the Text to an Option.

Example

In this example, the return value of the CLASS function is converted to Text and then converted to an Option. This example requires that you create the following variables.

Name | DataType
OptionVar | Option
FldRef | FieldRef

The value of the OptionString property of OptionVar is Normal,FlowFilter,FlowField.

Copy Code
EVALUATE(OptionVar,FORMAT(FldRef.CLASS));

In this example, the return value of the CLASS function is converted to Text and then converted to an Option. This example uses the Field virtual table instead of an Option variable. The Field virtual table has a Class field, which is an Option and already has the correct OptionString.

This example requires that you create the following variables.

Name | DataType | Subtype
FieldRec | Record | Field
FldRef | FieldRef | Not applicable
Copy Code
EVALUATE(FieldRec.Class,FORMAT(FldRef.CLASS));

See Also

Reference

FieldRef Data Type


FIELDERROR Function (FieldRef)

Stops the execution of the code, causing a run-time error, and creates an error message for a field.

FieldRef.FIELDERROR([Text])

Parameters

FieldRef

Type: FieldRef

Refers to the field for which you want to create an error message.

Text

Type: Text or Code

Use this optional parameter to include the text of the error message. If this parameter is not present, default text will be used.

Remarks

Similar to a run-time error, this function causes any transaction to be aborted automatically.

This function is like the FIELDERROR Function for the Record data type. For examples, see FIELDERROR Function (Record).

Example

The following example opens table 18 (Customer) as a RecordRef variable that is named CustomerRecref. The CustomerName variable is initialized with a blank text. CustomerRecref.FIELD creates a FieldRef that is named MyFieldRef for field1 (No.) and selects record 30000. Field 2 (Name) is then selected for record 30000. If the CustomerName variable is a blank text, then MyFieldRef.FIELDERROR is executed and an error message is displayed. The text in Text000 text constant is inserted into the error message that is displayed by Microsoft Dynamics NAV. This example uses the default error message. This example requires that you create the following variables and text constant in the C/AL Globals windows.

Variable name | DataType
CustomerRecref | RecordRef
MyFieldRef | FieldRef
CustomerName | Text

Text constant | ENU value
Text000 | cannot be blank
Copy Code
CustomerRecref.OPEN(18);
CustomerName := '';
MyFieldRef := CustomerRecref.FIELD(1);
MyFieldRef.VALUE('30000');
MyFieldRef := CustomerRecref.FIELD(2);
IF CustomerName = '' THEN
  MyFieldRef.FIELDERROR(Text000)
ELSE
  //Do some processing

This code example displays the following error message:

Name cannot be blank in Customer No.=”30000”.

Programming Guidelines

We recommend the following guidelines for error messages:

  • Describe what is wrong and how to solve the problem.

  • Write a short descriptive message. Do not use more words than necessary.

  • Note that a period is automatically inserted at the end of a FIELDERROR.

  • Use a text constant for the Text parameter.

For more information, see Progress Windows, MESSAGE, ERROR, and CONFIRM Functions.

See Also

Reference

FieldRef Data Type


GETFILTER Function (FieldRef)

Gets the filter that is currently applied to the field referred to by FieldRef.

String := FieldRef.GETFILTER

Parameters

FieldRef

Type: FieldRef

Refers to the field for which you want to return the filter.

Property Value/Return Value

Type: Text

This string contains the filter that is applied to the field in the record.

Remarks

See also GETFILTERS Function (RecordRef), SETFILTER Function (FieldRef), and SETRANGE Function (FieldRef).

This function is like the GETFILTER Function (Record)function.

Example

The following example opens the Customer table as a RecordRef variable that is named CustomerRecref. The FIELD Function (RecordRef) creates a FieldRef for the first field (No.) and stores the reference in the MyFieldRef variable. The GETFILTER function retrieves the filters that are set on the No. field and stores the value in the Filters1 variable. The value of any filter that is set is displayed in a message box. The SETFILTER Function (FieldRef) sets the filter that selects records from 10000 to 40000 in the No. field. The GETFILTER function retrieves and stores the filter in the Filter2 variable and displays it in a message. The value in the Filter1 variable is blank because no filter is set. The value in Filter2 is 10000..40000 because of the filter that is set by the SETFILTER Function (FieldRef). This example requires that you create the following variables and text constants in the C/AL Globals windows.

Variable name | DataType
CustomerRecref | RecordRef
MyFieldRef | FieldRef
Filters1 | Text
Filters2 | Text

Text constant | ENU value
Text000 | Filter before filters set: %1.
Text001 | Filter after filters set: %1.
Copy Code
CustomerRecref.OPEN(DATABASE::Customer);
MyFieldRef := CustomerRecref.FIELD(1);
Filters1 := MyFieldRef.GETFILTER;
MESSAGE(Text000, Filters1);
MyFieldRef.SETFILTER('10000..40000');
Filters2 := MyFieldRef.GETFILTER;
MESSAGE(Text001, Filters2);

See Also

Reference

FieldRef Data Type


GETRANGEMAX Function (FieldRef)

Gets the maximum value in a range for a field.

Value := FieldRef.GETRANGEMAX

Parameters

FieldRef

Type: FieldRef

Refers to the current field.

Property Value/Return Value

Type: depends on the field referred to by the FieldRef.

Contains the maximum value of the range set for the field referred to by the FieldRef.

The type of value must match the type of the field referred to by the FieldRef.

Remarks

This function is like the GETRANGEMAX Function (Record) function.

Example

The following example opens the Customer table as RecordRef variable, creates a FieldRef for the first field (No.) and stores the reference in the MyFieldRef variable. The SETFILTER Function (FieldRef) sets a filter that selects records in the range 10000 to 40000 from the No. field. The GETRANGEMAX function retrieves and stores the maximum value that was set in the filter, stores the value in the varMax variable and displays it in a message box. The varMax variable contains 40000 which is the maximum value that is set in the filter. This example requires that you create the following variables and text constant in the C/AL Globals windows.

Variable name | DataType
CustomerRecref | RecordRef
MyFieldRef | FieldRef
varMax | Text

Text constant | ENU value
Text000 | The maximum value in the filter is %1.
Copy Code
CustomerRecref.OPEN(DATABASE::Customer);
MyFieldRef := CustomerRecref.FIELD(1);
MyFieldRef.SETFILTER('10000..40000');
varMax := MyFieldRef.GETRANGEMAX;
MESSAGE(Text000, varMax);

See Also

Reference

GETRANGEMIN Function (FieldRef)
FieldRef Data Type


GETRANGEMIN Function (FieldRef)

Gets the minimum value in a range for a field.

Value := FieldRef.GETRANGEMIN

Parameters

FieldRef

Type: FieldRef

Refers to the current field.

Property Value/Return Value

Type: Text constant or Code

Contains the minimum value of the range set for the field referred to by the FieldRef.

The data type of value must match the data type of the field referred to by the FieldRef.

Remarks

This function is like the GETRANGEMIN Function (Record) function.

Example

The following example opens the Customer table as RecordRef variable, creates a FieldRef for the first field (No.) and stores the reference in the MyFieldRef variable. The SETFILTER Function (FieldRef) sets a filter that selects records in the range 10000 to 40000 from the No. field. The GETRANGEMIN function retrieves and stores the minimum value that is set in the filter, stores the value in the varMin variable and displays it in a message box. The varMin variable contains 10000 which is the minimum value that is set in the filter. This example requires that you create the following variables and text constant in the C/AL Globals windows.

Variable name | DataType
CustomerRecref | RecordRef
MyFieldRef | FieldRef
varMin | Text

Text constant | ENU value
Text000 | The minimum value in the filter is %1.
Copy Code
CustomerRecref.OPEN(DATABASE::Customer);
MyFieldRef := CustomerRecref.FIELD(1);
MyFieldRef.SETFILTER('10000..40000');
varMin := MyFieldRef.GETRANGEMIN;
MESSAGE(Text000, varMin);

See Also

Reference

GETRANGEMAX Function (Record)
FieldRef Data Type


LENGTH Function (FieldRef)

Gets the maximum size of the field (the size specified in the DataLength property of the field). This function is usually used for finding the defined length of code and text fields.

Length := FieldRef.LENGTH

Parameters

FieldRef

Type: FieldRef

Refers to the current field.

Return Value

Type: Integer

The defined length of the field.

Remarks

For Text and Code fields this function returns the defined length. For other types of fields, it returns the fixed byte size, for example, Integer fields returns 4.

Example

The following example opens the Customer table as a RecordRef variable. The FIELD Function (RecordRef) creates a FieldRef for any specified field and stores the reference in the MyFieldRef variable. The LENGTH function retrieves the maximum size of the field and stores the value in the varLength variable. The value that is stored in the varLength is displayed in a message box. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
CustomerRecref | RecordRef
MyFieldRef | FieldRef
varLength | Integer
varFieldNo | Integer

Text constant | ENU value
Text000 | The maximum size of the field is %1.
Copy Code
varFieldNo := 1;
CustomerRecref.OPEN(DATABASE::Customer);
MyFieldRef := CustomerRecref.FIELD(varFieldNo);
varLength := MyFieldRef.LENGTH;
MESSAGE(Text000, varLength);

See Also

Reference

FieldRef Data Type


NAME Function (FieldRef)

Gets the name of a field as a string.

Name := FieldRef.NAME

Parameters

FieldRef

The FieldRef of the field in the record.

Property Value/Return Value

Type: Text Constant or Code

The name of the field given as input.

Remarks

The CAPTION Function (FieldRef, TestPage Field) function retrieves the Caption Property of a field. To enable your application for multilanguage functionality, you must use the FIELDCAPTION Function (Record) instead.

This function is similar to the FIELDNAME Function (Record) function.

Example

The following example opens the Customer table as a RecordRef variable that is named CustomerRecref. The FIELD Function (RecordRef) creates a reference to the fields in the table and stores the FieldRef in the MyFieldRef variable. The code loops through field 1 through 5. For each field, the NAME function retrieves the name of the field and stores the value in the varName variable. The field number and the value in the varName variable are displayed in a message box. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
CustomerRecref | RecordRef
MyFieldRef | FieldRef
varName | Text
i | Integer

Text constant | ENU value
Text000 | The name of field %1 is "%2".\
Copy Code
FOR i := 1 TO 5 DO BEGIN
CustomerRecref.OPEN(DATABASE::Customer);
MyFieldRef := CustomerRecref.FIELD(i);
varName := MyFieldRef.NAME;
MESSAGE(Text000, i, varName);
CustomerRecref.CLOSE;
END;

See Also

Reference

FieldRef Data Type

Concepts

Multilanguage Development


NUMBER Function (FieldRef)

Gets the number of a field as a string.

No := FieldRef.NUMBER

Parameters

FieldRef

Type: FieldRef

Refers to the current field.

Property Value/Return Value

Type: Integer

The number of the table or of the field.

Remarks

This function is like the FIELDNO Function (Record) function.

Example

The following example displays the caption and the field number of the first 10 fields in the Location table. The Location table is open as a RecordRef Data Type object and the reference is stored in the LocationRecref variable. The FieldIndex variable that stores the field index is initialized to 0. The LocationRecref variable uses the FIELDINDEX Function (RecordRef) to create a FieldRef that is named MyFieldRef for the specified field index. MyFiledRef now references the field that is specified by the FieldIndex. MyFieldref is then used to display the number and caption of the field The NUMBER Function (FieldRef) function retrieves the field number. This is repeated for the first ten fields in the table. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType
LocationRecref | RecordRef
MyFieldRef | FieldRef
FieldIndex | Integer
Copy Code
LocationRecref.OPEN(DATABASE::Location);
FieldIndex := 0;
REPEAT
  FieldIndex  := FieldIndex + 1;
  MyFieldRef := LocationRecref.FIELDINDEX(FieldIndex);
  MESSAGE('Field Number: %1  Field Caption: %2.' , MyFieldRef.NUMBER, MyFieldRef.CAPTION);
UNTIL FieldIndex = 10;

See Also

Reference

FieldRef Data Type


OPTIONCAPTION Function (FieldRef)

Gets the option caption of the field that is currently selected.

OptionCaption := FieldRef.OPTIONCAPTION

Parameters

FieldRef

Type: FieldRef

Refers to the current field.

Property Value/Return Value

Type: Text

The option caption of the field.

Remarks

The option caption of the field is returned as a comma separated string.

If the field is not an Option, an empty string is returned.

This function returns an error if no field is selected.

Example

The following example opens the Item table as a RecordRef variable that is named ItemRecref. and creates a reference to field 19 (Price/Profit Calculation field), which is an Option field. The OPTIONCAPTION function retrieves the caption of the option field and displays the options as a comma separated list. This example requires that you create the following variables in the C/AL Globals windows.

Variable name | DataType
ItemRecref | RecordRef
MyFieldRef | FieldRef
OptionCaption | Text
Copy Code
ItemRecref.OPEN(DATABASE::Item);
MyFieldRef := ItemRecref.FIELD(19);
OptionCaption := MyFieldRef.OPTIONCAPTION;
MESSAGE('%1', OptionCaption);

See Also

Reference

FieldRef Data Type


OPTIONSTRING Function (FieldRef)

Gets the list of options that are available in the field that is currently selected.

OptionString := FieldRef.OPTIONSTRING

Parameters

FieldRef

Type: FieldRef

Refers to the current field.

Property Value/Return Value

Type: Text

The list of options that is available in the field.

Remarks

All the options for this field are returned as a comma separated string.

This function returns an error if no field is selected.

If the field is not an option an empty string is returned

Example

The following example opens the Item table with RecordRef variable that is named ItemRecref and creates a reference to field 19 (Price/Profit Calculation), which is an Options field. The OPTIONSTRING function retrieves the options in the field and displays them as a comma separated list. This example requires that you create the following variables in the C/AL Globals windows.

Variable name | DataType
ItemRecref | RecordRef
MyFieldRef | FieldRef
OptionString | Text
Copy Code
ItemRecref.OPEN(DATABASE::Item);
MyFieldRef := ItemRecref.FIELD(19);
OptionString := MyFieldRef.OPTIONSTRING;
MESSAGE(' %1', OptionString);

See Also

Reference

FieldRef Data Type


RECORD Function (FieldRef)

Gets the RecordRef of the field that is currently selected.

This function returns an error if no field is selected.

RecordRef := FieldRef.RECORD

Parameters

FieldRef

Type: FieldRef

Refers to the current field.

Return Value

Type: RecordRef

The RecordRef of the field that is currently selected.

See also RecordRef Data Type.

Example

The following example opens the Item table as a RecordRef variable that is named ItemRecref, creates a reference to field 1 (No.), and stores the value in the variable named MyFieldRef. The RECORD function uses the MyFieldRef variable to return the RecordRef of field 1 and stores the reference in a variable named MyRecRef. MyRecRef.NUMBER returns the table that the selected field belongs to. This example requires that you create the following variables and text constant in the C/AL Globals windows.

Variable name | DataType
ItemRecref | RecordRef
MyFieldRef | FieldRef
MyRecRef | RecordRef

Text constant | ENU value
Text000 | The selected field is from table %1.
Copy Code
ItemRecref.OPEN(DATABASE::Item);
MyFieldRef := ItemRecref.FIELD(1);
MyRecRef := MyFieldRef.RECORD;
MESSAGE(Text000, MyRecRef.NUMBER);

See Also

Reference

FieldRef Data Type


RELATION Function (FieldRef)

Finds the table relationship of a given field.

TableNumber := FieldRef.RELATION

Parameters

FieldRef

Type: FieldRef

The FieldRef that refers to the field for which you want to find the table relationship.

Property Value/Return Value

Type: Integer

The number of the table that has a relationship with the field referred to by FieldRef.

This relationship is set up through the properties.

Remarks

You can use this function for several purposes such as to determine lookups or to check to see if you have permission to read from a table.

This function is similar to the RELATION Function (Record) function.

Example

The following example opens table 37, the Sales Line table, as a RecordRef variable and creates a reference to field 2 (Sell-to Customer No.). The FieldRef Data Type of field 2 is stored in the MyFieldRef variable. The RELATION function retrieves the number of the table that has a relation with the Sell-To-Customer field (field 2). The table number is stored the varRelation variable and displayed in the message box. This example requires that you create the following variables and text constant in the C/AL Globals windows.

Variable name | DataType
SaleRecref | RecordRef
MyFieldRef | FieldRef
varRelation | Integer

Text constant | ENU value
Text000 | Field 2 in the Sales Line (37) table has a relation with table %1.
Copy Code
SaleRecref.OPEN(37);
MyFieldRef := SaleRecref.FIELD(2);
varRelation := MyFieldRef.RELATION;
MESSAGE(Text000, varRelation);

See Also

Reference

FieldRef Data Type


SETFILTER Function (FieldRef)

Assigns a filter to a field that you specify.

FieldRef.SETFILTER(String [, Value],...)

Parameters

FieldRef

Type: FieldRef

The FieldRef that refers to the field that you want to place a filter on.

String

Type: Text or Code

The filter expression. A valid expression consists of alphanumeric characters and one or more of the following operators: <, >, *, &, |, and =. You can use replacement fields (%1, %2, and so on) to insert values at run time.

Value

Type: any

Replacement values to insert in replacement fields in the filter expression. The data type of Value must match the type of FieldRef.

Remarks

If the function is called with a field for which a filter already exists, the filter is removed before a new one is set. You can construct filters using the following operators.

Operator | Description
.. | Range
& | And
| | Or
< | Less than
<= | Less than or equal to
> | Greater than
>= | Greater than or equal to
<> | Different from
* | Forms a part of value
@ | Case-insensitive

This function is like the SETFILTER Function (Record) function.

Example

The following example opens the Customer table as a RecordRef variable that is named CustomerRecref. The FIELD Function (RecordRef) creates a FieldRef for the first field (No.) and stores the reference in the MyFieldRef variable. The GETFILTER Function (FieldRef) retrieves the filters that are set on the No. field and stores the value in the Filter1 variable. The value of any filter that is set is displayed in a message box. The SETFILTER function sets a filter that selects records from 10000 to 40000 in the No. field. The GETFILTER Function (FieldRef) retrieves and stores the new filter in the Filter2 variable and displays it in a message. The value in the Filter1 variable is blank because no filter is set. The value in Filter2 is 10000..40000 because of the filter that is set by the SETFILTER function. This example requires that you create the following variables and text constants in the C/AL Globals windows.

Variable name | DataType
CustomerRecref | RecordRef
MyFieldRef | FieldRef
Filter1 | Text
Filter2 | Text

Text constant | ENU value
Text000 | Filter before filters set: %1.
Text001 | Filter after filters set: %1.
Copy Code
CustomerRecref.OPEN(DATABASE::Customer);
MyFieldRef := CustomerRecref.FIELD(1);
Filter1 := MyFieldRef.GETFILTER;
MESSAGE(Text000, Filter1);
MyFieldRef.SETFILTER('10000..40000');
Filter2 := MyFieldRef.GETFILTER;
MESSAGE(Text001, Filter2);

See Also

Reference

FieldRef Data Type


SETRANGE Function (FieldRef)

Sets a simple filter on a field, such as a single range or a single value.

FieldRef.SETRANGE([FromValue] [, ToValue])

Parameters

FieldRef

Type: FieldRef

The FieldRef that refers to the field that you want to place a filter on.

FromValue

Type: any

The lower limit of the range. The data type of FromValue must match the data type of the field referred to by FieldRef.

ToValue

Type: any

The upper limit of the range. If you omit this parameter, the FromValue you specified is used. The data type of ToValue must match the data type of the field referred to by FieldRef.

Remarks

The SETRANGE function provides a quick way to set a simple filter on a field.

If you call this function by using a field that already has a filter, that filter is removed before the new filter is set.

If you omit all of the optional parameters, all filters set for that field are removed.

The SETRANGE function fails if no field is selected.

This function is like the SETRANGE Function (Record) function.

Example

The following example opens the Customer table as a RecordRef object, creates a reference to the first (No.) field, and stores the reference in the MyFieldRef variable. The SETRANGE function sets a filter that selects all records from 10000 to 40000 in the No. field. The FIND Function (RecordRef) searches and selects the first record in the filter and counts the number of records that are found. The number of records is stored in the Count variable. The process is repeated by looping through all the records in the filter until no more records are found. The number of records that are found in the range is stored in the Count variable and displayed in a message box. This example requires that you create the following variables in the C/AL Globals windows.

Variable name | DataType
CustomerRecref | RecordRef
MyFieldRef | FieldRef
Count | Integer

Text constant | ENU value
Text000 | %1 records were retrieved.
Copy Code
CustomerRecref.OPEN(DATABASE::Customer);
MyFieldRef := CustomerRecref.FIELD(1);
MyFieldRef.SETRANGE('10000' , '40000');
Count := 0;
IF CustomerRecref.FIND('-') THEN
  REPEAT
    Count := Count + 1;
  UNTIL CustomerRecref.NEXT = 0;
MESSAGE(Text000 , Count);

See Also

Reference

FieldRef Data Type


TESTFIELD Function (FieldRef)

Determines whether the contents of a field matches a given value. If the contents differ from the given value, an error message is displayed.

FieldRef.TESTFIELD([Value])

Parameters

FieldRef

Type: FieldRef

Refers to the current field.

Value

Type: any

The value that you want to compare with the contents of the field referred to by

FieldRef. The data type of Value must match the type of the field.

If you include Value and the contents of the field do not match, an error message is displayed.

If you omit Value and the content of the field is zero or blank (empty string), an error message is displayed.

Remarks

This function is like the TESTFIELD Function (Record) function.

Example

The following example opens the Customer table as a RecordRef variable that is named CustomerRecref, created a reference to the first field (No) and stores the reference in the MyFieldRef variable. The VALUE Function (FieldRef, TestPage Field) sets the No. field to a blank text. The TESTFIELD function determines whether the contents of the field match 10000, the specified value. In this case, the content does not match so the Microsoft Dynamics NAV throws an exception. If the there is a match, no exception is thrown. This example requires that you create the following variables in the C/AL Globals windows.

Variable name | DataType
CustomerRecref | RecordRef
MyFieldRef | FieldRef
Copy Code
CustomerRecref.OPEN(DATABASE::Customer);
MyFieldRef := CustomerRecref.FIELD(1);
MyFieldRef.VALUE := '';
MyFieldRef.TESTFIELD('10000');

In this example, the Microsoft Dynamics NAV displays following error message:

No. must be equal to 10000 in Customer: No.=. Current value is ‘’.

Example

If the value of the No. field is set to a value other than 10000, Microsoft Dynamics NAV displays the following error message:

No. must be equal to 10000 in Customer: No.=AAA10000. Current value is ‘AAA10000’.

Copy Code
CustomerRecref.OPEN(DATABASE::Customer);
MyFieldRef := CustomerRecref.FIELD(1);
MyFieldRef.VALUE := 'AAA 10000';
MyFieldRef.TESTFIELD('10000');

See Also

Reference

FieldRef Data Type


TYPE Function (FieldRef)

Gets the data type of the field that is currently selected.

Type := FieldRef.TYPE

Parameters

FieldRef

Type: FieldRef

Refers to the current field.

Property Value/Return Value

Type: The data type of the field.

Example

The following example opens the Customer table as a RecordRef variable that is named CustomerRecref. The code loops through fields 1 to 5 and creates a FieldRef that is named MyFieldRef for each field that is selected. MyFieldRef.TYPE retrieves the data of each field and displays it in a message box. This example requires that you create the following variables and text constant in the C/AL Globals windows.

Variable name | DataType
CustomerRecref | RecordRef
MyFieldRef | FieldRef
varType | Variant

Text constant | ENU value
Text000 | Field %1 is a %2 data type.
Copy Code
CustomerRecref.OPEN(DATABASE::Customer);
FOR i := 1 TO 5 DO BEGIN
  MyFieldRef := CustomerRecref.FIELD(i);
  MESSAGE(Text000, i, MyFieldRef.TYPE);
END;

See Also

Reference

FieldRef Data Type


VALIDATE Function (FieldRef)

Use this function to enter a new value into a field and have the new value validated by the properties and code that have been defined for that field.

FieldRef.VALIDATE([NewValue])

Parameters

FieldRef

Type: FieldRef

Refers to the current field.

NewValue

Type: must be compatible with the data type of the field referred to by the FieldRef.

The value to insert in the field.

Remarks

The VALIDATE function first checks any TableRelation Property, and then executes the OnValidate (Fields) Trigger of the field.

If you omit NewValue, the function validates the current value.

This function is like the VALIDATE Function (Record).

Example

The following example opens table 17 (G/L Entry) as a RecordRef that is named EntryRecref. The FINDFIRST Function (RecordRef) searches for the first record in the table. The FIELD Function (RecordRef) sets the field to 3, which is the G/L Account No. field. The VALIDATE function validates and inserts the specified value (1210) into the field. The MODIFY Function (RecordRef) modifies the table. A message that indicates the G/L Account No. field has changed is displayed. To show that the code in the OnValidate trigger is executed, design the G/L Entry table and add the following code to the G/L Account No. - OnValidate trigger: MESSAGE('The OnValidate trigger is called.');

This example requires that you create the following variables and text constants in the C/AL Globals windows.

Variable name | DataType
EntryRecref | RecordRef
MyFieldRef | FieldRef

Text constant | ConstValue
Text000 | The G/L Account No. for record %1 is %2.
Text001 | The G/L Account No. for record %1 has changed to %2.
Copy Code
EntryRecref.OPEN(17);
IF EntryRecref.FINDFIRST THEN BEGIN
  MyFieldRef := EntryRecref.FIELD(3);
  MESSAGE(Text000, EntryRecref.RECORDID, MyFieldRef.VALUE);
  MyFieldRef.VALIDATE('1210');
  EntryRecref.MODIFY;
  MESSAGE(Text001, EntryRecref.RECORDID, MyFieldRef.VALUE);
END;

See Also

Reference

FieldRef Data Type


VALUE Function (FieldRef, TestPage Field)

Sets or gets the value of the field that is currently selected.

This function returns an error if no field is selected.

[CurrValue :=] FieldRef.VALUE([NewValue])

Parameters

FieldRef

Type: FieldRef or TestPage Field

Refers to the current field.

NewValue

Type: Variant

The new value that you want to set for the field.

Property Value/Return Value

Type: Variant

The current value of the field.

Remarks

If you omit NewValue, the function returns the current value of the field.

If you want to format the value of a FieldRef you must use FORMAT(FieldRef) instead of FORMAT(FieldRef.VALUE).

Example

The following example opens table 18, the Customer table, a RecordRef variable that is named CustomerRecref. The FIELD Function (RecordRef) creates a FieldRef for the first field (No.). The reference to the field is stored in the MyFieldRef variable. The ACTIVE Function (FieldRef) function determines whether the field is enabled. If the field is enabled, then the record that is identified by the number in the CustomerNo variable is selected. The MyFieldRef variable is updated to refer to the second field (Name). Then the value in the second field is changed to Contoso. The MODIFY Function (RecordRef) modifies the record in the table to reflect the change. MyFieldRef.VALUE retrieves the new name and displays it in message box. This example requires that you create the following variables and text constant in the C/AL Globals windows.

Variable name | DataType
CustomerRecref | RecordRef
MyFieldRef | FieldRef
CustomerNo | Code

Text constant name | ConstValue
Text000 | Customer name has changed to %1.
Copy Code
CustomerNo := '50000';
CustomerRecref.OPEN(18);
MyFieldRef := CustomerRecref.FIELD(1);
IF MyFieldRef.ACTIVE THEN BEGIN
  MyFieldRef.VALUE(CustomerNo);
  MyFieldRef := CustomerRecref.FIELD(2);
  MyFieldRef.VALUE('Contoso');
  CustomerRecref.MODIFY;
  MESSAGE(Text000, MyFieldRef.VALUE);
END

See Also

Reference

FieldRef Data Type


File Data Type

The File data type gives access to files. Files can be opened in text or binary mode. For more information, see TEXTMODE Function (File).

You can read from or write to a file by creating input and output streams, respectively. To do so, use the CREATEINSTREAM Function (File) and CREATEOUTSTREAM Function (File). For more information, see InStream and OutStream Data Types.

See Also

Reference

CLOSE Function (File)
COPY Function (File)
CREATE Function (File)
CREATEINSTREAM Function (File)
CREATEOUTSTREAM Function (File)
CREATETEMPFILE Function (File)
DOWNLOAD Function (File)
DOWNLOADFROMSTREAM Function (File)
ERASE Function (File)
EXISTS Function (File)
GETSTAMP Function (File)
LEN Function (File)
NAME Function (File)
OPEN Function (File)
POS Function (File)
READ Function (File)
RENAME Function (File)
SEEK Function (File)
SETSTAMP Function (File)
TEXTMODE Function (File)
TRUNC Function (File)
UPLOAD Function (File)
UPLOADINTOSTREAM Function (File)
WRITE Function (File)
WRITEMODE Function (File)


CLOSE Function (File)

Closes a file that has been opened by the OPEN Function (File).

File.CLOSE

Parameters

File

Type: File

Specifies the file.

Remarks

If the file is not open, a run-time error will occur.

Example

The following example determines whether the specified file exists. If it exists, the WRITEMODE Function (File) allows the file to be open for writing. The OPEN Function (File) opens the file, the WRITE Function (File) writes the text “Hello World” to the file, and then the CLOSE function closes the file. If the file does not exist, an error message is displayed. This example requires that you create the following variables in the C/AL Globals window. This example assumes that you have created the following file C:\TestFolder\TestFile2.txt.

Variable name | DataType
FileName | Text
TestFile | File
Copy Code
FileName := 'C:\TestFolder\TestFile2.txt';
IF EXISTS(FileName) THEN BEGIN
  TestFile.WRITEMODE(TRUE);
  TestFile.OPEN(FileName);
  TestFile.WRITE('Hello World');
  TestFile.CLOSE;
END
ELSE
MESSAGE('%1 does not exist.', FileName);

See Also

Reference

File Data Type


COPY Function (File)

Use this function to copy a file.

[Ok :=] File.COPY(FromName, ToName)

Parameters

FromName

Type: Text or code

The name of the file that you want to make a copy of, including its path. When you enter the path, consider these shortcuts:

  • You can omit the drive designation if the file is located on the current drive.

  • You can omit the full path if the file is located in the current directory.

  • You can enter only the subdirectory name if the file is located in a subdirectory of the current directory.

ToName

Type: Text or code

The name that you want to assign to the copy that includes its path. When you enter the path, consider these shortcuts:

  • You can omit the drive designation if the file is located on the current drive.

  • You can omit the full path if the file is located in the current directory.

  • You can enter only the subdirectory name if the file is located in a subdirectory of the current directory.

Property Value/Return Value

Type: Boolean

This optional return parameter shows you whether the file was copied.

Remarks

If you do not use the return value and the file cannot be copied, a run-time error will occur. If you do include the return value in your code, you must handle any errors yourself.

Example

The following example copies a file that is named OldFile from a folder that is named Old on drive C to a folder that is named New. If the file is copied, a message is displayed and the program continues. Otherwise, an error occurs. This example requires that you create the following variables in the C/AL Globals window. This example assumes that you have created the following file 'c:\Old\' OldFile.

Variable name | DataType
OldFile | Text
NewFile | Text
Copy Code
OldFile := 'old.txt';
NewFile := 'new.txt';
IF FILE.COPY('c:\Old\' + OldFile, 'c:\New\' + NewFile) THEN
  // Continue your program.
  MESSAGE('The file was copied.')
ELSE
  // Handle the error.
  MESSAGE('The file was not copied.')

See Also

Reference

File Data Type


CREATE Function (File)

Creates and opens an ASCII or binary file. If the file already exists, it will be truncated and then opened.

[Ok := ] File.CREATE(Name[,TextEncoding.value])

Parameters

File

Type: File

Specifies the file to create.

Name

Type: Text or code

The name of the file that include the path. The following rules apply:

  • You can omit the drive designation if the file is located on the current drive.

  • You can omit the full path if the file is located in the current directory.

  • You can enter only the subdirectory name if the file is located in a subdirectory of the current directory.

TextEncoding

Value: MsDos, UTF8, UTF16, or Windows

Optionally, you can specify the encoding on the file. By specifying the text encoding, you ensure that all the language-specific characters are represented correctly in Microsoft Dynamics NAV when you read data and write data.

For more information, see Text Encoding.

Property Value/Return Value

Type: Boolean

Specifies whether the file was created.

true if the file was created; otherwise, false.

Remarks

If the TEXTMODE Function (File) returns true and you read or write to the file, text is put in the buffer.

If the TEXTMODE Function (File) function returns false, binary information is put in the buffer.

If you call CREATE on a File variable that refers to an open file, the function does not automatically close the existing file and create the new file. You must explicitly call the CLOSE Function (File) to close the existing file. Otherwise, a run-time error occurs.

Example

The following example creates a file that is named TestFile.txt in the path C:\TestFolder\. The TestFile variable stores the file and path that is created. If the file is created, a message that states that the file is created is displayed. Otherwise, an error message is displayed. This example requires that you create the following variable in the C/AL Globals window.

Variable name | DataType
TestFile | File
Copy Code
IF TestFile.CREATE('C:\TestFolder\TestFile.txt') THEN BEGIN
  MESSAGE('%1 is created', TestFile.NAME)
END
ELSE
ERROR('The file could not be created');

See Also

Reference

File Data Type

Concepts

Text Encoding


CREATEINSTREAM Function (File)

Creates an InStream object for a file. This enables you to import or read data from the file.

File.CreateInStream(Stream)

Parameters

File

Type: File

The file that you want to create the InStream object for.

Stream

The InStream object that will be used to read or write the data to the file.

Example

The following example imports data from an XML document to a table. The code uses the OPEN Function (File) to open the XML document named NewCustomer.xml from a folder named Import on the C drive. The CREATEINSTREAM Function (File) creates a data stream to get the data from the XML document into the table. The IMPORT Function (XMLport) then imports, parses the data, and adds it as a record to the table by using an XMLport (50004). The CLOSE Function (File) then closes the data stream. This example assumes that you have created a NewCustomer.xml file in a folder that is named Import on the C drive and you have created an XMLport and given it ID 50004. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType
ImportXmlFile | File
XmlINStream | InStream
Copy Code
ImportXmlFile.OPEN('C:\Import\NewCustomer.xml');
ImportXmlFile.CREATEINSTREAM(XmlINStream);
XMLPORT.IMPORT(50004, XmlINStream);
ImportXmlFile.CLOSE;

See Also

Reference

File Data Type


CREATEOUTSTREAM Function (File)

Creates an OutStream object for a file. This enables you to export or write data to the file.

File.CreateOutStream(Stream)

Parameters

File

Type: File

Use this variable to refer to the file.

Stream

The OutStream object type that has been created.

For more information, see How to: Use Streams to Write to Text Files.

Example

The following example uses the CREATEOUTSTREAM function to export data from a table to an XML document. The code uses the CREATE Function (File) to create an XML file that is named CustXmlFile.xml in a folder that is named xmlData on drive C. The CREATEOUTSTREAM Function (File) opens a data stream to output the data from the table to the XML file. The EXPORT Function (XMLport) then exports the data and saves it at the specified location. The CLOSE Function (File) closes the data stream. This example assumes that you have created a folder named xmlData on drive C. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Subtype
CustXmlFile | File | Not applicable
XmlStream | OutStream | Not applicable
varXmlPort | XMLport | 50002 This inserts the name of the XMLport.
Copy Code
CustXmlFile.CREATE('C:\XmlData\Customer.xml');
CustXmlFile.CREATEOUTSTREAM(XmlStream);
XMLPORT.EXPORT(50002, XmlStream);
CustXmlFile.CLOSE;

See Also

Reference

File Data Type


CREATETEMPFILE Function (File)

Creates a temporary file. This enables you to save data of any format to a temporary file. This file has a unique name and will be stored in a temporary file folder.

File.CreateTempFile[(TextEncoding.value)]

Parameters

File

Type: File

Use this variable to refer to the file.

TextEncoding

Value: MsDos, UTF8, UTF16, or Windows

Optionally, you can specify the encoding on the file. By specifying the text encoding, you ensure that all the language-specific characters are represented correctly in Microsoft Dynamics NAV when you read data and write data.

For more information, see Text Encoding.

Remarks

You can use this function together with NAME Function (File) and CLOSE Function (File).

Example

This example creates a temporary file that has the text Hello and then deletes the file by using the File.CLOSE function. This example requires that you create the following variable.

Variable | DataType
FileName | File
Copy Code
FileName.CREATETEMPFILE;
FileName.WRITE('Hello');
FileName.CLOSE;

See Also

Reference

File Data Type

Concepts

Text Encoding


DOWNLOAD Function (File)

Sends a file from a Microsoft Dynamics NAV Server computer to the client computer. The client computer is the computer that is running the Microsoft Dynamics NAV Windows client or the computer that is running a browser that accesses the Microsoft Dynamics NAV Web client.

[Ok :=] DOWNLOAD(FromFile, DialogTitle, ToFolder, ToFilter, ToFile)

Parameters

FromFile

Type: Text

The name of the file on the Microsoft Dynamics NAV Server computer that you want to download to the client computer.

DialogTitle

Type: Text

The title that you want to display in the dialog box for downloading the file.

Note
This parameter is not supported by the Microsoft Dynamics NAV Web client. The title is determined by the end-user's browser.

ToFolder

Type: Text

The default folder in which to save the file to be downloaded. The folder name is displayed in the dialog box for downloading the file. The folder can be changed by the user.

Note
This parameter is not supported by the Microsoft Dynamics NAV Web client. By default, files are saved to the default download location that is configured in the end-user's browser.

ToFilter

Type: Text

The type of file that can be downloaded to the client computer. The type is displayed in the dialog box for downloading the file.

Note
This parameter is not supported by the Microsoft Dynamics NAV Web client.

ToFile

Type: Variant

The name to give the downloaded file. This is the default file name that is shown in the dialog box for downloading the file. This value can be changed by the user.

Property Value/Return Value

Type: Boolean

If you omit this optional return value, then a run-time error occurs if the file cannot be found. If you include a return value, then it is assumed that you will handle any errors.

true if the file was downloaded; otherwise, false.

Remarks

Note
This function is not fully supported by the Microsoft Dynamics NAV Web client on devices that run Apple iOS, such as iPad. You can only download a file if the Apple iOS device on which you are downloading the file has an application that supports the file type.

In Microsoft Dynamics NAV, the business logic is run on the computer that is running Microsoft Dynamics NAV Server and not on the client. Files are created on the computer that is running Microsoft Dynamics NAV Server and not locally on the client computer.

UPLOAD Function (File) and UPLOADINTOSTREAM Function (File) are used to send a file from the client to a Microsoft Dynamics NAV Server instance.

DOWNLOAD Function (File) and DOWNLOADFROMSTREAM Function (File) are used to send a file from a Microsoft Dynamics NAV Server instance to the client.

We recommend that you use the functions in codeunit 419, File Management, to upload and download files.

Example

This example shows how to use the DOWNLOAD function. It requires that you create the following variable.

Variable name | DataType
ToFile | Text
Copy Code
ToFile := 'ToFile.txt';
DOWNLOAD('FromFile.txt','Download file','C:\','Text file(*.txt)|*.txt',ToFile);

See Also

Reference

File Data Type


DOWNLOADFROMSTREAM Function (File)

Sends a file from Microsoft Dynamics NAV Server computer to the client computer. The client computer is the computer that is running the Microsoft Dynamics NAV Windows client or the computer that is running the browser that accesses the Microsoft Dynamics NAV Web client.

[Ok :=] DOWNLOADFROMSTREAM(VarInstream, DialogTitle, ToFolder, ToFilter, ToFile)

Parameters

VarInStream

Type: Variant

An InStream that you want to use to send the data in a file on Microsoft Dynamics NAV Server to a file on the client computer.

DialogTitle

Type: Text

The title that you want to display in the dialog box for downloading the file.

Note
This parameter is not supported by the Microsoft Dynamics NAV Web client. The title is determined by the end-user's browser.

ToFolder

Type: Text

The default folder in which to save the file to be downloaded. The folder name is displayed in the dialog box for downloading the file. The folder can be changed by the user.

Note
This parameter is not supported by the Microsoft Dynamics NAV Web client. By default, files are saved to the default download location that is configured in the end-user's browser.

ToFilter

Type: Text

The type of file that can be downloaded to the client computer. The type is displayed in the dialog box for downloading the file.

Note
This parameter is not supported by the Microsoft Dynamics NAV Web client.

ToFile

Type: Variant

The name to give the downloaded file. This is the default file name that is shown in the dialog box for downloading the file. This value, can be changed by the user.

Property Value/Return Value

Type: Boolean

If you omit this optional return value, then a run-time error occurs if the record cannot be found. If you include a return value, then you must handle any errors.

true if the file was downloaded; otherwise, false.

Remarks

Note
This function is not fully supported by the Microsoft Dynamics NAV Web client on devices that run Apple iOS, such as iPad. You can only download a file if the Apple iOS device on which you are downloading the file has an application that supports the file type.

The business logic runs on the computer that is running Microsoft Dynamics NAV Server and not on the client. Files are created on a Microsoft Dynamics NAV service and not locally on the client computer. When you write code, you must consider where files are created.

Use UPLOAD Function (File) and UPLOADINTOSTREAM Function (File) to send a file from a client to a Microsoft Dynamics NAV Server instance.

Use DOWNLOAD Function (File) and DOWNLOADFROMSTREAM Function (File) to send a file from a Microsoft Dynamics NAV Server instance to a client.

We recommend that you use the functions in codeunit 419, File Management, to upload and download files.

Example

This example requires that you create the following variables.

Name | DataType
TempFile | File
NewStream | InStream
ToFileName | Variant
Copy Code
TempFile.CREATETEMPFILE();
TempFile.WRITE('abc');
TempFile.CREATEINSTREAM(NewStream);
ToFileName := 'SampleFile.txt';
DOWNLOADFROMSTREAM(NewStream,'Export','','All Files (*.*)|*.*',ToFileName)

See Also

Tasks

Walkthrough: Transferring a File from Microsoft Dynamics NAV Server to the Client

Reference

File Data Type


ERASE Function (File)

Deletes a file.

[Ok :=]ERASE(Name)

Parameters

Name

Type: Text or code

The name of the file that you want to delete, including the path. When you enter the path, consider these shortcuts:

  • You can omit the drive designation if the file is located on the current drive.

  • You can omit the full path if the file is located in the current directory.

  • You can enter only the subdirectory name if the file is located in a subdirectory of the current directory

Property Value/Return Value

Type: Boolean

Specifies whether the file was deleted.

true if the file was deleted; otherwise, false.

If you omit this optional return value and the file is not deleted, a run-time error occurs. If you include the return value, you must handle any errors.

Remarks

If the user who runs this function does not have the required permission to delete the file or if the file is read-only, then the file is not deleted.

Example

The following example deletes the file that is named C:\TestFolder\NewTestFile.txt.This example assumes that you have created the file on your computer.

Copy Code
ERASE('C:\TestFolder\NewTestFile.txt');

See Also

Reference

File Data Type


EXISTS Function (File)

Determines whether a file exists.

[Ok :=] EXISTS(Name)

Parameters

Name

Type: Text or code

The name of the file that you want to check. This includes the path. When you enter the path, consider these shortcuts:

  • You can omit the drive designation if the file is located on the current drive.

  • You can omit the full path if the file is located in the current directory.

  • You can enter only the subdirectory name if the file is located in a subdirectory of the current directory.

Property Value/Return Value

Type: Boolean

This return value shows whether the file exists.

true if the file exists; otherwise, false.

Example

The following example uses the EXISTS function to determine whether the specified file exists. If the file exists, then the WRITEMODE Function (File) allows the file to be open for writing. The OPEN Function (File) opens the file, the WRITE Function (File) writes the text “Hello World” to the file, and then the CLOSE Function (File) function closes the file. If the file does not exist, an error message is displayed. This example requires that you create the following variables in the C/AL Globals window. This example assumes that you have created the following file C:\TestFolder\TestFile2.txt.

Variable name | DataType
FileName | Text
TestFile | File
Copy Code
FileName := 'C:\TestFolder\TestFile2.txt';
IF EXISTS(FileName) THEN BEGIN
  TestFile.WRITEMODE(TRUE);
  TestFile.OPEN(FileName);
  TestFile.WRITE('Hello World');
  TestFile.CLOSE;
END
ELSE
MESSAGE('%1 does not exist.', FileName);

See Also

Reference

File Data Type


GETSTAMP Function (File)

Gets the exact time that a file was last written to.

[Ok :=] GETSTAMP(Name, Date [, Time])

Parameters

Name

Type: Code or Text

The name of the file, including the path. When you enter the path, consider these shortcuts:

  • You can omit the drive designation if the file is located on the current drive.

  • You can omit the full path if the file is located in the current directory.

  • You can enter only the subdirectory name if the file is located in a subdirectory of the current directory.

Date

Type: Date

The date that the file was last written to.

Time

Type: Time

(Optional) The time that the file was last written to.

Property Value/Return Value

Type: Boolean

If you omit this optional return value, then a run-time error occurs when the file cannot be found. When you include the return value, you must handle any errors. The return value can have these values:

true if the file exists and the function completes successfully; otherwise, false.

Example

The following example gets the date and time that a file was written to and displays the data in a message box. The code example assumes that you have created the file 'C:\MyFolder\MyText.txt'. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
varFileName | Text
varDate | Date
varTime | Time

Text constant name | ConstValue
Text000 | This document was last written to on %1 at %2.
Copy Code
varFileName := 'C:\MyFolder\MyText.txt';
GETSTAMP(VarFileName, varDate, varTime);
MESSAGE(Text000, varDate, varTime);

See Also

Reference

File Data Type


LEN Function (File)

Gets the length of an ASCII or binary file.

Length := File.LEN

Parameters

File

Type: File

Use this variable to refer to the file.

Property Value/Return Value

Type: Integer

The length of the file in bytes.

Remarks

This function is often used with POS Function (File) and SEEK Function (File).

Example

The following example opens a text file that is named 'C:\TestFolder\TestFile.txt' and contains the text ‘Hello World’. The SEEK Function (File) sets a pointer to position 6 in the file. The READ Function (File) reads the file and stores the retrieved contents in the varString variable. The LEN function retrieves the length of the file and stores it the varLength variable. The text that is read starts from the position of the pointer, so the text ‘World’ and the length of 12 are displayed in the message box. The length of the file is not affected by the SEEK Function (File). This example assumes that you have created the text file that is named C:\TestFolder\TestFile.txt and contains the text ‘Hello World’. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Length
Testfile | File | Not applicable
varString | Text | 200
varLength | Integer | Not applicable
Copy Code
Testfile.OPEN('C:\TestFolder\TestFile.txt');
Testfile.SEEK(6);
Testfile.READ(varString);
varLength := Testfile.LEN;
MESSAGE('The text is: %1. The length of the file is: %2', varString, varLength);

See Also

Reference

File Data Type


NAME Function (File)

Gets the name of an ASCII or binary file.

Name := File.NAME

Parameters

File

Type: File

Use this variable to refer the file.

Property Value/Return Value

Type: Text or Code

This string contains the name of the file, including its path.

Remarks

You must use the OPEN Function (File) to open the file before you can use this function.

Example

The following example opens a text file that is named C:\TestFolder\TestFile.txt. The NAME Function (File) retrieves the name and path of the text file and stores it in the varName variable. The value in the variable is displayed in a message box. This example assumes that you have created a text file named C:\TestFolder\TestFile.txt. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType
TestFile | File
varName | Text
Copy Code
TestFile.OPEN('C:\TestFolder\TestFile.txt');
varName := TestFile.NAME;
MESSAGE('The name of the file is: %1',varName);

See Also

Reference

File Data Type


OPEN Function (File)

Opens an ASCII or binary file. This function does not create the file if it does not exist.

[Ok := ] File.OPEN(Filename[,TextEncoding.value])

Parameters

File

Type: File

Specifies the file.

Filename

Type: Text

Specifies the name and path of the file to open.

TextEncoding

Value: MsDos, UTF8, UTF16, or Windows

Optionally, you can specify the encoding on the file. By specifying the text encoding, you ensure that all the language-specific characters are represented correctly in Microsoft Dynamics NAV when you read data and write data.

For more information, see Text Encoding.

Property Value/Return Value

Type: Boolean

Specifies whether the file was opened. If you omit this optional return value and if the file cannot be found, then a run-time error occurs.

true if the file was opened; otherwise, false.

Remarks

If you call OPEN on a file variable that refers to an open file, then the function does not automatically close the existing file and open the new file. You must explicitly call the CLOSE Function (File) to close the existing file. If you call OPEN on a file that is already open, then a run-time error occurs.

Example

This example shows how to open an .xml file for reading in text mode. To use this example, you must create the simple.xml file at C:\temp and create the following variable.

Variable | DataType
TestFile | File
Copy Code
TestFile.TEXTMODE(TRUE);
TestFile.WRITEMODE(FALSE);
TestFile.OPEN('C:\temp\simple.xml');

If you want to be explicit about the encoding of a file, you can set the TextEncoding parameter. The following code example replaces the last statement in the previous example.

Copy Code
TestFile.TEXTMODE(TRUE);
TestFile.WRITEMODE(FALSE);
TestFile.OPEN('C:\temp\simple.xml', TextEncoding::Windows);

See Also

Reference

File Data Type

Concepts

Text Encoding


POS Function (File)

Gets the current position of the file pointer in an ASCII or binary file.

Position := File.POS

Parameters

File

Type: file

Use this variable to refer to the file.

Property Value/Return Value

Type: Integer

This show the current position of the file pointer in bytes.

Remarks

This function is often used with LEN Function (File) and SEEK Function (File).

Example

The following example opens a text file that is named C:\TestFolder\TestFile.txt. The WRITEMODE Function (File) enables the file to be open in write mode. The POS function retrieves the position of the file pointer and stores it in the Position variable. When the file is open, the position of the pointer is 0 because a pointer is not set. The SEEK Function (File) function sets a file pointer at position 5. After the SEEK Function (File) is executed, the POS function returns 5 as the file pointer position. This example assumes that you have created a text file named C:\TestFolder\TestFile.txt. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType
TestFile | File
Position | Integer
Copy Code
TestFile.WRITEMODE(TRUE);
TestFile.OPEN('C:\TestFolder\TestFile.txt');
Position := TestFile.POS;
MESSAGE('Pointer position before SEEK: %1', Position);
Testfile.SEEK(5);
Position := Testfile.POS;
MESSAGE('Pointer position after SEEK: %1', Position);

See Also

Reference

File Data Type


READ Function (File)

Reads from an MS-DOS encoded file or binary file.

[Read :=] File.READ(Variable)

Parameters

File

Type: File

Use this variable to refer to the file.

Variable

Type: any

The destination variable. You must define the length of the Variable parameter to be greater than or equal to the length of the text in the file that is read, and less than 1024.

If the length of the Variable parameter is less than the length of the text in the file, or greater than 1024, then you get the following runtime error:

Invalid data encountered in stream, unable to read text.

In earlier versions of Microsoft Dynamics NAV, the Variable parameter did not have to be as long as the text in the file. The READ function could read partial data. In Microsoft Dynamics NAV 2016, it is not supported to read fewer than the bytes in the file.

If you do not define the length of the Variable parameter, then you get the following runtime error:

READ is not supported for Text without a maximum length.

Property Value/Return Value

Type: Integer

The number of bytes read.

This return value is optional.

Remarks

To read from a file that is larger than 1024 bytes, use streams instead of the File.READ function. For more information, see How to: Use Streams to Read from Text Files.

MS-DOS encoding, which is also referred to as OEM encoding, is an older format than UTF-8 and UTF-16, but it is still widely supported. MS-DOS encoding was the only format that was supported by earlier versions of Microsoft Dynamics NAV.

MS-DOS encoding requires a different character set for each language. MS-DOS text is encoded to the internal Unicode data type by using the system locale language of the computer that is running Microsoft Dynamics NAV Server. If you read a file that uses MS-DOS encoding, then you must set the system locale language of the computer that is running Microsoft Dynamics NAV Server to match the language of the data in the file that is being read. For example, if the file contains text in Danish, then you must set the system locale language of the computer that is running Microsoft Dynamics NAV Server to Danish before you call the READ function (FILE) or WRITE Function (File).

We recommend that you use the File data type for files that were created in earlier versions of Microsoft Dynamics NAV.

To read or write files in Unicode or in other formats, we recommend that you use .NET Framework interoperability and use the System.IO Namespace.

Example

The following example opens a text file that is named C:\TestFolder\TestFile.txt. The READ function read the contents of the file and stores it in the String variable. The function returns the size of the text that was read, stores it in the varSize variable, and displays it in a message box. This example assumes that you have created a text file named C:\TestFolder\TestFile.txt that contains less than 500 bytes. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Length
TestFile | File | Not applicable
String | Text | 500
varSize | Integer | Not applicable
Copy Code
TestFile.OPEN('C:\TestFolder\TestFile.txt');
varSize := TestFile.READ(String);
MESSAGE('The text "%1" is %2 bytes.', String, varSize);

See Also

Reference

File Data Type


RENAME Function (File)

Renames an ASCII or binary file.

[Ok :=]RENAME(OldName, NewName)

Parameters

OldName

Type: Text or Code.

The current name of the file that you want to change, including its path. When you enter the path, consider these shortcuts:

  • You can omit the drive designation, if the file is located on the current drive.

  • You can omit the full path, if the file is located in the current directory.

  • You can enter only the subdirectory name, if the file is located in a subdirectory of the current directory.

NewName

Type: Text or Code

The new name that you want to assign to the file, including its path. When you enter the path, consider these shortcuts:

  • You can omit the drive designation, if the file is located on the current drive.

  • You can omit the full path, if the file is located in the current directory.

  • You can enter only the subdirectory name, if the file is located in a subdirectory of the current directory.

Property Value/Return Value

Type: Boolean

If you omit this optional return value, a run-time error occurs when the file cannot be found. When you include the return value, it is assumed that you will handle any errors.

true if the file was renamed; otherwise, false.

Remarks

Typically the return value is false if the file does not exist, or if the file is a system or hidden file.

Example

The following example changes the name of a text file that is named Testfile.txt to NewTestFile.txt. The path of the file that is renamed is C:\TestFolder\Testfile.txt. The name and path are stored in the varOldFile variable. The new name and path of the file are stored the varNewfile variable. The RENAME function uses the variables to change the name of the file. This example assumes that you have created the following file on your computer: C:\TestFolder\Testfile.txt. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType
varOldfile | Text
varNewfile | Text
Copy Code
varOldfile := 'C:\TestFolder\Testfile.txt' ;
varNewfile := 'C:\TestFolder\NewTestFile.txt';
RENAME(varOldfile, varNewfile);

See Also

Reference

File Data Type


SEEK Function (File)

Sets a file pointer to a new position in an ASCII or binary file.

File.SEEK(Position)

Parameters

File

Type: File

The file in which to set the pointer.

Position

Type: Integer

The position at which to set the pointer.

Remarks

This function is often used with POS Function (File) and LEN Function (File).

Example

The following example sets a pointer at position 20 in a file and truncates the file at the pointer position. The WRITEMODE Function (File) enables a file named C:\TestFolder\TestFile.txt to open in write mode. The SEEK function sets a pointer at position 20 in the file and then the TRUNC Function (File) truncates the contents of the file at the pointer position. This example assumes that you have created the text file C:\TestFolder\TestFile.txt.This example requires that you create the following variable in the C/AL Globals window.

Variable name | DataType
TestFile | File
Copy Code
TestFile.WRITEMODE(TRUE);
TestFile.OPEN('C:\TestFolder\TestFile.txt');
TestFile.SEEK(20);
TestFile.TRUNC;

See Also

Reference

File Data Type


SETSTAMP Function (File)

Sets a timestamp for a file.

[Ok :=]SETSTAMP(Name, Date [, Time])

Parameters

Name

Type: Text or Code.

The name of the file, including its path. When you enter the path, keep in mind these shortcuts:

  • You can omit the drive designation, if the file is located on the current drive.

  • You can omit the full path, if the file is located in the current directory.

  • You can enter only the subdirectory name, if the file is located in a subdirectory of the current directory.

Date

Type: Date

The date that you want stamped on the file.

Time

Type: Time

The time that you want stamped on the file.

Property Value/Return Value

Type: Boolean

If you omit this optional return value, a run-time error occurs if the file cannot be found. When you include the return value, you must handle any errors.

true if the timestamp was set; otherwise, false.

Example

The following example sets timestamp for that a file that is named varFileName. The date and time are set to the current date and on your computer respectively. The code example assumes that you have created the following file: 'C:\MyFolder\MyText.txt'. The following example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
varFileName | Text
varDate | Date
varTime | Time

Text constant name | DataType | ENU value
Text000 | Text | The timestamp for this file is Date: %1 Time: %2.
Copy Code
VarFileName := 'C:\MyFolder\MyText.txt';
varDate := TODAY;
varTime := TIME;
SETSTAMP(VarFileName, varDate, varTime);
MESSAGE(Text000, varDate, varTime);

See Also

Reference

File Data Type


TEXTMODE Function (File)

Sets whether a file should be opened as an ASCII file or a binary file. Gets the current setting of this option for a file.

[IsTextmode := File.TEXTMODE([SetTextmode])

Parameters

File

Type: File

Specifies the file.

SetTextmode

Type: Boolean

Specifies the mode in which the file will be opened when File.OPEN is called.

If SetTextmode is true, the file will be opened as an ASCII file. If SetTextmode is false, the file will be opened as a binary file.

Property Value/Return Value

Type: Boolean

The current setting of this option for the file.

true if the file will be opened as an ASCII file; otherwise, false if the file will be opened as a binary file.

Remarks

This function should be used before File.OPEN is used to open the file. If you use this function on a file that is already open, then an error occurs.

Example

The following example sets the TEXTMODE to true when the file is open for writing. This means the file contents will be written to a text file that is named 'C:\TestFolder\TestFile.txt' by using ASCII characters. The WRITEMODE Function (File) and the OPEN Function (File) open the file for writing and the text ‘Hello World’ is written. The CLOSE Function (File) closes the file after the file is written to. This example requires that you create the following variable in the C/AL Globals window. This example assumes that you have created a text file that is named C:\TestFolder\TestFile.txt.

Variable name | DataType
TestFile | File
Copy Code
TestFile.TEXTMODE(TRUE);
TestFile.WRITEMODE(TRUE);
TestFile.OPEN('C:\TestFolder\TestFile.txt');
TestFile.WRITE('Hello World');
TestFile.CLOSE;

See Also

Reference

File Data Type


TRUNC Function (File)

Truncate an ASCII or binary file to the current position of the file pointer.

File.TRUNC

Parameters

File

Type: File

Use this variable to refer to the file.

Remarks

Typically, you use this function together with SEEK Function (File). Use File.SEEK to position the pointer in the file and then use File.TRUNC to truncate the file at that point.

Example

The following example sets a pointer at position 20 in a file and truncates the file at the pointer position. The WRITEMODE Function (File) allows the file that is named C:\TestFolder\TestFile.txt to open in write mode. The SEEK function sets a pointer at position 20 in the file and then the TRUNC Function (File) truncates the contents at the pointer position. This example assumes that you have created a text file named C:\TestFolder\TestFile.txt. The file is then saved a truncated file. This example requires that you create the following variable in the C/AL Globals window.

Variable name | DataType
TestFile | File
Copy Code
TestFile.WRITEMODE(TRUE);
TestFile.OPEN('C:\TestFolder\TestFile.txt');
TestFile.SEEK(20);
TestFile.TRUNC;

See Also

Reference

File Data Type


UPLOAD Function (File)

Sends a file from the client computer to the Microsoft Dynamics NAV Server computer. The client computer is the computer that is running the Microsoft Dynamics NAV Windows client or the computer that is running a browser that accesses the Microsoft Dynamics NAV Web client.

[Ok :=] UPLOAD(DialogTitle, FromFolder, FromFilter, FromFile, ToFile)

Parameters

DialogTitle

Type: Text

The title that you want to display in the dialog box for uploading the file.

Note
This parameter is not supported by the Microsoft Dynamics NAV Web client. The title is determined by the end-user's browser.

FromFolder

Type: Text

The name of the folder that is displayed in the dialog box. This is the default value, and the user can change it.

Note
This parameter is not supported by the Microsoft Dynamics NAV Web client. The browser uses the folder that was last accessed.

FromFilter

Type: Text

The type of file that can be uploaded to Microsoft Dynamics NAV Server.

In the Microsoft Dynamics NAV Windows client, the type is displayed in the upload dialog box, so that the user can only select files of the specified type. For the Microsoft Dynamics NAV Web client, a user can try to upload any file type but an error occurs if the file is not the specified type.

FromFile

Type: Text

The default file that you want to upload to the Microsoft Dynamics NAV service. The name displays in the dialog box for uploading the file. The user can change the file.

Note
This parameter is not supported by the Microsoft Dynamics NAV Web client.

ToFile

Type: Variant

The path and file name to give the uploaded file.

If you do not provide a path, or you upload the file that uses Microsoft Dynamics NAV Web client, then the file is uploaded to the following folder on the computing that is running Microsoft Dynamics NAV Server:

\ProgramData\Microsoft\Microsoft Dynamics NAV\90\Server\MicrosoftDynamicsNAVServer$DynamicsNAV90\users\ServiceAccount

ServiceAccount is the folder for the account for Microsoft Dynamics NAV Server.

Property Value/Return Value

Type: Boolean

If you omit this optional return value, then a run-time error occurs if the file cannot be found. If you include a return value, then you must handle any errors.

true if the file was uploaded; otherwise, false.

Remarks

Note
This function is not supported by the Microsoft Dynamics NAV Web client on devices that run Apple iOS, such as iPad. The dialog box for uploading a file displays in the Microsoft Dynamics NAV Web client, but it is disabled and the user cannot select a file.

In Microsoft Dynamics NAV, the business logic is run on the computer that is running Microsoft Dynamics NAV Server and not on the client. Files are created on the Microsoft Dynamics NAV service and not locally on the client computer.

UPLOAD Function (File) and UPLOADINTOSTREAM Function (File) are used to send a file from the client to a Microsoft Dynamics NAV service.

DOWNLOAD Function (File) and DOWNLOADFROMSTREAM Function (File) are used to send a file from a Microsoft Dynamics NAV service to the client.

We recommend that you use the functions in codeunit 419, File Management, to upload and download files.

Example

Copy Code
UPLOAD('Upload file','C:\','Text file(*.txt)|*.txt','Test.txt',varTest)

See Also

Reference

File Data Type


UPLOADINTOSTREAM Function (File)

Sends a file from the client computer to the corresponding Microsoft Dynamics NAV Server. The client computer is the computer that is running the Microsoft Dynamics NAV Windows client or the computer that is running a browser that accesses the Microsoft Dynamics NAV Web client.

[Ok :=] UPLOADINTOSTREAM(DialogTitle, FromFolder, FromFilter, FromFile, NVInStream)

Parameters

DialogTitle

Type: Text

The text displayed in the title bar of the Open dialog box.

Note
This parameter is not supported by the Microsoft Dynamics NAV Web client. The title is determined by the end-user's browser.

FromFolder

Type: Text

The path of the folder that is displayed in the File Open dialog box. This is the default folder, but the user can browse to any available location.

Note
This parameter is not supported by the Microsoft Dynamics NAV Web client. By default, the browser uses the folder that was last accessed.

FromFilter

Type: Text

The type of file that can be uploaded to Microsoft Dynamics NAV Server.

In the Microsoft Dynamics NAV Windows client, the type is displayed in the upload dialog box, so the user can only select files of the specified type. For the Microsoft Dynamics NAV Web client, a user can try to upload any file type but an error occurs if the file is not the specified type.

FromFile

Type: Text

The default file to upload to the Microsoft Dynamics NAV service. The name displays in the dialog box for uploading the file. The user can change the file.

Note
This parameter is not supported by the Microsoft Dynamics NAV Web client.

NVInStream

Type: Variant

The InStream that is used to send the file.

Property Value/Return Value

Type: Boolean

If you omit this optional return value, then a run-time error occurs if the record cannot be found. If you include a return value, then you must handle any errors.

true if the file was uploaded; otherwise, false.

Remarks

Note
This function is not supported by the Microsoft Dynamics NAV Web client on devices that run Apple iOS, such as iPad. The dialog box for uploading a file displays in the Microsoft Dynamics NAV Web client, but it is disabled and the user cannot select a file.

The maximum size of the file to be uploaded is specified by the MaxUploadSize setting in the CustomSettings.config file. The setting is specified in megabytes. For more information, see Configuring Microsoft Dynamics NAV Server.

In Microsoft Dynamics NAV, the business logic runs on the computer that is running Microsoft Dynamics NAV Server and not on the client. Files are created on Microsoft Dynamics NAV Server and not locally on the client computer.

Use UPLOAD Function (File) and UPLOADINTOSTREAM Function (File) to send a file from the client to Microsoft Dynamics NAV Server.

Use DOWNLOAD Function (File) and DOWNLOADFROMSTREAM Function (File) to send a file from Microsoft Dynamics NAV Server to the client.

We recommend that you use the functions in codeunit 419, File Management, to upload and download files.

Example

This example requires that you create the following variables.

Name | DataType
FileName | Text
NVInStream | InStream
Copy Code
FileName := 'c:\SomeFile.txt';
UPLOADINTOSTREAM('Import','',' All Files (*.*)|*.*',FileName,NVInStream);

See Also

Tasks

Walkthrough: Uploading a File from a Client to Microsoft Dynamics NAV Server

Reference

File Data Type


WRITE Function (File)

Writes to an MS-DOS encoded file or binary file.

File.WRITE(Value)

Parameters

File

Type: File

The file to write to.

Value

Type: all simple data types, and records

The data that you want to write to the file.

Remarks

You must call the TEXTMODE Function (File) before you call the WRITE function.

If TEXTMODE Function (File) is set to true and Value is an integer, then the integer is written as text, followed by a new line character.

If Value is a record, each field is separated by a tab character.

If TEXTMODE Function (File) is false and Value is an integer, an integer is written that is four bytes long.

MS-DOS encoding requires a different character set for each language. MS-DOS text is encoded to the internal Unicode data type by using the system locale language of the computer that is running Microsoft Dynamics NAV Server. If you write to a file that uses MS-DOS encoding, then you must set the system locale language of the computer that is running Microsoft Dynamics NAV Server to match the language of the data that you want to write to the file.

We recommend that you use the File data type for files that were created in earlier versions of Microsoft Dynamics NAV.

To read or write files in Unicode or in other formats, we recommend that you use .NET Framework interoperability and use the System.IO Namespace.

Example

The following example determines whether the specified file exists. If it exists, the WRITEMODE Function (File) allows the file to be open for writing. The OPEN Function (File) opens the file, the WRITE Function (File) writes the text “Hello World” to the file and then the CLOSE Function (File) closes the file. If the file does not exist, then an error message is displayed. This example assumes that you have created the following file: C:\TestFolder\TestFile.txt. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType
FileName | Text
TestFile | File
Copy Code
FileName := 'C:\TestFolder\TestFile.txt';
IF EXISTS(FileName) THEN BEGIN
  TestFile.WRITEMODE(TRUE);
  TestFile.OPEN(FileName);
  TestFile.WRITE('Hello World');
  TestFile.CLOSE;
END
ELSE
  MESSAGE('%1 does not exit.', FileName);

See Also

Reference

File Data Type
TEXTMODE Function (File)


WRITEMODE Function (File)

Use this function before you use OPEN Function (File) to set or test whether you can write to a file in later calls.

[IsWritemode :=] File.WRITEMODE([SetWritemode])

Parameters

File

Type: File

Use this variable to refer to the file.

SetWritemode

Type: Boolean

This variable is used to set the mode that the file will be opened in when File.OPEN is called.

true if the file is open for reading and writing; otherwise, false, if the file is open only for reading.

Property Value/Return Value

Type: Boolean

The current setting of this option for the file.

true if you can read from and write to the file; otherwise, false if you can only read from the file.

Remarks

This function should be used before OPEN Function (File) is used to open the file.

Example

The following example opens a file in write mode and writes text to the file. The WRITEMODE Function (File) allows the text file that is named C:/TestFolder/TestFile.txt for to be written to by setting SetWritemode parameter to true. The WRITE Function (File) writes the text ‘Hello World’ to the text file. The CLOSE Function (File) closes the file after the file is written to. This example assumes that you have created a text file that is named C:/TestFolder/TestFile.txt. This example requires that you create the following variable in the C/AL Globals window.

Variable name | DataType
TestFile | File
Copy Code
TestFile.WRITEMODE(TRUE);
TestFile.OPEN('C:/TestFolder/TestFile.txt');
TestFile.WRITE('Hello World’);
TestFile.CLOSE;

See Also

Reference

File Data Type


FilterPageBuilder Data Type

A FilterPageBuilder data type is a complex data type that stores filter configurations for a filter page. A filter page is a dynamic page type that contains one or more filter controls that enables users to set filters on fields of the underlying tables.

See Also

Reference

ADDFIELD Function
ADDFIELDNO Function
ADDRECORD Function
ADDRECORDREF Function
ADDTABLE Function
GETVIEW function (FilterPageBuilder)
SETVIEW Function
COUNT Function (FilterPageBuilder)
NAME Function (FilterPageBuilder)
RUNMODAL Function (FilterPageBuilder)


ADDTABLE Function

Adds filter control for a table to a filter page.

[Name :=] FilterPageBuilder.ADDTABLE(ItemName, TableNo)

Parameters

ItemName

Type: Text

Assigns a name to the filter control for the table.

The text displays as the caption for the filter control on the rendered filter page in the Microsoft Dynamics NAV client.

Note
Within the collection of filter controls on the filter page, you cannot assign the same ItemName to different table IDs; otherwise a runtime an error occurs.

TableNo

Type: Integer

The ID of the table object that you want to filter. The ID is specified by the table's ID Property.

Return Value

Type: Text

The text that is specified by the ItemName parameter.

If an error occurs at runtime, an empty text string is returned. An error message will be shown if the return value is not used.

Remarks

In the filter page that is rendered in the Microsoft Dynamics NAV client, the ADDTABLE function defines a filter control for the specified table where the user can set filters on specific fields in the table.

You can use the ADDFIELD or ADDFIELDNO function to add field of the table to the filter control.

Example

The following example initializes a filter page object that includes a filter control that uses the Date system table. The filter control has the caption of Date record.

This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | SubType
varDateItem | Text |
varFilterPageBuilder | FilterPageBuilder |
Copy Code
varDateItem := 'Date record';
FilterPageBuilder.ADDTABLE(varDateItem, DATABASE::Date);

See Also

Reference

ADDFIELD Function
ADDFIELDNO Function
ADDRECORD Function
ADDRECORDREF Function
GETVIEW function (FilterPageBuilder)
SETVIEW Function
COUNT Function (FilterPageBuilder)
NAME Function (FilterPageBuilder)
RUNMODAL Function (FilterPageBuilder)


ADDFIELD Function

Adds a table field to the filter control for a table on filter page.

[Ok :=] FilterPageBuilder.ADDFIELD(ItemName, Field[,Filter])

Parameters

ItemName

Type: Text

The name that is assigned to the table in the filter control. This value must match the value of the ItemName parameter that was specified by ADDTABLE, ADDRECORD, or ADDRECORDREF function that adds the table to the filter control.

Field

Type: Field

The name of the table field to add to the filter control for a table.

Filter

Type: Text

A default filter on the field that is specified by the Field parameter.

Return Value

Type: Boolean

true if the field was added to the field list for the specified filter control; otherwise, false.

Remarks

The filter control that specified by ItemName parameter must already exist in the FilterPageBuilder object before the ADDFIELD function is called. This means that either the ADDTABLE, ADDRECORD, or ADDRECORDREF functions must be called before the ADDFIELD function.

If the filter page implementation will call a SETVIEW function, then the SETVIEW function must be called before the ADDFIELD function call, otherwise the filter that is specified by the Filter parameter will be cleared by SETVIEW.

The filter that is specified by the Filter parameter will overwrite any previously defined filters for the field which were set by ADDVIEW function or read from the record or recordRef instance that defined the filter control.

Example

The following example initializes a filter page object that includes a filter control for the Date system table. The filter control has the caption of Date record. The example adds two fields of the Date record variable which will be available in the filter control on the filter page: Period End and Period Start. A default filter is set on the Period End field.

This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | SubType
varDateItem | Text |
varDateRecord | Record | Date
varFilterPageBuilder | FilterPageBuilder |
Copy Code
varDateItem := 'Date record';
varFilterPageBuilder.ADDRECORD(varDateItem, varDateRecord);
varFilterPageBuilder.ADDFIELD(varDateItem, varDateRecord."Period End",'12122015D');
varFilterPageBuilder.ADDFIELD(varDateItem, varDateRecord."Period Start");

See Also

Reference

ADDFIELD Function
ADDFIELDNO Function
ADDRECORD Function
ADDRECORDREF Function
GETVIEW function (FilterPageBuilder)
SETVIEW Function
COUNT Function (FilterPageBuilder)
NAME Function (FilterPageBuilder)
RUNMODAL Function (FilterPageBuilder)


ADDFIELDNO Function

Adds a table field to the filter control for a table on the filter page.

[Ok :=] FilterPageBuilder.ADDFIELDNO(ItemName, FieldNo[,Filter])

Parameters

ItemName

Type: Text

The name that is assigned to the table in the filter control. This value must match the value of the ItemName parameter that was specified by ADDTABLE, ADDRECORD, or ADDRECORDREF function that adds the table to the filter control.

FieldNo

Type: Integer

The number that is assigned to the field in the table as specified by the Field No. Property.

Filter

Type: Text

A default filter on the field that is specified by the Field parameter.

Return Value

Type: Boolean

true if the field was added to the field list for the specified filter control; otherwise, false.

Remarks

The filter control that is specified by ItemName must already exist in the FilterPageBuilder object before the ADDFIELDNO function is called. This means that either the ADDTABLE, ADDRECORD, or ADDRECORDREF functions must be called before the ADDFIELD function.

If the filter page implementation will call a SETVIEW function, then the SETVIEW function must be called before the ADDFIELDNO function call, otherwise the default filter that is specified by the Filter parameter for field, if any, will be cleared by SETVIEW.

The filter that is specified by the Filter parameter will overwrite any previously defined filters for the field which were set by ADDVIEW function or read from the record or recordRef instance that defined the filter control.

Example

The following example initializes a filter page object that includes a filter control for the Date system table. The filter control has the caption of Date record. The example adds two fields of the Date record variable which will be available in the filter control on the filter page: Period End and Period Start. A default filter is set on the Period End field.

This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | SubType
varDateItem | Text |
varDateRecord | Record | Date
varFilterPageBuilder | FilterPageBuilder |
Copy Code
varDateItem := 'Date record';
varFilterPageBuilder.ADDRECORD(varDateItem, varDateRecord);
varFilterPageBuilder.ADDFIELDNO(varDateItem, varDateRecord.FIELDNO(varDateRecord."Period End"),'03032014D');
varFilterPageBuilder.ADDFIELDNO=(varDateItem, varDateRecord.FIELDNO(varDateRecord."Period Start"));

See Also

Reference

ADDFIELD Function
ADDFIELDNO Function
ADDRECORD Function
ADDRECORDREF Function
GETVIEW function (FilterPageBuilder)
SETVIEW Function
COUNT Function (FilterPageBuilder)
NAME Function (FilterPageBuilder)
RUNMODAL Function (FilterPageBuilder)


ADDRECORD Function

Adds a filter control for a table to a filter page. The table is specified by a record data type variable that is passed to the function.

[Name :=] FilterPageBuilder.ADDRECORD(ItemName, Record)

Parameters

ItemName

Type: Text

Assigns a name to the filter control.

The text displays as the caption for the filter control on the rendered filter page in the Microsoft Dynamics NAV client.

Note
Within the collection of filter controls on the filter page, you cannot assign the same ItemName to different table IDs; otherwise a runtime an error occurs.

Record

Type: Record

The record to use in the filter control.

Return Value

Type: Text

The name assigned to the item or an empty string if an error occurred. An error message will be shown if the return value is not used.

Remarks

In the filter page that is rendered in the Microsoft Dynamics NAV client, the ADDRECORD function defines a filter control for the specified table where the user can set filters on specific fields in the table.

Fields in the table that already have filters are automatically included in the filter control. Filters in the record passed to the function will not be modified by any function in the FilterPageBuilder object.

Example

The following example initializes a filter page object that includes a filter control that uses the Date system table. The filter control has the caption of Date record. The example set two filters are on the Date record variable, which results in a filter control that includes two fields by default.

This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | SubType
varDateItem | Text |
varDateRecord | Record | Date
varFilterPageBuilder | FilterPageBuilder |
Copy Code
varDateItem := 'Date record';
varDateRecord.SETFILTER("Period End",'12122015D');
varDateRecord.SETFILTER("Period Start",'01012015D');
varFilterPageBuilder.ADDRECORD(varDateItem, varDateRecord);

See Also

Reference

ADDFIELD Function
ADDFIELDNO Function
ADDRECORDREF Function
ADDTABLE Function
GETVIEW function (FilterPageBuilder)
SETVIEW Function
COUNT Function (FilterPageBuilder)
NAME Function (FilterPageBuilder)
RUNMODAL Function (FilterPageBuilder)


ADDRECORDREF Function

Adds filter control for a table to a filter page. The table is specified by a recordref variable that is passed to the function .

This creates a filter control on the filter page, where users can set filter table data.

[Name :=] FilterPageBuilder.ADDRECORDREF(ItemName, RecordRef)

Parameters

ItemName

Type: Text

The text to display as the caption for the filter control for the specified table.

Note
Within the collection of filter controls on the filter page, you cannot assign the same ItemName to different table IDs; otherwise a runtime an error occurs.

RecordRef

Type: RecordRef

The record reference to use in the filter control.

Return Value

Type: Text

The name assigned to the item or an empty string if an error occurred. An error message will be shown if the return value is not used.

Remarks

In the filter page that is rendered in the Microsoft Dynamics NAV client, the ADDRECORDREF function defines a filter control for the specified table where the user can add and set the filters on the table.

Fields in the table that already have filters are automatically included in the filter control. Filters in the record reference passed to the function will not be modified by any function in the FilterPageBuilder object.

Example

The following example initializes a filter page object that includes a filter control that uses the Date system table. The filter control has the caption of Date record. The example set two filters are on the Date record variable, which results in a filter control that includes two fields by default.

This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | SubType
varDateItem | Text |
varDateRecord | Record | Date
varDateRecordRef | RecordRef |
varFilterPageBuilder | FilterPageBuilder |
Copy Code
varDateItem := 'Date record';
varDateRecord.SETFILTER("Period End",'12122015D');
varDateRecord.SETFILTER("Period Start",'01012015D');
varDateRecordRef.GetTable(varDateRecord);
varFilterPageBuilder.ADDRECORDREF(varDateItem,varDateRecordRef);

See Also

Reference

ADDFIELD Function
ADDFIELDNO Function
ADDRECORD Function
ADDTABLE Function
GETVIEW function (FilterPageBuilder)
SETVIEW Function
COUNT Function (FilterPageBuilder)
NAME Function (FilterPageBuilder)
RUNMODAL Function (FilterPageBuilder)


COUNT Function (FilterPageBuilder)

Gets the number of filter controls that are specified in the FilterPageBuilder object instance.

Count := FilterPageBuilder.COUNT

Return Value

Type: Integer

The number of filter controls in the current FilterPageBuilder object instance.

Example

The following example uses the COUNT function on a filter page object that includes a two filter controls for the Date system table.

This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | SubType
varDateItem | Text |
varCount | Integer | Date
varFilterPageBuilder | FilterPageBuilder |
Copy Code
varDateItem := 'Date record';
varFilterPageBuilder.ADDTABLE(varDateItem + ‘ 1’,DATABASE::Date);
varFilterPageBuilder.ADDTABLE(varDateItem + ‘ 2’,DATABASE::Date);
varCount := varFilterPageBuilder.COUNT;
IF varCount <> 2 THEN
  ERROR(‘There should be two controls in varFilterPageBuilder’);

See Also

Reference

ADDFIELD Function
ADDFIELDNO Function
ADDRECORD Function
ADDRECORDREF Function
ADDTABLE Function
GETVIEW function (FilterPageBuilder)
SETVIEW Function
NAME Function (FilterPageBuilder)
RUNMODAL Function (FilterPageBuilder)


GETVIEW function (FilterPageBuilder)

Gets the filter view (which defines the sort order, key, and filters) for the record in the specified filter control of a filter page.

The view contains all fields in the filter control that have a default filter value.

View := FilterPageBuilder.GETVIEW(ItemName[,UseNames])

Parameters

ItemName

Type: Text or Code

The name of the filter control.

This value must match the value of the ItemName parameter that was specified by ADDTABLE, ADDRECORD, or ADDRECORDREF function that adds the table to the filter control.

UseNames

Type: Boolean

Specifies whether a field caption or field number should be returned.

This parameter is optional. If this parameter is true (default value) or if it is empty, then the returned string contains references to field captions in the table with which the record is associated. If this parameter is false, then the returned string contains references to field numbers.

Return Value

Type: Text

The view that is configured for the filter control that is identified by ItemName.

Remarks

The filter control that is specified by ItemName must already exist in the FilterPageBuilder object before the ADDFIELDNO function is called. Either the ADDTABLE, ADDRECORD, or ADDRECORDREF functions must be called before the GETVIEW function.

Example

The following example initializes a filter page object that includes a filter control for the Date system table. The filter control has the caption of Date record. The example adds two filter fields to the filter control on the filter page as the result of applying a default view. The GETVIEW function is used to capture that filter view from the FilterPageBuilder object, and then apply it to the record.

This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | SubType
varDateItem | Text |
varDateRecord | Record | Date
varFilterPageBuilder | FilterPageBuilder |
varDefaultView | Text |
Copy Code
varDateItem := 'Date record';
varDateRecord.SETFILTER("Period End", '12122015D');
varDateRecord.SETFILTER("Period Start", '01012015D');
varDefaultView := varDateRecord.GETVIEW;
varFilterPageBuilder.ADDTABLE(MyDateItem, DATABASE::Date);
varFilterPageBuilder.SETVIEW(varDateItem, varDefaultView);
IF varFilterPageBuilder.RUNMODAL = TRUE THEN
  varDateRecord.SETVIEW(varFilterPageBuilder.GETVIEW(varDateVariable));

See Also

Reference

ADDFIELD Function
ADDFIELDNO Function
ADDRECORD Function
ADDRECORDREF Function
ADDTABLE Function
SETVIEW Function
COUNT Function (FilterPageBuilder)
NAME Function (FilterPageBuilder)
RUNMODAL Function (FilterPageBuilder)


NAME Function (FilterPageBuilder)

Gets the name of a table filter control that is included on a filter page based on an index number that is assigned to the filter control.

Name := FilterPageBuilder.NAME(Index)

Parameters

Index

Type: Integer

The index of a filter control. The value must be in the range 1 to N, where N is the number of filter controls on the filter page.

Return Value

Type: Text

The name of the filter control.

Example

The following example initializes a filter page object that includes two filter controls for the Date system table. The NAME function returns the names of filter control in a message dialog box.

This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | SubType
varDateItem | Text |
varCount | Integer | Date
varIndex | Integer |
varFilterPageBuilder | FilterPageBuilder |
Copy Code
varDateVariable := 'Date record';
varFilterPageBuilder.ADDTABLE(varDateVariable + ‘ 1’,DATABASE::Date);
varFilterPageBuilder.ADDTABLE(varDateVariable + ‘ 2’,DATABASE::Date);
varCount := varFilterPageBuilder.COUNT;
IF varCount <> 2 THEN
  error(‘There should be two controls in FilterPageBuilder’);
FOR varIndex := 1 to varCount do
  MESSAGE(‘Control item %1 is named %2’, varIndex, varFilterPageBuilder.Name(varIndex));

See Also

Reference

ADDFIELD Function
ADDFIELDNO Function
ADDRECORD Function
ADDRECORDREF Function
ADDTABLE Function
GETVIEW function (FilterPageBuilder)
SETVIEW Function
COUNT Function (FilterPageBuilder)
RUNMODAL Function (FilterPageBuilder)


RUNMODAL Function (FilterPageBuilder)

Builds and runs the filter page that includes the filter controls that are stored in FilterPageBuilder object instance.

[Ok :=] FilterPageBuilder.RUNMODAL()

Return Value

Type: Boolean

true if the user selects the OK button on the filter page; otherwise, false.

Remarks

The page is run modally and includes an OK and Cancel button for closing to modal popup.

You can call the GETVIEW function (FilterPageBuilder) function to retrieve the current filter view that is configured on the filter control and apply to the record.

Example

The following example initializes a filter page object that includes a filter control for the Date system table. The filter control has the caption of Date record. The example adds two filter fields to the filter control on the filter page as the result of applying a default view. The GETVIEW function is used to capture that filter view from the FilterPageBuilder object, and then apply it to the record.

This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | SubType
varDateItem | Text |
varDateRecord | Record | Date
varFilterPageBuilder | FilterPageBuilder |
varDefaultView | Text |
Copy Code
varDateItem := 'Date record';
varDateRecord.SETFILTER("Period End", '12122015D');
varDateRecord.SETFILTER("Period Start", '01012015D');
varDefaultView := varDateRecord.GETVIEW;
varFilterPageBuilder.ADDTABLE(varDateItem, DATABASE::Date);
varFilterPageBuilder.SETVIEW(varDateItem, varDefaultView);
IF varFilterPageBuilder.RUNMODAL = TRUE THEN
  varDateRecord.SETVIEW(varFilterPageBuilder.GETVIEW(varDateItem));

See Also

Reference

ADDFIELD Function
ADDFIELDNO Function
ADDRECORD Function
ADDRECORDREF Function
ADDTABLE Function
GETVIEW function (FilterPageBuilder)
SETVIEW Function
COUNT Function (FilterPageBuilder)
NAME Function (FilterPageBuilder)


SETVIEW Function

Sets the current filter view, which defines the sort order, key, and filters, for a record in a filter control on a filter page.

The view contains all fields that have default filters, but does not contain fields without filters.

[Ok :=] FilterPageBuilder.SETVIEW(ItemName, View)

Parameters

ItemName

Type: Text or Code

The name that is assigned to the filter control.

This value must match the value of the ItemName parameter that was specified by ADDTABLE, ADDRECORD, or ADDRECORDREF function that adds the table to the filter control.

View

Type: Text

The filter view to apply. This can be the output of the GETVIEW Function (Record) orGETVIEW Function (RecordRef) .

Return Value

Type: Boolean

true if view was applied to the specified filter control; otherwise, false.

Remarks

The filter control that is specified by ItemName must already exist in the FilterPageBuilder object before the ADDFIELDNO function is called. Either the ADDTABLE, ADDRECORD, or ADDRECORDREF functions must be called before the SETVIEW function.

The SETVIEW function will overwrite any previously defined filters for the fields that are also included in the view.

Example

The following example initializes a filter page object that includes a filter control for the Date system table. The filter control has the caption of Date record. The example adds two filter fields to the filter control on the filter page as the result of applying a default view from the GETVIEW function.

This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | SubType
varDateItem | Text |
varDateRecord | Record | Date
varFilterPageBuilder | FilterPageBuilder |
varDefaultView | Text |
Copy Code
varDateItem := 'Date record';
varDateRecord.SETFILTER("Period End", '12122015D');
varDateRecord.SETFILTER("Period Start", '01012015D');
varDefaultView := varDateRecord.GETVIEW;
varFilterPageBuilder.ADDTABLE(varDateItem, DATABASE::Date);
varFilterPageBuilder.SETVIEW(varDateItem, varDefaultView);

See Also

Reference

ADDFIELD Function
ADDFIELDNO Function
ADDRECORD Function
ADDRECORDREF Function
ADDTABLE Function
GETVIEW function (FilterPageBuilder)
COUNT Function (FilterPageBuilder)
NAME Function (FilterPageBuilder)
RUNMODAL Function (FilterPageBuilder)


GUID Data Type

Assigns a unique identifying number to any database object. The GUID data type is a 16 byte binary data type. This data type is used for the global identification of objects, programs, records, and so on. The important property of a GUID is that each value is globally unique. The value is generated by an algorithm, developed by Microsoft, which assures this uniqueness.

The GUID is a 16-byte binary data type that can be logically grouped into the following subgroups:

4byte-2byte-2byte-2byte-6byte.

The standard textual representation is {12345678-1234-1234-1234-1234567890AB}.

The virtual table OLE Control (2000000042) does not use the GUID data type. It uses a textual representation of the GUID in a text field instead. It is easier to make operations and references to this text field using the GUID data type than it is using the textual representation. The GUID data type is compatible with the existing textual representation.

The GUID data type is useful when you want to uniquely identify some data, so that it can be exchanged with external applications. For example, if you want to transfer an item catalog to an external application, you add a GUID field to the record in the table and use this as the primary reference when you communicate with the external application.

Compatibility

You can assign and compare the Text data type and the GUID data type. Assigning a GUID to a Text can be done as follows:

Copy Code
MyTableRec.MyGuid  :=  MyTableRec.MyText;

Useful C/AL Functions and Properties

The following C/AL functions can be used with the GUID data type:

Copy Code
Guid:=CREATEGUID();

This function creates a new unique GUID value. The value can then be assigned to a field of the GUID data type or of the Text data type.

Copy Code
Ok:=ISNULLGUID(Guid);

This function is a convenient way to check if a value has already been assigned to a GUID. A NULL GUID (consisting only of zeroes) is valid, but should never be used for reference purposes.

Copy Code
CLEAR(Guid);

The standard CLEAR function can also be used on the GUID data type. It nullifies the GUID.

Copy Code
AutoSplitKey

A NULL GUID is valid but is not useful in a table. Therefore, the AutoSplitKey property is implemented for the GUID data type when it is used in a page. When GUID is selected as a primary key, AutoSplitKey is enabled for the page, and the GUID value remains NULL. When you create a new record, a valid GUID is created and assigned automatically.

The CREATEGUID Function (GUID) and ISNULLGUID Function (GUID) functions are available in the C/AL Symbol Menu under SYSTEM, Variables.

CREATEGUID takes no arguments and returns a valid 16-byte GUID value. If the result is assigned to a TEXT variable or field, the value is converted to a string and follows the syntax explained earlier. The algorithm that generates the new GUID value uses Microsoft's CoCreateGuid function.

ISNULLGUID takes a GUID value as a required argument and returns TRUE/FALSE depending on whether the GUID value is NULL. This function does not accept a Text value as an argument.

CLEAR is the standard CLEAR function and takes one required argument. It nullifies the GUID value in the same way as it resets any other value.

AutoSplitKey is a property, not a function and can be applied to pages. If you have defined a GUID field as part of the primary key, the AutoSplitKey property automatically generates a new valid GUID value. When a new record is created and the GUID field is left as NULL, the AutoSplitKey property ensures that a valid GUID value is automatically inserted into the field. If you then enter a NULL GUID into this record, for example, by using the CLEAR function, this new NULL GUID value is not automatically replaced by the AutoSplitKey property. The AutoSplitKey property only applies to new records.

Format

The GUID value can also be represented as text. You can use the standard C/AL functions FORMAT and EVALUATE to convert from GUID values to Text values. If you do not use the correct format when you edit a GUID value in its textual format, the following error message is displayed:

Invalid Format of GUID string. The correct format of the GUID string is {CDEF7890-ABCD-1234-ABCD-1234567890AB} where 0-9, A-F symbolizes hexadecimal digits.

See Also

Reference

CREATEGUID Function (GUID)
ISNULLGUID Function (GUID)


CREATEGUID Function (GUID)

Creates a new unique GUID. The value can then be assigned to a GUID data type or a text data type. Use the text data type if you want to compare the GUID to another text string.

Guid := CREATEGUID;

Property Value/Return Value

Type: GUID

See Also

Reference

GUID Data Type


ISNULLGUID Function (GUID)

Indicates whether a value has been assigned to a GUID. A null GUID that consists only of zeros is valid but must never be used for references.

Ok := ISNULLGUID(Guid);

Parameters

Guid

The GUID that you want to check whether it is null.

Property Value/Return Value

Type: Boolean

true if a value has been assigned to the GUID; otherwise, false.

Remarks

The GUID data type is useful when you want to uniquely identify data so that it can be exchanged with external applications. For example, if you want to transfer an item catalog to an external application, you add a GUID field to the record in the table and use it as the primary reference when you communicate with the external application. A GUID is a 16-byte binary data type that can be logically grouped into the following subgroups: 4byte-2byte-2byte-2byte-6byte.

Example

The following example initializes two variables named validGuid and nullGuid. The validGuid variable is assigned a valid GUID value, and the nullGuid variable is assigned a null GUID that consists of only zeros. The ISNULLGUID function determines whether the GUID that is contained in the validGuid parameter is null. In this case, the GUID is not null so a message that states that the GUID is not null is displayed and the value is displayed. The function then checks the nullGuid parameter. This time, a message that states that the GUID is null is displayed because the GUID is a null GUID that consists of only zeros. This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
validGuid | GUID
nullGuid | GUID

Text constant name | ENU value
Text000 | The GUID is null.
Text001 | The GUID is not null.\
Text002 | The value is: %1.
Copy Code
validGuid := '{FC841BE6-0ADA-46C4-A6A9-142AEC211613}';
nullGuid  := '{00000000-0000-0000-0000-000000000000}';
IF ISNULLGUID(validGuid) THEN
  MESSAGE(Text000)
ELSE
  MESSAGE(Text001 + Text002, validGuid);
IF ISNULLGUID(nullGuid) THEN
  MESSAGE(Text000);

See Also

Reference

GUID Data Type


InStream and OutStream Data Types

Reads from or writes to files and BLOBs.

Remarks

The InStream (input stream) and OutStream (output stream) data types are generic stream objects that you can use to read from or write to files and BLOBs. In addition, the InStream and OutStream data types enable data to be read from and sent to Automation Data Type objects and OCX Data Type objects. The Microsoft XML DOM can read from an InStream object and write to an OutStream object.

You can define the internal structure of a stream as a flat stream of bytes. You can assign one stream to another. Reading from and writing to a stream occurs sequentially.

You can create a stream object by using the following functions:

  • CREATEINSTREAM Function (BLOB)

  • CREATEOUTSTREAM Function (BLOB)

  • CREATEINSTREAM Function (File)

  • CREATEOUTSTREAM Function (File)

You can use InStream in the following ways:

  • COPYSTREAM Function

  • InStream.READ Function

  • InStream.EOS Function

  • InStream.READTEXT Function

You can use OutStream in the following ways:

  • COPYSTREAM Function

  • OutStream.WRITE Function

  • OutStream.WRITETEXT Function


InStream

This section contains the following topics:

  • COPYSTREAM Function

  • InStream.EOS Function

  • InStream.READ Function

  • InStream.READTEXT Function


COPYSTREAM Function

Copies the information that is contained in an InStream to an OutStream.

[Ok :=] COPYSTREAM(OutStream, InStream)

Parameters

OutStream

Type: OutStream

The OutStream object to which you will copy the information; the destination stream.

InStream

Type: InStream

The InStream object from which you want to copy; the source stream.

Property Value/Return Value

Type: Boolean

Specifies whether the data was copied.

Example

This example requires that you create the following variables.

Variable name | DataType
F1 | File
F2 | File
InS | InStream
OutS | OutStream
Copy Code
F1.OPEN('c:\Test.txt');
F1.CREATEINSTREAM(InS);
F2.CREATE('c:\CopyTest.txt');
F2.CREATEOUTSTREAM(OutS);
COPYSTREAM(OutS,InS);
F1.CLOSE();
F2.CLOSE();

See Also

Reference

InStream and OutStream Data Types


InStream.EOS Function

Indicates whether an input stream has reached End of Stream (EOS).

IsEOS := InStream.EOS

Property Value/Return Value

Type: Boolean

Yes if the stream has reached End of Stream; otherwise, No.

Remarks

If you are reading data from an external component, EOS can return FALSE even though no more data is available. This may occur if you have not called READ first.

Example

The following example opens the text file in a folder that is named MyFolder. The data in the text file is read into and input stream variable named StreamInTest. The InStream.EOS Function is used to determine whether the input stream has reached the end. If the stream has not reached the end, the stream is read into a text buffer, which indicates that the stream has not reached the end until the stream reaches the end. This example requires that you create the following variables in the C/AL Globals window. You must also create the following file 'c:\MyFolder\MyText.txt'.

Variable name | DataType
FileTest | File
StreamInTest | InStream
Buffer | Text
Copy Code
FileTest.OPEN('c:\MyFolder\MyText.txt');
FileTest.CREATEINSTREAM(StreamInTest);
WHILE NOT StreamInTest.EOS DO BEGIN
  StreamInTest.READTEXT(Buffer);
  //Do some processing
  MESSAGE('Stream is still processing')
END;
MESSAGE('End of Stream');

See Also

Reference

InStream.READ Function
InStream.READTEXT Function
InStream and OutStream Data Types


InStream.READ Function

Reads a specified number of bytes from an InStream object. Data is read in binary format.

[Read := ] InStream.Read(Variable[, Length])

Parameters

Variable

Type: Text

Describes the variable that will receive the data that is read.

Length

Type: Integer

Describes the number of characters to be read. If you do not specify Length, the size of the variable is used. In the case of data types other than string, code, and binary, if you specify a length that differs from the size of the variable, you receive an error message.

Property Value/Return Value

Type: Integer

The return value is the number of characters that were read.

Remarks

If the optional return value (READ) is not present and the data being read is less than the length requested to be read, then you receive an error message.

If the return value is present, then you must verify the validity of the data that has been read.

Example

The following example shows how to use the Instream.READ function to read data in binary format. The FIND function finds the first record from the Company Information table. The CALCFIELDS function retrieves the Picture field, which is a BLOB field. The CREATEINSTREAM function uses the recBinaries variable to create an InStream object that is named varInstream. The varInstream.READ function then reads three characters from the varInstream variable and stores the binary data in the varChars variable. The number of characters that is read is stored in the numChars variable. The binary data and the number of characters that is read are displayed in a message box. This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Subtype | Length
recBinaries | Record | Company Information | Not applicable
Picture | Binary | Not applicable | 100
varInstream | InStream | Not applicable | Not applicable
varChars | Text | Not applicable | 50
numChars | Integer | Not applicable | Not applicable

Text constant name | ENU value
Text000 | Number of characters read: %1. Characters read: %2.
Copy Code
recBinaries.FIND('-');
recBinaries.CALCFIELDS(recBinaries.Picture);
recBinaries.Picture.CREATEINSTREAM(varInstream);
numChars := varInstream.READ(varChars,3);
MESSAGE(Text000, numChars, varChars);

See Also

Reference

InStream.EOS Function
InStream.READTEXT Function
OutStream.WRITE Function
InStream and OutStream Data Types


InStream.READTEXT Function

Reads text from an InStream object.

[Read := ] InStream.ReadText(Text[, Length])

Parameters

Text

Type: Text

The variable that receives the characters that were read.

Length

Type: Integer

The number of characters to be read. If you do not specify this parameter, the maximum length of the string is used.

Property Value/Return Value

Type: Integer

The number of characters that were read.

Remarks

READTEXT reads the specified number of bytes, the maximum length of the string, or until the end of the line.

Data is read in text format.

If you do not use the optional return value and the data being read is less than the length requested to be read, an error message is displayed.

If you use the return value, you must verify the validity of the data that has been read.

Example

This example shows how to use the InStream.READTEXT function. This example requires that you create the following variables.

Variable name | DataType
FileTest | File
StreamInTest | InStream
Int | Integer
Txt | Text
Copy Code
FileTest.OPEN('c:\XMLDocs\NewTest.txt');
FileTest.CREATEINSTREAM(StreamInTest);
// Starting a loop
WHILE NOT (StreamInTest.EOS) DO BEGIN
  Int := StreamInTest.READTEXT(Txt,100);
  MESSAGE(Txt + '\Size: ' + FORMAT(Int));
END;
FileTest.CLOSE();

See Also

Reference

InStream and OutStream Data Types
InStream.READ Function
InStream.EOS Function


OutStream

This section contains the following topics:

  • COPYSTREAM Function

  • OutStream.WRITE Function

  • OutStream.WRITETEXT Function


OutStream.WRITE Function

Writes a specified number of bytes to the stream. Data is written in binary format.

[Written := ] OutStream.Write(Variable[, Length])

Parameters

Variable

Type: Any

Contains the data to be written

Length

Type: Integer

The number of bytes to be written. In the case of data types other than string, code, and binary, if you specify a length that differs from the size of the variable, an error message is displayed.

Property Value/Return Value

Type: Integer

The number of bytes that were written.

Remarks

If the optional return value, Written, is not specified and it was not possible to write all the data, an error message is displayed.

If the return value is present, you must verify that all the data was streamed.

Example

Copy Code
recBinaries.FIND('-');
recBinaries.Data.CREATEOUTSTREAM(OutStream);
OutStream.WRITE('Secretary');
OutStream.WRITE('Alice');
OutStream.WRITE('Hart');
OutStream.WRITE(010696D);
recBinaries.MODIFY();

See Also

Reference

InStream and OutStream Data Types
OutStream.WRITETEXT Function


OutStream.WRITETEXT Function

Writes text to an OutStream object.

[Written := ] OutStream.WriteText([Text[, Length]])

Parameters

Text

Type: Text or Code

The text to write. If you do not specify this, a carriage return and a line feed are written.

Length

Type: Integer

The number of characters to be written.

Property Value/Return Value

Type: Integer

The number of characters that were written.

Example

This example requires that you create the following variables.

Variable name | DataType
MyHTMLFile | File
TestOutStream | OutStream

This example also requires that the c:\TestFiles folder exists.

Copy Code
MyHTMLFile.CREATE('c:\TestFiles\main.html');
MyHTMLFile.CREATEOUTSTREAM(TestOutStream);
TestOutStream.WRITETEXT('<html>');
TestOutStream.WRITETEXT;
TestOutStream.WRITETEXT('<head>');
TestOutStream.WRITETEXT('<title>My Page</title>');
TestOutStream.WRITETEXT('</head>');
TestOutStream.WRITETEXT;
TestOutStream.WRITETEXT('<P>Hello world!</p>');
TestOutStream.WRITETEXT;
TestOutStream.WRITETEXT('</html>');
FileMyHTML.CLOSE;

See Also

Reference

InStream and OutStream Data Types
OutStream.WRITE Function


KeyRef Data Type

Identifies a key in a table and the fields in this key.

Remarks

This complex data type gives you access to the key and the fields it contains.

The KeyRef object can refer to any key in any table in the database.

See Also

Reference

ACTIVE Function (KeyRef)
FIELDCOUNT Function (KeyRef)
FIELDINDEX Function (KeyRef)
RECORD Function (KeyRef)


ACTIVE Function (KeyRef)

Indicates whether the key is enabled.

Ok := KeyRef.ACTIVE

Parameters

KeyRef

Type: KeyRef

The keyref that refers to a key.

Property Value/Return Value

Type: Boolean

true if the key is enabled; otherwise, false.

Example

The following example uses the KeyRef.ACTIVE function to determine whether a key in a record is enabled. The table with ID 18 (the Customer table) is open with a reference to table 18. The KEYINDEX Function (RecordRef) function retrieves the first key in the record and the varKeyRef.ACTIVE function returns a Boolean value that indicates whether the retrieved key is enabled. The Boolean value is displayed in a message box. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType
RecRef | RecordRef
varKeyRef | KeyRef
IsActive | Boolean
Copy Code
RecRef.OPEN(18);
varKeyRef := RecRef.KEYINDEX(1);
IsActive := varKeyRef.ACTIVE;
MESSAGE('Is the key active =  %1 ', IsActive);

See Also

Reference

KeyRef Data Type


FIELDCOUNT Function (KeyRef)

Gets the number of fields that have been defined in a key. Returns an error if no key is selected.

No := KeyRef.FIELDCOUNT

Parameters

KeyRef

Type: KeyRef

The keyref that refers to the key.

Property Value/Return Value

Type: Integer

The number of fields that have been defined in the key.

Example

The following example retrieves the number of fields that are defined in a key in record. The table with ID 18 (the Customer table) is open with a reference to table 18. The KEYINDEX Function (RecordRef) function retrieves the second key in the record and store the KeyRef in the varKeyRef variable. The FIELDCOUNT Function (KeyRef) is then used to return the number of fields defined in the key and displayed in a message box. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType
RecRef | RecordRef
varKeyRef | KeyRef
VarCount | Integer
Copy Code
RecRef.OPEN(18);
varKeyRef := RecRef.KEYINDEX(2);
VarCount := varKeyRef.FIELDCOUNT;
MESSAGE('The number of fields defined in the key is: %1', VarCount);

See Also

Reference

KeyRef Data Type


FIELDINDEX Function (KeyRef)

Gets the FieldRef of the field that has this index in the key referred to by the KeyRef variable. Returns an error if no key is selected.

FieldRef := KeyRef.FIELDINDEX(Index)

Parameters

KeyRef

Type: KeyRef

The KeyRef that refers to the key.

Index

Type: Integer

The input index.

Property Value/Return Value

Type: FieldRef

The FieldRef that refers to the field with this index in the key.

Remarks

The first field in the index must have index 1, the second index 2, and so on. The last field must have index = FIELDCOUNT. If the index is out of the range supplied or if no table is selected, the function returns an error.

Example

The following example displays the caption of a field in a record. The table with ID 18 (the Customer table) is open with a reference. The Keyref for the record is retrieved by using the KEYINDEX Function (RecordRef). The function retrieves the second key in the record and stores the value in the varKeyRef variable. The varKeyRef variable is then used to return the FieldRef. The varFieldRef variable is used to display the caption of the field. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType
RecRef | RecordRef
varKeyRef | KeyRef
varFieldRef | FieldRef
Copy Code
RecRef.OPEN(18);
varKeyRef := RecRef.KEYINDEX(2);
varFieldRef := varKeyRef.FIELDINDEX(1);
MESSAGE('The Field name is: %1' ,varFieldRef.CAPTION);

See Also

Reference

KeyRef Data Type


RECORD Function (KeyRef)

Returns a RecordRef for the current record referred to by the key.

RecordRef := KeyRef.RECORD

Parameters

KeyRef

Type: KeyRef

The keyref that refers to the key that is currently selected.

Property Value/Return Value

Type: RecordRef

The RecordRef of the record that is currently selected referenced by the key. If a key is not selected, an error is returned.

Example

The table with ID 18 (the Customer table) is open with a reference. The KeyRef Data Type for the record is retrieved by using the KEYINDEX Function (RecordRef). The function retrieves the key that has an index of 1 in the record and stores the value in the varKeyRef variable. The varKeyRef variable is then used to return the RecordRef Data Type. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType
RecRef | RecordRef
varKeyRef | KeyRef
Copy Code
RecRef.OPEN(18);
varKeyRef := RecRef.KEYINDEX(1);
RecRef := varKeyRef.RECORD;

See Also

Reference

KeyRef Data Type
RecordRef Data Type


Numbers

This section contains the following topics:

  • BigInteger Data Type

  • Decimal Data Type

  • Integer Data Type

  • Numeric Functions


BigInteger Data Type

Stores very large whole numbers that range from -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807.

Remarks

This data type is a 64-bit integer.

You must add an L to the constant definition to inform C/AL that the integer must be interpreted and treated as a BigInteger.

If you assign -9,223,372,036,854,775,808 directly to a BigInteger variable, then you get an error when you try to compile the code. However, you can indirectly assign -9,223,372,036,854,775,808 to a BigInteger variable by using the following code.

Copy Code
BigIntegerVar := -9223372036854775807L;
BigIntegerVar := BigIntegerVar - 1;

If you try to indirectly assign a value that is smaller than -9,223,372,036,854,775,808, or larger than 9,223,372,036,854,775,807, then you get a run-time error.

Example

Copy Code
BI := 1L;
BI := 455500000000L;

See Also

Reference

Decimal Data Type
Integer Data Type
ABS Function (Decimal, Integer, BigInteger)
POWER Function (Decimal, Integer, BigInteger)
RANDOM Function (Integer)
RANDOMIZE Function (Integer)
ROUND Function (Decimal)


Decimal Data Type

This simple data type denotes decimal numbers ranging from -999,999,999,999,999.99 to +999,999,999,999,999.99.

Example

The following are examples of decimal values.

Copy Code
546.88
3425.57

The following is not a decimal, but rather an Integer Data Type.

Copy Code
342

Changes from Previous Versions

In Microsoft Dynamics NAV 2016, the Decimal data type is mapped to the Microsoft .NET Framework common language runtime (CLR) Decimal data type and the precision and limits behave slightly differently than the Binary Coded Decimal (BCD) data type in previous versions of C/AL. This example shows how decimal data types are different in Microsoft Dynamics NAV 2016.

The following table shows the limits for variables of type DECIMAL in Microsoft Dynamics NAV 2016 and in previous versions.

Limit Microsoft Dynamics NAV 2016 Previous versions of Microsoft Dynamics NAV

Maximum format value.

This is the maximum value that can be:

  • Formatted into a TEXT variable by the FORMAT function.

  • Input from the UI or XMLPorts.

  • Assigned directly in source code.

+/- 999,999,999,999,999.99

+/- 999,999,999,999,999.99

Maximum field data type value.

This is the maximum value that a field variable in a record can hold while not being persisted.

+/- 999,999,999,999,999.99

+/- (9,99999999999999E+63)

Maximum persisted value.

This is the maximum value that can be stored in the database.

Can read previous stored values but cannot store values outside the formatting range since field variables cannot be assigned values outside the formatting range.

+/- 999.999.999.999.999.999,99

Maximum calculating value.

This is the maximum value that can be calculated by code statements while not assigning to a field variable, storing to the database, or formatting to a text variable.

+/- 79,228,162,514,264,337,593,543,950,335

+/- (9,99999999999999E+63)

This table shows that the maximum safe value that will work on all versions of Microsoft Dynamics NAV is +/- 999,999,999,999,999.99.

It is possible to assign to a variable the maximum value that can be formatted and then multiply that variable by a large positive number, thereby generating a greater value. However, we do not recommend doing this. If you do, you will get errors if you attempt to format this variable to a text variable or assign the variable to a field variable in a record.

See Also

Reference

BigInteger Data Type
Integer Data Type
ABS Function (Decimal, Integer, BigInteger)
POWER Function (Decimal, Integer, BigInteger)
RANDOM Function (Integer)
RANDOMIZE Function (Integer)
ROUND Function (Decimal)


Integer Data Type

This simple data type stores whole numbers with values that range from -2,147,483,647 to 2,147,483,647.

Remarks

In addition to representing whole numbers in this range, you can use integers to represent Boolean values. For Boolean values, -1 represents true and 0 represents false.

If you assign -2,147,483,648 directly to an Integer variable, then you get an error when you try to compile the code. However, you can indirectly assign -2,147,483,648 to an Integer variable by using the following code.

Copy Code
IntegerVar := -2147483647;
IntegerVar := IntegerVar - 1;

If you try to indirectly assign a value that is smaller than -2,147,483,648 or larger than 2,147,483,647, then you get a run-time error.

Example

The following are examples of integer values.

Copy Code
546
-3425

The following example is a decimal and not an integer.

Copy Code
342.45

See Also

Reference

BigInteger Data Type
Decimal Data Type
ABS Function (Decimal, Integer, BigInteger)
POWER Function (Decimal, Integer, BigInteger)
RANDOM Function (Integer)
RANDOMIZE Function (Integer)
ROUND Function (Decimal)


Numeric Functions

This section contains the following topics:

  • ABS Function (Decimal, Integer, BigInteger)

  • POWER Function (Decimal, Integer, BigInteger)

  • RANDOM Function (Integer)

  • RANDOMIZE Function (Integer)

  • ROUND Function (Decimal)


ABS Function (Decimal, Integer, BigInteger)

Calculates the absolute value of a number (Decimal, Integer or BigInteger). ABS always returns a positive numeric value or zero.

NewNumber := ABS(Number)

Parameters

Number

Type: Integer

The input value.

Property Value/Return Value

Type: Integer

The return value is greater than or equal to 0 (zero).

Remarks

The system automatically converts all of the numeric data types for you.

Example

This example shows how to remove the sign from a negative numeric value. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
x | Decimal
y | Decimal

Text constant name | ENU Value
Text000 | x = %1, y = %2
Copy Code
x := -10.235; // x is assigned a negative value
y := ABS(x); // y is assigned the value of x without sign
MESSAGE(Text000, x, y);

The message window displays the following:

x = -10.235, y = 10.235

See Also

Reference

POWER Function (Decimal, Integer, BigInteger)
RANDOM Function (Integer)
RANDOMIZE Function (Integer)
ROUND Function (Decimal)


POWER Function (Decimal, Integer, BigInteger)

Raises a number to a power. For example, you can use this function to square the number 2 to get the result of 4.

NewNumber := POWER(Number, Power)

Parameters

Number

Type: Integer or Decimal

The number you want to raise exponentially. This number is the base in the exponential function.

Power

Type: Integer or Decimal

The exponent in the exponential function.

Property Value/Return Value

Type: Decimal

The result of raising Number by Power.

Example

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
Number1 | Decimal
Power1 | Decimal
Result1 | Decimal

Text constant name | Constant value
Text000 | %1 raised to the power of %2 = %3
Copy Code
Number1 := 64;
Power1 := 0.5;
Result1 := POWER(Number1, Power1);
MESSAGE(Text000, Number1, Power1, Result1)

On a computer that has the regional format set to English (United States), the first message window displays the following:

64 raised to the power of 0.5 = 8

This example shows that raising a number to the power of 0.5 corresponds to the square root of the number.

Example

This example shows a typical use for the POWER function.

If a principal amount P is deposited at interest rate R and compounded annually, then at the end of N years, the accumulated amount (A) is:

A = P(1 + R)N

For example, you put LCY 2800 into a bank account that pays 5 percent, which is compounded quarterly. To determine what the amount will be in eight years, you must consider:

N = 32 payment periods (8 years times 4 quarterly periods)

R = 0.0125 per period (5 percent divided by 4 quarterly periods)

The accumulated amount A is:

A = LCY 2800(1 + 0.0125)32 =LCY 2800(1.4881) = LCY 4166.77

If a principal amount P is deposited at the end of each year at interest rate R (in decimal notation) compounded annually, then at the end of N years, the accumulated amount is:

A = P[((1 + R)N - 1)/R]

This is typically called an annuity.

For example, you have an annuity in which a payment of LCY 500 is made at the end of each year. The interest on this annuity is 4 percent, which is compounded annually. To determine what the annuity will be worth in 20 years, you must consider:

R = 0.04

N = 20

The amount of the annuity A will be:

A = LCY 500[((1 + 0.04)20 - 1)/0.04 = LCY 14,889.04

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
P | Decimal
R | Decimal
N | Decimal
A | Decimal
FormatString | Text

Text constant name | Constant value
Text000 | Principal $%1 at a 5 percent interest rate is compounded quarterly.\
Text001 | (Rate = %2)\
Text002 | The amount after %3 years = $%4.
Text003 | Principal $%1 is deposited at the end of each year at a 4 percent interest rate, compounded annually.\
Text004 | (Rate = %2)\
Text005 | The amount after %3 years = $%4.
Copy Code
FormatString := '<Precision,2><Standard Format,1>';
// Example 1
P := 2800;
R := 0.0125;
N := 32;
A = P * (POWER(1 + R, N));
MESSAGE(Text000 + Text001 + Text002, P, R, N, FORMAT(A,0,FormatString);
// Example 2
P = 500;
R = 0.04;
N = 20;
A = P * ((POWER(1 + R, N) - 1)/R);
MESSAGE(Text001, P, R, N, FORMAT(A,0,FormatString));

On a computer that has the regional format set to English (United States), the first message window displays the following:

Principal $2,800 at a 5 percent interest rate is compounded quarterly.

(Rate = 0.0125)

The amount after 32 years = $4166.77.

The second message window displays the following:

Principal $500 is deposited at the end of each year at a 4 percent interest rate, compounded annually.

(Rate = 0.04)

The amount after 20 years = $14889.04.

See Also

Reference

ABS Function (Decimal, Integer, BigInteger)
RANDOM Function (Integer)
RANDOMIZE Function (Integer)
ROUND Function (Decimal)


RANDOM Function (Integer)

Returns a pseudo-random number.

Number := RANDOM(MaxNumber)

Parameters

MaxNumber

Type: Integer

The largest acceptable number. In effect, you are setting a range from one (1) to the number that you specify with the MaxNumber parameter.

Property Value/Return Value

Type: Integer

A pseudo-random number between one (1) and the number that you entered for MaxNumber.

Remarks

If MaxNumber is negative it acts as a positive.

If MaxNumber is zero, this function always returns 1.

A number is always chosen from the same set of numbers. Use RANDOMIZE Function (Integer) to generate a new set of numbers.

Example

This example shows how to generate a pseudo-random number. This example requires that you create the following variables and text constant in the C/AL Globals window. The value of the variable Number2 is positive though the value of MaxNumber is negative and the value of the variable Number3 is always 1 because MaxNumber is 0.

Variable name | DataType
x | Integer
y | Integer
z | Integer
Number1 | Integer
Number2 | Integer
Number3 | Integer

Text constant name | ENU Value
Text000 | Number1 = %1, Number2 = %2, Number3 = %3
Copy Code
x := 100; // x is assigned a positive value.
y := -100; // y is assigned a negative value.
z := 0; // z is assigned zero.
Number1 := RANDOM(x);
Number2 := RANDOM(y);
Number3 := RANDOM(z);
MESSAGE(Text000, Number1, Number2, Number3);

See Also

Reference

ABS Function (Decimal, Integer, BigInteger)
POWER Function (Decimal, Integer, BigInteger)
RANDOMIZE Function (Integer)
ROUND Function (Decimal)


RANDOMIZE Function (Integer)

Generates a set of random numbers from which the RANDOM Function (Integer) will select a random number.

RANDOMIZE([Seed])

Parameters

Seed

Type: Integer

A number used to create a unique set of numbers.

Remarks

If you use the same number as Seed, the same set of numbers is generated. If you omit this optional parameter, RANDOMIZE uses the current system time (total number of milliseconds since midnight). Calling the RANDOMIZE function before the RANDOM function makes the random numbers more unpredictable.

Furthermore, the random generator is specific to each connection so the sequence of numbers that is returned when you call the RANDOM function will be the same after each call to RANDOMIZE with a specific seed.

Example

The following example generates random numbers between 1 and 5 by using the Seed from the RANDOMIZE function to initialize the random number generator in the RANDOM function. The RANDOMIZE function uses the data from system clock as the Seed value.

Variable name | DataType
x | Integer

Text constant name | ENU value
Text000 | X=%1
Copy Code
RANDOMIZE();
x := RANDOM(5);
MESSAGE(Text000, x);

See Also

Reference

ABS Function (Decimal, Integer, BigInteger)
POWER Function (Decimal, Integer, BigInteger)
RANDOM Function (Integer)
ROUND Function (Decimal)


ROUND Function (Decimal)

Rounds the value of a numeric variable.

NewNumber := ROUND(Number [, Precision] [, Direction])

Parameters

Number

Type: Decimal

The number that you want to round.

Precision

Type: Decimal

This optional parameter determines the precision used when rounding. If you do not specify a Precision parameter, then the following steps are used to specify the precision:

  1. The function ReadRounding in Codeunit 1, Application Management, is called. ReadRounding returns a decimal value that is the precision. By default, the ReadRounding function returns the Amount Rounding Precision field from the GLSetup table.

  2. If you have customized Codeunit 1 and it does not implement the ReadRounding function, then the precision is specified as 2 digits after the decimal.

Direction

Type: Text or Code

This optional parameter specifies how to round the Number parameter. The default rounding method is '='. The following are the options for rounding:

  • '=' rounds up or down to the nearest value (default). Values of 5 or greater are rounded up. Values less than 5 are rounded down.

  • '>' rounds up

  • '<' rounds down

Property Value/Return Value

Type: Decimal

The rounded result.

Example

This example shows how to use the ROUND function. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
DecimalToRound | Decimal
Direction | Text
Precision | Decimal
Result | Decimal

Text Constant | ENU Value
Text000 | ROUND(%1, %2, %3) returns %4.
Copy Code
DecimalToRound := 1234.56789;
Direction := '>';
Precision := 0.001;
Result := ROUND(DecimalToRound, Precision, Direction);
MESSAGE(Text000, Format(DecimalToRound,0,1), Precision, Direction, Result);

On a computer that has the regional format set to English (United States), the message window displays the following:

ROUND(1234.56789, 0.001, >) returns 1,234.568

The following table displays some additional ROUND examples.

Number | Precision | Direction | Rounded number
1234.56789 | 100 | = | 1200
1234.56789 | 0.1 | = | 1234.6
1234.56789 | 0.001 | = | 1234.568
1234.56789 | 0.001 | < | 1234.567
1234.56789 | 0.001 | > | 1234.568
-1234.56789 | 100 | = | -1200
-1234.56789 | 0.1 | = | -1234.6
-1234.56789 | 0.001 | = | -1234.568
-1234.56789 | 0.001 | < | -1234.567
-1234.56789 | 0.001 | > | -1234.568

When you round down ('<') a negative number, such as -1234.56789, it is rounded down to -1234.567. However, -1234.567 is a mathematically greater value than -1234.56789.

When you round up ('>') a negative number, such as -1234.56789, it is rounded up to -1234.568. However, -1234.568 is a mathematically smaller value than -1234.56789.

See Also

Reference

ABS Function (Decimal, Integer, BigInteger)
POWER Function (Decimal, Integer, BigInteger)
RANDOM Function (Integer)
RANDOMIZE Function (Integer)


OCX Data Type

References a custom control, such as OCX or ActiveX control.

Remarks

Important
OCX data types are not supported by Microsoft Dynamics NAV Web client.

To use a control in Microsoft Dynamics NAV Development Environment, define a variable of type OCX and give it a name. Then choose the lookup button in the Subtype field to locate and select the control that you want to use. You select from a list of installed controls, and when you select one, the GUID of the control is inserted. When the focus leaves the Subtype field, the name of the control is substituted for the GUID.

When you have defined a control as a variable, you can use the control through the variable, and you can browse its methods and properties in the Symbol Menu.

When you are using a control, there is no one-to-one relationship between C/AL data types and COM data types. For an overview of the data type mapping, see Using COM Technologies in Microsoft Dynamics NAV.


Option Data Type

This simple data type denotes an option value.

Remarks

In the OptionString Property of the field or variable, you can enter the option values as a comma-separated list. The Option type is a zero-based enumerator type, which means that the option values are assigned to sequential numbers, starting with 0. You can convert option data types to integers.

For more information about option variables in multilanguage-enabled applications, see Developing Multilanguage-Enabled Applications.

Example

In the Purchase Header table, the Status field is an Option data type. In the following example, the option value is converted into an integer. This example requires that you create the following variables.

Name | Data type | Subtype
Number | Integer | Not applicable
PurchHeaderRec | Record | Purchase Header
Copy Code
Number := PurchHeaderRec."Document Type";

This example shows how you can use the value of an option field as a constant in your C/AL code.

Copy Code
PurchHeaderRec."Document Type" := PurchHeaderRec."Document Type"::Invoice;


Page Data Type

This complex data type stores pages.

Remarks

Pages contain a number of simpler elements called controls. Controls are used to display information to the user or receive information from the user.

See Also

Reference

OBJECTID Function (Page)
PAGE.RUN Function
PAGE.RUNMODAL Function
RUN Function (Page)
RUNMODAL Function (Page)
SETRECORD Function (Page)
SETSELECTIONFILTER Function
SETTABLEVIEW Function (Page, Report, XMLport)
UPDATE


OBJECTID Function (Page)

Returns a string in the "Page xxx" format, where xxx is the name or ID of the application object.

String := Page.OBJECTID([UseNames])

Parameters

Page

Type: Page

The page for which you want to get the name or object ID.

UseNames

Type: Boolean

Set this parameter to true if you want the returned string to contain the name of the page. Set this parameter to false if you want the returned string to contain the page ID.

The default value is true.

Property Value/Return Value

Type: Text or code

The string: Page <Page name | Page ID>

Example

If you add the following code to a page function or trigger, then the returned string is displayed in a message window.

Copy Code
MESSAGE(CurrPage.OBJECTID(TRUE));


PAGE.RUN Function

Creates and launches a page object, which you specify.

PAGE.RUN(Number[, Record] [, Field])

Parameters

Number

Type: Integer

The number of the page that you want to run. If you enter zero (0), the system displays the default lookup window for the current page. Choose View, and then choose C/AL Symbols Menu to select the page from a list.

If the page you specify does not exist, a run-time error occurs.

Record

Type: Record

The Page.RUN function shows, by default, the record last displayed on the page. For each object, the system stores information about the most recently displayed record and the attached key and filters.

Use this optional parameter to select a specific record to display on the page. The record must be of the same type as the table attached to the window. When the record is displayed, the key and filters attached to the record are used.

Field

Type: Field

Use this optional parameter to select a specific field on which focus will be placed.

Remarks

If, at design time, you do not know the specific page you want to run, then use this function or the PAGE.RUNMODAL Function and specify the page in the Number parameter.

If you do know which page you want to run, then you can create a Page variable, set the subtype of the variable to a specific page, and then use the RUN Function (Page) or RUNMODAL Function (Page) on the Page variable.

When you want to close the page, use CurrPage.CLOSE. CurrPage is a predefined system variable.

Example

Copy Code
Page.RUN(4711)

See Also

Reference

Page Data Type


PAGE.RUNMODAL Function

Creates, runs, and closes a specified page object. When a page is run modally, no input, such as a keyboard or mouse click, can occur except for objects on the modal page.

[Action :=] Page.RUNMODAL(Number[, Record][, Field])

Parameters

Number

Type: Integer

The number of the page that you want to run. If you enter zero (0), then the default lookup window for the current page is displayed. On the View menu, choose the C/AL Symbols Menu to select the page from a list.

If the page that you specify does not exist, then a run-time error occurs.

Record

Type: Record

By default, this function shows the record that was last displayed on the page. For each object, information is stored about the most recently shown record and the attached key and filters.

Use this optional parameter to select a specific record to display on the page. The record must be of the same type as the table that is attached to the page. When the record is displayed, the key and filters that are attached to the record are used.

Field

Type: Field

Use this optional parameter to select a specific field on which focus will be put.

Property Value/Return Value

Type: Action

Specifies what action the user took on the page. The following table shows the possible return values for the different user actions. In some cases, the actions for the return values are different when the page displays in the Microsoft Dynamics NAV Web client than in the Microsoft Dynamics NAV Windows client.

Return value Microsoft Dynamics NAV Windows client Microsoft Dynamics NAV Web client

OK

To close the page window, the user does one of the following:

  • Chooses the OK button.

  • Chooses the X button when there was no Cancel button on the window.

  • Presses the Esc key when there is no Cancel button on the window.

To close the page window, the user does one of the following:

  • Chooses the Close button.

  • Chooses the X button when there is no Cancel button on the window.

Cancel

To close the page window, the user does one of the following:

  • Chooses the Cancel button.

  • Chooses the X button when there is a Cancel button on the window.

  • Presses the Esc key when there is a Cancel button on the window.

To close the page window, the user does one of the following:

  • Chooses the Cancel button.

  • Chooses the X button when there is a Cancel button on the window.

LookupOK

To close a lookup window, the user does one of the following:

  • Chooses the OK button.

  • Chooses an item in the Lookup window.

To close a lookup window, the user chooses the OK button.

LookupCancel

To close a lookup window, the user chooses the Cancel button.

Same as Microsoft Dynamics NAV Windows client.

Yes

To close a confirmation window, the user selects Yes.

Same as Microsoft Dynamics NAV Windows client.

No

To close a confirmation window, the user does one of the following:

  • Chooses the No button.

  • Chooses the X button.

  • Presses the Esc key.

To close a confirmation window, the user does one of the following:

  • Chooses the No button.

  • Chooses the X button.

RunObject

The user selected an option that ran another Microsoft Dynamics NAV object.

Same as Microsoft Dynamics NAV Windows client.

RunSystem

The user selected an option that ran an external program.

Same as Microsoft Dynamics NAV Windows client.

Remarks

The page is run modally. If you do not know the specific page that you want to run when you are designing your application, then use this function or the PAGE.RUN Function and specify the page in the Action parameter.

If you do know which page that you want to run, then you can create a Page variable, set the Subtype of the variable to a specific page, and then use the RUN Function (Page) or RUNMODAL Function (Page) on the Page variable.

When you want to close the page, use the CurrPage.CLOSE function. CurrPage is a predefined system variable.

Example

This example shows how to call page 21.

Copy Code
IF Page.RUNMODAL(21, MyRecord, ...) = Action::LookupOK THEN...;

See Also

Reference

Page Data Type


RUN Function (Page)

Creates and launches a page that you specify. You can use CLEAR Function to remove the page.

Page.RUN

Parameters

Page

Type: Page

After you define this variable, you can run the following page functions:

  • SETTABLEVIEW

  • SETRECORD

  • GETRECORD

  • RUN

  • RUNMODAL.

The variable is automatically cleared after this function is executed.

If the page you specify does not exist, you receive a compile error.

Remarks

If, at design time, you know the specific page that you want to run, then you can create a Page variable, set the Subtype of the variable to a specific page, and then use this function or the RUNMODAL Function (Page) on the Page variable.

If you do not know the page that you want to run, then use the PAGE.RUN Function or the PAGE.RUNMODAL Function and specify the page in the Number parameter.

After you define the page variable, you can use it before you run the page. If you use the RUNMODAL Function (Page), you can use the variable before and after you run the page.

Example

This example shows how to use the RUN function. Assume the variable MyPage has been defined as Page 1.

Copy Code
MyPage.XXX; // any user-defined function
MyPage.SETTABLEVIEW(MyRecord);
MyPage.SETRECORD(MyRecord);
MyPage.RUN;

See Also

Reference

Page Data Type


RUNMODAL Function (Page)

Creates, opens, and closes a page that you specify. When a page is run modally, no input, such as a keyboard or mouse click, can occur except for objects on the modal page.

[Action :=] Page.RUNMODAL

Parameters

Page

Type: Variable

After you define this variable, you can run the following page functions:

  • SETTABLEVIEW

  • SETRECORD

  • GETRECORD

  • RUN

  • RUNMODAL

Unlike the PAGE.RUN Function, the variable is not automatically cleared after this function runs.

If the page that you specify does not exist, then a compile-time error occurs.

Property Value/Return Value

Type: Action

Specifies what action the user took on the page. The following table shows the possible return values for the different user actions. In some cases, the actions for the return values are different when the page displays in the Microsoft Dynamics NAV Web client than in the Microsoft Dynamics NAV Windows client.

Return value Microsoft Dynamics NAV Windows client Microsoft Dynamics NAV Web client

OK

To close the page window, the user does one of the following:

  • Chooses the OK button.

  • Chooses the X button when there was no Cancel button on the window.

  • Presses the Esc key when there is no Cancel button on the window.

To close the page window, the user does one of the following:

  • Chooses the Close button.

  • Chooses the X button when there is no Cancel button on the window.

Cancel

To close the page window, the user does one of the following:

  • Chooses the Cancel button.

  • Chooses the X button when there is a Cancel button on the window.

  • Presses the Esc key when there is a Cancel button on the window.

To close the page window, the user does one of the following:

  • Chooses the Cancel button.

  • Chooses the X button when there is a Cancel button on the window.

LookupOK

To close a lookup window, the user does one of the following:

  • Chooses the OK button.

  • Chooses an item in the Lookup window.

To close a lookup window, the user chooses the OK button.

LookupCancel

To close a lookup window, the user chooses the Cancel button.

Same as Microsoft Dynamics NAV Windows client.

Yes

To close a confirmation window, the user selects Yes.

Same as Microsoft Dynamics NAV Windows client.

No

To close a confirmation window, the user does one of the following:

  • Chooses the No button.

  • Chooses the X button.

  • Presses the Esc key.

To close a confirmation window, the user does one of the following:

  • Chooses the No button.

  • Chooses the X button.

RunObject

The user selected an option that ran another Microsoft Dynamics NAV object.

Same as Microsoft Dynamics NAV Windows client.

RunSystem

The user selected an option that ran an external program.

Same as Microsoft Dynamics NAV Windows client.

Remarks

If you know the specific page that you want to run when you are designing your application, then you can create a Page variable, set the Subtype of the variable to a specific page, and then use this function or the RUN Function (Page).

If you do not know the specific page that you want to run, then use the PAGE.RUN Function or the PAGE.RUNMODAL Function and specify the page in the Number parameter.

After you define the page variable, you can use it before and after you run the page. If you use the PAGE.RUN Function, then you can only use the variable before you run the page.

Example

This example shows how to use this function. Assume that the SomePage variable has been defined as Page 1.

Copy Code
CLEAR(SomePage)
SomePage.XXX; // Any user-defined function
SomePage.SETTABLEVIEW(MyRecord);
SomePage.SETRECORD(MyRecord);
IF SomePage.RUNMODAL = Action::LookupOK THEN
  SomePage.GETRECORD(MyRecord)...
Note
This code example includes the CLEAR Function to make sure that the variable has been cleared.

See Also

Reference

Page Data Type


SETRECORD Function (Page)

Sets the current record for the page.

Visual Basic
Page.SETRECORD(Record)
C#

Parameters
Page

            Type: Page

            The page on which to set the current record.
Record

            Type: Record

            The record to set as the current record.
  Note

              You cannot use a temporary record for the Record parameter.

  Remarks
You can use this function to set the record to display when the user opens the page.
  Example
The following example retrieves the record that has a primary key value of ‘30000’ from the Customer table. If the record is found, it is stored in the MyRecord variable. The SETRECORD function uses the retrieved record as the current record and sets record for MyPage, which is a Customer Card page. When the code unit is run, the record is displayed on the MyPage page. If the record is not found, a message box displays a message that indicates that the record was not found. This example requires that you create the following variables and text constant in the C/AL Globals window.
Variable name | DataType | Subtype
MyPage | Page | Customer Card
MyRecord | Record | Customer
Text constant name | ENU value
Text 000 | The record was not found.
    Copy Code
IF
  MyRecord.GET('30000') THEN BEGIN
  MyPage.SETRECORD(MyRecord);
  MyPage.RUN;
   END
ELSE BEGIN
  MESSAGE(Text000);
  END;


SETSELECTIONFILTER Function

Microsoft Dynamics NAV Documentation
SETSELECTIONFILTER Function
See Also

Notes the records that the user has selected on the page, marks those records in the table specified, and sets the filter to "marked only".

CurrPage.SETSELECTIONFILTER(Record)

Parameters

Record

Type: Record

A specific record or records.

Remarks

If all records are selected, marks will not be used.

If only the current record is selected on the page, then SetSelectionFilter does the following:

  • Sets the current filter group to 0 on the destination record

  • Adds filters on the primary key fields that point to the current record of the page

If more than one record is selected on the page, then SetSelectionFilter does the following:

  • Copies the current key from the page source table to the destination record

  • Copies the current sort order from the table to the destination record

  • Copies the current filters that are set in all filter groups

  • Copies the current filter group

  • Marks the selected records and sets the "marked only" filter

See Also

Reference

Page Data Type


SETTABLEVIEW Function (Page, Report, XMLport)

Applies the table view on the current record as the table view for the page, report, or XMLport.

SETTABLEVIEW(Record)

Parameters

Record

Type: Record

The record that has a table view that you want to apply to the page or data item.

Remarks

The table view is the view of the table that you present to the user. You determine what records that the user can see by setting filters, determining the sorting order, and selecting the keys.

This function only narrows the view of the table that was set through the SourceTableView Property of the page or through the DataItemTableView Property of the data item.

Important
SETTABLEVIEW is not supported for setting views on subpages from code on table headers. For example, you cannot set a table view on the SalesOrder subpage from the SalesHeader.

Example

This example is based on the Sales Header table and shows how SETTABLEVIEW is used for a page object. It requires that you create the following variables.

Variable name | DataType | Subtype
SalesHeader | Record | Sales Header
SomePage | Page | Sales List
Copy Code
SalesHeader.SETCURRENTKEY("Document Type");
SalesHeader.SETRANGE("Document Type",SalesHeader."Document Type"::Order);
SomePage.SETTABLEVIEW(SalesHeader); // Only view sales orders.
SomePage.RUN

The page that is reference by the SomePage variable can be any page object that has Sales Header as the value of the SourceTable Property.

See Also

Reference

Report Data Type
XMLport Data Type


UPDATE

Saves the current record and then updates the controls in the page. If you set the SaveRecord parameter to false, this function will not save the record before the page is updated.

Visual Basic
CurrPage.UPDATE[(SaveRecord)]

Parameters

SaveRecord

Type: Boolean

Set this parameter to true if you want to save the current record. Set this parameter to false if you want to update without saving the current record. The default value is true.

See Also

Reference

Page Data Type


Query Data Type

A complex data type that stores queries.

Remarks

A query enables you to retrieve data from multiple tables and combine the data in single dataset.

See Also

Reference

Accessing Columns of a Query Dataset
CLOSE Function (Query)
COLUMNCAPTION Function
COLUMNNAME Function
COLUMNNO Function
GETFILTER Function (Query)
GETFILTERS Function (Query)
OPEN Function (Query)
READ Function (Query)
SAVEASCSV Function
SAVEASXML Function
SETFILTER Function (Query)
SETRANGE Function (Query)
TOPNUMBEROFROWS Function


Accessing Columns of a Query Dataset

If the query is in the reading state, you can retrieve the value of columns in the current active row of the dataset by using the following syntax in C/AL.

ColumnValue := QueryVariable.ColumnName
  • QueryVariable is a variable of the Query data type that specifies the query object.

  • ColumnName is the name of the column in the query as specified by the Name Property of the column.

Return Value

Type: The data type of the field that is used by the column, unless the column applies a totaling method as specified by the Method Property. If the column applies a totaling method, then data type is an integer for the Count method and a decimal for all other totaling methods

Returns the value of the column in the current active row.

Remarks

A column of a row can only be accessed after the query has been opened by using a call to the OPEN function followed by a call to the READ function. The current active row is the row that has been included in the query variable after the last call to READ function.

Example

The following example demonstrates how to access a column of a query dataset. When the query is run, each row in the dataset is read and message box is displayed that contains the value of a column in the row.

This example requires that you do the following:

  • Create a query called Customer_SalesQuantity that links table 18 Customer with table 37 Sales Lines from the CRONUS International Ltd. demonstration database. Include columns for the Name and No. fields from the Customer table and the Quantity field from Sales Lines table.

    For step-by-step instructions for creating this query, see Walkthrough: Creating a Query to Link Two Tables.

  • Create the following variable and text constant:

    Variable name DataType Subtype

    myQuery

    Query

    Customer_SalesQuantity

    Text constant name ENU Value

    Text000

    Customer name = %1, Quantity = %2

The following C/AL code opens the query, reads each row of dataset, and then displays a message that has the content of each row. You can add the code to a codeunit, and then run the codeunit to see the results.

Copy Code
// Sets a filter to display only sales quantities greater than 20.
MyQuery.SETFILTER(Quantity, '>20');
// Runs the query.
MyQuery.OPEN;
// Reads each row in the dataset and displays a message with column values.
// Stops reading when there are no more rows remaining in the dataset (READ is FALSE).
WHILE MyQuery.READ DO
BEGIN
  MESSAGE(Text000, MyQuery.Name, MyQuery.Quantity);
END;
// Closes the query.
MyQuery.CLOSE;


CLOSE Function (Query)

Closes a query dataset and returns the query instance to the initialized state.

The following code shows the syntax of the CLOSE function. Query is a variable of the Query data type that specifies the query object.

Query.CLOSE

Remarks

The CLOSE function does not clear any filters that are set by the SETFILTERS function. If you want to clear the filters, then you must call the CLEAR function.

In most cases, you do not have to call the CLOSE function explicitly. The CLOSE function is called implicitly when the following conditions are true:

  • When the query variable goes out of scope.

  • When the OPEN function is called on a dataset that is currently open.

  • When the SETFILTER Function (Query) or SETRANGE Function (Query) are called on a dataset that is currently open.

Example

The following example demonstrates how to use the CLOSE function on a query. The example code sets filters on the query, opens the query, and then reads the dataset. For each row in the dataset, a message box is displayed that contains the values of the columns in the row.

This example requires that you do the following:

  • Create a query called Customer_SalesQuantity that is links table 18 Customer with table 37 Sales Lines from the CRONUS International Ltd. demonstration database. Include columns for the Name and No. fields from the Customer table and the Quantity field from Sales Lines table.

    For step-by-step instructions for creating this query, see Walkthrough: Creating a Query to Link Two Tables.

  • Create the following variable and text constant

    Variable name DataType Subtype

    MyQuery

    Query

    Customer_SalesQuantity

    Text constant name ENU Value

    Text000

    Customer name = %1, Quantity = %2

The following C/AL code opens the query, reads each row of the dataset, and then closes the query. You can add the code to a codeunit, and then run the codeunit to see the results.

Copy Code
// Sets a filter to display only sales quantities greater than 20.
MyQuery.SETFILTER(Quantity, '>20');
// Runs the query.
MyQuery.OPEN;
// Reads each row in the dataset and displays a message with column values.
// Stops reading when there are no more rows remaining in the dataset (READ is FALSE).
WHILE MyQuery.READ DO
BEGIN
  MESSAGE(Text000, MyQuery.Name, MyQuery.Quantity);
END;
MyQuery.CLOSE;

See Also

Tasks

How to: Create Queries

Concepts

Working with Queries in C/AL
Queries


COLUMNCAPTION Function

Returns the current caption of a query column as a text string.

Caption := Query.COLUMNCAPTION(Column)

Parameters

Query

Type: query

A variable that specifies the query object that contains the column.

Column

Type: Text

Refers to the name of the query column. The name of a query column is specified by the Name Property of the column in Query Designer.

Property Value/Return Value

Type: Text

The current value of CaptionML Property for the query column.

Remarks

The CaptionML property is multi-language enabled, so it can contain a list of text strings in different languages. The string that is used is selected according to the user's language settings. For more information, see Multilanguage Development.

Example

The following example shows how to get the caption for a column of a query. The query is called My Customer Query and has a column with the name Customer_No.

This example requires that you create the following variables.

Variable name | DataType | Subtype
Caption | Text | Not applicable
MyQuery | Query | My Customer Query
Copy Code
Caption := MyQuery.COLUMNCAPTION("Customer_No");
MESSAGE(Caption);

See Also

Tasks

How to: Create Queries


COLUMNNAME Function

Returns the name of a query column as a text string.

Name := Query.COLUMNNAME(Column)

Parameters

Query

Type: Query

A variable that specifies the query object that contains the column.

Column

Type: Text

Refers to the name of the query column. The name of a query column is specified by the Name Property of the column in Query Designer.

Property Value/Return Value

Type: Text

The name of the specified column.

Remarks

The COLUMNNAME function retrieves the name of the column as specified by its Name property and enables you to create actions based on the column name. If you want to retrieve the query column's caption, which displays in the user interface of the query, then call the COLUMNCAPTION Function instead.

Example

The following example shows how to get the name for a column of a query. The query is called My Customer Query and has a column with the name Customer_No. This example requires that you create the following variables.

Variable name | DataType | Subtype | Length
NameOfColumn | Text | Not applicable | 64
MyQuery | Query | My Customer Query | Not applicable
Copy Code
NameOfColumn := MyQuery.COLUMNNAME("Customer_No");

The name of the column is stored in a text string.

The advantage of using this statement instead of assigning the column name in a statement, such as NameOfColumn := 'Customer_No';, is that the COLUMNNAME function dynamically adapts to any change to the column name that is made in the development environment. The NameOfColumn := 'Customer_No'; statement performs a static assignment.

See Also

Tasks

How to: Create Queries
How to: Set Up Filter Rows in Query Designer

Reference

Record Data Type

Concepts

Queries
Multilanguage Development


COLUMNNO Function

Returns the ID that is assigned to a query column in the query definition.

Number := Query.COLUMNNO(Column)

Parameters

Query

Type: Query

A variable that specifies the query object that contains the column.

Column

Type: Text

Refers to the name of the query column. The name of a query column is specified by the Name Property of the column in Query Designer.

Property Value/Return Value

Type: Integer

The number that is assigned to the column.

Remarks

In Query Designer, each column of the query is assigned a number that is specified by the column's ID Property. The COLUMNNO function enables you to create actions based on the ID of a column.

Example

The following example shows how to get the ID of a column of a query. The query is called My Customer Query and has a column with the name Customer_No. This example requires that you create the following variables.

Variable name | DataType | Subtype
Number | Integer | Not applicable
MyQuery | Query | My Customer Query

This statement assigns the ID of the Customer_No column in the My Customer Query query to the Number variable.

Copy Code
Number := MyQuery.COLUMNNO("Customer_No");

See Also

Tasks

How to: Create Queries
How to: Set Up Filter Rows in Query Designer

Reference

Record Data Type

Concepts

Queries


GETFILTER Function (Query)

Returns the filters that are set on the field of a specified column in the query.

The following code shows the syntax of the GETFILTER function. Query is a variable of the Query data type that specifies the query object.

Filter := Query.GETFILTER(Column)

Parameters

Column

Type: Text

The name of the column in the query. A column name is defined by the Name Property in Query Designer.

Return Value

Type: Text

A text string that lists all the filters that are set on the column of the query. If there are no filters, then an empty string is returned.

Remarks

The GETFILTER function returns the filters that are currently set for a data column or filter row by the SETFILTER Function (Query) function, SETRANGE Function (Query) function, and the column's ColumnFilter Property in Query Designer. The GETFILTER function does not return filters that are set on a column's source field by the DataItemTableFilter Property in Query Designer or global filters that are set by the FILTERGROUP function.

Note
A filter row is row in Query Designer that is used to filter on a field that is not included in the resulting dataset. For more information, see Understanding Query Filters and How to: Set Up Filter Rows in Query Designer.

You can call the GETFILTER function multiple times and at any point in the code. If you call the GETFILTER function before the SETFILTER or SETRANGE function, then the GETFILTER function returns only filters on the column that are set by the column's ColumnFilter property.

Filters that are set by the SETFILTER function and SETRANGE function are applied to a query when the query is opened with a call to the OPEN, SAVEASXML, or SAVEASCSV functions. You must consider the location of the GETFILTERS function with respect to these functions to obtain the desired results. For example, in the following two code examples, the GETFILTER function will return the filter that is set by the SETFILTER function. However, in the first example, the filter has been applied to the query dataset; in the second example, the filter has not been applied.

Copy Code
Query.SETFILTER(Column, String);
Query.OPEN;
Query.GETFILTER(Column);
Query.READ;

Copy Code
Query.OPEN;
Query.SETFILTER(Column, String);
Query.GETFILTER(Column);
Query.READ;

Example

The following C/AL code example demonstrates how to use the GETFILTER function on a query. The example code sets a filter on a query column, and then displays a message when the query is run that indicates the filter on the column.

This example requires that you do the following:

  1. Create a query called Customer_SalesQuantity that has the following characteristics:

    • Links table 18 Customer with table 37 Sales Lines from the CRONUS International Ltd. demonstration database.

    • Includes columns for the Name and No. fields from the Customer table and the Quantity field from Sales Lines table.

      For step-by-step instructions for creating this query, see Walkthrough: Creating a Query to Link Two Tables.

    • The ColumnFilter property of the Quantity column is set to include values greater than 5.

  2. Create the following C/AL variables and text constant in the object that will run the query, such as a codeunit.

    Variable name DataType Subtype

    MyQuery

    Query

    Customer_SalesQuantity

    MyFilter

    Text

    Not applicable

    Text constant name ENU Value

    Text000

    The filter is: %1

The following C/AL code runs the query and displays a message that contains the filter that is set on a query column. You can add the code to a codeunit, and then run the codeunit to see the results.

Copy Code
// Sets a filter to display only sales quantities greater than 10. This overwrites the ColumnFilter property.
MyQuery.SETFILTER(Quantity, '>10');
// Runs the query and applies the filter.
MyQuery.OPEN;
// Returns the filter on the Quantity column and displays the filter in a message.
MyFilter := MyQuery.GETFILTER(Quantity);
MESSAGE(Text000, MyFilter);

Running the code returns the following message:

The filter is: Quantity > 10


GETFILTERS Function (Query)

Returns the filters that are applied to all columns in the query.

The following code shows the syntax of the GETFILTERS function. Query is a variable of the Query data type that specifies the query object.

Filter := Query.GETFILTERS

Return Value

Type: Text

A text string that lists the filters that are set on all columns of the query. If there are no applicable filters, then an empty string is returned.

Remarks

The GETFILTERS function returns the filters that are currently set for all data columns and filter rows by the SETFILTER Function (Query) function, SETRANGE Function (Query) function, and the ColumnFilter Property in Query Designer. The GETFILTER function does not return filters that are set on a column's source field by the DataItemTableFilter Property in Query Designer or global filters that are set by the FILTERGROUP function.

Note
A filter row is row in Query Designer that is used to filter on a field that is not included in the resulting dataset. For more information, see Understanding Query Filters and How to: Set Up Filter Rows in Query Designer.

You can call the GETFILTERS function multiple times and at any point in the code. If you call the GETFILTERS function before the first SETFILTER or SETRANGE function call, then the GETFILTERS function returns only filters that are set by the ColumnFilter property of the columns.

Filters that are set by the SETFILTER function and SETRANGE function are applied to a query when the query is opened by using a call to the OPEN, the SAVEASXML, or SAVEASCSV functions. You must consider the location of the GETFILTERS function with respect to these functions to obtain the results that you want. For example, in the following two code examples, the GETFILTERS function will return the filter set by the SETFILTER function call. However, in the first example, the filter has been applied to the query dataset; in the second example, the filter has not been applied.

Copy Code
Query.SETFILTER(Column, String);
Query.OPEN;
Query.GETFILTERS;
Query.READ;

Copy Code
Query.OPEN;
Query.SETFILTER(Column, String);
Query.GETFILTERS;
Query.READ;

Example

The following C/AL code example demonstrates how to use the GETFILTERS function on a query. The example code sets filters on a query column, and then displays a message when the query is run that indicates the filter on the column.

This example requires that you do the following:

  1. Create a query called Customer_SalesQuantity that has the following characteristics:

    • Links table 18 Customer with table 37 Sales Lines from the CRONUS International Ltd. demonstration database.

    • Includes columns for the Name and No. fields from the Customer table and the Quantity field from Sales Lines table.

      For step-by-step instructions for creating this query, see Walkthrough: Creating a Query to Link Two Tables.

    • The ColumnFilter property of the Quantity column is set with a filter that includes values greater than 10.

  2. Create the following C/AL variables and text constant in the object that will run the query.

    Variable name DataType Subtype

    MyQuery

    Query

    Customer_SalesQuantity

    MyFilters

    Text

    Not applicable

    Text constant name ENU Value

    Text000

    The filters are as follows: %1

The following C/AL code runs the query and displays a message that contains the filter that is set on a query column. You can add the code to the OnRun trigger of a codeunit, and then run the codeunit to see the results.

Copy Code
// Sets a filter to display only sales quantities greater than 10. This overwrites the value of ColumnFilter property.
MyQuery.SETFILTER(Quantity, '>10');
// Sets a filter to display the columns with the value Selangorian Ltd. only.
MyQuery.SETFILTER(NAME, 'Selangorian Ltd.');
// Runs the query and applies the filter.
MyQuery.OPEN;
// Returns the filters that are on the Quantity column and displays the filters in a message.
MyFilters := MyQuery.GETFILTERS;
MESSAGE(Text000, MyFilters);

Running the code returns the following message:

The filters are as follows: Quantity > 10, Name = Selangorian Ltd.

See Also

Tasks

How to: Set Up Filter Rows in Query Designer

Concepts

Understanding Query Filters


OPEN Function (Query)

Runs a query object and generates a dataset that can be read.

The following code shows the syntax of the OPEN function. Query is a variable of the Query data type that specifies the query object.

[Ok :=] Query.OPEN

Return Value

Type: Boolean

true if the query was opened without errors; otherwise, false.

If you omit this optional return value and if the query does not execute successfully, then a run-time error occurs. If you include a return value, then it is assumed that you will handle any errors and no run-time error occurs when the OPEN function is called. However, a run-time error will occur if the READ function is called afterward.

Remarks

When the OPEN function is called, the query is executed and the Query variable is put in a state in which the resulting dataset can be read by the READ function. The OPEN function has the following behavior:

  • To apply filters for the SETFILTERS function or SETRANGE function, you call the SETFILTERS function or SETRANGE function before the OPEN function.

  • To read a row from the dataset, you must call the OPEN function before the READ function, as shown in the following code example.

    Copy Code
    Query.SETFILTER(Column1, String);
Query.OPEN;
Query.READ;
  • To close an open query and return it to the initialized state, you can call the CLOSE function. However, you can call the OPEN function multiple times without calling the CLOSE function because the OPEN function implicitly calls the CLOSE function if the query dataset is currently in an opened state.

    • If the OPEN function is called on a query that is already in the opened or in the reading state, then the query dataset is closed, and then the query is executed again. To continue to loop through the dataset, the READ function must be called again. The next READ function call returns the first row in the dataset, as shown in the following code example.

      Copy Code
      // Opens the query and generates a dataset.
Query.OPEN;
Query.READ;
// Closes the query and reopens it.
Query.OPEN;
// Reads the first row in the new dataset.
Query.READ;
    • OPEN function does not clear any filters that were set by the SETFILTER or SETRANGE functions on a previous OPEN call. If you want to clear the filters, then you must call the CLEAR function on the query variable.

      Copy Code
      Query.SETFILTER(Column1, String);
Query.OPEN;
Query.READ;
CLEAR(query);
Query.OPEN;
Query.READ;
  • You are required to call the OPEN function before the SAVEASXML Function or SAVEASCSV Function. The SAVEASXML and SAVEASCSV functions automatically close the current query dataset and initialize a new instance of the query.

Example

The following example demonstrates how to use the OPEN function on a query. The example code sets filters on the query, opens the query, and then reads the dataset. For each row in the dataset, a message box is displayed that contains the values of the columns in the row.

This example requires that you do the following:

  1. Create a query called Customer_SalesQuantity that links table 18 Customer with table 37 Sales Lines from the CRONUS International Ltd. demonstration database. Include columns for the Name and No. fields from the Customer table and the Quantity field from Sales Lines table.

    For step-by-step instructions for creating this query, see Walkthrough: Creating a Query to Link Two Tables.

  2. Create the following variable and text constant.

    Variable name DataType Subtype

    MyQuery

    Query

    Customer_SalesQuantity

    Text constant name ENU Value

    Text000

    Customer name = %1, Quantity = %2

The following C/AL code opens the query, reads each row of the dataset, and then displays a message that uses the content of the row. You can add the code to a codeunit, and then run the codeunit to see the results.

Copy Code
// Sets a filter to display only sales quantities greater than 20.
MyQuery.SETFILTER(Quantity, '>20');
// Runs the query.
MyQuery.OPEN;
// Reads each row in the dataset and displays a message with column values.
// Stops reading when there are no more rows remaining in the dataset (READ is FALSE).
WHILE MyQuery.READ DO
BEGIN
  MESSAGE(Text000, MyQuery.Name, MyQuery.Quantity);
END;
MyQuery.CLOSE;

When the code is run, a message that resembles the following appears for each row in the dataset:

Customer name = The Device Shop, Quantity = 30

See Also

Tasks

How to: Create Queries

Concepts

Working with Queries in C/AL
Queries


READ Function (Query)

Reads data from a row in the resulting dataset of a query.

The following code shows the syntax of the READ function. Query is a variable of the Query data type that specifies the query object.

[Ok :=] Query.READ

Return Value

Type: Boolean

true if a row in the resulting dataset was retrieved; otherwise, false.

Remarks

When the READ function is called, the next row in the dataset query is retrieved. While in the reading state, values of columns in the row can be accessed by calling Query.ColumnName, where Query is the query type variable that specifies the query object and ColumnName is the column of the query.

To read a row in the dataset, you must call the OPEN function before the READ function. After the READ function call, columns can be accessed as shown in the following code example.

Copy Code
query.OPEN;
query.READ;
query.ColumnName

You can call the READ function multiple times after the OPEN function to read consecutive rows in the dataset. The first READ function call retrieves the first row from the resulting dataset and each subsequent READ function retrieves the next row from the dataset. For example, the second READ function call retrieves the second row, the third READ function call retrieves the third row, and so on.

Copy Code
Query.OPEN;
// Reads the first row in the dataset.
Query.READ;
// Accesses a column in the first row of the dataset.
Query.ColumnName
// Reads the second row in the dataset.
Query.READ;
// Accesses a column in the first row of the dataset.
Query.ColumnName
Note
If the READ function is called and there are no more rows in the dataset, then the READ function returns false.

Example

The following example demonstrates how to use the READ function on a query. The example code sets filters on the query, opens the query, and then reads the dataset. For each row in the dataset, a message box is displayed that contains the values of the columns in the row.

This example requires that you do the following:

  • Create a query called Customer_SalesQuantity that is links table 18 Customer with table 37 Sales Lines from the CRONUS International Ltd. demonstration database. Include columns for the Name and No. fields from the Customer table and the Quantity field from Sales Lines table.

    For step-by-step instructions for creating this query, see Walkthrough: Creating a Query to Link Two Tables.

  • Create the following variable and text constant.

    Variable name DataType Subtype

    MyQuery

    Query

    Customer_SalesQuantity

    Text constant name ENU Value

    Text000

    Customer name = %1, Quantity = %2

The following C/AL code opens the query, reads each row of dataset, and then displays a message that has the content of the row. You can add the code to a codeunit, and then run the codeunit to see the results.

Copy Code
// Sets a filter to display only sales quantities greater than 20.
MyQuery.SETFILTER(Quantity, '>20');
// Runs the query.
MyQuery.OPEN;
// Reads each row in the dataset and displays message with column values.
// Stops reading when there are no more rows remaining in the dataset (READ is FALSE).
WHILE MyQuery.READ DO
BEGIN
  MESSAGE(Text000, MyQuery.Name, MyQuery.Quantity);
END;
// Closes the query.
MyQuery.CLOSE;


SAVEASCSV Function

Saves the resulting dataset of a query as a comma separated values (CSV) file.

The following code shows the syntax of the SAVEASCSV function. The first line of code is the syntax for an instance function call. The second line of code is the syntax for a static function call.

[OK := ] QueryVariable.SAVEASCSV (FileName[, Format][, FormatArgument])
[OK := ] QUERY.SAVEASCSV(Number, FileName[, Format][, FormatArgument)

Parameters

QueryVariable

Type: Query

A variable that specifies the query object.

Number

Type: Integer

The ID of the query object.

Tip
On the View menu, choose C/AL Symbol Menu, choose Query, and then select the query from a list.

If the query that you specify does not exist, then a run-time error occurs.

FileName

Type: Text

The path and name of the file that you want to save the query dataset to.

Format

Type: Integer

Specifies whether the columns of the resulting dataset are at fixed positions in the CSV file or separated only by a delimiter. The parameter has the following values:

Value Description

0

Places columns in fixed positions in lines of the CSV file. You can use this parameter to left align column values between lines in the CSV file. The following code illustrates a simple CSV example that includes two lines with three columns.

Copy Code
aa   bbb            cccc
xxxx yyyyyyyyyyy   zzzzz

You set the starting position using the FormatArgument parameter.

1

Separates columns with a delimiter, There are no spaces between the columns. The following code illustrates a simple CSV example that includes two lines with three columns.

Copy Code
aa;bbb;cccc
xxxx;yyyyyyyyyyy;zzzzz

You specify the delimiter using the FormatArgument parameter. In this example, the FormatArgument parameter is set to ';'.

Note
This is an optional parameter. If you omit the Format parameter, then columns are separated by a comma with no spaces.

FormatArgument

Type: Text

You set the FormatArgument parameter based on the setting of the Format parameter.

  • If the Format parameter is set to 0, then the FormatArgument parameter specifies the starting position of each column in the dataset. The value is a comma separated string of integers that includes an integer for every column. In a CSV file, each line is evenly divided into positions for holding characters. The first integer corresponds to the starting position of the first column, the second integer corresponds to the starting position of the second column, and so on. For example, if the query includes three columns, then you could set the parameter to '1, 5, 20'. In CSV file, as illustrated in the following example, the first column would start at the first position, the second column at the fifth position, and the third column at the twentieth position.

    Copy Code
    aa   bbb            cccc
xxxx yyyyyyyyyyy    zzzzz
    Note
    In the CSV file, if the value for a column extends beyond the starting position of an adjacent column, then the column value is cut off where the adjacent column starts.

  • If the Format parameter is set to 1, then the FormatArgument parameter specifies the delimiter to use between columns. The value can be one or more characters, such as ‘,’, ‘;’, and ‘tab’. If you do not specify a value, then the parameter is set to ‘,’ by default.

Return Value

Type: Boolean

If you omit this optional return value and if the query cannot be saved as a CSV file, then a run-time error occurs that states that the query cannot be saved. If you include a return value, then it is assumed that you will handle any errors and no run-time error occurs, even though the query is not saved.

true if the query was saved; otherwise, false.

Remarks

A CSV file stores data in a plain text format. When you save a query dataset as a CSV file, each row of the dataset is stored on a separate line in the file, and each column in a row is separated by a comma or another delimiter of your choice. The first line of the file will contain the column names of the query. A query column name is specified by its Name Property.

When the SAVEASCSV function is called the query dataset is generated and then saved in CSV format to the file that is designated by the FileName parameter.

To apply filters with the SETFILTER and SETRANGE functions, the SAVEASCSV function must be called after SETFILTER and SETRANGE functions, as shown in the following example.

Copy Code
// Sets a filter on the Quantity column of the query
Query.SETFILTER(Quantity, '>50');
// Opens a new query that is filtered by the SETFILTER function and saves the dataset
Query.SAVEASCSV('c:\test.csv');

The SAVEASCSV function can be called at any place in the code and does not require that the CLOSE, OPEN or READ functions are called before it. When the SAVEASCSV function is called, a new instance of the query is created. The query is implicitly opened, read, and closed. If there is currently a dataset in the opened state when the SAVEASCSV function is called, then that instance is closed. This means that the following code is illegal because the query is not open on the second READ call.

Copy Code
Query.OPEN;
Query.READ;
Query.SAVEASCSV('c:\test.csv');
Query.READ;

The correct code for this example is as follows.

Copy Code
Query.OPEN;
Query.READ;
Query.SAVEASCSV('c:\test.csv');
Query.OPEN;
Query.READ;

Example

The following example shows how to save the dataset of a query with the name My Customers Query as a CSV file. The file is given the name mycustomers.csv and is saved on the c: drive of the computer running Microsoft Dynamics NAV Server. The query consists of three columns: No., Name, and City. The file is set to place the columns at the following positions: 1, 10, and 40.

This example requires that you do the following:

  • Create a query called My Customer Query that is based on table 18 Customer and contains the No, Name, and City columns. For more information, see How to: Create Queries.

  • Create the following variables and text constant:

    Variable name DataType Subtype

    OK

    Boolean

    Not applicable

    MyCustomerQuery

    Query

    My Customer Query

    Text constant name ENU Value

    Text000

    Query was not saved.

Copy Code
OK := MyCustomerQuery.SAVEASCSV('c:\mycustomers.csv', 0, '1,10,40');
IF NOT OK THEN
  ERROR(Text000);

The following code shows an example of the content of the saved file.

Copy Code
No       Name                          City
01121212 Spotsmeyer's Furnishings      Miami
01445544 Progressive Home Furnishings  Chicago
01454545 New Concepts Furniture        Atlanta
01905893 Candoxy Canada Inc.           Thunder Bay
01905899 Elkhorn Airport               Elkhorn
01905902 London Candoxy Storage Campus London

If for some reason the file cannot be saved, then the message Query was not saved. appears.


SAVEASXML Function

Saves the resulting dataset of a query as an .xml file.

The following code shows the syntax of the SAVEASXML function. The first line of code is the syntax for an instance function call. The second line of code is the syntax for a static function call.

[Ok :=] QueryVariable.SAVEASXML(FileName)
[Ok :=] QUERY.SAVEASXML(Number, FileName)

Parameters

QueryVariable

Type: Query

A variable that specifies the query object to save as an .xml file.

Number

Type: Integer

The ID of the query object that you want to save as an .xml file. On the View menu, choose C/AL Symbol Menu to select the query from a list. If the query that you specify does not exist, then a run-time error occurs.

FileName

Type: Text

The path and name of the file that you want to save the query to.

Return Value

Type: Boolean

true if the query dataset was saved; otherwise, false.

If you omit this optional return value and if the query cannot be saved as an .xml file, then a run-time error occurs that states that the query cannot be saved. If you include a return value, then it is assumed that you will handle any errors and no run-time error occurs, even though the query is not saved as an .xml file.

Remarks

When the SAVEASXML function is called, the dataset is generated and then saved in XML format in the file and location that is designated by the FileName parameter.

The SAVEASXML function can be called at any place in the code and does not require that the CLOSE, OPEN, or READ functions are called before it. When the SAVEASXML function is called, a new instance of the query is created. The query is implicitly opened, read, and closed. If there is currently a dataset in the opened state when the SAVEASXML function is called, then that instance is closed. This means that the following code is unauthorized because the query is not open on the second READ call.

Copy Code
Query.OPEN;
Query.READ;
Query.SAVEASXML('c:\test.xml');
Query.READ;

The correct code for this example is as follows.

Copy Code
Query.OPEN;
Query.READ;
Query.SAVEASXML('c:\test.xml');
Query.OPEN;
Query.READ;

Example

The following example shows how to save a query with the name My Customer Query as an .xml file. The file is given the name myquery.xml and is saved on the c: drive of the computer running Microsoft Dynamics NAV Server.

This example requires that you create the following variables and text constant.

Variable name | DataType | Subtype
OK | Boolean | Not applicable
MyCustomerQuery | Query | My Customer Query

Text constant name | ENU Value
Text000 | Query was not saved.
Copy Code
OK := MyCustomerQuery.SAVEASXML('c:\myquery.xml');
IF NOT OK THEN
  ERROR(Text000);

If the file cannot be saved, then the follow message appears:

Query not saved.


SETFILTER Function (Query)

Sets a filter on a column of a query to limit the records in the resulting dataset of a query.

The following code shows the syntax of the SETFILTER function. Query is a variable of the Query data type that specifies the query object.

Query.SETFILTER(Column, String[, Value],...)

Parameters

Column

Type: Text

The name of the column in the query that you want to filter. The name is defined by the column's Name Property in Query Designer.

String

Type: Text or code

The filter expression. A valid expression consists of alphanumeric characters and one or more of the following operators: <, >, *, &, |, and =. You can use replacement fields (%1, %2, and so on) to insert values at run-time. For more information about filter expressions and syntax, see Entering Criteria in Filters.

Value

Type: Any

Replacement values to insert in replacement fields in the filter expression. The data type of Value must match the data type of field that is referred to by the ColumnName.

Remarks

To apply filters to a dataset, the SETFILTER function must be called before the OPEN, SAVEASXML, and SAVEASCSV functions, as shown in the following example. To remove filters from query, you call the CLEAR Function.

Copy Code
Query.SETFILTER(Column1, String);
Query.OPEN;
Query.READ;
CLEAR(Query);

A call to the SETFILTER function automatically closes a query dataset that is currently open. Therefore, the following code is unauthorized and will fail because there is no open dataset for the READ function to read.

Copy Code
Query.OPEN;
Query.READ;
Query.SETFILTER(Column2, String);
Query.READ;

You can have multiple calls to the SETFILTER function. If SETFILTER function calls set filters on different columns, then the filters are combined and applied to the dataset. If consecutive SETFILTER function calls set filters on the same column, then the last SETFILTER function call is applied to the column.

In addition to the SETFILTER function, you can apply filters to a query using the SETRANGE Function (Query) function, the FILTERGROUP function, and the DataItemTableFilter Property and ColumnFilter Property in Query Designer.

If the SETFILTER function... | then...
Sets a filter on the same field as the DataItemTableFilter property | The two filters are joined into a resulting filter.
Sets a filter on the same field as the ColumnFilter property | The SETFILTER function overwrites the ColumnFilter property, so the filter that is set by the SETFILTER function that is applied to the dataset.
Sets a filter on the same field as the SETRANGE function | The function that is called last is applied to the dataset.
Sets a filter on a field that has global filters that are applied by the FILTERGROUP(1) function | The filters of the SETFILTER function are added to the global filters.

For example, a query has the following filters set on the Quantity column in Query Designer:

  • DataItemTableFilter property: Quantity=FILTER(<100)

  • ColumnFilter property: Quantity=FILTER(<>50)

Query.SETFILTER ("Quantity", '>1’) will result in a filter that is equivalent to: 1<Quantity <100.

For more information about how to set filters in Query Designer, see Understanding Query Filters.

Example

The following C/AL code example demonstrates how to use the SETFILTER function on a query. The example code sets a filter on a query column, and then displays a message when the query is run that indicates the filter on the column.

This example requires that you do the following:

  1. Create a query called Customer_SalesQuantity that has the following characteristics:

    • Links table 18, Customer with table 37, Sales Lines from the CRONUS International Ltd. demonstration database.

    • Includes columns for the Name and No. fields from the Customer table and the Quantity field from Sales Lines table.

      For step-by-step instructions for creating this query, see Walkthrough: Creating a Query to Link Two Tables.

  2. Create the following C/AL variables and text constant in the object that will run the query, such as a codeunit.

    Variable name DataType Subtype

    MyQuery

    Query

    Customer_SalesQuantity

    Text constant name ENU Value

    Text000

    Customer name = %1, Quantity = %2

The following C/AL code uses the SETFILTER function to filter the query dataset on the Quantity and Name columns. You can add the code to a codeunit, and then run the codeunit to see the results.

Copy Code
// Sets a filter to display only sales quantities greater than 10.
MyQuery.SETFILTER(Quantity, '>10');
// Sets a filter to display the columns with the value Selangorian Ltd. only.
MyQuery.SETFILTER(NAME, 'Selangorian Ltd.');
// Runs the query.
MyQuery.OPEN;
// Reads each row in the dataset and displays message with column values.
// Stops reading when there are no more rows remaining in the dataset (READ is FALSE).
WHILE MyQuery.READ DO
BEGIN
  MESSAGE(Text000, MyQuery.Name, MyQuery.Quantity);
END;
// Saves the resulting dataset as a CSV file.
MyQuery.SAVEASCSV('c:\temp\CustomerSales.csv');
// Closes the query.
Myquery.CLOSE;

When the code is run, a message that resembles the following appears for each row in the dataset:

Customer name = Selangorian Ltd., Quantity = 30


SETRANGE Function (Query)

Sets a filter on a range of values on a column of a query dataset.

Query.SETRANGE(Column[, FromValue][, ToValue])

Parameters

Query

Type: Query

A variable of the Query data type that specifies the query that you want to filter.

Column

Type: Text

The name of the column in the query that you want to filter. The name is defined by the column's Name Property in Query Designer.

FromValue

Type: Any

The lower limit of the range. The data type of this parameter must match the data type of Column.

If you set only the FromValue parameter, then the ToValue parameter is set to the same value as FromValue.

ToValue

Type: Any

The upper limit of the range. The data type of this parameter must match the data type of Column. If you omit the ToValue parameter, then the only the value that is specified for FromValue is used, which enables you to filter on a single column value instead of a range.

Note
If you omit both the FromValue and ToValue parameters, then the function removes all filters that are already set on the column.

Remarks

SETRANGE is a quick way to set a simple filter on a field. The SETRANGE function is functionally equivalent to calling Query.SetFilter(ColumnName, ‘FromValue..ToValue’).

To apply filters to a dataset, the SETRANGE function must be called before the OPEN, SAVEASXML, and SAVEASCSV functions, as shown in the following example. To remove filters, you call the CLEAR Function or SETRANGE without values for the FromValue and ToValue parameters.

Copy Code
Query.SETRANGE(Column1, FromValue, ToValue);
Query.OPEN;
Query.READ;
CLEAR(Query);

A call to the SETRANGE function automatically closes a query dataset that is currently open. Therefore, the following code is unauthorized and will fail because there is no open dataset for the READ function to read.

Copy Code
Query.OPEN;
Query.READ;
Query.SETRANGE(Column1, FromValue, ToValue);
Query.READ;

In addition to the SETRANGE function, you can apply filters to a query using the SETFILTER function and the DataItemTableFilter Property and ColumnFilter Property in Query Designer.

If the SETRANGE function... | then...
Sets a filter on the same field as the DataItemTableFilter property | The two filters are joined into a resulting filter.
Sets a filter on the same field as the ColumnFilter property | The SETRANGE function overwrites the ColumnFilter property, so the filter that is set by the SETRANGE function that is applied to the dataset.
Sets a filter on the same field as the SETFILTER function | The function that is called last is applied to the dataset.
Sets a filter on a field that has global filters that are applied by the FILTERGROUP(1) function | The filters of the SETRANGE function are added to the global filters.

For example, a query has the following filters set on the Quantity column in Query Designer:

  • DataItemTableFilter property: Quantity=FILTER(<>10)

  • ColumnFilter property: Quantity=FILTER(<>5)

Query.setRange(Quantity, 1, 15) will result in a filter that is equivalent to: 1 < Quantity <15, except for 10.

For more information about how to set filters in Query Designer, see Understanding Query Filters.

Example

The following C/AL code example demonstrates how to use the SETRANGE function on a query. The example code sets a filter on a query column and saves the resulting dataset as a CSV file. A message also displays when the query is run that indicates the filter on the column.

This example requires that you do the following:

  1. Create a query called Customer_SalesQuantity that has the following characteristics:

    • Links table 18 Customer with table 37 Sales Lines from the CRONUS International Ltd. demonstration database.

    • Includes columns for the Name and No. fields from the Customer table and the Quantity field from Sales Lines table.

      For step-by-step instructions for creating this query, see Walkthrough: Creating a Query to Link Two Tables.

  2. Create the following C/AL variables and text constant in the object that will run the query, such as a codeunit.

    Variable name DataType Subtype

    MyQuery

    Query

    Customer_SalesQuantity

    Text constant name ENU Value

    Text000

    Customer name = %1, Quantity = %2

The following C/AL code uses the SETRANGE function to filter a query dataset over a range of values on the Quantity column. You can add the code to a codeunit, and then run the codeunit to see the results.

Copy Code
// Sets a filter to display only sales quantities greater than 10.
MyQuery.SETRANGE(Quantity, '10', '50');
// Sets a filter to display the columns with the value Selangorian Ltd. only.
MyQuery.SETFILTER(NAME, 'Selangorian Ltd.');
// Runs the query.
MyQuery.OPEN;
// Reads each row in the dataset and displays message with column values.
// Stops reading when there are no more rows remaining in the dataset (READ is FALSE).
WHILE MyQuery.READ DO
BEGIN
  MESSAGE(Text000, MyQuery.Name, MyQuery.Quantity);
END;
// Saves the resulting dataset as a CSV file.
MyQuery.SAVEASCSV('c:\temp\CustomerSales.csv');
MyQuery.CLOSE;

When the code is run, a message that resembles the following appears for each row in the dataset:

Customer name = Selangorian Ltd., Quantity = 30


TOPNUMBEROFROWS Function

Specifies the maximum number of rows to include in the resulting dataset of a query.

[CurrRows :=] TOPNUMBEROFROWS([NewRows]]

Parameters

NewRows

Type: Integer

The number of rows to include in the resulting dataset. If you do not set the NewRows parameter, then the resulting dataset will include all rows.

Note
If you set the value to 0, then there is no limit and all rows of the dataset are returned.

Property Value/Return Value

Type: Integer

The number of rows that are included in the dataset.

Remarks

You use the TOPNUMBEROFROWS property to limit the resulting dataset to the first set of rows that are generated for the query. For example, you can include only the first 10 or first 100 rows in the resulting dataset. The TOPNUMBEROFROWS property is useful for key performance indicators such as the top number of customers or sales.

You can also specify the number of rows to include in the dataset by setting the TopNumberOfRows Property in Query Designer. The TOPNUMBEROFROWS function will overwrite the TopNumberOfRows property setting.

Example

The following C/AL code example demonstrates how to use the TOPNUMBEROFROWS function on a query to return the top 10 customer sales orders based on the quantity of items.

This example requires that you do the following:

  1. Create a query called Customer_SalesQuantity that has the following characteristics:

    • Links table 18, Customer with table 37, Sales Lines from the CRONUS International Ltd. demonstration database.

    • Includes columns for the Name and No. fields from the Customer table and the Quantity field from Sales Lines table.

      For step-by-step instructions for creating this query, see Walkthrough: Creating a Query to Link Two Tables.

    • The TopNumberOfRows Property is set to include only the first 5 rows in the resulting dataset. This setting will be overwritten by the TOPNUMBEROFROWS function.

    • The OrderBy Property is set on the Quantity column to sort results in descending order.

  2. Create the following C/AL variables in the object that will run the query.

    Variable name DataType Subtype

    MyQuery

    Query

    Customer_SalesQuantity

    Counter

    Integer

    Not applicable

    Text constant name ENU Value

    Text000

    The top number of rows is: %1

C/AL Code

The following C/AL code runs the query, saves it as a CSV file, and displays a message that states the number of rows that are returned in the resulting dataset. You can add the code as a codeunit, and then run the codeunit to see the results.

Copy Code
// Overwrites the TopNumberOfRows property and returns the first 10 rows in the dataset.
MyQuery.TOPNUMBEROFROWS(10);
// Opens the query.
MyQuery.OPEN;
// Reads each row of the dataset and counts the number of rows.
While MyQuery.READ DO
BEGIN
  Counter +=1;
END;
// Saves the dataset as a CSV file.
MyQuery.SAVEASCSV('c:\temp\CustomerSales.csv');
// Displays a message that shows the number of rows.
MESSAGE(Text000, counter);


Record Data Type

This complex data type corresponds to a row in a table. Each record consist of fields that form the columns of the table. A record is typically used to hold information about a fixed number of properties.

Remarks

To access a field in a table in your C/AL code, use the following syntax: TableName.FieldName


ADDLINK Function (Record)

Adds a link to a record.

[ID := ] Record.ADDLINK(URL[, Description])

Parameters

Record

Type: Record

The record that you want to add a link to.

URL, Description

Type: String

The link that you want to add to the record and an optional description of that link.

Property Value/Return Value

Type: Integer

The ID of the URL that you want to add to the record.

Remarks

When you add a link to a page or a table, an entry is created in the Record Link system table. Each entry is given an ID.

The URL can be a link to a website, a file stored on the local computer or on a remote computer, or a link to a Microsoft Dynamics NAV page.

Example

In this example, you get the customer record that has a primary key number of 15000 and then add the specified URL to the Record Link table for that customer. You can then view the link in the Links FactBox on the Customer list or Customer card pages. This example requires that you create the following variables.

Name | DataType | Subtype
Customer | Record | Customer
ID | Integer | Not applicable
Copy Code
Customer.GET('15000');
ID := Customer.ADDLINK('www.northwindtraders.com','Northwind Traders');

See Also

Reference

Record Data Type


ASCENDING Function (Record)

Gets or sets the order in which the system searches through a table.

[IsAscending :=] Record.ASCENDING([SetAscending])

Parameters

Record

Type: Record

The record in the table to search.

SetAscending

Type: Boolean

Specifies the order of the search.

true if the search is to be done in ascending order; otherwise, false if the search is to be done in descending order.
If you do not use this parameter, the function returns the current search order.

Property Value/Return Value

Type: Boolean

The order in which a search will be done.

true if the search will be done in ascending order; otherwise, false.

Example

The following example returns a value that indicates the current search order of the Customer table, to which MyRecord record belongs. The return value is stored in the IsAscending variable and displayed in a message box. In this example, the value Yes is displayed in the message box, which mean the search order is ascending. This is because the SetAscending parameter is not used. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType | Subtype
MyRecord | Record | Customer
IsAscending | Boolean | Not applicable

Text constant name | Data type | ENU value
Text000 | Text | Is the current sort order ascending?: %1
Copy Code
IsAscending := MyRecord.ASCENDING;
MESSAGE(Text000, IsAscending);

Example

The following example sets the current sort order to descending by setting the SetAscending parameter to false. The value displayed in the message box is No.

Copy Code
IsAscending := MyRecord.ASCENDING(FALSE);
MESSAGE(Text000, IsAscending);

See Also

Reference

Record Data Type


CALCFIELDS Function (Record)

Calculates the FlowFields in a record. You specify which fields to calculate by using parameters.

[Ok :=] Record.CALCFIELDS(Field1, [Field2],...)

Parameters

Record

Type: Record

The record in the table to update.

Field1, Field2, …

Type: Field

The FlowFields or BLOB fields that you want to calculate or retrieve. Each field must belong to the same record variable.

Property Value/Return Value

Type: Boolean

Remarks

FlowFields are virtual fields. The values in these fields are not saved in the table. This means that you must use either the CALCFIELDS function or the SETAUTOCALCFIELDS Function (Record) to update them. For example, if you retrieve a record using the FIND Function (Record) and NEXT Function (Record), the FlowFields in those records are set to zero (0). Then, when you call CALCFIELDS, their values are updated.

When a FlowField is a direct source expression on a page or a report, the calculation is performed automatically.

You can also use the CALCFIELDS function to retrieve binary large objects (BLOBs). For more information, see BLOB Data Type.

If possible, the CALCFIELDS function uses SumIndexField Technology (SIFT). SIFT is used only if the following conditions are true:

  • The Microsoft Dynamics NAV key contains the fields that are used in the filters that are defined for the FlowField.

  • The SumIndexFields on the Microsoft Dynamics NAV key contain the fields that are provided as parameters for calculation.

  • The MaintainSIFTIndex Property is set to Yes.

    Note
    By default this property is set to Yes for all keys.

Note
Microsoft Dynamics NAV 2016 automatically maintains a count for all SIFT indexes. Therefore, if the calculation method for a FlowField is COUNT or AVERAGE, then the condition that the SumIndexFields on the Microsoft Dynamics NAV key contain the fields that are provided as parameters for calculation is not required.

For Microsoft Dynamics NAV 2016, CALCFIELDS execution is decoupled from Microsoft Dynamics NAV SIFT index definitions. This means that if the conditions for using SIFT indexes are not true, then Microsoft Dynamics NAV traverses all records in the base table to perform the calculation instead of using SIFT. This can reduce the number of required SIFT indexes, which can improve performance. In earlier versions of Microsoft Dynamics NAV, if the conditions for using SIFT indexes were not true and the MaintainSIFTIndex property was enabled, then you received an error when you called the CALCFIELDS function. This provided a degree of protection in earlier versions against accidentally requesting a sorting for which no index existed. In Microsoft Dynamics NAV 2016, an index is not required to support a certain sorting, but sorting without an index could lead to bad performance if a search returns a large result set, which would then have to be sorted before the first row is returned.

Example

This example shows how to use the CALCFIELDS function to find the balance on December 31, 2008 and the net change for a customer in 2008.

This example requires that you create the following variable.

Variable name | DataType | Subtype
CustomerRec | Record | Customer
Copy Code
CustomerRec.SETRANGE("Date Filter",010108D,123108D);
CustomerRec.CALCFIELDS(Balance, "Net Change");

The first line sets up a filter for the Date Filter field in the Customer record. This field is a FlowFilter field which is used in the filter definition for several FlowFields in the Customer record. In the second line, the FlowFields are calculated.

See Also

Reference

FieldClass Property

Concepts

FlowFields
FlowFields


CALCSUMS Function (Record)

Calculates the total of a column in a table. You specify which fields to calculate by using parameters.

[Ok :=] Record.CALCSUMS (Field1, [Field2],...)

Parameters

Record

Type: Record

The record that contains the SumIndexFields that you want to calculate.

Field1, Field2, …

Type: Decimal, Integer, BigInteger, or Duration

The fields that you want to calculate. Each field must be defined as a SumIndexField, in the current key. The field class of the field must be Normal. For more information about field class, see FieldClass Property.

Property Value/Return Value

Type: Boolean

If you omit this optional return value and if one of the fields is not a SumIndexField, a run-time error occurs. If you include a return value, you must handle any errors.

Remarks

Use this function to total columns in a table. This function operates only on records that meet the conditions of any filters associated with the record.

If possible, the CALCSUMS function uses SumIndexField Technology (SIFT). SIFT is used only if the following conditions are true:

  • The Microsoft Dynamics NAV key contains the fields that are used in the filters that are defined for the FlowField.

  • The SumIndexFields on the Microsoft Dynamics NAV key contain the fields that are provided as parameters for calculation.

  • The MaintainSIFTIndex Property is set to Yes.

    Note
    By default this property is set to Yes for all keys.

For Microsoft Dynamics NAV 2016, CALCSUMS execution is decoupled from Microsoft Dynamics NAV SIFT index definitions. This means that if any of the conditions for using SIFT indexes are not true, then Microsoft Dynamics NAV traverses all records in the base table to perform the calculation instead of using SIFT. This can reduce the number of required SIFT indexes, which can improve performance. In earlier versions of Microsoft Dynamics NAV, if the conditions for using SIFT indexes were not true and the MaintainSIFTIndex property was enabled, then you received an error when you called the CALCSUMS function. This provided a degree of protection in earlier versions against accidentally requesting a sorting for which no index existed. In Microsoft Dynamics NAV 2016, an index is not required to support a certain sorting, but sorting without an index could lead to bad performance if a search returns a large result set, which would then have to be sorted before the first row is returned.

The CALCSUMS function adheres to the SecurityFiltering Property. For more information about security filters, see Record-Level Security.

Example

This example shows how to use the CALCSUMS function. It requires that you create a Record variable named WhseEntry for the Warehouse Entry table.

Copy Code
WhseEntry.SETFILTER("Item No.", 'LS-*');
WhseEntry.SETRANGE("Bin Code", 'W-11-0001');
WhseEntry.SETRANGE("Location Code", 'WHITE');
WhseEntry.CALCSUMS("Qty. (Base)");

The first three lines set filters on fields in the Warehouse Entry record so the total that is calculated in the last line of code uses records only in the specified range.

See Also

Reference

SumIndexFields Property

Concepts

SumIndexField Technology (SIFT)


CHANGECOMPANY Function (Record)

Redirects references to table data from one company to another.

[Ok :=] Record.CHANGECOMPANY([CompanyName])

Parameters

Record

Type: Record

The record that you want to access from a table in another company.

CompanyName

Type: Text or code

The name of the company to which you want to change. If you omit this parameter, you change back to the current company.

Property Value/Return Value

Type: Boolean

true if the company was found; otherwise, false.

If you omit this optional return value and the company cannot be found, a run-time error occurs. If you include the return value, you must handle any errors.

Remarks

When executing this function, the user's access rights are respected. For example, a user cannot access data in CompanyName unless he already has the necessary access rights.

The CHANGECOMPANY function is not affected by the RESET Function (Record). You can deselect a company by making a new call to CHANGECOMPANY or by using the CLEAR Function.

Global filters always belong to a specific company. If you use the following code to select the company named NewCompany, any filters assigned to Record will be transferred to Record in the new company.

Copy Code
Record.CHANGECOMPANY(NewCompany);

Even if you run the CHANGECOMPANY function, triggers still run in the current company, not in the company that you specified in the CHANGECOMPANY function.

Example

This example shows how to use the CHANGECOMPANY function.

Copy Code
"G/L Account".CHANGECOMPANY('New Company');
"G/L Account".GET('1000');
"G/L Account".CALCFIELDS(Balance); // Calculates the balance
// for account no. 1000 in 'New Company'
"G/L Entry".CHANGECOMPANY('New Company');
"G/L Entry".SETCURRENTKEY("Entry No.","Posting Date");
"G/L Entry".SETRANGE("Entry No.",1000);
"G/L Entry".SETRANGE("Posting Date",010196D,013196D);
"G/L Entry".CALCSUMS(Amount); // Sums Amount from
// all G/L entries on account no. 1000 within the specified range,
// for 'New Company'
"G/L Entry".RESET;
"G/L Entry".FIND('+'); // Finds the largest "No." in the G/L Entry
// table in 'New Company'
"G/L Entry".DELETE; // Deletes this entry in 'New Company'

This example shows that after the CHANGECOMPANY function has been called, all future references to the G/L Account and G/L Entry tables will refer to the table data in New Company.

This example shows that CHANGECOMPANY only changes the company on a data level. Triggers and functions will still run in the context of the current company.

Copy Code
Rec.CHANGECOMPANY('B');
Rec.FINDFIRST;
Rec.MODIFY(TRUE);

If you run the code in this example from Company A, it will modify Rec in Company B, but it will run the OnModify trigger in Company A.

See Also

Reference

Record Data Type


CLEARMARKS Function (Record)

Removes all the marks from a record.

Record.CLEARMARKS

Parameters

Record

Type: Record

The record from which you want to remove all marks.

Example

This example requires that you create a CustomerRec variable that has data type of Record and subtype of Customer.

Copy Code
CustomerRec.CLEARMARKS

See Also

Reference

Record Data Type


CONSISTENT Function (Record)

Marks a table as being consistent or inconsistent.

Record.CONSISTENT(Consistent)

Parameters

Record

Type: Record

The table that you want to mark.

Consistent

Type: Boolean

The mark to be set on the table.

If this parameter is true, the table is marked as consistent. If this parameter is false, the table is marked as inconsistent.

Remarks

Usually this function is only used for accounting routines. If your accounts do not balance, then the accounts are inconsistent. This function makes sure that inconsistent changes are not made in your accounts.

If an attempt is made to commit a write transaction when a table is marked as inconsistent, then a message is displayed and all updates that were made in the write transaction are aborted.

Example

A typical example of an inconsistency occurs when the sum of all the entries in a table that contains general ledger entries does not balance (is not equal to zero).

In this example, your application includes a function object that is named ChangeAmount. This function is used to withdraw amounts that were put into the General Ledger Entry table in your application. When an amount is withdrawn from an account, the system is inconsistent until a corresponding amount is put in. The following code example illustrates the ChangeAmount function. The ChangeAmount function has one parameter, Amount, which is a Decimal data type.

Copy Code
GLEntry."G/L Account No." := '1000';
GLEntry.Amount := Amount;
GLEntry.INSERT;
Balance := Balance + Amount;
IF Balance = 0 THEN
  Consistent := TRUE
ELSE
  Consistent := FALSE;
GLEntry.CONSISTENT(Consistent);
END;

The function uses the variable Balance to express the change in balance. For example, when the function is used to withdraw $100, the Balance variable will reflect this as -$100.

When you use the function to put in one or more amounts whose total equals +$100, the Balance variable then equals zero and the table is marked as consistent. This means that if an attempt is made to put in an amount and end the write transaction (commit the change) without withdrawing a corresponding amount, an error occurs and the write transaction is canceled.

See Also

Reference

Record Data Type


COPY Function (Record)

Copies a specified record, filters, marks, and keys that are associated with the record from a table or creates a reference to a record.

Record.COPY(FromRecord [, ShareTable])

Parameters

Record

Type: Record

The record where the copy will be placed.

FromRecord

Type: Record

The record to copy.

ShareTable

Type: Boolean

Specifies whether the function copies filters, marks, and keys of the record or creates a reference to a temporary record.

If FromRecord and Record are both temporary and ShareTable is true, then the COPY function causes Record to reference the same table as FromRecord.

Important
If ShareTable is true, then both Record and FromRecord must be temporary; otherwise an error will occur.

The default value is false. If you specify false, only filters, marks, and keys are copied.

Example

The following example copies a record to another record in the Customer table. The GET Function (Record) retrieves record number 30000 from the Customer table and stores record in the sourceRecord variable. The COPY function copies the record that is stored in the sourceRecord to the destRecord. The ShareTable parameter is set to true because the Temporary Property for the both sourceRecord and destRecord are set to Yes to make the records temporary. If the record is copied, then a message indicating that the record is copied is displayed in a message box. Otherwise, a message indicating that the record is not copied is displayed. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType | Subtype
sourceRecord | Record | Customer
destRecord | Record | Customer

Text constant name | ConstValue
Text000 | The record is copied.
Text001 | The record is not copied.
Copy Code
IF sourceRecord.GET(30000) THEN BEGIN
  destRecord.COPY(sourceRecord, TRUE);
  MESSAGE(Text000);
END
ELSE BEGIN
  MESSAGE(Text001);
END;

See Also

Reference

Record Data Type


COPYFILTER Function (Record)

Copies the filter that has been set for one field and applies it to another field.

Record.COPYFILTER(FromField, ToRecord.ToField)

Parameters

Record

Type: Record

The record from which to copy the filter.

FromField

Type: Field

The field from which the filter will be copied.

ToRecord.ToField

Type: Record.Field

The record and field to which you want to apply the copied filter.

Remarks

The FromField and ToField parameters must be of the same data type, but they do not have to belong to the same table.

Example

This example requires that you create a Record variable for the Customer table named Customer and an Integer variable named Count.

Copy Code
Customer.SETFILTER("No.", '<1000');
Customer.COPYFILTER("No.", Vendor."No.");
.
.
Count := Vendor.COUNT;

The filter set for Customer."No." is copied and applied to Vendor."No.". This affects the result of the COUNT Function (Record), which counts how many vendors have a number less than 1000.

See Also

Reference

COPYFILTERS Function (Record)
Record Data Type


COPYFILTERS Function (Record)

Copies all the filters set by the SETFILTER Function (Record) or the SETRANGE Function (Record) from one record to another.

Record.COPYFILTERS(FromRecord)

Parameters

Record

Type: Record

The record to which you want to copy filters.

FromRecord

Type: Record

The record from which you want to copy filters.

Remarks

This function is used to apply the filters defined for one record to another record. The filters are used as a basis for counting, searching, calculating, or a similar operation.

Example

This example requires that you create the following variables.

Variable name | DataType | Subtype
Customer1 | Record | Customer
Customer2 | Record | Customer
Count | Integer | Not applicable
Copy Code
// Set filters on fields in a Customer record
Customer1.SETFILTER("No.", '<1000');
Customer1.SETRANGE("Credit Limit (LCY)", 10000, 20000);
Customer1.MARKEDONLY(TRUE);
// Apply filters to another record
Customer2.COPYFILTERS(Customer1);
Count := Customer2.COUNT;

The filters defined for Customer1 are copied and applied to Customer2. This affects the result returned by the COUNT Function (Record).

See Also

Reference

COPYFILTER Function (Record)
Record Data Type


COPYLINKS Function (Record)

Copies all the links from a specified record.

DestRecord.COPYLINKS(FromRecord)

Parameters

DestRecord

Type: Record

Specifies the record you want to copy the links to.

FromRecord

Type: Record or RecordRef

Specifies the record from which you want to copy links.

Remarks

Use this function to copy all the links from a specified record and paste the links to the current record.

The link can be a link to a website, a file stored on the local or on a remote computer, or a link to a page.

Example

The following example copies all the links from a record named SourceRecord to the record named DestRecord. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Subtype
SourceRecord | Record | Customer
DestRecord | Record | Customer
Copy Code
DestRecord.COPYLINKS(SourceRecord);

See Also

Reference

Record Data Type


COUNT Function (Record)

Counts the number of records in a table.

Number := Record.COUNT

Parameters

Record

Type: Record

Refers to the table to be counted.

Property Value/Return Value

Type: Integer

The number of records in the table.

Remarks

This function returns the number of records that meet the conditions of any filters associated with the records. If no filters are set, then the function shows the total number of records in the table.

Note
The COUNT function does not lock the table before retrieving the number of records in the table. This means that the function reads both uncommitted and committed data, which could cause the number of records that are returned to be inaccurate. To ensure that the count is accurate, use the LOCKTABLE Function (Record) before you use the COUNT function.

In previous versions of Microsoft Dynamics NAV, the COUNT function ignored security filters and always returned the total number of records unless you called the SETPERMISSIONFILTER function to get a filtered count. In Microsoft Dynamics NAV 2016, the COUNT function adheres to the SecurityFiltering Property. For more information, see Security Filter Modes.

Example

This example requires that you create the following variables.

Variable name | DataType | Subtype
CustomerCount | Integer | Not applicable
CustomerRec | Record | Customer
Copy Code
CustomerCount := CustomerRec.COUNT;
// This statement assigns the number of records in the Customer table
// to the CustomerCount variable. This statement is the same as:
CustomerCount := 0;
IF CustomerRec.FIND('-') THEN
  REPEAT
    CustomerCount := CustomerCount + 1;
  UNTIL CustomerRec.NEXT = 0;

Retrieving the count by using the first statement in the example is much faster because only one command to the Database Management System (DBMS) is needed.

See Also

Reference

Record Data Type


CURRENTCOMPANY Function (Record)

Gets the current company of a database table record.

CurrentCompany := Record.CURRENTCOMPANY

Parameters

Record

Type: Record

A record that refers to the table for which you want to find the company that is currently in use.

Property Value/Return Value

Type: Text or code

The name of the current company of Record.

Example

The following example returns the current company that is used in the Customer table and displays it in a message box. The MyRecord record is from the Customer table. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType | Subtype
MyRecord | Record | Customer
CurrentCompany | Text |

Text constant name | ConstValue
Text000 | The current company is: %1
Copy Code
CurrentCompany := MyRecord.CURRENTCOMPANY;
MESSAGE(Text000, CurrentCompany);

See Also

Reference

CHANGECOMPANY Function (Record)
Record Data Type


CURRENTKEY Function (Record)

Gets the current key of a database table.

CurrentKey := Record.CURRENTKEY

Parameters

Record

Type: Record

A record that refers to the table for which you want to find the key that is currently in use.

Property Value/Return Value

Type: Text or code

The name of the current key of Record.

Example

The following example returns the current key that is used in the Customer table and displays it in a message box. The MyRecord record is from the Customer table. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType | Subtype
MyRecord | Record | Customer
CurrentKey | Text | Not applicable

Text constant name | ConstValue
Text000 | The current key is: %1
Copy Code
CurrentKey := MyRecord.CURRENTKEY;
MESSAGE(Text000, CurrentKey);

See Also

Reference

Record Data Type


DELETE Function (Record)

Deletes a record in a Microsoft Dynamics NAV table.

[Ok :=] Record.DELETE([RunTrigger])

Parameters

Record

Type: Record

The record to be deleted. The record itself does not change.

Note
The record cannot be from table 2000000001, the Object table or table 2000000006, the Company table.

RunTrigger

Type: Boolean

Specifies whether to run the C/AL code in the OnDelete Trigger.

If this parameter is true, then the code in the OnDelete trigger is executed. If this parameter is false, then the code in the OnDelete trigger is not executed.

The default value is false.

This parameter is optional.

Property Value/Return Value

Type: Boolean

true if the record was deleted; otherwise false. If the C/AL code terminates, then false is returned.

If you omit this optional return value and if the record is not deleted, then a run-time error occurs. If you include the return value, then you must handle any errors.

Remarks

The current key and any filters on the record do not affect this operation. The record to delete is identified by the values in its primary key.

If an end-user modifies a record between the time that another end-user or another process reads the record and modifies it, then the second user must refresh the value of the record variable before editing the record. Otherwise, the end-user receives the following run-time error:

Another user has modified the record for this <Table Name> after you retrieved it from the database.

Enter your changes again in the updated window, or start the interrupted activity again.

In earlier versions of Microsoft Dynamics NAV, certain situations allowed code that an end-user runs to modify a record after a newer version of the record was written and committed to the database. This would overwrite the newer changes. However, in Microsoft Dynamics NAV 2016, we have restricted the MODIFY Function (Record), RENAME Function (Record), and DELETE Function (Record) so that the end-user receives the following run-time error in these certain situations:

Unable to change an earlier version of the <Table Name> record. The record should be read from the database again. This is a programming error.

You must design your application so that you use the most up-to-date version of the record for modifications to the database. You use the GET Function (Record) to refresh the record with the latest version. The second example illustrates this situation.

Example

The first two lines of code in this example do not use the return value from the DELETE function. This means that a run-time error occurs if the record to be deleted cannot be found.

The next lines of code show how you can handle errors using the return value.

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec | Record | Customer

Text constant name | ConstValue
Text000 | The customer has been deleted.
Text001 | The customer could not be found.
Copy Code
// Without using the return value:
CustomerRec."No." := '100';
CustomerRec.DELETE;
// Using the return value:
CustomerRec."No." := '100';
IF CustomerRec.DELETE THEN
  MESSAGE(Text000)
ELSE
  ERROR(Text001);

Example

This example shows that you get an error if you attempt to delete a record after a newer version of the record has been written and committed to the database. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec1 | Record | Customer
CustomerRec2 | Record | Customer

In this example, you get a copy of a record from the Customer table and put it into the CustomerRec1 variable, then you modify the record. Next, you get a copy of the same record from the Customer table and put it into the CustomerRec2 variable. You modify the record and commit the changes to the database. Now the CustomerRec1 variable is out-of-date with the value in the database. If you were allowed to modify the database using the CustomerRec1 record, then the changes that you made with CustomerRec2 would be overwritten by the values in the CustomerRec1 variable. Microsoft Dynamics NAV 2016 does not allow you to delete a record using an old version of the record.

Note
If you do not call the COMMIT function in this example, then you do not receive an error.

Copy Code
CustomerRec1.LOCKTABLE;
CustomerRec1.GET('10000');
CustomerRec1."Address 2" := 'Suite 101';
CustomerRec1.MODIFY;
CustomerRec2.GET('10000');
CustomerRec2."Phone No.":= '206-555-0109';
CustomerRec2.MODIFY;
COMMIT;
CustomerRec1.DELETE;

If you run this code example, then you get the following error:

Unable to change an earlier version of the Customer record. The record should be read from the database again. This is a programming error.

Identification fields and values:

No.='10000'

See Also

Reference

Record Data Type
DELETEALL Function (Record)
DELETE Function (RecordRef)
COMMIT Function (Database)
LOCKTABLE Function (Record)


DELETEALL Function (Record)

Deletes all records in a table that fall within a specified range.

Record.DELETEALL([RunTrigger])

Parameters

Record

Type: Record

Identifies the table in which the deletion will occur. Only those records selected by the filters set for Record are deleted.

RunTrigger

Type: Boolean

Specifies whether to run the C/AL code in the OnDelete Trigger.

If this parameter is true, then the code in the OnDelete trigger will be executed. If this parameter is false, then the code in the OnDelete trigger will not be executed.

The default value is false.

Example

This example requires that you create a Record variable for the Customer table named CustomerRec.

Copy Code
// This C/AL code:
WHILE CustomerRec.FIND('-') DO
  CustomerRec.DELETE;
// Performs the same operation as:
CustomerRec.DELETEALL;

When RunTrigger is false (the default), the DELETEALL function in this example is much faster than the DELETE function because it requires only one call to the server, while the first method requires multiple calls. If RunTrigger is true, then there will not be any gain in performance because each record needs to be loaded to the client anyway in order to execute the OnDelete trigger.

See Also

Reference

DELETE Function (Record)
Record Data Type


DELETELINK Function (Record)

Deletes a specified link from a record in a table.

Record.DELETELINK(ID)

Parameters

Record

Type: Record

The record that contains the link to delete.

ID

Type: Integer

The ID of the link to delete.

Remarks

When you add a link to a page or a table, an entry is created in the Record Link system table. Each entry is given an ID.

Example

The following example removes the link that has link ID 20 from the MyRecord record (record number 30000) in the Vendor table. This example requires that you create the following variable in the C/AL Globals window.

Variable name | DataType | Subtype
MyRecord | Record | Vendor
Copy Code
MyRecord.GET('30000')
MyRecord.DELETELINK(20)

See Also

Reference

Record Data Type


DELETELINKS Function (Record)

Deletes all of the links that have been added to a record.

Record.DELETELINKS

Parameters

Record

Type: Record

The record that contains the links to delete.

Example

The following example removes all the links from the specified record (number 30000) in the Vendor table. This example requires that you create the following variable in the C/AL Globals window.

Variable name | DataType | Subtype
MyRecord | Record | Vendor
Copy Code
MyRecord.GET('30000');
MyRecord.DELETELINKS;

See Also

Reference

DELETELINKS Function (RecordRef)
Record Data Type


FIELDACTIVE Function (Record)

Checks whether a field is enabled.

Ok := Record.FIELDACTIVE(Field)

Parameters

Record

Type: Record

The record that contains the field to check.

Field

Type: Field

The field that you want to check.

Property Value/Return Value

Type: Boolean

true if the field is enabled; otherwise, false.

Remarks

Each field in a record can be set as enabled or disabled in the table description. You cannot use a disabled field because disabled fields cannot contain data.

Example

This example requires that you create the following variable and text constants in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec | Record | Customer

Text constant name | ENU value
Text000 | Atlanta
Text001 | The field is not marked as enabled.
Copy Code
CustomerRec."Address 2" := Text000;
// If the Address 2 field has not been marked as enabled, then this
// statement causes a run-time error.
// You can avoid this error by performing the following test.
IF CustomerRec.FIELDACTIVE("Address 2") THEN
  CustomerRec."Address 2" := Text000
ELSE
  MESSAGE(Text001);

See Also

Reference

Record Data Type


FIELDCAPTION Function (Record)

Gets the current caption of the specified field as a string.

Caption := Record.FIELDCAPTION(Field)

Parameters

Record

Type: Record

The record that holds the field for which you want to retrieve the caption.

Field

Type: Field

The field for which you want to retrieve the caption.

Property Value/Return Value

Type: Text or code

The caption is a string.

Remarks

The FIELDCAPTION function returns the caption of a specified field. FIELDCAPTION searches for a CaptionML Property. If none is found, the Name Property is used. This means that FIELDCAPTION has multilanguage functionality.

Example

The following example uses the FIELDCAPTION function to retrieve the caption of the Address 2 field in the Customer table. The function stores the retrieved caption in the varFieldCaption variable and displays it in a message box. In this Customer table, the field name is the same as the caption so the value Address 2 is displayed for the caption. If you change the caption for Address 2 in the Address 2 property window, then the new caption will be displayed. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Subtype
MyRecord | Record | Customer
varFieldCaption | Text | Not applicable
Copy Code
varFieldCaption := MyRecord.FIELDCAPTION("Address 2");
MESSAGE(varFieldCaption);

See Also

Reference

TABLECAPTION Function (Record)
Record Data Type

Concepts

Multilanguage Development


FIELDERROR Function (Record)

Stops the execution of the code causing a run-time error, and creates an error message for a field.

Record.FIELDERROR(Field, [Text])

Parameters

Record

Type: Record

The record that contains the field.

Field

Type: Field

The field for which you want to create an error message.

Text

Type: Text or code

Use this optional parameter to include the text of the error message. If you do not use this parameter, then default text is used as shown in the following examples. You can use backslashes (\) to break lines.

Remarks

Like a run-time error, this function causes the system to automatically abort any transaction.

Programming Guidelines

We recommend the following guidelines for error messages:

  • Describe what is wrong and how to solve the problem.

  • Write a short descriptive message. Do not use more words than necessary.

  • Note that a period is automatically inserted at the end of a FIELDERROR.

  • Use a text constant for the Text parameter.

For more information, see Progress Windows, MESSAGE, ERROR, and CONFIRM Functions.

Example

In the first example, there is no Text parameter and the field does not have a value. This example requires that you create a Record variable for the Customer table named CustomerRec.

Copy Code
CustomerRec."No." := '';
CustomerRec.FIELDERROR("No.");

The following message is displayed:

You must specify No. in Customer No.=''.

In the next example, there is no Text parameter and the field has a value. This example requires that you create a Record variable for the Customer table named CustomerRec.

Copy Code
CustomerRec."No." := 'NEW 3500';
CustomerRec.FIELDERROR("No.");

The following message is displayed:

No. must not be NEW 3500 in Customer No.='NEW 3500'.

The third example uses a non-empty string as the Text parameter. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec | Record | Customer

Text constant name | ConstValue
Text001 | is not valid
Copy Code
CustomerRec."No." := 'NEW 3500';
CustomerRec.FIELDERROR("No.", Text001);

The following message is displayed:

No. is not valid in Customer No.='NEW 3500'.

See Also

Reference

Record Data Type


FIELDNAME Function (Record)

Gets the name of a field as a string.

Name := Record.FIELDNAME(Field)

Parameters

Record

Type: Record

The name of the record that contains the field.

Field

Type: Field

The name of the field in the record.

Property Value/Return Value

Type: Text constant or code

The name of the field specified.

Remarks

The FIELDCAPTION Function (Record) retrieves the Caption Property of a field. If you want to enable your application for multilanguage functionality now or in the future, you must use the FIELDCAPTION function instead of the FIELDNAME function.

Example

This example requires that you create the following variables.

Variable name | DataType | Subtype
NameOfField | Text | Not applicable
CustomerRec | Record | Customer
Copy Code
NameOfField := CustomerRec.FIELDNAME("No.");

The name of the field is stored in a string.

The advantage of using this statement instead of Name := 'No.'; is that using the FIELDNAME function dynamically adapts to any change to the field name made in the development system. The statement Name := 'No.'; performs a static assignment.

See Also

Reference

Record Data Type

Concepts

Multilanguage Development


FIELDNO Function (Record)

Gets the number assigned to a field in the table description.

Number := Record.FIELDNO(Field)

Parameters

Record

Type: Record

The name of the record that contains the field.

Field

Type: Field

The name of the field in the record.

Property Value/Return Value

Type: Integer

The number of the field specified.

Example

This example requires that you create the following variables.

Variable name | DataType | Subtype
Num | Integer | Not applicable
CustomerRec | Record | Customer
Copy Code
Num := CustomerRec.FIELDNO("No.");

This statement assigns the number of the No. field in the CustomerRec record to the number variable.

In this example, the FIELDNO function is used to determine which field that a variable, which contains a field number, points to in a record. This example requires that you create the following variables.

Variable name | DataType | Subtype
CurrentFieldNo | Integer | Not applicable
CustomerRec | Record | Customer
Copy Code
CASE CurrentFieldNo OF
  Customer.FIELDNO("No."):
    ...
  Customer.FIELDNO(Name):
    ...
  Customer.FIELDNO(Address):
    ...
  ELSE
    ...
END;

This construct allows you to take actions based on the field number contained in the CurrentFieldNo variable.

See Also

Reference

Record Data Type


FILTERGROUP Function (Record)

Gets or sets the filter group that is applied to a table.

[CurrGroup] := Record.FILTERGROUP([NewGroup])

Parameters

Record

Type: Record

The record from the table for which the filter group will be set or returned.

NewGroup

Type: Integer

The number of the filter group to set.

Property Value/Return Value

Type: Integer

The number of the current filter group.

Remarks

A filter group can contain a filter for a Record that has been set earlier with the SETFILTER Function (Record) or the SETRANGE Function (Record). The total filter applied is the combination of all the filters set in all the filtergroups.

When you select a filter group, subsequent filter settings by the SETFILTER Function (Record) or the SETRANGE Function (Record) apply to that group.

All groups are active at all times. The only way to disable a group is to remove the filters set in that group.

Filters in different groups are all effective simultaneously. For example, if in one group, a filter is set on customer numbers 1000 to 2000, while in another group, a filter is set on customer numbers 1800 to 3000, then only numbers in the range 1800 to 2000 are visible.

Microsoft Dynamics NAV uses the following filter groups internally.

Number Name Description

-1

Cross-column

Used to support the cross-column search.

0

Std

The default group where filters are placed when no other group has been selected explicitly. This group is used for filters that can be set from the filter dialogs by the end user.

1

Global

Used for filters that apply globally to the entire application.

2

Form

Used for the filtering actions that result from the following:

  • SETTABLEVIEW Function (Page, Report, XMLport)

  • SourceTableView Property

  • DataItemTableView Property.

3

Exec

Used for the filtering actions that result from the following:

  • SubPageView Property

  • RunPageView Property

4

Link

Used for the filtering actions that result from the following:

  • DataItemLink Property (Reports)

  • SubPageLink Property

5

Temp

Not currently used.

6

Security

Used for applying security filters for user permissions.

7

Factboxes

Used for clearing the state of factboxes.

A filter set in a group different from filter group 0 cannot be changed by a user that uses a filter dialog to set a filter. If, for example, a filter has been set on customer numbers 1000 to 2000 in group 4, then the user can set a filter that delimits this selection further, but cannot widen it to include customer numbers outside the range 1000 to 2000.

It is possible to use one of the internally used groups from C/AL. If you do this, you replace the filter that Microsoft Dynamics NAV assumes is in this group. If, for example, you use filter group 4 in a page, you will replace the filtering that is actually the result of applying the SubPageLink Property. This could seriously alter the way pages and subpages interact.

Using filter group 7 may cause factboxes to not work as intended.

To reset the filters in filter group 1, you add an empty filter to the group. To add an empty filter, to filter group 1, you must first set the filter group.

Copy Code
Rec.FILTERGROUP(1);

Then, for each field in the table that to which the Rec variable refers, set an empty filter.

Copy Code
Rec.SETFILTER(<field>,’’);

Example

The following example uses the SETFILTER Function (Record) to set a filter that selects records with No. field between 10000 and 20000. Then the FILTERGROUP function returns the number for the filter group. No filter group was selected explicitly so the filter is set in filter group 0. This value is stored in the varOrigGroup variable and displayed in a message box. Next, the FILTERGROUP function changes the filter group to 100. The new value is stored in the varCurrGroup variable and displayed in a message box.

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Subtype
MyRecord | Record | Customer
varOrigGroup | Integer | Not applicable
varCurrGroup | Integer | Not applicable

Text constant name | ConstValue
Text000 | The original filtergroup is: %1
Text001 | The current filtergroup is: %1
Copy Code
MyRecord.SETFILTER("No.", '10000..20000');
varOrigGroup := MyRecord.FILTERGROUP;
MESSAGE(Text000, varOrigGroup);
varCurrGroup := MyRecord.FILTERGROUP(1);
MESSAGE(Text001, varCurrGroup);

The following example finds all customers where the Customer Name or Contact Name contains the string John.

This example requires that you create the following variable in the C/AL Globals window.

Variable Name | Datatype
SearchString | Text
Copy Code
Customer.FILTERGROUP := -1;
SearchString := '@*John*';
Customer.SETFILTER(Customer.Name, SearchString);
Customer.SETFILTER(Customer.Contact, SearchString);

See Also

Reference

Record Data Type


FIND Function (Record)

Finds a record in a table that is based on the values stored in keys.

Ok := Record.FIND([Which])

Parameters

Record

Type: Record

On input, Record identifies the record that you want to find. On output, the following possibilities exist:

  • If the record was found, then the record is returned in the Record parameter and any FlowFields in the record are set to zero. You must update the FlowFields using the CALCFIELDS Function (Record).

  • If the record was not found and if you omitted the return value, a run-time error occurs.

Which

Type: Text or code

Specifies how to perform the search. The table is searched until either a record is found or there are no more records. Each character in this string can be present only one time. You can combine the '=', '<', and '>' characters. You can use the following characters:

  • = to search for a record that equals the key values (default)

  • > to search for a record that is larger than the key values

  • < to search for a record that is less than the key values

  • + to search for the last record in the table (+ can only be used alone)

  • - to search for the first record in the table (- can only be used alone)

If this parameter contains '=', '>' or '<', then you must assign value to all fields of the current and primary keys before you call FIND.

Property Value/Return Value

Type: Boolean

true if the record was found; otherwise, false.

If you omit this optional return value and if the record cannot be found, a run-time error occurs. If you include a return value, you must handle any errors.

Remarks

FIND retrieves the first record that meets the conditions set by Which and the filters associated with Record. The search path reflects the sort order defined by the current key. If the current key is not the primary key, several records might have the same values in current key fields. If this occurs, the sort order defined by the primary key as the search path is used.

Example

The following example shows how use the FIND function to find a record in a table. The code sets the number of the record to find to 1100, which is the primary key of the record to find. The FIND function uses the '=' parameter to find the record that has a primary value that equals the specified primary key. If the record is found, then the item number, description, and unit price of the item are displayed in a message box. Otherwise, a message that specifies that the item is not found is displayed. This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Subtype
ItemRec | Record | Item

Text constant | ENU value
Text000 | Item No. %1.\Description: %2. Price: $%3.
Text001 | The item was not found.
Copy Code
ItemRec."No." := '1100';
IF ItemRec.FIND('=') THEN
  MESSAGE(TEXT000,  ItemRec."No.", ItemRec.Description, ItemRec."Unit Price")
ELSE
  MESSAGE(TEXT001);

Example

The following example defines a record variable that is named ItemRec. The FIND function uses the ‘+’ parameter to find the last record in the table. If the record is found, then the item number, description, and unit price of the item are displayed in a message box. Otherwise, the message that specifies that the item was not found is displayed. This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Subtype
ItemRec | Record | Item

Text constant | ENU value
Text000 | Item No. %1.\Description: %2. Price: $%3.
Text001 | The item was not found.
Copy Code
IF ItemRec.FIND('+') THEN
  MESSAGE(Text000, ItemRec."No.", ItemRec.Description, ItemRec."Unit Price")
ELSE
  MESSAGE(Text001);

See Also

Reference

Record Data Type

Concepts

GET, FIND, and NEXT Functions


FINDFIRST Function (Record)

Finds the first record in a table based on the current key and filter.

[Ok :=] Record.FINDFIRST

Parameters

Record

Type: Record

If the record is found, then it is returned in this parameter and any FlowFields in the record are set to zero. You must update the FlowFields by using the CALCFIELDS Function (Record).

If the record is not found and if you omit the return value, then a run-time error occurs.

Property Value/Return Value

Type: Boolean

true if the record was found; otherwise, false.

If you omit this optional return value and the record is not found, then a run-time error occurs. If you include a return value, then you must handle any errors.

Remarks

This function should be used instead of FIND('-') when you only need the first record.

You should only use this function when you explicitly want to find the first record in a table or set. Do not use this function in combination with REPEAT.. UNTIL.

Example

This example requires that you create the following variable.

Variable name | Datatype | Subtype
SalesSetupRec | Record | Sales & Receivables Setup

This example also assumes that you have a ConfigurePost function.

Copy Code
// Read the first record only.
IF SalesSetupRec.FINDFIRST THEN BEGIN
  ConfigurePost(SalesSetupRec);
END;

See Also

Reference

FIND Function (Record)
FINDLAST Function (Record)
FINDSET Function (Record)
Record Data Type


FINDLAST Function (Record)

Finds the last record in a table based on the current key and filter.

[Ok :=] Record.FINDLAST

Parameters

Record

Type: Record

If the record was found, it is returned in this parameter and any FlowFields in the record are set to zero. You must update the FlowFields by using the CALCFIELDS Function (Record).

If the record was not found and if you omitted the return value, a run-time error occurs.

Property Value/Return Value

Type: Boolean

true if the record was found; otherwise, false.

If you omit this optional return value and the record cannot be found, a run-time error occurs. If you include a return value, you must handle any errors.

Remarks

This function should be used instead of FIND('+') when you only need the last record.

You should only use this function when you explicitly want to find the last record in a table/set. Do not use this function in combination with REPEAT...UNTIL.

Example

This example requires that you create a Record variable named GLEntryRec for the G/L Entry table.

Copy Code
// Read the last record only.
IF GLEntryRec.FINDLAST THEN
  …

See Also

Reference

FIND Function (Record)
FINDFIRST Function (Record)
FINDSET Function (Record)
Record Data Type


FINDSET Function (Record)

Finds a set of records in a table based on the current key and filter.

[Ok :=] Record.FINDSET([ForUpdate][, UpdateKey])

Parameters

Record

Type: Record

If the record is found, then the record is returned in this parameter and any FlowFields in the record are set to zero. You must update the FlowFields by using the CALCFIELDS Function (Record).

ForUpdate

Type: Boolean

Set this parameter to true if you want to modify any records in the set; otherwise, set the parameter to false.

If you set this parameter to true, then the LOCKTABLE Function (Record) is immediately run on the table before the records are read.

If you set this parameter to false, then you can still modify the records in the set, but these updates will not be performed optimally.

The default value is false.

UpdateKey

Type: Boolean

Set this parameter to true if you want to modify any field value within the current key.

This parameter only applies if the ForUpdate parameter is true.

If you set this parameter to false, then you can still modify the records in the set, but these updates will not be performed optimally.

The default value is false.

Property Value/Return Value

Type: Boolean

true if the record set was found; otherwise, false.

If you omit this optional return value and if the record cannot be found, then a run-time error occurs. If you include a return value, then you must handle any errors.

Remarks

You should use this function only when you explicitly want to loop through a recordset. You should only use this function in combination with REPEAT.. UNTIL.

Example

This example shows how to use the FINDSET function to loop through a set without updating it. This example requires that have a CopyLine function and that you create the following variable.

Variable name | DataType | Subtype
SalesLine | Record | Sales Line
Copy Code
SalesLine.SETFILTER("Purch. Order Line No.",'<>0');
IF SalesLine.FINDSET THEN BEGIN
  REPEAT
    CopyLine(SalesLine);
  UNTIL SalesLine.NEXT = 0;
END;

Example

This example shows how to use the FINDSET function to loop through a set and update a field that is not within the current key. This example requires that you create the following variables.

Variable name | DataType | Subtype
SalesLine | Record | Sales Line
DocumentType | Option | Not applicable
DocumentNo | Code | Not applicable

This example assumes that you have assigned values to the DocumentType and DocumentNo variables and that you have a GetNewLocation function, which returns a value that is a Code data type.

Copy Code
SalesLine.SETRANGE("Document Type",DocumentType);
SalesLine.SETRANGE("Document No.",DocumentNo);
IF SalesLine.FINDSET(TRUE, FALSE) THEN BEGIN
  REPEAT
    SalesLine."Location Code" := GetNewLocation(SalesLine);
    SalesLine.MODIFY;
  UNTIL SalesLine.NEXT = 0;
END;

Example

This example shows how to use the FINDSET function to loop through a set and update a field that is within the current key. This example requires that you create the following variables.

Variable name | DataType | Subtype
SalesShptLine | Record | Sales Shipment Line
SalesShptLine2 | Record | Sales Shipment Line
SalesLine | Record | Sales Line
Copy Code
SalesShptLine.SETCURRENTKEY("Order No.","Order Line No.");
SalesShptLine.SETRANGE("Order No.",SalesLine."Document No.");
SalesShptLine.SETRANGE("Order Line No.",SalesLine."Line No.");
IF SalesShptLine.FINDSET(TRUE, TRUE) THEN BEGIN
  REPEAT
    SalesShptLine2 := SalesShptLine;
    SalesShptLine2."Order Line No." := SalesShptLine."Order Line No." + 10000;
    SalesShptLine2.MODIFY;
  UNTIL SalesShptLine.NEXT = 0;
END;

See Also

Reference

FIND Function (Record)
FINDFIRST Function (Record)
FINDLAST Function (Record)
Record Data Type


GET Function (Record)

Gets a record based on values stored in primary key fields.

[Ok :=] Record.GET([Value] ,...)

Parameters

Record

Type: Record

The record in the table.

Value,…

Type: any

Values in primary key fields. The data type of this parameter must match the data type of the corresponding primary key field. For example, if you enter an integer, the data type of the corresponding primary key field must also be an integer. The value 0 (zero) or an empty string is assigned to unspecified fields.

Property Value/Return Value

Type: Boolean

true if the record was found; otherwise, false.

If you omit this optional return value and if the record cannot be found, then a run-time error occurs. If you include the return value, then you must handle any errors.

Remarks

This function always uses the primary key for the table. It ignores any filters that are set, except security filters. Security filters are applied or ignored based on the Security Filter Mode. The current key and filters are not changed after you call this function. For more information, see Security Filter Modes.

This function ignores any call to the SETAUTOCALCFIELDS Function (Record). Therefore, a GET call on a record after a SETAUTOCALCFIELDS call does not automatically calculate FlowFields in the record.

Example

This example requires that you create the following variable and text constants in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec | Record | Customer

Text constant | ConstValue
Text000 | The record was found.
Text001 | The record could not be found.
Copy Code
CustomerRec.GET('1120');
// This statement causes a run-time error if customer 1120 cannot be
// found. To avoid this, use the following construct:
IF CustomerRec.GET('1120') THEN
  MESSAGE(Text000)
ELSE
  MESSAGE(Text001);

See Also

Reference

Record Data Type
FILTERGROUP Function (Record)

Concepts

GET, FIND, and NEXT Functions


GETASCENDING Function (Record)

Gets the sort order for the records returned. You can use GETASCENDING to identify the sort order of the specified field because fields can be sorted in ascending or descending order.

For example, you can read data from an ODATA web service where the data is sorted in ascending order on the Name field but in descending order on the City field.

OK:= Record.GETASCENDING(Field)

Parameters

Record

Type: Record

The record in the table to search.

Field

Type: Field

The field that you want to get the sort order for.

Return Value

Type: Boolean

true, if the specified filed is sorted in ascending order; otherwise false.

See Also

Reference

SETASCENDING Function (Record)

Concepts

OData Web Services


GETFILTER Function (Record)

Gets a list of the filters within the current filter group that are applied to a field.

String := Record.GETFILTER(Field)

Parameters

Record

Type: Record

The input record.

Field

Type: Field

The input field.

Property Value/Return Value

Type: Text constant or code

This string contains a list of the filters applied to the field in the record.

Example

This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | Data type | Subtype
String | Text | Not applicable
CustomerEntry | Record | Cust. Ledger Entry

Text constant | ConstValue
Text000 | The filter is:\%1
Copy Code
// Write the following code in the OnRun trigger.
CustomerEntry.SETRANGE(Amount, -100, 100);
String := CustomerEntry.GETFILTER(Amount);
MESSAGE(Text000, String);

The following message is displayed:

The filter is:

-100..100

Example

This example requires that you create the following variable in the C/AL Globals window.

Variable name | DataType | Subtype
Item | Record | Item
Copy Code
Item.FILTERGROUP(2); // Filter group 2 is applied.
Item.SETFILTER("No.", '1000..1450'); // A filter is set in filter group 2.
MESSAGE('Filtergroup 2 filters, No. field: ' + Item.GETFILTER("No."));
// GETFILTERS prints the filter that is set in filter group 2
Item.FILTERGROUP(0); // Change the current filter group.
// Now filter group 0 is applied.
MESSAGE('Filtergroup 0 filter, No. field: ' + Item.GETFILTER("No."));
// GETFILTERS returns an empty string because there is no filter set
// in the current filter group (0).
Item.SETFILTER("No.", '70000..79999'); // Set another filter, now in filter group 0.
MESSAGE('Now Filtergroup 0 filters, No. field: ' + Item.GETFILTER("No."));
// GETFILTERS prints the new filter set in the filter group 0.

The message windows display the following:

Filtergroup 2 filters, No. field: 1000..1450

Filtergroup 0 filters, No. field:

Now Filtergroup 0 filters, No. field: 70000..79999

See Also

Reference

GETFILTERS Function (Record)
SETFILTER Function (Record)
SETRANGE Function (Record)
FILTERGROUP Function (Record)
Record Data Type


GETFILTERS Function (Record)

Gets a string that contains a list of the filters within the current filter group for all fields in a record. In addition, this function also returns the state of the MARKEDONLY Function (Record).

String := Record.GETFILTERS

Parameters

Record

Type: Record

The record from which you want a list of filters.

Property Value/Return Value

Type: Text or code

This string contains a list of the filters for all fields in Record.

Example

This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType | Subtype
Str | Text | Not applicable
CustLedgerEntry | Record | Cust. Ledger Entry

Text constant | ENU value
Text000 | The filters are:\
Copy Code
CustLedgerEntry.SETRANGE(Amount, -100, 100);
CustLedgerEntry.SETRANGE("Posting Date", 010108D, 123108D);
Str := CustLedgerEntry.GETFILTERS;
MESSAGE(Text000 + '%1', Str);

On a computer with the regional format set to English (United States), the message window displays the following:

The filters are:

Posting Date: 01/01/08..12/31/08, Amount: -100..100

Example

This example requires that you create the following variable in the C/AL Globals window.

Variable name | DataType | Subtype
Item | Record | Item
Copy Code
Item.FILTERGROUP(2); // Filter group 2 is applied.
Item.SETFILTER("No.", '1000..1450'); // A filter is set in filter group 2.
MESSAGE('Filtergroup 2 filters: ' + Item.GETFILTERS);
// GETFILTERS prints the filter that is set in filter group 2
Item.FILTERGROUP(0); // Change the current filter group.
// Now filter group 0 is applied.
MESSAGE('Filtergroup 0 filter: ' + Item.GETFILTERS);
// GETFILTERS returns an empty string because there is no filter set
// in the current filter group (0).
Item.SETFILTER("No.", '70000..79999'); // Set another filter, now in filter group 0.
MESSAGE('Now Filtergroup 0 filters: ' + Item.GETFILTERS);
// GETFILTERS prints the new filter set in the filter group 0.

The message windows display the following:

Filtergroup 2 filters: No.: 1000..1450

Filtergroup 0 filters:

Now Filtergroup 0 filters: No.: 70000..79999

See Also

Reference

GETFILTER Function (Record)
SETFILTER Function (Record)
SETRANGE Function (Record)
FILTERGROUP Function (Record)
Record Data Type


GETPOSITION Function (Record)

Gets a string that contains the primary key of the current record.

String := Record.GETPOSITION([UseNames])

Parameters

Record

Type: Record

The record that contains the primary key.

UseNames

Type: Boolean

Property Value/Return Value

Type: Text or code

The primary key of the current record. The string has the same format as the SourceTable Property on a page.

Remarks

The UseNames parameter is optional. If it is set to true (default value) or if it is empty, then the returned string contains references to field names in the table with which the record is associated. If the parameter is set to false, then field numbers are used instead.

Example

The following example uses the GETPOSITION function to retrieve the primary key of the current record (MyRecord) from the Customer table. The primary key is stored in the varPrimaryKey variable and displayed in a message box. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Subtype
MyRecord | Record | Customer
varPrimaryKey | Text | Not applicable
Copy Code
varPrimaryKey := MyRecord.GETPOSITION(TRUE);
MESSAGE(varPrimaryKey);

See Also

Reference

Record Data Type


GETRANGEMAX Function (Record)

Gets the maximum value in a range for a field.

Value := Record.GETRANGEMAX(Field)

Parameters

Record

Type: Record

The record that contains the field.

Field

Type: Field

The field for which you want to find the maximum value. The current filter on Field must be a single range filter; otherwise, a run-time error occurs.

Property Value/Return Value

Type: Depends on Field

Contains the maximum value of the range set for Field. The type of the return value must match the type of Field.

Example

In this example, you have a filter that defines a single range.

This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType | Subtype | Length
CustomerRec | Record | Customer | Not applicable
Val | Code | Not applicable | 10

Text constant | ENU value
Text000 | The maximum value is: %1.
Copy Code
CustomerRec.SETFILTER("No.",'100..200');
Val := CustomerRec.GETRANGEMAX("No.");
MESSAGE(Text000, Val);

The following message is displayed:

The maximum value is: 200.

In this example, you have a filter that is a single value.

This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType | Subtype | Length
CustomerRec | Record | Customer | Not applicable
Val | Code | Not applicable | 10

Text constant | ENU value
Text000 | The maximum value is: %1.
Copy Code
CustomerRec.SETFILTER("No.",'100');
Val := CustomerRec.GETRANGEMAX("No.");
MESSAGE(Text000, Val);

The following message is displayed:

The maximum value is: 100.

In this example, you have a filter that is not a single range.

This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType | Subtype | Length
CustomerRec | Record | Customer | Not applicable
Val | Code | Not applicable | 10

Text constant | ENU value
Text000 | The maximum value is: %1.
Copy Code
CustomerRec.SETFILTER("No.",'200|300');
Val := CustomerRec.GETRANGEMAX("No.");
MESSAGE(Text000, Val);

This example causes a run-time error to occur.

See Also

Reference

GETRANGEMIN Function (Record)
Record Data Type


GETRANGEMIN Function (Record)

Gets the minimum value in a range for a field.

Value := Record.GETRANGEMIN(Field)

Parameters

Record

Type: Record

The record that contains the field.

Field

Type: Field

The field for which you want to find the minimum value. The current filter on Field must be a single range filter; otherwise, a run-time error occurs.

Property Value/Return Value

Type: Depends on Field

Contains the minimum value of the range set for Field. The type of the return value must match the type of Field.

Example

In this example, you have a filter that defines a single range.

This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType | Subtype | Length
CustomerRec | Record | Customer | Not applicable
Val | Code | Not applicable | 10

Text constant | ENU value
Text000 | The minimum value is: %1.
Copy Code
CustomerRec.SETFILTER("No.",'100..200');
Val := CustomerRec.GETRANGEMIN("No.");
MESSAGE(Text000, Val);

The following message is displayed:

The minimum value is: 100.

In this example, you have a filter that is a single value.

This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType | Subtype | Length
CustomerRec | Record | Customer | Not applicable
Val | Code | Not applicable | 10

Text constant | ENU value
Text000 | The minimum value is: %1.
Copy Code
CustomerRec.SETFILTER("No.",'100');
Val := CustomerRec.GETRANGEMIN("No.");
MESSAGE(Text000, Val);

The following message is displayed:

The minimum value is: 100.

In this example, you have a filter which is not a single range.

This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType | Subtype | Length
CustomerRec | Record | Customer | Not applicable
Val | Code | Not applicable | 10

Text constant | ENU value
Text000 | The minimum value is: %1.
Copy Code
CustomerRec.SETFILTER("No.",'200|300');
Val := CustomerRec.GETRANGEMIN("No.");
MESSAGE(Text000, Val);

This example causes a run-time error to occur.

See Also

Reference

GETRANGEMAX Function (Record)
Record Data Type


GETVIEW Function (Record)

Gets a string that describes the current sort order, key, and filters on a table.

String := Record.GETVIEW([UseNames])

Parameters

Record

Type: Record

Specifies a record in the table for which you want to get the key and filters.

UseNames

Type: Boolean

Indicates whether a field caption or field number should be returned.

This parameter is optional. If this parameter is true (default value) or if it is empty, then the returned string contains references to field captions in the table with which the record is associated. If this parameter is false, then the returned string contains references to field numbers.

Property Value/Return Value

Type: Text or code

The current sort order, key, and filters on a table. The string format is the same as the SourceTableView Property on pages.

Remarks

If the SETVIEW Function (Record) has been executed, then the function will return the value that is set by SETVIEW.

Example

The following example uses the GETVIEW function to retrieve the key, the current sort order, and the filters that are set on the CustomerRec record in the Customer table. The function starts by returning the current key on which the Customer table is sorted. No., which is the field caption, is returned because the UseNames parameter is omitted. The key is stored in the ViewString variable and displayed in a message box. The sort key is then changed to the Name field and a filter that selects records with No. field values between 10000 and 20000 is set by using the SETVIEW Function (Record). The function returns the keys, sort order, and filter again. The return value is stored in the ViewString variable and displayed in a message box. The values that are displayed are Name, Addrees, and City, for the WHERE No.= FILTER(10000…20000) filter. Finally, the function displays the field numbers instead of the captions because UserName is set to false. The sort order that is displayed is Field2, Field5 and Field7 instead of the field names. The filter is also displayed. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec | Record | Customer
ViewString | Text | Not applicable
Copy Code
ViewString := CustomerRec.GETVIEW;
MESSAGE('The string:%1', ViewString);
CustomerRec.SETVIEW('SORTING(Name) ORDER(Ascending) WHERE(No.=CONST(10000..20000))');
ViewString := CustomerRec.GETVIEW;
MESSAGE('The string:%1', ViewString);
ViewString := CustomerRec.GETVIEW(FALSE);
MESSAGE('The string:%1', ViewString);

See Also

Reference

Record Data Type


HASFILTER Function (Record)

Determines whether a filter is attached to a record within the current filter group.

Ok := Record.HASFILTER

Parameters

Record

Type: Record

The record within the current filter group to check for a filter.

Property Value/Return Value

Type: Boolean

true if there is a filter; otherwise, false.

Example

The following example uses the HASFILTER function to determine whether the Customer table that contains the MyRecord record has a filter. The function returns No because the MyRecord record has no filters. The return value is displayed in a message box. The SETFILTER Function (Record) is then used to set a filter for the table. This time, the return value is Yes because the table now has a filter. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Subtype
MyRecord | Record | Customer
HasFilter | Boolean | Not applicable
Copy Code
HasFilter := MyRecord.HASFILTER;
MESSAGE('Does this record have a filter? %1', HasFilter);
MyRecord.SETFILTER("No.", '100..200');
HasFilter := MyRecord.HASFILTER;
MESSAGE('Does this record have a filter? %1', HasFilter);

See Also

Reference

Record Data Type


HASLINKS Function (Record)

Determines whether a record contains any links.

Ok := Record.HASLINKS

Parameters

Record

Type: Record

The record in the table for which you want to find the link.

Property Value/Return Value

Type: Boolean

true if the record contains at least one link; otherwise, false.

Remarks

The link can be a link to a web site, a file stored on the local or on a remote computer, or a link to a Microsoft Dynamics NAV page.

Example

The following code example retrieves record number 10000 from the Vendor table and stores it in the MyRecord variable. The HASLINKS function determines whether the record contains one or more links. Record number 10000 contains one link so the varHasLink variable displays Yes. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Subtype
MyRecord | Record | Vendor
varHasLinks | Boolean | Not applicable
Copy Code
MyRecord.GET('10000');
varHasLinks := MyRecord.HASLINKS;
MESSAGE('Does this record have one or more links: %1', varHasLinks);

See Also

Reference

Record Data Type


INIT Function (Record)

Initializes a record in a table.

Record.INIT

Parameters

Record

Type: Record

The record that you want to initialize.

Remarks

This function assigns default values to each field in the record. The values that are assigned in the record correspond to those defined when the table was created. If no value was assigned when the table was created, the values are assigned based on the data type, as shown in the following table.

Data type | Default value
BigInteger | 0
BigText | <Empty>
BLOB | <Empty>
Boolean | No
Code | '' (empty string)
Date | 0d (Undefined date)
DateFormula | '' (empty string)
DateTime | 0DT (Undefined datetime)
Decimal | 0.0
Duration | 0
GUID | 00000000-0000-0000-0000-000000000000
Integer | 0
Option | 0
RecordID | <Empty>
TableFilter | <Empty>
Text | '' (empty string)
Time | 0T (Undefined time)

Primary key and timestamp fields are not initialized.

After the function executes, you can change the values in any of the fields before you call the INSERT Function (Record) to enter the record in the table. Be sure that the fields that make up the primary key contain values that make the total primary key unique. If the primary key is not unique (such as the record already exists), then the record is rejected.

Example

In this example, assume that the primary key includes the "No." field. This example requires that you create a Record variable named CustomerRec for the Customer table.

Copy Code
// Scenario 1
CustomerRec.INIT;
CustomerRec."No." := '1120';
CustomerRec.INSERT;
// Scenario 2
CustomerRec."No." := '1120';
CustomerRec.INIT;
CustomerRec.INSERT;

Since INIT does not initialize the primary key fields, the order of the statements in this example is not important. Scenario 1 causes the same result as scenario 2.

See Also

Reference

Record Data Type


INSERT Function (Record)

Inserts a record into a table.

[Ok :=] Record.INSERT([RunTrigger])

Parameters

Record

Type: Record

The record that you want to insert.

Warning
The record cannot be from table 2000000001, the Object table or table 2000000006, the Company table.

RunTrigger

Type: Boolean

If this parameter is true, the code in the OnInsert Trigger is executed. If this parameter is false, the code in the OnInsert trigger is not executed. The default value is false.

Property Value/Return Value

Type: Boolean

true if the record was inserted; otherwise, false.

If you omit this optional return value and if the record cannot be inserted, then a run-time error occurs. If you include the return value, then you must handle any errors.

Remarks

Records are uniquely identified by the values in primary key fields. The Database Management System (DBMS) checks the primary key for the table before it inserts a new record.

If the table contains an auto-increment field, the auto-increment feature is used if the record contains a zero value in that field. The auto-increment feature enters the new value into the field as part of the insert.

If the auto-increment field contains a non-zero value, that value is inserted into the table and the auto-increment feature is not used. If the value in the auto-increment field is greater than the last auto-increment value in the table, then the next auto-increment value that is entered into the table will be greater than the value in the field that you just inserted. If the value in the auto-increment field already occurs in the table, then a run-time error occurs.

Example

This example shows how to use the INSERT function without a return value.

Copy Code
Customer.INIT
Customer."No." := '1120';
Customer.INSERT;

If customer 1120 already exists, then a run-time error occurs.

This example requires that you create the following variable and text constants in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec | Record | Customer

Text constant name | ConstValue
Text000 | Customer no: %1 inserted.
Text001 | Customer no: %1 already exists.
Copy Code
CustomerRec.INIT
CustomerRec."No." := '1120';
If CustomerRec.INSERT THEN
  MESSAGE(Text000, CustomerRec."No.")
ELSE
  MESSAGE(Text001, CustomerRec."No.");

No run-time error occurs if customer 1120 already exists.

See Also

Reference

Record Data Type


ISEMPTY Function (Record)

Determines whether a table or a filtered set of records is empty.

Empty := Record.ISEMPTY

Parameters

Record

Type: Record

The filtered set of records that you want to check.

Property Value/Return Value

Type: Boolean

Remarks

true if the record or table is empty; otherwise, false. If you have applied filters, the function determines whether the filtered set of records is empty. The number of filters that you have applied to the records affects the speed of the ISEMPTY function. The fewer the number of filters, the faster the operation is performed.

When you are using SQL Server, this function is faster than using the COUNT Function (Record) and then testing the result for zero.

Example

The following code example uses a record from the Customer table to determine whether the table has any records. The ISEMPTY function uses the CustomerRec variable to determine whether the Customer table is empty, stores the return value in the varIsEmpty variable, and displays the value in a message box. The value of the varIsEmpty variable is No because the Customer table has records (that is, not empty). The function then uses the PrinterSelec variable, which is a record from the Printer Selection table to check whether the Printer Selection table has any records and stores the return value in the varIsEmpty variable. The value of Yes is displayed in the message box because the Printer Selection table has no records (that is, empty). This example requires that you create the following variables in the C/AL Globals window.

Variable name | Data Type | Subtype
CustomerRec | Record | Customer
PrinterSelec | Record | Printer Selection
varIsEmpty | Boolean | Not applicable
Copy Code
varIsEmpty := CustomerRec.ISEMPTY;
MESSAGE('Is the Customer table empty?: %1', varIsEmpty);
varIsEmpty := PrinterSelec.ISEMPTY;
MESSAGE('Is the Printer Selection table empty?: %1', varIsEmpty);

See Also

Reference

Record Data Type


ISTEMPORARY Function (Record)

Determines whether a record refers to a temporary table.

Temp := Record.ISTEMPORARY

Parameters

Record

Type: Record

A record that refers to a table.

Property Value/Return Value

Type: Boolean

true if the record refers to a temporary table; otherwise, false.

See Also

Reference

Record Data Type
ISTEMPORARY Function (RecordRef)


LOCKTABLE Function (Record)

Locks a table to protect it from write transactions that conflict with each other.

Record.LOCKTABLE

Parameters

Record

Type: Record

The record that refers to the table that you want to lock.

Remarks

Because all write operations automatically lock the table that is being used, LOCKTABLE appears unnecessary. However, you could have a transaction in which an application wants to inspect data and then only possibly change it. You require a guarantee that the data being changed has not been modified by other applications since the read operation. The solution is to explicitly lock the table before the read operation. This guarantees that no other application makes changes between the read operation and the possible write operation.

Example

This example uses pseudo-language to show the scope of write locks. Both an explicit lock and an automatic lock are illustrated.

The first line (1) explicitly locks table A. If this explicit lock was not set on table A, the Database Management System (DBMS) would automatically lock this table when a record was inserted (3). Table B is not locked explicitly, but is locked automatically by the DBMS when a record is inserted (4). Both locks are active until the system exits the C/AL code module (5).

Copy Code
BeginWriteTransaction
TableA.LockTable // (1)
FindRec(TableA, ...) // (2)
.
.
InsertRec(TableA,...) // (3)
.
InsertRec(TableB) // (4)
.
.
EndWriteTransaction // (5)

If a data update depends on a prior read operation and there is a long time between the read operation and the write operation, then you may not want to lock the table as you usually would during a transaction. This enables you to avoid preventing other users from updating the table until your transaction is committed.

See Also

Reference

Record Data Type


MARK Function (Record)

Marks a record. You can also use this function to determine whether a record is marked.

[IsMarked :=] Record.MARK([SetMarked])

Parameters

Record

Type: Record

The input record.

SetMarked

Type: Boolean

If this parameter is true, the function will mark the record. (Previously marked records remain marked.)

If this parameter is false, the function will remove any mark.

Property Value/Return Value

Type: Boolean

true if the record is marked; otherwise, false.

The mark is effective until the application stops running.

Example

This example shows how to use the MARK function. Assume that at first no records are marked.

This example requires that you create the following text constant in the C/AL Globals window.

Text constant | ENU value
Text000 | Customer.No.: %1, Marked?: %2

This example also requires that you create the following variables.

Variable name | DataType | Subtype
Customer | Record | Customer
Marked | Boolean | Not applicable
Copy Code
Customer.SETCURRENTKEY("No.");
Customer."No." := 'NEW 3500';
Customer.FIND('=');
Customer.MARK(TRUE); // Mark a record.
Customer.FIND('-'); // Find first record.
REPEAT // Go through records
Marked := Customer.MARK; // Test if marked.
MESSAGE(Text000, Customer."No.", Marked);
UNTIL Customer.NEXT = 0;

The message windows could show the following:

Customer No.: AAA 1050, Marked?: No

Customer No.: DEL 3500, Marked?: No

Customer No.: NEW 3500, Marked?: Yes

Customer No.: PEA 2500, Marked?: No

Customer No.: SOP 7500, Marked?: No

This example shows how to use the MARK function together with the MARKEDONLY function. Assume that at first no records are marked.

This example requires that you create the following text constants in the C/AL Globals window.

Text constant | ENU value
Text001 | Number of records before MARKEDONLY: %1\
Text002 | Number of records after MARKEDONLY: %2

This example also requires that you create the following variables.

Variable name | DataType | Subtype
Customer | Record | Customer
No1 | Integer | Not applicable
No2 | Integer | Not applicable
Copy Code
SETCURRENTKEY(Customer."No.");
Customer."No." := 'NEW 3500';
FIND(Customer, '=');
MARK(Customer, TRUE); //Mark a record.
No1 := COUNT(Customer);
MARKEDONLY(Customer, TRUE);
No2 := COUNT(Customer);
MESSAGE(Text001 + Text002, No1, No2);

The message windows could show the following:

Number of records before MARKEDONLY: 5

Number of records after MARKEDONLY: 1

See Also

Reference

MARKEDONLY Function (Record)
Record Data Type


MARKEDONLY Function (Record)

Activates a special filter. After you use this function, your view of the table includes only records marked by this function.

[IsMarkedOnly :=] Record.MARKEDONLY([SetMarkedOnly])

Parameters

Record

Type: Record

A record from the table that you want mark.

SetMarkedOnly

Type: Boolean

Changes the state of the special filter. This parameter is optional.

If this parameter if true, only marked records are included. If this parameter is false, all records are included.

Property Value/Return Value

Type: Boolean

true if the special filter is being used; otherwise, false.

Example

This example shows how to use MARK and MARKEDONLY. Assume that at first no records are marked.

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec | Record | Customer
No1 | Integer | Not applicable
No2 | Integer | Not applicable

Text constant | ENU value
Text000 | Number of records before MARKEDONLY: %1.\
Text001 | Number of records after MARKEDONLY: %2.
Copy Code
CustomerRec.SETCURRENTKEY("No.");
CustomerRec."No." := '10000';
CustomerRec.FIND('=');
CustomerRec.MARK(TRUE); // Mark a record.
No1 := CustomerRec.COUNT;
CustomerRec.MARKEDONLY(TRUE);
No2 := CustomerRec.COUNT;
MESSAGE(Text000 + Text001, No1, No2);

The following messages could be displayed:

Number of records before MARKEDONLY: 68.

Number of records after MARKEDONLY: 1.

See Also

Reference

MARK Function (Record)
Record Data Type


MODIFY Function (Record)

Modifies a record in a table.

[Ok :=] Record.MODIFY([RunTrigger])

Parameters

Record

Type: Record

The record that you want to modify.

Warning
The record cannot be from table 2000000001, the Object table or table 2000000006, the Company table.

RunTrigger

Type: Boolean

Specifies whether to run the C/AL code in the OnModify Trigger.

If this parameter is true, then the code in the OnModify trigger is executed. If this parameter is false (default), then the code in the OnModify trigger is not executed.

Property Value/Return Value

Type: Boolean

true if the record was modified; otherwise, false.

If you omit this optional return value and if the record is not found, then a run-time error occurs. If you include the return value, then you must handle any errors.

Remarks

If an end-user modifies a record between the time that another end-user or another process reads the record and modifies it, then the second user must refresh the value of the record variable before editing the record. Otherwise, the end-user receives the following run-time error:

Another user has modified the record for this <Table Name> after you retrieved it from the database.

Enter your changes again in the updated window, or start the interrupted activity again.

In earlier versions of Microsoft Dynamics NAV, certain situations allowed code that an end-user runs to modify a record after a newer version of the record was written and committed to the database. This would overwrite the newer changes. However, in Microsoft Dynamics NAV 2016, we have restricted the MODIFY Function (Record), RENAME Function (Record), and DELETE Function (Record) so that the end-user receives the following run-time error in these certain situations:

Unable to change an earlier version of the <Table Name> record. The record should be read from the database again. This is a programming error.

You must design your application so that you use the most up-to-date version of the record for modifications to the database. You use the GET Function (Record) to refresh the record with the latest version. The second example that is shown here illustrates this situation.

Example

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec | Record | Customer
No1 | Integer | Not applicable
No2 | Integer | Not applicable

Text constant | ConstValue
Text000 | The customer no. %1 is:\
Text001 | Now customer no. %1 is:\
Copy Code
// Find customer.
CustomerRec.FIND('-');
// Display name.
MESSAGE(Text000 + '%2', CustomerRec."No.", CustomerRec.Name);
// Modify customer name.
CustomerRec.Name := 'Progressive Home Furnishings';
CustomerRec.MODIFY;
// Display new name.
MESSAGE(Text001 + '%2', CustomerRec."No.", CustomerRec.Name);

Messages that resemble the following are displayed:

The customer no. AAA 1050 is:

AAA Furniture Manufacturing

Now customer no. AAA 1050 is:

Progressive Home Furnishings

Example

This example shows that you get an error if you attempt to modify a record after a newer version of the record has been written and committed to the database. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec1 | Record | Customer
CustomerRec2 | Record | Customer

In this example, you get a copy of a record from the Customer table and put it into the CustomerRec1 variable, then you modify the record. Next, you get a copy of the same record from the Customer table and put it into the CustomerRec2 variable. You modify the record and commit the changes to the database. Now the CustomerRec1 variable is out of date with the value in the database. If you were allowed to modify the database with the CustomerRec1 record, then the Phone No. field that you modified with CustomerRec2 would be overwritten by the old value of the Phone No. field that is in the CustomerRec1 variable. Microsoft Dynamics NAV 2016 does not allow you to modify the database with the old version of the record.

Note
If you do not call the COMMIT function in this example, then you do not receive an error.

Copy Code
CustomerRec1.LOCKTABLE;
CustomerRec1.GET('10000');
CustomerRec1."Address 2" := 'Suite 101';
CustomerRec1.MODIFY;
CustomerRec2.GET('10000');
CustomerRec2."Phone No.":= '206-555-0109';
CustomerRec2.MODIFY;
COMMIT;
CustomerRec1."Salesperson Code" := 'JR';
CustomerRec1.MODIFY;

If you run this code example, then you get the following error:

Unable to change an earlier version of the Customer record. The record should be read from the database again. This is a programming error.

Identification fields and values:

No.='10000'

See Also

Reference

MODIFYALL Function (Record)
MODIFY Function (RecordRef)
Record Data Type
COMMIT Function (Database)
LOCKTABLE Function (Record)


MODIFYALL Function (Record)

Modifies a field in all records within a range that you specify.

Record.MODIFYALL(Field, NewValue [, RunTrigger])

Parameters

Record

Type: Record

The record that contains the field that you want to modify.

Field

Type: Field

The field that you want to modify.

NewValue

Type: Any

The value that you want to assign to Field in all records. The data type of NewValue must match the data type of Field.

RunTrigger

Type: Boolean

If this parameter is true, the code in the OnModify Trigger is executed. If this parameter is false (default), the code in the OnModify trigger is not executed.

Remarks

If no filter is set, the field is modified in all records in the table. If a filter is set, the fields are modified only in the records which fall within the range specified by the filter.

The OnValidate (Fields) Trigger is never executed when MODIFYALL is used.

Example

This example requires that you create the following variable in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec | Record | Customer
Copy Code
// The result of this statement:
CustomerRec.MODIFYALL("Statistics Group", 2);
// is equivalent to:
IF CustomerRec.FIND('-') THEN
  REPEAT
    CustomerRec."Statistics Group" := 2;
    CustomerRec.MODIFY;
  UNTIL CustomerRec.NEXT = 0;

See Also

Reference

MODIFY Function (Record)
Record Data Type


NEXT Function (Record)

Steps through a specified number of records and retrieves a record.

Steps := Record.NEXT([Steps])

Parameters

Record

Type: Record

The record from which the search starts.

Steps

Type: Integer

Specifies the direction of the search and how many records to step over. This parameter follows the following rules:

  • >0 Search Steps records forward in the table.

  • <0 Search Steps records backward in the table.

  • =0 Stay on the same record in the table.

If you do not specify this parameter, then the next record is found.

Property Value/Return Value

Type: Integer

The number of records inspected which meet the criteria of any filters and the current key. This value can be less than Steps, depending on the number of records in the table. If the table is empty, then zero is returned and Record does not change.

Remarks

This function locates a record positioned a given number of steps forward or backward from Record. Movement through the table is governed by the filters and the current key associated with the records. The fields in Record that will be compared with the current key fields must contain appropriate values before the function is called.

Example

This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Subtype
Count | Integer | Not applicable
CustomerRec | Record | Customer
Copy Code
Count := 0;
IF CustomerRec.FIND('-') THEN
  REPEAT
    Count := Count + 1;
  UNTIL CustomerRec.NEXT = 0;

This code uses a REPEAT UNTIL loop to count the number of entries in the Customer table. The FIND function finds the first entry in the table. Each time the NEXT function is called, it steps one record forward. When NEXT equals zero (0), there are no more entries in the table and the loop is exited.

See Also

Reference

Record Data Type

Concepts

GET, FIND, and NEXT Functions


READPERMISSION Function (Record)

Determines whether a user is granted read permission to the table that contains a record. This function can test for both full read permission and partial read permission that has been granted with a security filter.

Ok := Record.READPERMISSION

Parameters

Record

Type: Record

The record in the table for which you want to check for read access.

Property Value/Return Value

Type: Boolean

Specifies whether the user is granted read access to the table.

true if you can read from some or the entire table; otherwise, false.

Remarks

This function uses the filter that is currently applied to the Record to determine whether you have read permission. If no filter is applied, the function tests for full read permission. If a filter has been set, the function only tests for read permission within the range of the filter.

To determine whether the user has a partial read permission because a security filter has been applied, view the Permissions page. For more information, see How to: Set Security Filters.

If you do not have permission to read from a table and you attempt to read, a run-time error occurs. This function allows you to determine in advance if you have read permission. When the permissions are checked, the combination of permissions in the license file and the user's permissions in the Permission table is considered.

Example

The following code example retrieves record number 10000 from the Vendor table and stores the record in the MyRecord variable. The READPERMISSION function determines whether the user is granted read permission to the Vendor table. The value Yes is displayed in the message box because the user can read from the vendor table. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Subtype
MyRecord | Record | Vendor
varHasRead | Boolean | Not applicable
Copy Code
MyRecord.GET('10000');
varHasRead := MyRecord.READPERMISSION;
MESSAGE(Is user the granted Read permission? %1', varHasRead);

See Also

Reference

Record Data Type


RECORDID (Record)

Gets the RecordID of the record that is currently selected in the table. If no table is selected, an error is generated.

RecordID := Record.RECORDID

Parameters

Record

Type: Record

The record whose recordID you want to get.

Property Value/Return Value

Type: RecordID

Remarks

You can show strings that include RECORDID in the user interface by using the FORMAT Function (Code, Text). In most cases, use the standard format value 1, which ensures that captions are shown in the current language. The following table illustrates the effect of the different standard formats when RECORDID is used in a FORMAT statement in a Danish locale.

Standard Format | Renders as
FORMAT(Customer.RECORDID,0,0) | Customer: 1212121
FORMAT(Customer.RECORDID,0,1) | Kunde: 1212121
FORMAT(Customer.RECORDID,0,9) | Customer: 1212121

When you use standard format 1, the caption of the record is returned. When you use other standard formats, the name of the record is returned, which is usually English (US). For more information, see Format Property.

Example

The following example opens table 18 (Customer) as a Record variable that is named MyRecord. The FINDLAST Function (Record) finds the last record in the table. The record ID of the last record is retrieved, stored in the RecID variable displayed in message box. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
MyRecord | Record
RecID | RecordID

Text constant name | DataType | ENU value
MyTextConst | Text | The record ID for the last record is: %1
Copy Code
MyRecord.OPEN(18);
MyRecord.FINDLAST;
RecID := MyRecord.RECORDID;
MESSAGE(MyTextConst, RecID);

See Also

Reference

Record Data Type
Format Property


RELATION Function (Record)

Determines the table relationship of a given field.

TableNumber := Record.RELATION(Field)

Parameters

Record

Type: Record

The record that contains Field.

Field

Type: Field

The field for which you want to find the table relationship.

Property Value/Return Value

Type: Integer

The number of the table that has a relationship with Field. This relationship is set up through the properties.

Remarks

You can use this function for several purposes, such as to determine lookups or to check if you have permission to read from a table.

Example

The following example displays the number of the table that has a relation with the City field in the Customer table. In this example, table number 225, the Post Code table, is displayed because a table relation exists in the City field. If a relation does not exist, then an error message is displayed. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec | Record | Customer
varTableNumber | Integer | Not applicable
Copy Code
varTableNumber := CustomerRec.RELATION (CustomerRec.City);
MESSAGE('%1', varTableNumber);

See Also

Reference

Record Data Type


RENAME Function (Record)

Changes the value of a primary key in a table.

[Ok :=] Record.RENAME(Value1[, Value2,...])

Parameters

Record

Type: Record

The record that contains the primary key that you want to change.

Value1, Value2, …

Type: Text

The new values for the primary key.

Property Value/Return Value

Type: Boolean

true if the primary key was renamed; otherwise, false. If the record does not exist or if you do not have permission to write to the table, then false is returned.

If you omit this optional return value and if the record is not renamed, then a run-time error occurs. If you include the return value, then you must handle any errors.

Remarks

For example, you can use the RENAME function if you use the customer's telephone number as the customer number. You can use this function to change the customer number if the telephone number changes.

You cannot rename some tables. Examples of the types of tables that you cannot rename are as follows:

  • Tables in which the user cannot rename the Document No. field for legal or business reasons.

  • Tables in which an Option data type field, such as Document Type, is part of the primary key.

Some examples of tables that you cannot rename are as follows:

  • Table 36, Sales Header

  • Table 38, Purchase Header

  • Table 5405, Production Order

  • Table 5766, Warehouse Activity Header

    If an end-user modifies a record between the time that another end-user or another process reads the record and modifies it, then the second user must refresh the value of the record variable before editing the record. Otherwise, the end-user receives the following run-time error:

    Another user has modified the record for this <Table Name> after you retrieved it from the database.

    Enter your changes again in the updated window, or start the interrupted activity again.

    In earlier versions of Microsoft Dynamics NAV, certain situations allowed code that an end-user runs to modify a record after a newer version of the record was written and committed to the database. This would overwrite the newer changes. However, in Microsoft Dynamics NAV 2016, we have restricted the MODIFY Function (Record), RENAME Function (Record), and DELETE Function (Record) so that the end-user retrieves the following run-time error in these certain situations:

    Unable to change an earlier version of the <Table Name> record. The record should be read from the database again. This is a programming error.

    You must design your application so that you use the most up-to-date version of the record for modifications to the database. You use the GET Function (Record) to refresh the record with the latest version. The second example illustrates this situation.

When a record is renamed, the change is written and committed to the database without calling the OnModify Trigger. This is done because renaming a record changes the primary key and updates the primary key value in all related tables. Therefore, you should use the Rename function and Modify function on a record separately.

Example

This example requires that you create the following variable in the C/AL Globals window.

Variable name | DataType | Subtype
ItemRec | Record | Item
Copy Code
ItemRec.GET(‘1150’);
ItemRec.RENAME(‘1105’);

Example

This example shows that you get an error if you attempt to rename a record after a newer version of the record has been written and committed to the database. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec1 | Record | Customer
CustomerRec2 | Record | Customer

In this example, you get a copy of a record from the Customer table and put it into the CustomerRec1 variable, then you modify the record. Next, you get a copy of the same record from the Customer table and put it into the CustomerRec2 variable. You modify the record and commit the changes to the database. Now the CustomerRec1 variable is out of date with the value in the database. If you were allowed to modify the record using the CustomerRec1 record, then the changes that you made with CustomerRec2 would be overwritten by the values in the CustomerRec1 variable. Microsoft Dynamics NAV 2016 does not allow you to rename a record with the old version of the record.

Note
If you do not call the COMMIT function in this example, then you do not receive an error.

Copy Code
CustomerRec1.LOCKTABLE;
CustomerRec1.GET('10000');
CustomerRec1."Address 2" := 'Suite 101';
CustomerRec1.MODIFY;
CustomerRec2.GET('10000');
CustomerRec2."Phone No.":= '206-555-0109';
CustomerRec2.MODIFY;
COMMIT;
CustomerRec1."Phone No." := '425-555-0184';
CustomerRec1.RENAME('10001');

If you run this code example, then you get the following error:

Unable to change an earlier version of the Customer record. The record should be read from the database again. This is a programming error.

Identification fields and values:

No.='10000'

See Also

Reference

Record Data Type
RENAME Function (RecordRef)
COMMIT Function (Database)
LOCKTABLE Function (Record)


RESET Function (Record)

Removes all filters, including any special filters set by MARKEDONLY, and changes the current key to the primary key. Also removes any marks on the record and clears any C/AL variables on the record.

Record.RESET

Parameters

Record

Type: Record

The record that you want to reset.

Remarks

RESET does not reset filters in filter group 1. For more information about filter groups, see FILTERGROUP Function (Record).

Example

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec | Record | Customer
Count1 | Integer | Not applicable
Count2 | Integer | Not applicable

Text constant | ConstValue
Text000 | Before RESET: %1.\
Text001 | After RESET: %2.
Copy Code
CustomerRec.SETFILTER("No.", '10000');
CustomerRec.SETRANGE("Salesperson Code", 'PS');
CustomerRec.MARKEDONLY(TRUE);
Count1 := CustomerRec.COUNT; // Count marked customers in the range.
CustomerRec.RESET;
Count2 := CustomerRec.COUNT; // Count all customers.
MESSAGE(Text000 + Text001, Count1, Count2);

Messages similar to the following are displayed:

Before RESET: 0

After RESET: 68

The example shows that RESET removed all filters.

See Also

Reference

Record Data Type


SETASCENDING Function (Record)

Sets the sort order for the records returned. Use this function after you have set the keys to sort after, using SETCURRENTKEY. The default sort order is ascending. You can use SETASCENDING to change the sort order to descending for a specific field, while the other fields in the specified key are sorted in ascending order.

For example, you can read data from an ODATA web service where the data is sorted in ascending order on the Name field but in descending order on the City field.

[Ascending :=]Record.SETASCENDING(Field,[ SetAscending])

Parameters

Record

Type: Record

The record in the table that you want to set the sort order for.

Field

Type: Field

The field that you want to set the sort order for.

SetAscending

Type: Boolean

The sort order. Specify Descending if data must be sorted in descending order; otherwise Ascending.

Example

The following code example illustrates how you can use SETCURRENTKEY and SETASCENDING to sort data in two different directions based on two fields.

Copy Code
Customer.SETCURRENTKEY(City,"Name");

Customer.SETASCENDING(City,Descending);

In this example, you use SETCURRENTKEY to specify that you want to sort based on City and Name. This means that data will be sorted in ascending order based on those two fields, first by City, then by Name. Next, you use SETASCENDING to sort City in descending order instead. As a result, your data will look like this:

Copy Code
CTown

   ACustomer

   BCustomer

BTown

   ACustomer

   BCustomer

   CCustomer

ATown

   ACustomer

   BCustomer

See Also

Reference

SETCURRENTKEY Function (Record)

Concepts

OData Web Services


SETAUTOCALCFIELDS Function (Record)

Sets the FlowFields that you specify to be automatically calculated when the record is retrieved from the database.

[OK :=] Record.SETAUTOCALCFIELDS([Field1,Field2, …])

Parameters

Record

Type: Record

The record in the table for which you want to automatically calculate FlowFields.

Field1, Field2, …

Type: Field

The FlowFields that you want to automatically calculate. Each field must be defined as a FlowField and must belong to the same record variable.

To remove the automatic calculation setting on a field that you previously set with the SETAUTOCALCFIELDS function, you must call SETAUTOCALCFIELDS without parameters.

Property Value/Return Value

Type: Boolean

true if the record was set successfully; otherwise, false. If you omit this optional return value and if the record cannot be set to automatically calculate, then a run-time error occurs. If you include a return value, then you must handle any errors.

Remarks

FlowFields are virtual fields. The values in these fields are not saved in the table. This means that you must use either the CALCFIELDS Function (Record)or the SETAUTOCALCFIELDS function to update them. For example, if you retrieve records using the FIND Function (Record) and NEXT Function (Record), then the FlowFields in those records are set to zero (0). However, if you call SETAUTOCALCFIELDS before you retrieve the records, then when you call FIND and NEXT, the FlowFields values are automatically calculated.

When a FlowField is a direct source expression on a page or a report, the calculation will be performed automatically.

You can improve performance by using the SETAUTOCALCFIELDS function before looping through records with FlowFields instead of calling the CALCFIELDS function on each record in the loop.

The automatic calculation setting applies to the fields that you specify until the Record parameter goes out of scope or until you call SETAUTOCALCFIELDS without any parameters.

The fields that you specify in the Field parameters are added to any fields that you previously set with the SETAUTOCALCFIELDS function. Previously set fields are not overwritten when you call SETAUTOCALCFIELDS with different parameters. To clear the list of fields that are automatically calculated, call the SETAUTOCALCFIELDS function without parameters.

If you assign a record to another record variable, then the automatic calculation setting on FlowFields is not transferred with the record.

If you copy a record by using the COPY Function (Record), then the automatic calculation setting on FlowFields is copied with the record.

The Rec and xRec system variables are set to always automatically calculate FlowFields. If you call the NEXT function on Rec or xRec, then FlowFields in the record are automatically calculated.

Example

The first six lines of this example show how to use the CALCFIELDS function. The last lines of this example show how you can use the SETAUTOCALCFIELDS function instead of the CALCFIELDS function to improve performance.

This example requires that you create the following variable.

Variable name | DataType | Subtype
Customer | Record | Customer
Copy Code
// Using CALCFIELDS
IF (Customer.FIND(’-’)=true) THEN
  REPEAT
    Customer.CALCFIELDS(Balance,"Net Change");
    … // Do some additional processing.
  UNTIL (Customer.NEXT=0)
// Using SETAUTOCALCFIELDS
Customer.SETAUTOCALCFIELDS(Balance,"Net Change");
IF (Customer.FIND(’-’)=true) THEN
  REPEAT
    // Customer.Balance and Customer."Net Change" have been auto calculated.
    … //Do some additional processing.
  UNTIL (Customer.NEXT=0)

Example

The following example shows how to add fields to the list of automatically calculated FlowFields and how to clear the list of automatically calculated FlowFields

This example requires that you create the following variable.

Variable name | DataType | Subtype
Customer | Record | Customer
Copy Code
Customer.SETAUTOCALCFIELDS(Balance);
Customer.SETAUTOCALCFIELDS("Net Change");
// The previous lines are equivalent to the following:
Customer.SETAUTOCALCFIELDS(Balance,"Net Change");
// To clear the list of automatically calculated FlowFields so that no fields are calculated automatically, use the following code.
Customer.SETAUTOCALCFIELDS();

See Also

Reference

FieldClass Property

Concepts

FlowFields


SETCURRENTKEY Function (Record)

Selects a key for a table.

[Ok :=] Record.SETCURRENTKEY(Field1, [Field2],...)

Parameters

Record

Type: Record

The record that contains the fields that identify the key that you want to select. The key can be composed of fields of any supported data type. Data types that are not supported include BLOBs, FlowFilters, variables, and functions.

Field1, Field2, …

Type: Field

One or more fields that identify the key that you want to select.

Property Value/Return Value

Type: Boolean

true if the key was selected; otherwise, false.

If you omit this optional return value and if the key cannot be found, then a run-time error occurs. If you include a return value, then you must handle any errors.

Remarks

SETCURRENTKEY is used to select a key for a record and set the sort order that is used for the table in question. This key becomes the current key and is used by the FIND Function (Record), the NEXT Function (Record), and other functions until another key is selected. Until this function is called, the table's primary key is used as the current key.

In Microsoft Dynamics NAV 2016, the CALCFIELDS Function (Record), CALCSUMS Function (Record), AND CALCSUM Function (FieldRef) do not require that a SIFT index is defined for the fields that are being calculated. Therefore, you do not need to define keys solely for SIFT indexes. Fewer SIFT indexes and fewer keys can improve performance. In earlier versions of Microsoft Dynamics NAV, if a Microsoft Dynamics NAV key that started with the fields that you specified as parameters to SETCURRENTKEY did not exist, then you received an error when you called the SETCURRENTKEY function. This provided a degree of protection in earlier versions against accidentally requesting a sorting for which no index existed. In Microsoft Dynamics NAV 2016, an index is not required to support a certain sorting, but sorting without an index could lead to bad performance if a search returns a large result set, which would then have to be sorted before the first row is returned.

Use the following guidelines when you use SETCURRENTKEY:

  • Inactive fields are ignored. Only active keys are scanned.

  • When searching for a key, Microsoft Dynamics NAV selects the first occurrence of the specified field(s). This means the following:

    • If you specify only one field as a parameter when you call SETCURRENTKEY, then the key that is actually selected may consist of more than one field.

    • If the field that you specify is the first component of several keys, then the key that is selected is the first one that matches, which may not be the key that you expect.

  • If no keys can be found that include the field(s) that you specify, then a run-time error occurs unless you test the Boolean return value of SETCURRENTKEY in your code.

  • If you do test the return value, then you must decide what to do if the function returns false, because without a run-time error, the application continues to run even though no key was found and may fail later.

  • Use only the necessary key fields in a call to SETCURRENTKEY. If the definition of the key includes the fields that you specify in the call to SETCURRENTKEY in the order given, then you can change the definition of the key without having to change any code. If the table order is not important, then consider one of the following:

    • If the expected result set is small, then do not call SETCURRENTKEY at all. The result will be sorted according to the smallest possible key, which is the primary key.

    • If the expected result set is large, then call SETCURRENTKEY with a field set that matches subsequent calls to SETRANGE and SETFILTER functions. This way, there is less risk that extra sorting of the large result must be done.

Example

This example shows how to use the SETCURRENTKEY function without using a return value. This example requires that you create the following variable.

Name | DataType | Subtype
MyCustomer | Record | Customer
Copy Code
MyCustomer.SETCURRENTKEY(Name);

This statement selects the Name key for the Customer table. If the key cannot be found, a run-time error occurs.

Example

This example shows how to use the SETCURRENTKEY function with a return value.

This example requires that you create the following variable.

Name | DataType | Subtype
MyCustomer | Record | Customer

This example requires that you create the following text constants.

Name | ConstValue
Text000 | The key was successfully selected.
Text001 | The key could not be found.
Copy Code
IF MyCustomer.SETCURRENTKEY(Name) THEN
  MESSAGE(Text000)
ELSE
  MESSAGE(Text001);

By including a return value, you can avoid a run-time error if a key cannot be found.

See Also

Reference

Record Data Type


SETFILTER Function (Record)

Assigns a filter to a field that you specify.

Record.SETFILTER(Field, String, [Value],...)

Parameters

Record

Type: Record

The record that contains the field that you want to filter.

Field

Type: Field

The field that you want to filter.

String

Type: Text or code

The filter expression. A valid expression consists of alphanumeric characters and one or more of the following operators: <, >, *, &, |, and =. You can use replacement fields (%1, %2, and so on) to insert values at run-time.

Value

Type: Any

Replacement values to insert in replacement fields in the filter expression. The data type of Value must match the data type of Field.

Remarks

If the function is called with a field for which a filter already exists, that filter will be removed before the new one is set. You can construct filters using the following operators:

  • .. Range

  • & And

  • | Or

  • < Less than

  • <= Less than or equal to

  • > Greater than

  • >= Greater than or equal to

  • <> Different from

  • * Forms a part of value

  • @ Case-insensitive

Example

The following table shows examples of filters.

Filter | Description
A..Z | A range from A to Z
A|G | A or G
F.. & *A/S | A range from F and A/S is included in the field
<>B | All except B
<>'' | All not blank
<=200 | >500 | All less than or equal to 200 or greater than 500

This example requires that you create the following variable.

Name | DataType | Subtype
GLAccountRec | Record | G/L Account
Copy Code
// Using a filter with replacement field.
// This filter selects all accounts in the range from 100 to 200
//   and No. 300.
GLAccountRec.SETFILTER("No.", '%1..%2|%3', '100', '200', '300');
// Using a filter entered directly in a string.
// This filter, which is entered as a string, has the same result as
//   the previous example.
//   This filter selects all accounts in the range from 100 to 200 and
//   and No. 300.
GLAccountRec.SETFILTER("No.", '100..200|300');

See Also

Reference

Record Data Type


SETPOSITION Function (Record)

Sets the fields in a primary key on a record to the values specified in the supplied string. The remaining fields are not changed.

Record.SETPOSITION(String)

Parameters

Record

Type: Record

The record on which you want to set the primary key field.

String

Type: Text or code

The string that is used to set the primary key. This string contains the primary key value to set.

Example

The following example changes the value in the primary key, the No. field, in table 23, the Vendor table. Other fields are not changed. The code starts by opening table 23 as a record variable that is named MyRecord. The SETRANGE Function (Record) sets a filter that selects records from 10000 to 20000 in the No. field. The FINDLAST Function (RecordRef) finds and retrieves the last record in the record set. The SETPOSITION function uses the value stored in the InputString parameter to change the value in the No. field from 20000 to 20001. The record No. and the name of the record are displayed before and displayed again after the primary key value is changed. The string that contains the new primary key is initialized in the InputString variable. This example requires that you create the following variables and text constants in the C/AL Globals window

Variable name | DataType | Subtype
InputString | Text | Not applicable
MyRecord | Record | Vendor

Text constant name | ConstValue
Text000 | The record No. before the primary key was changed is %1.\ The vendor name before the primary key was changed is %2.
Text001 | The record No. after the primary key was changed is %1. \ The vendor name after the primary key was changed is %2.
Copy Code
InputString := 'No.=CONST(20001)';
MyRecord.SETRANGE("No.", '10000','20000');
MyRecord.FINDLAST;
MESSAGE(Text000, MyRecord."No.", MyRecord.Name);
MyRecord.SETPOSITION(InputString);
MESSAGE(Text001, MyRecord."No.", MyRecord.Name);

The following is displayed before the SETPOSITION function is called:

The record No. before the primary key was changed is 20000.

The vendor name before the primary key was changed is AR Day property Management.

The following is displayed after the SETPOSITION function is called:

The record No. after the primary key was changed is 20001.

The vendor name after the primary key was changed is AR Day property Management.

See Also

Reference

Record Data Type


SETRANGE Function (Record)

Sets a simple filter, such as a single range or a single value, on a field.

Record.SETRANGE(Field [,FromValue] [,ToValue])

Parameters

Record

Type: Record

The record that contains the field that you want to filter.

Field

Type: Field

The field that you want to filter.

FromValue

Type: Any

The lower limit of the range. The data type of this parameter must match the data type of Field.

ToValue

Type: Any

The upper limit of the range. If you omit this parameter, then the value that you specified for FromValue is used. The data type of this parameter must match the data type of Field.

Remarks

SETRANGE is a quick way to set a simple filter on a field.

SETRANGE removes any filters that were set previously and replaces them with the FromValue and ToValue parameters that you specify.

If you use SETRANGE without setting the FromValue and ToValue parameters, then the function removes any filters that are already set.

If you set only the FromValue, then the ToValue is set to the same value as the FromValue.

Example

This example shows how to use the SETRANGE function to specify that you want to see only customers 100 through 200. This example requires that you create the following variable in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec | Record | Customer
Copy Code
CustomerRec.SETRANGE("No.", '100', '200');
// The above statement is a quick way to set the same filter as:
CustomerRec.SETFILTER("No.", '>=100&<=200');

Example

This example shows how to find the first record that has a blank for the requested delivery date. It requires that you create the following variable.

Name | Data type | Subtype
SalesLineRec | Record | Sales Line
Copy Code
SalesLineRec.SETRANGE("Requested Delivery Date",0D);
IF SalesLineRec.FIND('-') THEN
  MESSAGE('Sales Order %1 has no requested delivery date.', SalesLineRec."Document No.");

See Also

Reference

Record Data Type


SETRECFILTER Function (Record)

Sets the values in the current key of the current record as a record filter.

Record.SETRECFILTER

Parameters

Record

Type: Record

Specifies the current record for which you want to set the filter.

Example

You can use this function to set a filter on a table before you run a report. Enter C/AL code similar to the following example in the OnAction Trigger of an action on a page. When the code is triggered, the current key fields of the current record in the page will be used as a filter when the report is run.

This example requires that you create the following variable in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec | Record | Customer
Copy Code
CustomerRec.SETRECFILTER;
REPORT.RUN(REPORT::"111",FALSE,FALSE,CustomerRec);

See Also

Reference

Record Data Type


SETVIEW Function (Record)

Sets the current sort order, key, and filters on a table.

Record.SETVIEW(String)

Parameters

Record

Type: Record

The record in the table for which to set the sort order, key, and filters.

String

Type: Text or code

A string that contains the sort order, key, and filter to set.

The string format is the same as the SourceTableView Property on pages.

Remarks

The value of the String parameter can be returned by the GETVIEW Function (Record).

If the SETVIEW function is executed with an empty string, all filters are removed and the primary key is used.

Example

The following code example uses the SETVIEW function to set the sort key to the Name field and the sort order to Ascending, and sets a filter that selects records with the No. field between 1000 and 2000 in the Customer table. The GETVIEW Function (Record) function retrieves the sort order, key, and filters that have been set and stores the value in the ViewString variable. The value in the ViewString variable is then displayed in a message box. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec | Record | Customer
ViewString | Text | Not applicable
Copy Code
CustomerRec.SETVIEW('SORTING(Name) ORDER(Ascending) WHERE(No.=CONST(10000..20000))');
ViewString := CustomerRec.GETVIEW;
MESSAGE('The string:%1', ViewString)

See Also

Reference

Record Data Type


TABLECAPTION Function (Record)

Gets the current caption of a table as a string.

Caption := Record.TABLECAPTION

Parameters

Record

Type: Record

The record in the table for which to retrieve the table caption.

Property Value/Return Value

Type: Text or code

The caption of the table.

Remarks

TABLECAPTION returns the caption of a table. TABLECAPTION first looks for a CaptionML Property. If it does not find one, it uses the Name Property. This means that TABLECAPTION has multilanguage functionality.

Example

The following example retrieves the caption of the Customer table by using the CustomerRec variable, a record from the Customer table. The value of the Customer table caption is stored in the TableCaption variable and displayed in a message box. The value that is displayed is Customer. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec | Record | Customer
TableCaption | Text | Not applicable
Copy Code
TableCaption := CustomerRec.TABLECAPTION;
MESSAGE('The caption for the customer table is: %1', TableCaption);

See Also

Reference

FIELDCAPTION Function (Record)
Record Data Type

Concepts

Multilanguage Development


TABLENAME Function (Record)

Gets the name of a table.

Name := Record.TABLENAME

Parameters

Record

Type: Record

The record in the table for which you want to find the table name.

Property Value/Return Value

Type: Text or code

The name of the table.

Remarks

The TABLECAPTION Function (Record) retrieves the Caption Property of the table. If you want to enable your application for multilanguage functionality now or in the future, you must use the TABLECAPTION function instead of the TABLENAME function.

Example

The following example retrieves the name of the Customer table by using the CustomerRec variable, a record from the Customer table. The value of the Customer table name is stored in the TableName variable and displayed in a message box. The value that is displayed is Customer.

This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec | Record | Customer
TableName | Text | Not applicable
Copy Code
TableName := CustomerRec.TABLENAME;
MESSAGE('The name of the table is: %1', TableName);

See Also

Reference

Record Data Type

Concepts

Multilanguage Development


TESTFIELD Function (Record)

Tests whether the contents of a field match a given value.

Record.TESTFIELD(Field, [Value])

Parameters

Record

Type: Record

The record that contains the field that you want to test.

Field

Type: Field

The field that you want to test.

Value

Type: Any

The value that you want to compare to Field. The data type of this parameter must match the data type of Field. If you include this optional parameter and the contents of Field do not match, then an error message is displayed. If you omit this parameter and the contents of Field is zero or blank (empty string), then an error message is displayed.

Remarks

If the contents of the field differ from the given value, then an error message is displayed.

Example

This example shows how to use the TESTFIELD function without the Value parameter. This example requires that you create the following variable in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec | Record | Customer
Copy Code
CustomerRec."No." := '';
CustomerRec.TESTFIELD("No.")

The following error message is displayed:

You must specify No. in Customer No.=''.

Example

This example shows how to use the TESTFIELD function with the Value parameter. This example requires that you create the following variable in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec | Record | Customer
Copy Code
CustomerRec."No." := 'AAA 1050';
CustomerRec.TESTFIELD("No.",'1000')

If No. is not 1000, then the following message is displayed:

No. must be 1000 in Customer No.='AAA 1050'.

See Also

Reference

Record Data Type


TRANSFERFIELDS Function (Record)

Copies all matching fields in one record to another record.

Record.TRANSFERFIELDS(FromRecord [, InitPrimaryKeyFields])

Parameters

Record

Type: Record

The record to which you want to copy the contents of the fields in FromRecord.

FromRecord

Type: Record

The record from which to copy.

InitPrimaryKeyFields

Type: Boolean

Default: true

If this parameter is true and the records are in the same table, both the timestamp and the Primary Key fields of the destination record will be changed.

If this parameter is true and the records are not in the same table, then the Primary Key fields of the destination record will be changed but the timestamp of the destination record will not be changed.

If this parameter is false, then neither the timestamp nor the Primary Key fields of the destination record are changed.

Remarks

TRANSFERFIELDS copies fields based on the Field No. Property of the fields. For each field in Record (the destination), the contents of the field that has the same Field No. in FromRecord (the source) will be copied, if such a field exists.

The fields must have the same data type for the copying to succeed (text and code are convertible, other types are not.) There must be room for the actual length of the contents of the field to be copied in the field to which it is to be copied. If any one of these conditions are not fulfilled, a run-time error will occur.

Example

This example shows how to use the TRANSFERFIELDS function together with a BLOB field. If you are copying a record that contains a BLOB field, then you must calculate the BLOB field before it can be copied with the rest of the record. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Subtype
GLAccountRec | Record | G/L Account
FromRecord | Record | G/L Account
Copy Code
…
IF GLAccountRec.Picture.HASVALUE THEN
  GLAccountRec.CALCFIELDS(Picture);
GLAccountRec.TRANSFERFIELDS(FromRecord);
GLAccountRec.INSERT(TRUE);

See Also

Reference

Record Data Type


VALIDATE Function (Record)

Calls the OnValidate trigger for the field that you specify.

Record.VALIDATE(Field [, NewValue])

Parameters

Record

Type: Record

The record that contains the field that you specify.

Field

Type: Field

A field together with associated triggers.

NewValue

Type: Must be the same data type as Field, or a data type that is convertible.

The value to insert into Field.

Remarks

VALIDATE first checks any TableRelation Property and then executes the OnValidate (Fields) Trigger of the field.

If you omit NewValue, then the function validates the current value.

Example

This example shows how to use the VALIDATE function.

When you enter an account number in a ledger, some table trigger code is executed to transfer the name of the account from the chart of accounts.

If you enter an account number in a batch job, then the code which transfers the name of the account is not automatically executed. The following code specifies that the appropriate field-level trigger code must be executed.

This example requires that you create the following variable.

Variable | Data type | Subtype
GeneralLedgerEntry | Record | G/L Entry
Copy Code
GeneralLedgerEntry.VALIDATE("G/L AccountNo", '100');
// This corresponds to:
GeneralLedgerEntry."G/L AccountNo" := '100';
GeneralLedgerEntry.VALIDATE("G/L AccountNo");

The VALIDATE function is useful for centralizing processing, which makes your application easier to maintain.

For example, if the OnValidate trigger of the Total Amount field performs a calculation that uses values from three other fields as operands, then the calculation must be performed again if the contents of any one of these fields changes.

You should avoid entering the calculation formula in the OnValidate triggers of each field. This can create errors if the calculation formula has to be changed later and you have to update the code in all the triggers. Instead, you should enter the calculation formula in the OnValidate trigger of only one of the fields and call this trigger code from the OnValidate triggers of the other fields.

See Also

Reference

Record Data Type


WRITEPERMISSION Function (Record)

Determines whether a user can write to a table. This function can test for both full write permission and partial write permission that has been granted with a security filter. A write permission consists of Insert, Delete, and Modify permissions.

Ok := Record.WRITEPERMISSION

Parameters

Record

Type: Record

A record in the table from which you want to determine if you have write permission.

Property Value/Return Value

Type: Boolean

Specifies whether you have permission to write to the table using any of the following record functions:

  • INSERT Function (Record)

  • DELETE Function (Record)

  • MODIFY Function (Record)

  • RENAME Function (Record)

  • DELETEALL Function (Record)

  • MODIFYALL Function (Record)

true if you can write to some or all of the table. false if you cannot write to the table.

Remarks

This function uses the filter that is currently applied to the Record to determine whether you have write permission. If no filter is applied, the function tests for full write permission. If a filter has been set, the function only tests for write permission within the range of the filter.

To determine whether the user has a partial read permission, because a security filter has been applied, view the Permissions page. For more information, see How to: Set Security Filters.

If you do not have permission to write to a table and you attempt to write, a run-time error occurs. This function allows you to determine in advance if you have write permission. When the permissions are checked, the combination of permissions in the license file and the user's permissions in the Permission table is considered.

Example

The following example uses a record from the Vendor table to check whether the user is granted write permission to the Vendor table. The return value from the WRITEPERMISSION function is stored in the varHasWrite variable and displayed in a message box. The value, Yes is displayed because the user can write to the Vendor table. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Subtype
MyRecord | Record | Vendor
varHasWrite | Boolean | Not applicable
Copy Code
MyRecord.GET('10000');
varHasWrite := MyRecord.WRITEPERMISSION;
MESSAGE('Table has Write permission? %1', varHasWrite);

See Also

Reference

Record Data Type


RecordID Data Type

This data type contains the table number and the primary key of a table. You can store a RecordID in the database but you cannot set filters on a RecordID.

See Also

Reference

GETRECORD Function (RecordID)
TABLENO Function (RecordID)


GETRECORD Function (RecordID)

Gets a RecordRef that refers to the record identified by the RecordID.

RecordRef := RecordID.GETRECORD

Parameters

RecordID

Type: RecordID

The RecordID of the record for which you want the RecordRef.

Property Value/Return Value

Type: RecordRef

The RecordRef of the record.

Remarks

No data is read from the database when you run this function and therefore, no other fields in the record are set. Furthermore, no filters are set on the record.

Example

The following example opens table number 18 (Customer table) and sets a reference to the table. The FINDLAST Function (RecordRef) selects the last record in the table. The RECORDID Function (RecordRef) retrieves the ID of the currently selected record. In this case, it is the last record in the table. The GETRECORD Function (RecordID) uses the retrieved record ID to determine the RecordRef of the selected record (the last record). This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
RecRef | RecordRef
RecID | RecordID
Copy Code
RecRef.OPEN(18);
RecRef.FINDLAST;
RecID := RecRef.RECORDID;
RecRef := RecID.GETRECORD;

See Also

Reference

RecordID Data Type


TABLENO Function (RecordID)

Gets the table number of the table that is identified by RecordID. This function returns an error if the record is blank.

No := RecordID.TABLENO

Parameters

RecordID

Type: RecordID

The RecordID of the record whose number you want returned.

Property Value/Return Value

Type: Integer

The number of the table.

Remarks

In previous versions of Microsoft Dynamics NAV, if a RecordID referred to a temporary table, then the table number value of the RecordID was the run-time generated sequence ID, which is from the base value of 2000100000. You could use the table number to determine if a RecordID referred to a temporary table. In Microsoft Dynamics NAV, the table number value of a RecordID always contains the ID of the originating physical table and not the run-time generated sequence ID. If you previously used the TABLENO Function (RecordID) to test for the sequence number and determine if the RecordID was temporary, then you use the ISTEMPORARY Function (RecordRef) in Microsoft Dynamics NAV 2016 instead.

Example

The following example opens the Customer table with the record reference variable named RecRef and finds the first record in the Customers table. If a record is found, the RECORDID Function (RecordRef) gets the ID of the first record in the table. The TABLENO function then uses the RecID variable to retrieve the number of the table that contains the record. The table number is then displayed in a message box. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType
RecID | RecordID
RecRef | RecordRef
varTableNumber | Integer
Copy Code
RecRef.OPEN(DATABASE::Customer);
IF RecRef.FIND('-') THEN BEGIN
  RecID := RecRef.RECORDID;
  varTableNumber := RecID.TABLENO;
  MESSAGE('The Customer table is number: %1', varTableNumber);
  END
ELSE BEGIN
MESSAGE('No records found in the table');
END;

See Also

Reference

RecordID Data Type


RecordRef Data Type

A RecordRef object references a record in a table. Typically, you use a RecordRef object in functions that must apply to more than one table, not to a specific table. For example, you could use a RecordRef object in a function that loops through several tables or as a parameter of a function that is called for records of different tables.

The RecordRef object can refer to any table in the database. Use the OPEN Function (RecordRef) to use the table number to select the table that you want to access, or use the GETTABLE Function (RecordRef) to use another record variable to select the table that you want to access.

If one RecordRef variable is assigned to another RecordRef variable, then they both refer to the same table instance.

See Also

Reference

FieldRef Data Type


ADDLINK Function (RecordRef)

Adds a link to a record in a table.

[ID := ]ADDLINK(URL[, Description])

Parameters

URL

Type: String

The link that you want to add to the record.

Description

Type: String

Optional description of the link.

Property Value/Return Value

Type: Integer

The ID of the URL that you want to add to the record. Every time that you add a link to a page or a table, an entry is created in the Record Link system table. Each entry is given an ID.

Remarks

The URL can be a link to a Web site, a file stored on the local or on a remote computer, or a link to a Microsoft Dynamics NAV page. You can then view the link in the Links FactBox on pages that display the record.

Example

The following example adds a link to a record in the Customer table. The code starts by opening table 18 (Customer) as a RecordRef variable that is named CustomerRecref. The FIELD Function (RecordRef) creates a FieldRef variable that is named MyFieldRef for the first field (No.). Next, MyFieldRef.VALUE is set to record 01121212. The FIND Function (RecordRef) function searches the records for record no. 01121212. If the record is found, then the ADDLINK function adds a link to the record. The link is assigned a link ID, which is stored in the LinkID variable. The link ID is displayed in a message box. You can view the link you added in the Links FactBox on the Customer List or Customer Card pages. This example requires that you create the following variables and text constants in C/AL Globals window.

Variable name | DataType
CustomerNum | Code
varLink | Text
CustomerRecref | RecordRef
MyFieldRef | FieldRef
LinkID | Integer

Text constant name | DataType | ENU value
Text000 | Text | The link with ID %1 has been added.
Text001 | Text | The customer cannot be found.
Copy Code
CustomerNum := '01121212';
CustomerRecref.OPEN(18);
MyFieldRef := CustomerRecref.FIELD(1);
MyFieldRef.VALUE := CustomerNum;
IF CustomerRecref.FIND('=') THEN BEGIN
  LinkID := CustomerRecref.ADDLINK(varLink);
  MESSAGE(Text000, LinkID);
END
ELSE
  MESSAGE(Text001);

See Also

Reference

RecordRef Data Type


ASCENDING Function (RecordRef)

Changes or checks the order in which a search through the table that is referred to by RecordRef will be performed.

[IsAscending :=] RecordRef.ASCENDING([SetAscending])

Parameters

RecordRef

Type: RecordRef

SetAscending

Type: Boolean

Determines the order of the search.

If this parameter is true, it will search in ascending order. If this parameter is false, it will search in descending order. If you do not specify this parameter, it will check the search order.

Property Value/Return Value

Type: Boolean

Specifies the order in which a search will be performed.

Remarks

This function works just like the ASCENDING Function (Record).

Example

The following example opens table 18 (Customer) as a RecordRef variable that is named CustomerRecref. The SETVIEW Function (RecordRef) sets a filter that includes sorting the data in ascending order. The ASCENDING function then checks whether the sort order is ascending, stores the return value in the IsAscending variable and displays Yes in a message box. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
CustomerRecref | RecordRef
IsAscending | Boolean

Text constant name | DataType | ENU value
Text000 | Text | Is the sort order ascending? %1
Copy Code
CustomerRecref.OPEN(18);
CustomerRecref.SETVIEW('SORTING(Name) ORDER(Ascending) WHERE(No.=CONST(10000..20000))');
IsAscending := CustomerRecref.ASCENDING;
MESSAGE(Text000, IsAscending);

Example

The following example opens table 18 (Customer) as a RecordRef variable that is named CustomerRecref. The SETVIEW Function (RecordRef) sets a filter that includes sorting the data in descending order. The ASCENDING function then checks whether the sort order is ascending, stores the return value in the IsAscending variable and displays No in a message box because the sort order is descending. The ASCENDING function changes the sort order to ascending by setting the SetAscending parameter to true. The ASCENDING function checks the sort order again. This time Yes is displayed.

Copy Code
CustomerRecref.OPEN(18);
CustomerRecref.SETVIEW('SORTING(Name) ORDER(Descending) WHERE(No.=CONST(10000..20000))');
IsAscending := CustomerRecref.ASCENDING;
MESSAGE(Text000, IsAscending);
IsAscending := CustomerRecref.ASCENDING(TRUE);
MESSAGE(Text000, IsAscending);

See Also

Reference

RecordRef Data Type


CAPTION Function (RecordRef)

Gets the caption of the table that is currently selected. Returns an error if no table is selected.

Caption := RecordRef.CAPTION

Parameters

RecordRef

Type: RecordRef

The RecordRef that identifies the table in which you are interested.

Property Value/Return Value

Type: Text

The caption of the table.

Remarks

This function works just like the TABLECAPTION Function (Record).

Example

The following example selects tables 3 through 5 and opens each table as a RecordRef variable that is named MyRecordRef. The CAPTION function uses the RecorRef variable to retrieve the caption for each of the tables and displays the table number and the caption in a message box. The CLOSE Function (RecordRef) closes the table. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
MyRecordRef | RecordRef
varCaption | Text
i | Integer

Text constant name | DataType | ENU value
Text000 | Text | Table No: %1 Caption: %2
Copy Code
FOR i := 3 TO 6 DO BEGIN
MyRecordRef.OPEN(i);
varCaption := MyRecordRef.CAPTION;
MESSAGE(Text000, i, varCaption);
MyRecordRef.CLOSE;
END;

This example displays the following:

Table No: 3 Caption: Payment terms

Table No: 4 Caption: Currency

Table No: 5 Caption: Finance Charge Terms

See Also

Reference

RecordRef Data Type


CLOSE Function (RecordRef)

Closes the current page or table.

RecordRef.CLOSE

Parameters

RecordRef

Type: RecordRef

The RecordRef of a record in the table that you want to close.

Remarks

You must use this function if you have several recordrefs defined as variables because these will be maintained until the variable gets out of scope.

Example

The following example opens tables 3 through 10 as a Recordref variable that is named MyRecordRef. For each table that is open, the CAPTION Function (RecordRef) retrieves the caption of the table and displays the table number and the caption in a messages box. After each caption is displayed, the CLOSE function closes the table before the next table is open. This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
MyRecordRef | RecordRef
varCaption | Text
i | Integer

Text constant name | DataType | ENU value
Text000 | Text | Table No: %1 Caption: %2
Copy Code
FOR i := 3 TO 10 DO BEGIN
MyRecordRef.OPEN(i);
varCaption := MyRecordRef.CAPTION;
MESSAGE(Text000, i, varCaption);
MyRecordRef.CLOSE;
END;

See Also

Reference

RecordRef Data Type


COPYLINKS Function (RecordRef)

Copies all the links from a particular record.

RecordRef.COPYLINKS(FromRecord)

Parameters

FromRecord

Type: Record or RecordRef

Specifies the record from which you want to copy links.

Remarks

Use this function to copy all the links from a specified record and paste the links to the current record.

The link can be a link to a Web site, a file stored on the local or on a remote computer, or a link to a Microsoft Dynamics NAV page.

Example

The following example copies all links from a source record that is named VendorRecord to the currently open record in the Customer table. The source record is record 10000 from the Vendor table. The code opens the Customer table as a RecordRef variable that is named CustomerRecref. The FIELD Function (RecordRef) creates a FieldRef variable that is named MyFieldRef for field 1 (No.) in the Customer table. The SETRANGE Function (FieldRef) selects records in the range 20000 to 40000 from the Customer table and record 10000 from the Vendor table. The FIND Function (RecordRef) searches the Customer table for the records in the filtered range. If the record that meets the filter criteria is found, the links from the Vendor record No. 10000 are copied to the customer records in the range 30000 to 40000. The record id of the record to which the links were copied is displayed in a message box. The process is repeated until there is no more record in the range. The CLOSE Function (RecordRef) closes the table. This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRecref | RecordRef | Not applicable
MyFieldRef | FielRef | Not applicable
VendorRecord | Record | Vendor
Count | Integer | Not applicable

Text constant name | DataType | ENU value
Text000 | Text | The links have been copied to %1.
Copy Code
CustomerRecref.OPEN(DATABASE::Customer);
MyFieldRef := CustomerRecref.FIELD(1);
MyFieldRef.SETRANGE('30000' , '40000');
VendorRecord.SETRANGE("No.", '10000');
Count := 0;
IF CustomerRecref.FIND('-') THEN
  REPEAT
    Count := Count + 1;
    CustomerRecref.COPYLINKS(VendorRecord);
    MESSAGE(Text000, CustomerRecref.RECORDID);
  UNTIL CustomerRecref.NEXT = 0;
CustomerRecref.CLOSE;

See Also

Reference

RecordRef Data Type


COUNT Function (RecordRef)

Counts the number of records that are in the filters that are currently applied to the table referred to by the RecordRef.

Number := RecordRef.COUNT

Parameters

RecordRef

Type: RecordRef

The RecordRef that refers to the table.

Property Value/Return Value

Type: Integer

The number of records in the table.

Remarks

This function returns the number of records that meet the conditions of any filters associated with the records. If no filters are set, the function shows the total number of records in the table.

Note
The COUNT function does not lock the table before it retrieves the number of records in the table. This means that the function reads both uncommitted and committed data, which could cause the number of records that is returned to be inaccurate. To make sure that the count is accurate, use the LOCKTABLE Function (RecordRef) before you use the COUNT function.

In previous versions of Microsoft Dynamics NAV, the COUNT function ignored security filters and always returned the total number of records unless you called the SETPERMISSIONFILTER function to get a filtered count. In Microsoft Dynamics NAV 2016, the COUNT function adheres to the SecurityFiltering Property. For more information, see Security Filter Modes.

This function works just like the COUNT Function (Record).

Example

The following example opens table number 18 (Customer) as a RecordRef that is named MyRecordRef. The LOCKTABLE Function (RecordRef) locks the table. The COUNT function then retrieves the number of records in the table. The number of records is stored in the Count variable. The name of the table and the number of records in the table is displayed in a message box. The varTableNo variable can be used to open any table and get the number of records in that table by changing the value of the varTableNo variable. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
MyRecordRef | RecordRef
Count | Integer
varTableNo | Integer

Text constant name | DataType | ENU value
Text000 | Text | The number of records in the %1 table is: %2.
Copy Code
varTableNo := 18;
MyRecordRef.OPEN(varTableNo);
MyRecordRef.LOCKTABLE;
Count := MyRecordRef.COUNT;
MESSAGE(Text000, MyRecordRef.NAME, Count);

See Also

Reference

RecordRef Data Type


CURRENTCOMPANY Function (RecordRef)

Gets the current company of a database table referred to by a RecordRef.

CurrentCompany := RecordRef.CURRENTCOMPANY

Parameters

RecordRef

Type: RecordRef

A RecordRef that refers to the table for which you want to find the company that is currently in use.

Property Value/Return Value

Type: Text or code

The name of the current company of Record.

See Also

Reference

RecordRef Data Type
CURRENTCOMPANY Function (Record)


CURRENTKEY Function (RecordRef)

Gets the current key of the table referred to by the RecordRef. The current key is returned as a string.

CurrentKey := RecordRef.CURRENTKEY

Parameters

RecordRef

Type: RecordRef

The RecordRef that refers to the table for which you want to identify the current key.

Property Value/Return Value

Type: Text

The name of the current key of the record.

Example

This example requires that you create the following text constants and variables in the C/AL Globals window.

Text constant | ENU value
Text000 | The current key in the "%1" table is "%2".

Variable | Data type
RecRef | RecordRef
Copy Code
RecRef.OPEN(18);
MESSAGE(Text000,RecRef.CAPTION,RecRef.CURRENTKEY)

RecRef.Open(18) - Opens table 18 or causes a run-time error if table 18 does not exist.

RecRef.Caption - Returns the caption of the table.

RecRef.CURRENTKEY - Returns the caption of the current key in the table.

See Also

Reference

RecordRef Data Type


CURRENTKEYINDEX Function (RecordRef)

Gets or sets the current key of the table referred to by the RecordRef. The current key is set or returned as a number. This first key = 1, and so on.

Warning
If RecordRef does not have an active record, CURRENTKEYINDEX will return -1. If this value is then passed to KEYINDEX, an index out of bounds error will occur. Therefore it is important to implement a check of the RecordRef parameter.

[CurrKeyIndex :=] RecordRef.CURRENTKEYINDEX([NewKeyIndex])

Parameters

RecordRef

Type: RecordRef

NewKeyIndex

Type: Integer

The number of the new key.

Property Value/Return Value

Type: Integer

The number of the current key.

Example

The following example loops through four tables (36-39) opens each table as a RecordRef variable that is named MyRecordRef. The CURRENTKEYINDEX function retrieves the current key index of the tables. The name of the table and the current key index of each table are displayed in a message box. Each table is close before the next one is opened. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
MyRecordRef | RecordRef
CurrentKeyIndex | Integer
i | Integer
varFromTable | Integer
varToTable | Integer

Text constant name | DataType | ENU value
Text000 | Text | Table: %1 Current key index: %2
Copy Code
varFromTable := 36;
varToTable := 39;
FOR i := varFromTable TO varToTable DO BEGIN
  MyRecordRef.OPEN(i);
  CurrentKeyIndex := MyRecordRef.CURRENTKEYINDEX;
  MESSAGE(Text000, MyRecordRef.NAME, CurrentKeyIndex);
  MyRecordRef.CLOSE;
END

See Also

Reference

RecordRef Data Type


DELETE Function (RecordRef)

Deletes a record in a table.

[Ok :=] RecordRef.DELETE([RunTrigger])

Parameters

RecordRef

Type: RecordRef

The RecordRef that refers to the record that you want to delete.

Warning
The record cannot be from table 2000000001, the Object table or table 2000000006, the Company table.

RunTrigger

Type: Boolean

Specifies whether the code in the OnDelete trigger will be executed. If this parameter is true, the code will be executed. If this parameter is false, then the code in the OnDelete trigger is not executed.

The default value is false.

This parameter is optional.

Property Value/Return Value

Type: Boolean

true if the record was deleted. false if the record was not deleted because it could not be found in the table, because the user did not have the correct permissions, or because the C/AL code terminated.

If the record is not deleted and you do not include a return value, then a run-time error occurs. If you include the return value, then you must handle any errors.

Remarks

The current key and any filters on the record do not affect this operation. The record to delete is identified by the values in its primary key.

If an end-user modifies a record between the time that another end-user or another process reads the record and modifies it, then the second user must refresh the value of the record variable before editing the record. Otherwise, the end-user receives the following run-time error:

Another user has modified the record for this <Table Name> after you retrieved it from the database.

Enter your changes again in the updated window, or start the interrupted activity again.

In earlier versions of Microsoft Dynamics NAV, certain situations allowed code that an end-user runs to modify a record after a newer version of the record was written and committed to the database. This would overwrite the newer changes. However, in Microsoft Dynamics NAV 2016, we have restricted the MODIFY Function (RecordRef), RENAME Function (RecordRef), and DELETE Function (RECORDREF) so that the end-user receives the following run-time error in these certain situations:

Unable to change an earlier version of the <Table Name> record. The record should be read from the database again. This is a programming error.

You must design your application so that you use the most up-to-date version of the record for modifications to the database. You use the GET Function (RecordRef) to refresh the record with the latest version.

Example

The following example deletes a record from the Customer table. The code starts by opening the Customer table (18) as a RecordRef variable that is named MyRecordRef. The FIELD Function (RecordRef) creates a FieldRef that is named MyFieldRef for field 1, which is the primary key of the Customer table. The VALUE Function (FieldRef, TestPage Field) assigns the value 10000 to the field that the MyFieldRef variable refers to. The FIND Function (RecordRef) searches the table for a record with field 1 = 10000. If the record is found, then it is deleted, the table is modified, and a message is displayed. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
varRecordToDelete | Code
MyRecordRef | RecordRef
MyFieldRef | FieldRef

Text constant name | ConstValue
Text000 | Customer %1 is deleted.
Copy Code
varRecordToDelete := '10000';
MyRecordRef.OPEN(18);
MyFieldRef := MyRecordRef.FIELD(1);
MyFieldRef.VALUE := varRecordToDelete;
IF MyRecordRef.FIND('=') THEN BEGIN
  IF MyRecordRef.DELETE THEN BEGIN
    MyRecordRef.MODIFY;
    MESSAGE(Text000, MyFieldRef.VALUE);
  END;
END;

See Also

Reference

RecordRef Data Type
OnDelete Trigger


DELETEALL Function (RecordRef)

Deletes all records in a table that fall within a specified range.

RecordRef.DELETEALL([RunTrigger])

Parameters

RecordRef

Type: RecordRef

Identifies the table in which the deletion will occur. Only those records selected by the filters set for RecordRef are deleted.

RunTrigger

Type: Boolean

Specifies whether the code in the OnDelete trigger will be executed. If this parameter is true, the code will be executed. If this parameter is false (default), the code will not be executed.

This parameter is optional.

Remarks

This function works the same way as the DELETEALL Function (Record).

Example

The following example opens table 18 (Customer) as a RecordRef variable that is named CustomerRecRef. The FIELD Function (RecordRef) creates a FieldRef variable that is named MyFieldRef for field 1 (No.). From the No. field, the SETRANGE Function (FieldRef) selects records in the range from 10000 to 20000. The number of records in the range is displayed in a message box. The DELETEALL function deletes all records in that range. The number of records is displayed again. This time, 0 is displayed because all the records in the range are deleted. This example requires that you create the following variable and text constant in the C/AL Globals window.

Variable name | DataType
CustomerRecRef | RecordRef
MyFieldRef | FieldRef

Text constant name | DataType | ENU value
Text000 | Text | The number of records in the range is %1.
Copy Code
CustomerRecRef.OPEN(18);
MyFieldRef := CustomerRecRef.FIELD(1);
MyFieldRef.SETRANGE('10000' , '20000');
MESSAGE(Text000 ,CustomerRecRef.COUNT);
CustomerRecRef.DELETEALL;
MESSAGE(Text000 ,CustomerRecRef.COUNT);

See Also

Reference

RecordRef Data Type
OnDelete Trigger


DELETELINK Function (RecordRef)

Deletes a specified link from a record in a table.

RecordRef.DELETELINK(ID)

Parameters

ID

Type: Integer

The ID of the link you want to delete.

Remarks

When you add a link to a page or a table, an entry is created in the Record Link system table. Each entry is given an ID. This ID is specified as a parameter in the DELETELINK function.

Example

The following example deletes a link from a customer record in the Customer table. The code starts by opening table 18 (Customer) as a RecordRef variable that is named CustomerRecref. The FIELD Function (RecordRef) creates a FieldRef variable that is named MyFieldRef for the first field in the table (No.). MyFieldRef.VALUE selects record 01121212 from the No. field. This record is initialized in the CustomerNum variable. The FIND Function (RecordRef) searches for record 01121212. If the record is found, the DELETELINK function deletes the link that is specified in the varLinkid variable. A message that states that the link is deleted is displayed in a message box. You can verify that the link is deleted in the Links FactBox on the Customer List or Customer Card pages. This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
CustomerNum | Integer
varLinkid | Integer
CustomerRecref | RecordRef
MyFieldRef | FieldRef

Text constant name | DataType | ENU value
Text000 | Text | The link with id %1 is deleted.
Text001 | Text | The customer cannot be found.
Copy Code
CustomerNum := '01121212';
varLinkid := 21;
CustomerRecref.OPEN(18);
MyFieldRef := CustomerRecref.FIELD(1);
MyFieldRef.VALUE := CustomerNum;
IF CustomerRecref.FIND('=') THEN BEGIN
  CustomerRecref.DELETELINK(varLinkid);
  MESSAGE(Text000, varLinkid);
END
ELSE
  MESSAGE(Text001);

See Also

Reference

RecordRef Data Type


DELETELINKS Function (RecordRef)

Deletes all of the links that have been added to a record.

RecordRef.DELETELINKS

Parameters

RecordRef

Type: RecordRef

The record in the table where the links should be deleted from.

Example

The following example deletes all links from a customer record in the Customer table. The code starts by opening table 18 (Customer) as a RecordRef variable that is named CustomerRecref. The FIELD Function (RecordRef) creates a FieldRef variable that is named MyFieldRef for the first field in the table (No.). MyFieldRef.VALUE selects record 01121212 from the No. field. This record is initialized in the CustomerNum variable. The FIND Function (RecordRef) searches for record 01121212. If the record is found, the DELETELINKS function deletes all the links in the record. A message that states that the links are deleted is displayed in a message box. You can verify that the links are deleted in the Links FactBox on the Customer List or Customer Card pages. This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
CustomerNum | Integer
CustomerRecref | RecordRef
MyFieldRef | FieldRef

Text constant name | DataType | ENU value
Text000 | Text | All the links for customer %1 have been deleted.
Text001 | Text | The customer cannot be found.
Copy Code
CustomerNum := '01121212';
CustomerRecref.OPEN(18);
MyFieldRef := CustomerRecref.FIELD(1);
MyFieldRef.VALUE := CustomerNum;
IF CustomerRecref.FIND('=') THEN BEGIN
  CustomerRecref.DELETELINKS;
  MESSAGE(Text000, CustomerNum);
END
ELSE
  MESSAGE(Text001);

See Also

Reference

RecordRef Data Type


DUPLICATE Function (RecordRef)

Duplicates the table that contains the RecordRef.

RecordRef := RecordRef.DUPLICATE

Parameters

RecordRef

Type: RecordRef

The RecordRef that identifies the record and the table that you want to duplicate.

Property Value/Return Value

Type: RecordRef

Remarks

The RecordRef that is returned refers to a new record with the same filters, current keys, and marks as the original RecordRef. Any changes that you make to the filters, current keys, and marks of the new record are not observed in the original. This differs from assigning one RecordRef to another RecordRef. If you assign one RecordRef to another RecordRef, then both refer to the same record and changes that you make to one RecordRef are observed in the other RecordRef.

Example

The following example opens table 18 (Customer) as a RecordRef variable named RecordRef1 and uses the DUPLICATE function to copy the filters, current keys and marks from RecordRef1 into a new RecordRef variable named RecordRef2. After the DUPLICATE function is executed, the RecordRef1 and RecordRef2 variables are identical. This example requires that you create the following variables and text constant in the C/AL Globals windows.

Name | DataType
RecordRef1 | RecordRef
RecordRef2 | RecordRef

Text constant name | ENU value
Text000 | 'RecordRef1 refers to the %1 table.\ RecordRef2 refers to the %2 table.'
Copy Code
RecordRef1.OPEN(18);
RecordRef2 := RecordRef1.DUPLICATE;
MESSAGE(Text000, RecordRef1.CAPTION, RecordRef2.CAPTION);

See Also

Reference

RecordRef Data Type


FIELD Function (RecordRef)

Gets a FieldRef for the field that has the number FieldNo in the table that is currently selected. If no field has this number, the function returns an error.

FieldRef := RecordRef.FIELD(FieldNo)

Parameters

RecordRef

Type: RecordRef

The RecordRef of the record for which you want the fieldref.

FieldNo

Type: Integer

The number that the field has in the table that is currently selected. This is the field for which you want the fieldref.

Property Value/Return Value

Type: FieldRef

Remarks

This function returns an error if the record is not opened and if the field is not found.

You might obtain better performance by using the FIELDINDEX Function (RecordRef).

Example

The following example opens table 18 (Customer) as a RecordRef variable that is named MyRecordRef. MyRecordRef uses the FIELD function to create a reference to the No. field (field 1). The value in the No. field is then set to a specified record No. In this example, the record is set to 30000. The FIND Function (RecordRef) function searches the records for record 30000. If record is found, the FIELD function retrieves the value in the Name field (field 2), stores it in the varOldName variable and displays it in a message box. The VALUE Function (FieldRef, TestPage Field) changes the value in the Name field to a new name. In this example, the new name is ‘Contoso’. The table is then modified to reflect this change and the new value in the Name field is retrieved and displayed in a message box. You can specify any record in the table and change the value in the Name field. This example requires that you create the following variables in the C/AL Globals window.

Name | DataType
MyRecordRef | RecordRef
MyFieldRef | FieldRef
varOldName | FieldRef
varNewName | Text
MyRecord | Code
Copy Code
MyRecord := '30000';
varNewName := 'Contoso';
MyRecordRef.OPEN(18);
MyFieldRef := MyRecordRef.FIELD(1);
MyFieldRef.VALUE := MyRecord;
IF MyRecordRef.FIND('=') THEN BEGIN
  varOldName := MyRecordRef.FIELD(2);
  MESSAGE('Old Name: %1', varOldName);
  varOldName.VALUE := varNewName;
  MyRecordRef.MODIFY;
  MESSAGE('New Name: %1', MyRecordRef.FIELD(2));
END;

See Also

Reference

RecordRef Data Type


FIELDCOUNT Function (RecordRef)

Gets the number of fields in the table that are currently selected or returns the number of fields that have been defined in a key. Returns an error if no table or no key is selected.

Count := RecordRef.FIELDCOUNT

Parameters

RecordRef

Type: RecordRef

The RecordRef of the record that you use to identify the table.

Property Value/Return Value

Type: Integer

The number of fields in the table.

Example

The following example loops through tables 3 through 5 and displays the number of fields that are defined in each table. The code starts by opening table 3 (Payment Terms) as a RecordRef variable that is named MyRecordRef. MyRecordRef variable uses the FIELDCOUNT function to retrieve the number of fields that are defined in the table and stores it in the varFieldCount variable. The name of each table and the total number of fields in the table are displayed in a message box. The table that is open is closed before the next one is open. This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
MyRecordRef | RecordRef
varFieldCount | Integer

Text constant name | DataType | ENU value
Text000 | Text | The %1 table contains %2 field(s).\
Copy Code
FOR i := 3 TO 5 DO BEGIN
  MyRecordRef.OPEN(i);
  varFieldCount := MyRecordRef.FIELDCOUNT;
  MESSAGE(Text000, MyRecordRef.NAME, varFieldCount);
  MyRecordRef.CLOSE;
 END;

See Also

Reference

RecordRef Data Type


FIELDEXIST Function (RecordRef)

Determines if the field that has the number FieldNo exists in the table that is referred to by the RecordRef. Returns an error if no table is currently selected.

Exist := RecordRef.FIELDEXIST(FieldNo)

Parameters

RecordRef

Type: RecordRef

The RecordRef that identifies the record and the table in which you are interested.

FieldNo

Type: Integer

The FieldNo that you want to know whether it exists in the table.

Property Value/Return Value

Type: Boolean

true if the field exists in the table; otherwise, false.

Example

The following example opens table 18 (Customer) as a RecordRef variable that is named MyRecordRef. The code loops through fields 1 through 12 and uses the FIELDEXIST function to determine whether the specified field exists. If the field exists, the name of the field and a message that indicates that the field exists is displayed. Otherwise, a message that indicates that the field does not exist is displayed. This example requires that you create the following variables and text constants in the C/AL Globals window.

Name | DataType
MyRecordRef | RecordRef
i | Integer
VarFieldName | FieldRef

Text constant name | DataType | ENU value
Text000 | Text | Field %1 exists.\The name of the Field is: " %2 ".
Text001 | Text | Field %1 does not exist.
Copy Code
MyRecordRef.OPEN(18);
FOR i := 1 TO 12 DO BEGIN
  IF MyRecordRef.FIELDEXIST(i) THEN BEGIN
     VarFieldName := MyRecordRef.FIELD(i);
     MESSAGE(Text000, i, VarFieldName.NAME);
    END
  ELSE
    MESSAGE(Text001, i);
  END;

See Also

Reference

RecordRef Data Type


FIELDINDEX Function (RecordRef)

Gets the FieldRef of the field that has the specified index in the table that is referred to by the RecordRef.

Field := RecordRef.FIELDINDEX(Index)

Parameters

RecordRef

Type: RecordRef

Index

Type: Integer

Property Value/Return Value

Type: FieldRef

The FieldRef of the field that has the specified index.

Remarks

The fields in the primary key are always listed first in the index. Therefore, the order of the fields in the index is not necessarily the same as the order of the fields in the table.

If the index is out of the range supplied or if no table is selected, then the function returns an error.

Example

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Length
SalesInvHdr | RecordRef | Not applicable
FldRef | FieldRef | Not applicable
Str | Text | 1024

Text constant name | Constant value
Text001 | Index 1: %1\
Text002 | Index 2: %2\
Text003 | Index 3: %2
Copy Code
SalesInvHdr.OPEN(112);
FldRef1 := SalesInvHdr.FIELDINDEX(1);
FldRef2 := SalesInvHdr.FIELDINDEX(2);
FldRef3 := SalesInvHdr.FIELDINDEX(3);
MESSAGE(Text001 + Text002 + Text003, FldRef1.CAPTION, FldRef2.CAPTION, FldRef3.CAPTION);

The message window displays the following:

  • Index 1: No.

  • Index 2: Sell-to Customer No.

  • Index 3: Bill-to Customer No.

The following illustration shows the first fields in table 112, Sales Invoice Header, when you design the table in Object Designer, and shows the keys for table 112. The order of the fields in the index differs from the order of the fields in the table. The index lists the field in the primary key first.

Table 112 designer and keys

See Also

Reference

RecordRef Data Type


FILTERGROUP Function (RecordRef)

Changes the filter group that is being applied to the table. You can also use this function to return the number of the current filtergroup. You cannot return the number of the filtergroup and set a new filtergroup at the same time.

[CurrGroup :=] RecordRef.FILTERGROUP([NewGroup])

Parameters

RecordRef

Type: RecordRef

The recordref that is used to identify the table.

NewGroup

Type: Integer

Property Value/Return Value

Type: Integer

Remarks

A filtergroup can contain a filter for a RecordRef that has been set earlier with SETFILTER or SETRANGE. The total filter applied is the combination of all the filters set in all the filtergroups.

This function works the same way as the FILTERGROUP Function (Record).

Example

The following example determines the filtergroup that is set on the Customer table and then changes filtergroup to 1, which is the filtergroup that is applied globally to the entire application. The code starts by opening the Customer table with a RecordRef variable. The SETRECFILTER Function (RecordRef) sets the values in the current key of the current record as a record filter. This filter is a standard filtergroup so it has a filtergroup number of 0. Then the FILTERGROUP function returns the number for the filtergroup. This filtergroup is a standard filter so the return value is 0. This value is stored in the varOrigGroup variable and displayed in a message box. The FILTERGROUP function changes the filtergroup to 1, which is the number for the global filtergroup. The new value is stored in the varCurrGroup variable and displayed in a message box. This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
MyRecordRef | RecordRef
varOrigGroup | Integer
varCurrGroup | Integer

Text constant name | ENU value
Text000 | The original filtergroup is: %1
Text001 | The current filtergroup is: %1
Copy Code
MyRecordRef.OPEN(DATABASE::Customer);
MyRecordRef.SETRECFILTER;
varOrigGroup := MyRecordRef.FILTERGROUP;
MESSAGE(Text000, varOrigGroup);
varCurrGroup := MyRecordRef.FILTERGROUP(1);
MESSAGE(Text001, varCurrGroup);

See Also

Reference

RecordRef Data Type


FIND Function (RecordRef)

Finds a record in a table based on the values stored in the key fields.

[Ok :=] RecordRef.FIND([Which])

Parameters

RecordRef

Type: RecordRef

The RecordRef that refers to the table in which you want to find a record.

Which

Type: Text or code

Specifies how to perform the search. The table will be searched until the record is found or there are no more records. Each character in the string can be present only one time. You can use the following characters:

  • = search for a record that equals the key values (default)

  • > search for a record that is larger than the key values

  • < search for a record that is less than the key values

  • + search for the last record in the table (+ can only be used alone)

  • - search for the first record in the table (- can only be used alone)

You can combine the '=', '<', and '>' characters.

If this parameter contains '=', '>', or '<', then you must assign value to all fields of the current and primary keys before you call FIND.

Property Value/Return Value

Type: Boolean

true if the record was found; otherwise, false.

If you omit this optional return value and the record cannot be found, a run-time error occurs. If you include a return value, it is assumed that you will handle any errors.

Remarks

FIND retrieves the first record that meets the conditions set by the Which parameter and the filters associated with the record. The search path reflects the sort order defined by the current key. If the current key is not the primary key, there is a chance that several records might have the same values in current key fields. If this occurs, the sort order defined by the primary key is used as the search path.

Example

The following example opens table 18 (Customer) as a RecordRef variable named CustomerRecref. The value for the field 1 (No.) is set to a specified record. In this example, the field is set to record 40000. The code uses the FIND function to find the record that matches. 40000 in the table. If the record is found, the number, name, address and city of the customer are displayed in message boxes. The values in the fields are retrieved by using the FIELD Function (RecordRef). This example requires that you create the following variables and text constants in the C/AL Globals window.

Name | DataType
CustomerRecref | RecordRef
MyFieldRef | FieldRef
varCustomerNo | Code

Text constant name | ConstValue
Text000 | The customer was found.\
Text001 | Customer No. %1 is:\%2
Text002 | Sorry, that customer could not be found.
Copy Code
varCustomerNo := '40000';
CustomerRecref.OPEN(18);
MyFieldRef := CustomerRecref.FIELD(1);
MyFieldRef.VALUE := varCustomerNo;
IF CustomerRecref.FIND('=') THEN BEGIN
  MESSAGE(Text000 + Text001,  CustomerRecref.FIELD(1), CustomerRecref.FIELD(2));
  MESSAGE('Address: %1, %2',  CustomerRecref.FIELD(5),  CustomerRecref.FIELD(7));
END
ELSE
  MESSAGE(Text002);

See Also

Reference

RecordRef Data Type


FINDFIRST Function (RecordRef)

Finds the first record in a table based on the current key and filter.

[Ok :=] RecordRef.FINDFIRST

Parameters

RecordRef

Type: RecordRef

The RecordRef that refers to the table in which you want to find a record.

If the record is found, it is returned in RecordRef and any FlowFields in the record are set to zero. You must update any FlowFields using CALCFIELDS Function (Record).

Property Value/Return Value

Type: Boolean

true if the record was found; otherwise, false.

If you omit this optional return value and if the record cannot be found, a run-time error occurs. If you include a return value, it is assumed that you will handle any errors.

Remarks

You should use this function instead of FIND('-') when you need only the first record.

You should use this function only when you explicitly want to find the first record in a table or set. Do not use this function in combination with REPEAT..UNTIL.

Example

The following example opens the Item table (27) as a RecordRef variable that is named ItemRecref. The FINDFIRST function searches for the first record in the table. If the record is found, the description and unit price of the item in the record are displayed in a message box. Otherwise, a message that indicates that the first item was not found is displayed. This example requires that you create the following variable and text constant in the C/AL Globals window.

Variable name | DataType
ItemRecref | RecordRef

Text constant name | DataType | ENU value
Text000 | Text | The first item is %1 and the unit price is %2.
Text001 | Text | The first item was not found.
Copy Code
ItemRecref.OPEN(27);
IF ItemRecref.FINDFIRST THEN
  MESSAGE(Text000, ItemRecref.FIELD(3),  ItemRecref.FIELD(18))
ELSE
  MESSAGE(Text001);

See Also

Reference

RecordRef Data Type
FIND Function (RecordRef)
FINDLAST Function (RecordRef)
FINDSET Function (RecordRef)


FINDLAST Function (RecordRef)

Finds the last record in a table based on the current key and filter.

[Ok :=] RecordRef.FINDLAST

Parameters

RecordRef

Type: RecordRef

The RecordRef that refers to the table in which you want to find the last record.

If the record is found, it is returned in RecordRef and any FlowFields in the record are set to zero. You must update any FlowFields using CALCFIELDS Function (Record).

If the record is not found and if you omitted the return value, a run-time error occurs.

Property Value/Return Value

Type: Boolean

true if the record was found; otherwise, false.

If you omit this optional return value and if the record cannot be found, a run-time error occurs. If you include a return value, it is assumed that you will handle any errors.

Remarks

You should use this function instead of FIND('+') when you need only the last record.

You should use this function only when you explicitly want to find the last record in a table or set. Do not use this function in combination with REPEAT..UNTIL.

Example

The following example opens the Item table (27) as a RecordRef variable that is named ItemRecref. The FINDLAST function searches for the last record in the table. If the record is found, the description and unit price of the item in the record are displayed in a message box. Otherwise, a message that indicates that the last item was not found is displayed. This example requires that you create the following variable and text constant in the C/AL Globals window.

Variable name | DataType
ItemRecref | RecordRef

Text constant name | DataType | ENU value
Text000 | Text | The last item is %1 and the unit price is %2.
Text001 | Text | The last item was not found.
Copy Code
ItemRecref.OPEN(27);
IF ItemRecref.FINDLAST THEN
  MESSAGE(Text000, ItemRecref.FIELD(3),  ItemRecref.FIELD(18))
ELSE
  MESSAGE(Text001);

See Also

Reference

RecordRef Data Type
FIND Function (RecordRef)
FINDFIRST Function (RecordRef)
FINDSET Function (RecordRef)


FINDSET Function (RecordRef)

Finds a set of records in a table based on the current key and filter. FINDSET can only retrieve records in ascending order.

[Ok :=] RecordRef.FINDSET([ForUpdate][,UpdateKey])

Parameters

RecordRef

Type: RecordRef

The RecordRef that refers to the table in which you want to find the set of records.

If the record is found, it is returned in RecordRef and any FlowFields in the record are set to zero. You must update any FlowFields using CALCFIELDS Function (Record).

If the record is not found and if you omitted the return value, a run-time error occurs.

ForUpdate

Type: Boolean

Set this parameter to false if you do not want to modify any records in the set. Set this parameter to true if you want to modify records in the set.

If you set this parameter to true, the LOCKTABLE Function (RecordRef) is immediately performed on the table before the records are read.

UpdateKey

Type: Boolean

This parameter only applies if ForUpdate is true.

If you are going to modify any field value within the current key, set this parameter to true.

Property Value/Return Value

Type: Boolean

true if the record set was found; otherwise, false.

If you omit this optional return value and if the record cannot be found, a run-time error occurs. If you include a return value, it is assumed that you will handle any errors.

Remarks

You should use this function only when you explicitly want to loop through a recordset. You should only use this function in combination with REPEAT..UNTIL.

Furthermore, FINDSET only allows you to loop through the recordset from the top down. If you want to loop from the bottom up, you should use FIND(‘+’).

The general rules for using FINDSET are the following:

  • FINDSET(FALSE,FALSE) - Read-only. This uses no server cursors and the record set is read with a single server call.

  • FINDSET(TRUE,FALSE) - This is used to update non-key fields. This uses a cursor with a fetch buffer similar to FIND(‘-’).

  • FINDSET(TRUE,TRUE) - This is used to update key fields.

This function is designed to optimize finding and updating sets. If you set any or both of the parameters to false, you can still modify the records in the set but these updates will not be performed optimally.

This function works the same way as the FINDSET Function (Record).

Example

The following example opens table 18 (Customer) as a RecordRef variable that is named MyRecordRef. The FIELD Function (RecordRef) creates a FieldRef variable that is named MyFieldRef with the first field (No.). The SETFILTER Function (FieldRef) uses the MyFieldRef variable to set a filter that selects records from 30000 to 32000. MyRecordRef.FIELD(2) creates a FieldRef for the second field (Name). The FINDSET function finds the set of records based on the key and the filters that have been set. The ForUpdate parameters and UpdateKeys are both set to FALSE. This makes the records in the set read-only. The record ID and name of each customer in the record set is displayed in a message box until no records are left in the record set. The following example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
MyRecordRef | RecordRef
MyFieldRef | FieldRef

Text constant name | DataType | ENU value
Text000 | Text | %1: "%2" is found in the set of records.
Copy Code
MyRecordRef.OPEN(18);
MyFieldRef := MyRecordRef.FIELD(1);
MyFieldRef.SETFILTER('30000..32000');
MyFieldRef := MyRecordRef.FIELD(2);
IF MyRecordRef.FINDSET(FALSE, FALSE) THEN BEGIN
  REPEAT
    MESSAGE(Text000 , MyRecordRef.RECORDID, MyFieldRef.VALUE);
  UNTIL MyRecordRef.NEXT = 0;
END;

See Also

Reference

RecordRef Data Type
FIND Function (RecordRef)
FINDFIRST Function (RecordRef)
FINDLAST Function (RecordRef)


GET Function (RecordRef)

Gets a record based on the ID of the record.

[Ok :=] RecordRef.GET(RecordID)

Parameters

RecordRef

Type: RecordRef

The RecordRef that refers to a table.

RecordID

Type: RecordID

The RecordID that contains the table number and the primary key of the table and is used to identify the record that you want to get.

Property Value/Return Value

Type: Boolean

true if the record was found; otherwise, false.

If you omit this optional return value and if the record cannot be found, then a run-time error occurs. If you include the return value, you must handle any errors.

Remarks

This function always uses the primary key for the table. It ignores any filters that are set, except security filters. Security filters are applied or ignored based on the Security Filter Mode. The current key and filters are not changed after you call this function. For more information, see Security Filter Modes.

Example

The following example opens the Customer table with the RecordRef variable, RecRef. The code assigns the first field in the table, which is the No. field, to MyFieldRef variable. The variable is assigned a value of 30000 by using the FIELD Function (RecordRef). The RECORDID Function (RecordRef) retrieves the record ID of the record that has a value of 30000 in the No. field. The GET function then uses the RecID variable then to retrieves the record. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType
RecRef | RecordRef
MyFieldRef | FieldRef
RecID | RecordID
Copy Code
RecRef.OPEN(DATABASE::Customer);
MyFieldRef := RecRef.FIELD(1);
MyFieldRef.VALUE := '30000';
IF RecRef.FIND('=') THEN BEGIN
  RecID := RecRef.RECORDID;
  RecRef.GET(RecID);
END

See Also

Reference

RecordRef Data Type
FILTERGROUP Function (Record)


GETFILTERS Function (RecordRef)

Determines which filters have been applied to the table referred to by the RecordRef.

String := RecordRef.GETFILTERS

Parameters

RecordRef

Type: RecordRef

The RecordRef to use to identify the record in the table on which filters may have been applied.

Remarks

This function works just like the GETFILTERS Function (Record).

Property Value/Return Value

Filters that have been applied to the table that is referred to by the RecordRef parameter.

Example

The following example opens a table as a RecorRef variable. The variable, RecRef, is used with the GETFILTERS function to retrieve the filters that are applied in the Customer table. If filters are applied, they will be stored in the Filters1 variable. The Filters1 variable does not contain any filters because filters have not been set. Then the SETRECFILTER Function (RecordRef) is used to set the value in the current key of the current record as a filter. The variable Filters2 will now contain No. as a filter. The example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
RecRef | RecordRef
Filters1 | Text
Filters2 | Text

Text constant name | DataType | ENU value
Text000 | Text | Filters1 contains : %1 Filters2 contains: %2
Copy Code
RecRef.OPEN(DATABASE::Customer);
Filters1 := RecRef.GETFILTERS;
RecRef.SETRECFILTER;
Filters2 := RecRef.GETFILTERS;
MESSAGE(Text000, Filters1, Filters2);

See Also

Reference

RecordRef Data Type


GETPOSITION Function (RecordRef)

Gets a string that contains the primary key of the current record.

String := RecordRef.GETPOSITION([UseNames])

Parameters

RecordRef

Type: RecordRef

The RecordRef that refers to the record for which you want to know the primary key.

UseNames

Type: Boolean

Indicates whether a reference to the field name or the field number should be returned.

If this parameter is true (default) or if it is empty, the returned string contains references to field names in the table with which the record is associated. If the parameter is false, the returned string contains references to field numbers in the table with which the record is associated.

This parameter is optional.

Property Value/Return Value

Type: Text or code

The name or number of the field that contains the primary key.

Remarks

This function works just like the GETPOSITION Function (Record).

Example

The following example opens the Customer table as a RecodRef that is named RecRef. The RecordRef variable uses the GETPOSITION function to retrieve the position of the primary key. The UseNames parameter is set to true so the name of the field that contains the primary key is returned. If you set UseNames to false, the number of the field is returned. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType
RecRef | RecordRef
varPrimaryKey | Text

Text constant | ENU value
Text000 | The primary key is: %1.
Copy Code
RecRef.OPEN(DATABASE::Customer);
varPrimaryKey := RecRef.GETPOSITION(TRUE);
MESSAGE(Text000, varPrimaryKey);

See Also

Reference

RecordRef Data Type


GETTABLE Function (RecordRef)

Gets the table of a Record variable and causes the RecordRef to refer to the same table.

RecordRefVar.GETTABLE(RecordVar)

Parameters

RecordRefVar

Type: RecordRef

The RecordRef for which you want to specify a table.

RecordVar

Type: Record

Use this record variable to specify the table to which the RecordRefVar refers.

Remarks

Any filters that are applied to the RecordVar are also applied to the RecordRefVar.

Another way to select the table to which a RecordRef refers is to use the OPEN Function (RecordRef) and specify a table number in the parameters.

Example

The following example is an excerpt from codeunit 8, AccSchedManagement. It iterates through records in the G/L Account table. It sets some values on the fields of a new record in the Acc. Schedule Line table based on the current G/L Account record and inserts the new record into the Acc. Schedule Line table. It calls GETTABLE to cause a RecordRef variable to refer to the same table as the new Acc. Schedule Line record, and then calls the LogInsertion function from codeunit 423, Change Log Management to log the change. The LogInsertion function requires a RecordRef as a parameter.

This example requires that you create the following variables.

Variable name | DataType | Subtype
AccSchedLine | Record | Acc. Schedule Line
AccSchedLineNo | Integer | Not applicable
GLAcc | Record | G/L Account
RecRef | RecordRef | Not applicable
ChangeLogMgt | Codeunit | Change Log Management

This example assumes that the AccSchedLineNo variable has been assigned a value previously in the code.

Copy Code
IF GLAcc.FIND('-') THEN
  REPEAT
    AccSchedLine.INIT;
    AccSchedLine."Line No." := AccSchedLineNo;
    AccSchedLineNo := AccSchedLineNo + 10000;
    AccSchedLine.Description := GLAcc.Name;
    IF GLAcc."Account Type" IN [GLAcc."Account Type"::Posting,GLAcc."Account Type"::Total,GLAcc."Account Type"::"End-Total"] THEN BEGIN
      AccSchedLine.Totaling := GLAcc."No.";
      AccSchedLine."Row No." := COPYSTR(GLAcc."No.",1,MAXSTRLEN(AccSchedLine."Row No."));
    END;
    IF GLAcc."Account Type" IN [GLAcc."Account Type"::Total,GLAcc."Account Type"::"End-Total"] THEN
      AccSchedLine."Totaling Type" := AccSchedLine."Totaling Type"::"Total Accounts"
    ELSE
      AccSchedLine."Totaling Type" := AccSchedLine."Totaling Type"::"Posting Accounts";
    AccSchedLine.INSERT;
    RecRef.GETTABLE(AccSchedLine);
    ChangeLogMgt.LogInsertion(RecRef);
  UNTIL GLAcc.NEXT = 0;

See Also

Reference

RecordRef Data Type
SETTABLE Function (RecordRef)


GETVIEW Function (RecordRef)

Returns a string that describes the current sort order, key, and filters on a table.

String := RecordRef.GETVIEW([UseNames])

Parameters

RecordRef

Type: RecordRef

The RecordRef that refers to the table.

If no table is selected, the function returns an empty string.

UseNames

Type: Boolean

If this parameter is true (default) or if it is empty, the returned string contains references to field captions in the table with which the record is associated. If this parameter is false, the returned string contains references to field numbers in the table with which the record is associated.

This parameter is optional.

Property Value/Return Value

Type: Text or code

The string format is the same as the SourceTableView Property on pages.

Remarks

If the SETVIEW Function (RecordRef) has been executed, the String parameter will return the value set by SETVIEW.

This function works the same way as the GETVIEW Function (Record).

Example

The following example opens the Customer table as a RecordRef variable that is named RecRef. The RecRef variable uses the GETVIEW function to retrieve the field that the table is sorted on and stores the value in the varView variable. The Customer table does not have any filters and keys set so no filters or keys are displayed. The UseNames parameter is set to true so the name of the field is displayed. If you set the UseNames to false, the field number will be displayed. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
RecRef | RecordRef
varView | Text

Text constant name | DataType | ENU value
Text000 | Text | The current view of the table is: %1.
Copy Code
RecRef.OPEN(DATABASE::Customer);
varView := RecRef.GETVIEW(TRUE);
MESSAGE(Text000, varView);

See Also

Reference

RecordRef Data Type


HASFILTER Function (RecordRef)

Determines whether a filter has been applied to the table that the RecordRef refers to.

Ok := RecordRef.HASFILTER

Parameters

RecordRef

Type: RecordRef

The RecordRef that is used to identify the table.

Property Value/Return Value

Type: Boolean

true if the table referred to by RecordRef has a filter; otherwise, false.

If you omit this return value and if the record cannot be found, a run-time error occurs. If you include the return value, it is assumed that you will handle any errors.

Remarks

This function works just like the HASFILTER Function (Record).

Example

The following example opens the Customer table with a RecordRef variable that is named RecRef. The HASFILTER function determines whether a filter has been applied in the Customer table. The function returns false because no filters are applied. The return value is stored in the varHasFilters variable. The SETRECFILTER Function (RecordRef) is used to set a filter. The HASFILTER function now returns true. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
RecRef | RecordRef
varHasFilters | Text

Text constant name | DataType | ENU value
Text000 | Text | Are there any filters? %1
Copy Code
RecRef.OPEN(DATABASE::Customer);
VarHasFilters := RecRef.HASFILTER;
MESSAGE('Are there any filters? %1', VarHasFilters);
RecRef.SETRECFILTER;
VarHasFilters := RecRef.HASFILTER;
MESSAGE(Text000, VarHasFilters);

See Also

Reference

RecordRef Data Type


HASLINKS Function (RecordRef)

Determines whether a record contains any links.

OK := HASLINKS

Property Value/Return Value

Type: Boolean

true if the record contains at least one link; otherwise, false.

Remarks

The link can be a link to a Web site, a file stored on the local computer or on a remote computer, or a link to a Microsoft Dynamics NAV page.

Example

The following example opens table 18 (Customer) as a RecordRef variable that is named CustomerRecref. The FIELD Function (RecordRef) creates a FieldRef variable for field 1 (No.) and stores the value in the MyFieldRef variable. The VALUE Function (FieldRef, TestPage Field) selects record number 20000. The HASLINKS function determines whether the selected record has any links. The function returns No because there are no links in the record. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
CustomerRecref | RecordRef
MyFieldRef | FieldRef
varHasLinks | Boolean

Text constant | ENU value
Text000 | Does this record have one or more links? %1.
Copy Code
CustomerRecref.OPEN(18);
MyFieldRef := CustomerRecref.FIELD(1);
MyFieldRef.VALUE := '20000';
varHasLinks := CustomerRecref.HASLINKS;
MESSAGE(Text000, varHasLinks);

See Also

Reference

RecordRef Data Type


INIT Function (RecordRef)

Initializes a record in a table.

RecordRef.INIT

Parameters

RecordRef

Type: RecordRef

The RecordRef that is used to identify the record that you want to initialize.

Remarks

This function assigns default values to each field in the record. The values that are assigned in the record correspond to those defined when the table was created. If no value was assigned when the table was created, the values are assigned based on the data type, as shown in the following table.

Data type | Default value
BigInteger | 0
BigText | <Empty>
BLOB | <Empty>
Boolean | No
Code | '' (empty string)
Date | 0d (Undefined date)
DateFormula | '' (empty string)
DateTime | 0DT (Undefined datetime)
Decimal | 0.0
Duration | 0
GUID | 00000000-0000-0000-0000-000000000000
Integer | 0
Option | 0
RecordID | <Empty>
TableFilter | <Empty>
Text | '' (empty string)
Time | 0T (Undefined time)

Primary key and timestamp fields are not initialized.

After the function executes, you can change the values in any or all of the fields before you call the INSERT Function (RecordRef) to enter the record in the table. Be sure that the fields that make up the primary key contain values that make the total primary key unique. If the primary key is not unique (such as the record already exists), then the record is rejected.

The function works the same as the INIT Function (Record).

Example

The following example opens a table 18 (Customer) with a RecordRef variable that is named CustomerRecref. The FIELD Function (RecordRef) creates a FieldRef variable that is named MyFieldRef for the field. The INIT function initializes the values in the fields by using default values and then uses the INSERT Function (RecordRef) to insert a new record. The new record is 1120. This is the primary key for the new record.

Note
In this example, the INIT function is called before the primary key is assigned a value. The INIT function does not initialize primary key fields. Therefore calling the INIT function before or after you assign values to the primary key field does not make any difference.

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
CustomerRecref | RecordRef
MyFieldRef | FieldRef

Text constant | ENU value
Text000 | The value of the field before initialization is %1.
Text001 | The value of the field after you insert the record is %1.
Copy Code
CustomerRecref.OPEN(18);
MyFieldRef := CustomerRecref.FIELD(1);
CustomerRecref.INIT;
MESSAGE(‘%1’, MyFieldRef.VALUE);
MyFieldRef.VALUE := '1120';
CustomerRecref.INSERT;
MESSAGE(‘%1’, MyFieldRef.VALUE);

See Also

Reference

RecordRef Data Type


INSERT Function (RecordRef)

Inserts a record into a table.

[Ok :=] RecordRef.INSERT([RunTrigger])

Parameters

RecordRef

Type: RecordRef

The RecordRef that refers to the record that you want to insert.

Warning
The record cannot be from table 2000000001, the Object table or table 2000000006, the Company table.

RunTrigger

Type: Boolean

Specifies whether to run the C/AL code in the OnInsert Trigger.

If this parameter is true, the code on the OnInsert trigger will be executed.

If this parameter is false, the code on the OnInsert trigger will not be exectued.

Property Value/Return Value

Type: Boolean

true if the record was inserted; otherwise, false.

If you omit this optional return value and if the record cannot be inserted, a run-time error occurs. If you include the return value, you must handle any errors.

Remarks

Records are uniquely identified by the values in primary key fields. The Database Management System (DBMS) checks the primary key for the table before it inserts a new record.

If the table contains an auto-increment field, the auto-increment feature is used if the record contains a zero value in that field. The auto-increment feature enters the new value into the field as part of the insert.

If the auto-increment field contains a non-zero value, that value is inserted into the table and the auto-increment feature is not used. If the value in the auto-increment field is greater than the last auto-increment value in the table, the next auto-increment value that is entered into the table will be greater than the value in the field that you just inserted. If the value in the auto-increment field already exists in the table, a run-time error occurs.

This function works the same as the INSERT Function (Record).

Example

The following example opens a table 18 (Customer) with a RecordRef variable that is named CustomerRecref. The FIELD Function (RecordRef) creates a FieldRef variable that is named MyFieldRef for the field. The INIT Function (RecordRef) initializes the values in the fields by using default values and then the INSERT function inserts a new record. The new record is 1120. This is the primary key for the new record.

Note
In this example, the INIT function is called before the primary key is assigned a value. The INIT function does not initialize primary key fields. Therefore calling the INIT Function (RecordRef) before or after you assign values to the primary key field does not make any difference.

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
CustomerRecref | RecordRef
MyFieldRef | FieldRef

Text constant | ENU value
Text000 | The value of the field after you insert the record is %1.
Copy Code
CustomerRecref.OPEN(18);
MyFieldRef := CustomerRecref.FIELD(1);
CustomerRecref.INIT;
MyFieldRef.VALUE := '1120';
CustomerRecref.INSERT;
MESSAGE(‘%1’, MyFieldRef.VALUE);

See Also

Reference

RecordRef Data Type


ISEMPTY Function (RecordRef)

Determines whether any records exist in a filtered set of records in a table.

Empty := RecordRef.ISEMPTY

Parameters

RecordRef

Type: RecordRef

The RecordRef of a record that refers to a table (possibly with filters).

Property Value/Return Value

Type: Boolean

true if the record or table is empty; otherwise, false.

Remarks

If you have not applied filters to the record, this function determines whether the table is empty. If you have applied filters, the function determines whether the filtered set of records is empty.

The number of filters that you have applied to the records affects the speed of the ISEMPTY function. The fewer the number of filters, the faster the operation is performed.

When you are using SQL Server, this function is faster than using the COUNT Function (Record) and then testing the result for zero.

This function works the same as the ISEMPTY Function (Record).

Example

The following example opens table 18, the customer table as a RecordRef variable that is named. CustomerRecref. The ISEMPTY Function (RecordRef) determines whether the table is empty. The message box displays No because the Customer table is not empty. No represents false. This example requires that you create the following variable text constant in the C/AL Global window.

Variable name | DataType
CustomerRecref | RecordRef

Text constant | ENU value
Text000 | Is the table empty? %1.
Copy Code
CustomerRecref.OPEN(18);
IsEmpty := CustomerRecref.ISEMPTY;
MESSAGE(Text000, IsEmpty);

If you open table 78 (Printer Selection), the message will display Yes because the table is empty.

See Also

Reference

RecordRef Data Type


ISTEMPORARY Function (RecordRef)

Determines whether a RecordRef refers to a temporary table.

Temp := RecordRef.ISTEMPORARY

Parameters

RecordRef

Type: RecordRef

The RecordRef of a record that refers to a table.

Property Value/Return Value

Type: Boolean

true if the RecordRef refers to a temporary table; otherwise, false.

Remarks

In versions of Microsoft Dynamics NAV earlier than Microsoft Dynamics NAV 2013, if a RecordID or a RecordRef referred to a temporary table, then the table number value of the RecordID or RecordRef was the run-time generated sequence ID, which is from the base value of 2000100000. You could use the table number to determine if a RecordID or a RecordRef referred to a temporary table. In Microsoft Dynamics NAV 2016, the table number value of a RecordID or a RecordRef always contains the ID of the originating physical table and not the run-time generated sequence ID. If you previously used the TABLENO Function (RecordID) or the NUMBER Function (RecordRef) to test for the sequence number and determine if the RecordID or RecordRef was temporary, then you must use the ISTEMPORARY function in Microsoft Dynamics NAV instead.

Example

This example shows that you can replace code that you used previously to determine if a RecordRef referred to a temporary table. This example requires that you create a RecordRef variable named RecordRefVar.

Copy Code
// Previous code
IF RecordRefVar.Number >= 2000100000 THEN BEGIN
  // Code for temporary tables
END;
// New code
IF RecordRefVar.IsTemporary THEN BEGIN
  // Code for temporary tables
END;

See Also

Reference

RecordRef Data Type


KEYCOUNT Function (RecordRef)

Gets the number of keys that exist in the table that is referred to by the RecordRef. Returns an error if no table is selected.

Count := RecordRef.KEYCOUNT

Parameters

RecordRef

Type: RecordRef

The RecordRef that identifies the record and the table in which you are interested.

Property Value/Return Value

Type: Integer

The number of keys that have been identified in the table.

Example

The following example opens the Customer table (18) as a RecordRef variable that is named CustomerRecref. The KEYCOUNT function retrieves the number of keys that are defined in the Customer table. The return value of the function is stored in the KeyCount variable and displayed in a message box. The KeyCount variable contains the number 13 because 13 keys are defined in the Customer table. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
CustomerRecref | RecordRef
KeyCount | Integer

Text constant | ENU value
Text000 | The table has %1 keys.
Copy Code
CustomerRecref.OPEN(18);
KeyCount := CustomerRecref.KEYCOUNT;
MESSAGE(Text000, KeyCount);

See Also

Reference

RecordRef Data Type


KEYINDEX Function (RecordRef)

Gets the KeyRef of the key that has the index specified in the table that is currently selected. The key can be composed of fields of any supported data type. Data types that are not supported include BLOBs, FlowFilters, variables, and functions. If the sorting key is set to a field that is not part of a key, then the KEYINDEX is -1.

Key := RecordRef.KEYINDEX(Index)

Parameters

RecordRef

Type: RecordRef

The RecordRef that identifies the record and the table in which you are interested.

Index

Type: Integer

The number of the index in which you are interested.

Property Value/Return Value

Type: KeyRef

The KeyRef of the field that has the specified index.

Remarks

The first key in the index must have index 1, the second index 2, and so on. The last key must have index = KEYCOUNT. If the specified index is out of the range or if no table is selected, the function returns an error.

Example

The following example opens table 18 (Customer) as a RecordRef variable that is named CustomerRecref. The loop starts from 1 and loops through the key indexes that are in the table. CustomerRecref.KEYCOUNT returns the maximum number of keys that are defined in the table. The loop continues until the last key is reached. For each index that is specified, the KEYINDEX function retrieves the KeyRef for the specified index. The key index and the KeyRef for the specified indexes are displayed in a message box. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
CustomerRecref | RecordRef
varKeyRef | KeyRef
i | Integer

Text constant name | DataType | ENU value
Text000 | Text | KeyIndex: %1 KeyRef: %2
Copy Code
CustomerRecref.OPEN(18);
  FOR i := 1 TO CustomerRecref.KEYCOUNT DO BEGIN
    varKeyRef := CustomerRecref.KEYINDEX(i);
    MESSAGE(Text000, i, varKeyRef);
  END;
CustomerRecref.CLOSE;

See Also

Reference

RecordRef Data Type


LOCKTABLE Function (RecordRef)

Locks a table to protect it from write transactions that conflict with each other.

RecordRef.LOCKTABLE

Parameters

RecordRef

Type: RecordRef

The RecordRef that refers to the table that you want to lock.

Remarks

Because all write operations automatically lock the table that is being used, LOCKTABLE would appear unnecessary. However, you could have a transaction in which an application wants to inspect data before possibly changing it, with a guarantee that the data being changed has not been modified by other applications since the read operation. The solution is to explicitly lock the table before the read operation. This makes sure that no other application makes changes between the read operation and the possible write operation.

This function works the same as the LOCKTABLE Function (Record).

Example

The following example opens table number 18 (Customer) as a RecordRef that is named MyRecordRef. The LOCKTABLE function locks the table. This is ensures that no records are inserted or deleted during the counting process. The COUNT Function (RecordRef) then retrieves the number of records in the table. The number of records is stored in the Count variable. The name of the table and the number of records in the table is displayed in a message box. The varTableNo variable can be used to open any table and get the number of records in that table by changing the value of the varTableNo variable. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
MyRecordRef | RecordRef
Count | Integer
varTableNo | Integer

Text constant name | DataType | ENU value
Text000 | Text | The number of records in the %1 table is: %2.
Copy Code
varTableNo := 18;
MyRecordRef.OPEN(varTableNo);
MyRecordRef.LOCKTABLE;
Count := MyRecordRef.COUNT;
MESSAGE(Text000, MyRecordRef.NAME, Count);

This example uses pseudo-language to show the scope of write locks. Both an explicit lock and an automatic lock are illustrated. The first line (1) explicitly locks table A. If this explicit lock was not set on table A, the Database Management System (DBMS) would automatically lock this table when a record is inserted (3). Table B is not locked explicitly, but is locked automatically by the DBMS when a record is inserted (4). Both locks are active until the system exits the C/AL code module (5).

Copy Code
BeginWriteTransaction
TableA.LockTable // (1)
FindRec(TableA, ...) // (2)
.
.
InsertRec(TableA,...) // (3)
.
InsertRec(TableB) // (4)
.
.
EndWriteTransaction // (5)

If a data update depends on a prior read operation and there is a long time between the read operation and the write operation, you may not want to lock the table as you usually would during a transaction. This enables you to prevent other users from updating the table until your transaction is committed.

See Also

Reference

RecordRef Data Type


MODIFY Function (RecordRef)

Modifies a record in a table.

[Ok :=] RecordRef.MODIFY([RunTrigger])

Parameters

RecordRef

Type: RecordRef

The RecordRef that identifies the record that you want to change.

Warning
The record cannot be from table 2000000001, the Object table, or table 2000000006, the Company table.

RunTrigger

Type: Boolean

Specifies whether to run the C/AL code in the OnModify Trigger.

If this parameter is true, then the code in the OnModify trigger is executed. If this parameter is false (default), then the code is not executed.

Property Value/Return Value

Type: Boolean

true if the record was modified; otherwise, false.

If you omit this optional return value and if the record cannot be modified, then a run-time error occurs. If you include the return value, then you must handle any errors.

Remarks

Select the record that you want to modify by using the primary key fields. The record's current key and filters do not affect the operation.

If an end-user modifies a record between the time that another end-user or another process reads the record and modifies it, then the second user must refresh the value of the record variable before editing the record. Otherwise, the end-user receives the following run-time error:

Another user has modified the record for this <Table Name> after you retrieved it from the database.

Enter your changes again in the updated window, or start the interrupted activity again.

In earlier versions of Microsoft Dynamics NAV, certain situations allowed code that an end-user runs to modify a record after a newer version of the record was written and committed to the database. This would overwrite the newer changes. However, in Microsoft Dynamics NAV 2016, we have restricted the MODIFY Function (RECORDREF), RENAME Function (RecordRef), and DELETE Function (RecordRef) so that the end-user receives the following run-time error in these certain situations:

Unable to change an earlier version of the <Table Name> record. The record should be read from the database again. This is a programming error.

You must design your application so that you use the most up-to-date version of the record for modifications to the database. You use the GET Function (RecordRef) to refresh the record with the latest version.

This function works the same as the MODIFY Function (Record).

See Also

Reference

MODIFYALL Function (Record)
RecordRef Data Type


NAME Function (RecordRef)

Gets the name of the table that is currently selected. Returns an error if no table is selected.

Name := RecordRef.NAME

Parameters

RecordRef

Type: RecordRef

The RecordRef that identifies the table in which you are interested.

Property Value/Return Value

Type: Text (30)

The name of the table.

Remarks

This function works the same as the TABLENAME Function (Record).

Example

The following example opens a table as a RecordRef variable that is named MyRecordRef. You can specify any table number in the OPEN Function (RecordRef). In this example, the table 18 (Customer) is open. The NAME function retrieves the name of table 18 and stores it in the varTableName variable. The table number and name are displayed in a message box. This example requires that you create the following variables text constant in the C/AL Globals window.

Variable name | DataType
MyRecordRef | RecordRef
varTableName | Text

Text constant name | DataType | ENU value
Text000 | Text | Table %1 is the %2 table.
Copy Code
TableNo := 18;
MyRecordRef.OPEN(TableNo);
varTableName := MyRecordRef.NAME;
MESSAGE(Text000, TableNo, varTableName);

See Also

Reference

RecordRef Data Type


NEXT Function (RecordRef)

Steps through a specified number of records and retrieves a record.

[Steps :=] RecordRef.NEXT([Steps])

Parameters

RecordRef

Type: RecordRef

The RecordRef that refers to the record that you want to use as the starting point for the steps. The function returns 0 if no table is selected.

Steps

Type: Integer

Defines the direction of the search and how many records to step over.

If this parameter is greater than zero, the function will search the number of records specified in Steps forward in the table. If this parameter is less than zero, the function will search the number of records specified in Steps backward in the table. If this parameter is 0, no records are stepped over.

If you do not specify this parameter, the function finds the next record.

Property Value/Return Value

Type: Integer

Returns the number of records inspected which meet the criteria of any filters and the current key. This value can be less than Steps, depending on the number of records in the table. If the table is empty, zero is returned and the record is not changed.

Remarks

This function locates a record positioned a given number of steps forward or backward from the record specified by RecordRef. Movement through the table is governed by the filters and the current key associated with the records. The fields in the record which will be compared with the current key fields must contain appropriate values before the function is called.

This function works the same as the NEXT Function (Record).

Example

The following example opens the Customer table as a RecordRef object, creates a reference to the first (No.) field, and stores the reference in the MyFieldRef variable. The SETRANGE function sets a filter that selects all records from 10000 to 40000 in the No. field. The FIND Function (RecordRef) searches and selects the first record in the filter and counts the number of records that are found. The number of records is stored in the Count variable. The process is repeated by looping through all the records in the filter until no more records are found. The NEXT function steps through the records and finds the next record because no value is specified for the Steps parameter. The number of records that are found in the range is stored in the Count variable and displayed in a message box. This example requires that you create the following variables and text constant in the C/AL Globals windows.

Variable name | DataType
CustomerRecref | RecordRef
MyFieldRef | FieldRef
Count | Integer

Text constant | ENU value
Text000 | %1 records were retrieved.
Copy Code
CustomerRecref.OPEN(DATABASE::Customer);
MyFieldRef := CustomerRecref.FIELD(1);
MyFieldRef.SETRANGE('10000' , '40000');
Count := 0;
IF CustomerRecref.FIND('-') THEN
  REPEAT
    Count := Count + 1;
  UNTIL CustomerRecref.NEXT = 0;
MESSAGE(Text000 , Count);

See Also

Reference

RecordRef Data Type


NUMBER Function (RecordRef)

Gets the table ID (number) of the table that contains the record that was referred to by the RecordRef.

No := RecordRef.NUMBER

Parameters

RecordRef

Type: RecordRef

The RecordRef that refers to the table in which you are interested.

Property Value/Return Value

Type: Integer

The number of the table or the number of the field.

Remarks

In versions of Microsoft Dynamics NAV earlier than Microsoft Dynamics NAV 2013, if a RecordRef referred to a temporary table, then the table number value of the RecordRef was the run-time generated sequence ID, which is from the base value of 2000100000. You could use the table number to determine whether a RecordRef referred to a temporary table. In Microsoft Dynamics NAV 2016, the table number value of a RecordRef always contains the ID of the originating physical table and not the run-time generated sequence ID. If you previously used the NUMBER Function (RECORDREF) to test for the sequence number and determine whether the RecordRef was temporary, then you must use the ISTEMPORARY Function (RecordRef) in Microsoft Dynamics NAV instead.

Example

The following example opens the Customer table (18) as a RecordRef object. The OPEN Function (RecordRef) accepts DATABASE::Customer as an integer. The NUMBER function retrieves the table number and displays the name and number of the table in a message box. This example requires that you create the following variables text constant in the C/AL Globals window.

Variable name | DataType
varDatabaseName | Integer
MyRecordRef | RecordRef
varTableNumber | Integer

Text constant name | DataType | ENU value
Text000 | Text | %1 is table %2.
Copy Code
varDatabaseName := DATABASE::Customer;
MyRecordRef.OPEN(varDatabaseName);
varTableNumber := MyRecordRef.NUMBER;
MESSAGE(Text000, MyRecordRef.CAPTION, varTableNumber);

See Also

Reference

RecordRef Data Type


OPEN Function (RecordRef)

Causes a RecordRef variable to refer to a table, which is identified by its number in a particular company.

RecordRef.OPEN(No[, Temp][, CompanyName])

Parameters

RecordRef

Type: RecordRef

No

Type: Integer

The number of the table.

Temp

Type: Boolean

CompanyName

Type: Text or code

The name of the company to which you want to change. If you omit this parameter, the current company is used.

Remarks

When you use the RecordRef.OPEN function a new object is created. This object contains references to the open table, filters, and the record itself and all the fields it contains. You can open a table by using the table number or the name of the table that represents the table number. For example, you open the Customer table by using following syntax: RecordRef.Open(18) or RecordRef.Open(DATABASE::Customer)

If you use the CompanyName parameter, then this function works the same as the CHANGECOMPANY Function (Record).

Example

The following example uses the OPEN function to create a RecordRef variable that is named MyRecordRef for the Customer table. The parameters are omitted in this example because there is only one company in this example and the table will not be open as temporary table. The caption and number of records in the table are displayed in a message box. At the end of the display, the CLOSE Function (RecordRef) closes the table. This example requires that you create the following variable and text constants in the C/AL Globals window.

Variable name | DataType
MyRecordRef | RecordRef

Text constant name | DataType | ENU value
Text000 | Text | 'The %1 table contains %2 records.'
Copy Code
MyRecordRef.OPEN(DATABASE::Customer);
MESSAGE(Text000, MyRecordRef.CAPTION, MyRecordRef.COUNT);
MyRecordRef.CLOSE;

This example shows how to use the OPEN function. In this example, "MyRecordRef" opens table 27 and then "FIND('-')" finds the first record in the table. "TempMyRecordRef" opens a temporary table which is empty and therefore the "FIND('-')" returns false. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType
MyRecordRef | RecordRef
TempMyRecordRef | RecordRef
Copy Code
MyRecordRef.OPEN(27,FALSE);
TempMyRecordRef.OPEN(27,TRUE);
IF MyRecordRef.FIND('-') THEN // This is true and will find the first record in the table.
  MESSAGE('MyRecordRef finds')
ELSE
  MESSAGE('MyRecordRef does not find');
IF TempMyRecordRef.FIND('-') THEN // This is false because there are no records in a temporary table.
  MESSAGE('TempMyRecordRef finds')
ELSE
  MESSAGE('TempMyRecordRef does not find');

See Also

Reference

GETTABLE Function (RecordRef)
CHANGECOMPANY Function (Record)
RecordRef Data Type


READPERMISSION Function (RecordRef)

Determines if you can read from a table.

Ok := RecordRef.READPERMISSION

Parameters

RecordRef

Type: RecordRef

The RecordRef that refers to the record in the table for which you want to know if you have read permission.

Property Value/Return Value

Type: Boolean

Specifies whether you have permission to read from the table.

true if you can read from some or all of the table; otherwise, false.

Remarks

This function can test for both full read permission and a partial read permission that has been granted with a security filter.

This function uses the filter that is currently applied to the RecordRef to determine whether you have read permission. If no filter is applied, the function tests for full read permission. If a filter has been set, the function only tests for read permission in the range of the filter.

To determine whether the user has a partial read permission because a security filter has been applied, view the Permissions page. For more information, see How to: Set Security Filters.

If you do not have permission to read from a table and you attempt to read, a run-time error occurs. This function lets you determine in advance if you have read permission. When the permissions are checked, the combination of the permissions in the license file and the user's permissions in the Permission table is considered.

This function works the same as the READPERMISSION Function (Record).

Example

The following example opens table 18 (Customer) and creates a RecordRef variable that is named MyRecordRef for the table. The READPERMISSION function determines whether the table has read permission and stores the return value in the varHasReadPerm variable. The Customer table has read permission, so the message displays Yes. You can initialize the varTableNo variable with any table number. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
MyRecordRef | RecordRef
varHasReadPerm | Boolean
varTableNo | Integer

Text constant name | DataType | ENU value
Text000 | Text | Does the %1 table have read permission? %2
Copy Code
varTableNo := 18;
MyRecordRef.OPEN(varTableNo);
varHasReadPerm := MyRecordRef.READPERMISSION;
MESSAGE(Text000, MyRecordRef.NAME, varHasReadPerm);

See Also

Reference

RecordRef Data Type


RECORDID Function (RecordRef)

Gets the RecordID of the record that is currently selected in the table. If no table is selected, an error is generated.

RecordID := RecordRef.RECORDID

Parameters

RecordRef

Type: RecordRef

The RecordRef of the record whose recordID you want to get.

Property Value/Return Value

Type: RecordID

Example

The following example opens table 18 (Customer) as a RecordRef variable that is named MyRecordRef. The FINDLAST Function (RecordRef) finds the last record in the table. The record id of the last record is retrieved, stored in the RecID variable displayed in message box. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
MyRecordRef | RecordRef
RecID | RecordID

Text constant name | DataType | ENU value
Text000 | Text | The record id for the last record is: %1
Copy Code
MyRecordRef.OPEN(18);
MyRecordRef.FINDLAST;
RecID := MyRecordRef.RECORDID;
MESSAGE(Text000, RecID);

See Also

Reference

RecordRef Data Type


RENAME Function (RecordRef)

Changes the value of a primary key in a table.

[Ok :=] RecordRef.RENAME(Value1[, Value2,...])

Parameters

RecordRef

Type: RecordRef

The RecordRef that refers to the table that contains the primary key that you want to change.

Value1, Value2, …

Type: Any

The new values for the primary key.

Property Value/Return Value

Type: Boolean

true if the primary key was renamed; otherwise, false. If the table does not exist or if you do not have permission to write to it, then false is returned.

If you omit this optional return value and if the record is not renamed, then a run-time error occurs. If you include the return value, then you must handle any errors.

Remarks

You cannot rename some tables. Examples of the types of tables that you cannot rename are:

  • Tables in which the user is not allowed to rename the Document No. for legal or business reasons.

  • Tables in which an Option data type field, such as Document Type, is part of the primary key.

Some examples of tables that you cannot rename are:

  • Table 36, Sales Header

  • Table 38, Purchase Header

  • Table 5405, Production Order

  • Table 5766, Warehouse Activity Header

If an end-user modifies a record between the time that another end-user or another process reads the record and modifies it, then the second user must refresh the value of the record variable before editing the record. Otherwise, the end-user receives the following run-time error:

Another user has modified the record for this <Table Name> after you retrieved it from the database.

Enter your changes again in the updated window, or start the interrupted activity again.

In earlier versions of Microsoft Dynamics NAV, certain situations allowed code that an end-user runs to modify a record after a newer version of the record was written and committed to the database. This would overwrite the newer changes. However, in Microsoft Dynamics NAV 2016, we have restricted the MODIFY Function (RecordRef), RENAME Function (RecordRef), and DELETE Function (RecordRef) so that the end-user receives the following run-time error in these certain situations:

Unable to change an earlier version of the <Table Name> record. The record should be read from the database again. This is a programming error.

You must design your application so that you use the most up-to-date version of the record for modifications to the database. You use the GET Function (RecordRef) to refresh the record with the latest version.

Example

This example shows how to change the value of the primary key of a Record variable, and how to change the value of the primary key of a RecordRef variable. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Subtype
CustomerRec | Record | Customer
NewNo1 | Code | Not applicable
NewNo2 | Code | Not applicable
result | Boolean | Not applicable
CustomerRecRef | RecordRef | Not applicable
Copy Code
CustomerRec.GET('0112121');
NewNo1 := ‘9999999’;
NewNo2 := ‘8888888’;
MESSAGE('Customer name: %1; Customer number: %2',CustomerRec.Name, CustomerRec."No.");
result := CustomerRec.RENAME(NewNo1);
IF result THEN
  MESSAGE('After rename - Customer name: %1; Customer number: %2',CustomerRec.Name, CustomerRec."No.")
ELSE
  MESSAGE('No rename.');
CustRecRef.GETTABLE(CustomerRec);
result := CustRecRef.RENAME(NewNo2);
IF result THEN BEGIN
  CustomerRec.GET(NewNo2);
  MESSAGE('After rename 2 - Customer name: %1; Customer number: %2',CustomerRec.Name, CustomerRec."No.")
END ELSE
  MESSAGE('No rename.');

If a record with No. 0112121 is found, and if the renames are successful, then the following messages are displayed:

Customer name: Spotsmeyer’s Furnishings; Customer number: 0112121

After rename - Customer name: Spotsmeyer’s Furnishings; Customer number: 9999999

After rename 2 - Customer name: Spotsmeyer’s Furnishings; Customer number: 8888888

See Also

Reference

RENAME Function (Record)


RESET Function (RecordRef)

Removes all filters, including any special filters set by the MARKEDONLY Function (Record) and changes the current key to the primary key. Also removes any marks on the record and clears any C/AL variables on the record.

RecordRef.RESET

Parameters

RecordRef

Type: RecordRef

Refers to the record that you want to reset.

Remarks

If no table is selected, this function returns an error.

This function works the same as the RESET Function (Record).

Example

The following example opens the Customer (18) table and creates a RecordRef variable that is named RecRef. The GETFILTERS Function (RecordRef) gets filters that have been applied to records in the table. The filters that are returned, if any, are stored in the Filters1 variable and displayed in message box. In this example, no filters are set so the message is blank. The SETRECFILTER Function (RecordRef) sets a filter on the current key of the current record that is represented by the RecRef variable. The GETFILTERS Function (RecordRef) gets the filters that have been set and stores the value in the Filters2 variable. The message displays No. because the No. field is set as a filter. The RESET function removes the filter that was set. The value of the filter that is returned by the GETFILTERS Function (RecordRef) after the RESET Function (RecordRef) is executed is stored in the Filters3 variable. Filter3 is blank because the filter that was set by RecRef.SETRECFILTER; is removed by the RESET function. This example requires that create the following variables text constants in the C/AL Globals window.

Variable name | DataType
RecRef | RecordRef
Filters1 | Text
Filters2 | Text
Filters3 | Text

Text constant name | DataType | ENU value
Text000 | Text | Filter before filter is set is: %1.
Text001 | Text | Filter after filter is set is: %1.
Text002 | Text | Filter after filter is reset is: %1.
Copy Code
RecRef.OPEN(DATABASE::Customer);
Filters1 := RecRef.GETFILTERS;
MESSAGE(Text000, Filters1);
RecRef.SETRECFILTER;
Filters2 := RecRef.GETFILTERS;
MESSAGE(Text001, Filters2);
RecRef.RESET;
Filters3 := RecRef.GETFILTERS;
MESSAGE(Text002, Filters3);

See Also

Reference

RecordRef Data Type


SETPOSITION Function (RecordRef)

Sets the fields in a primary key on a record to the values specified in the String parameter. The remaining fields are not changed.

RecordRef.SETPOSITION(String)

Parameters

RecordRef

Type: RecordRef

The RecordRef that refers to the record.

String

Type: Text or Code

The string that is used to set the primary key. This string contains the primary key value to set.

Remarks

This function works the same as the SETPOSITION Function (Record).

Example

The following example changes the value in the primary key, the No. field, in table 23 (Vendor). Other fields are not changed. The code starts by opening table 23 (Vendor) as a RecordRef variable that is named MyRecordRef. The FIELD Function (RecordRef) selects the first field (No.) and stores the value in the MyFieldRef variable. The SETFILTER Function (FieldRef) sets a filter that selects records from 10000 to 20000. The FINDLAST Function (RecordRef) finds and retrieves the last record in the record set. The SETPOSITION function changes the value in the No. field from 20000 to 20001. The record No. and the name of the record are displayed before and displayed again after the primary key value is changed. The string that contains the new primary key is initialized in the InputString variable. This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
InputString | Text
MyRecordRef | RecordRef
MyFieldRef | FieldRef

Text constant name | DataType | ENU value
Text000 | Text | The record No. before the primary key was changed is %1.\ The vendor name before the primary key was changed is %2.
Text001 | Text | The record No. after the primary key was changed is %1. \ The vendor name after the primary key was changed is %2.
Copy Code
InputString := 'No.=CONST(20001)';
MyRecordRef.OPEN(23);
MyFieldRef := MyRecordRef.FIELD(1);
MyFieldRef.SETFILTER('10000..20000');
MyRecordRef.FINDLAST;
MESSAGE(Text000, MyRecordRef.RECORDID, MyRecordRef.FIELD(2));
MyRecordRef.SETPOSITION(InputString);
MESSAGE(Text001, MyRecordRef.RECORDID, MyRecordRef.FIELD(2));

The following is displayed before the SETPOSITION function is called:

The record No. before the primary key was changed is Vendor: 20000.

The vendor name before the primary key was changed is AR Day property Management.

The following is displayed after the SETPOSITION function is called:

The record No. after the primary key was changed is Vendor: 20001.

The vendor name after the primary key was changed is AR Day property Management.

See Also

Reference

RecordRef Data Type


SETRECFILTER Function (RecordRef)

Sets a filter on a record that is referred to by a RecordRef.

RecordRef.SETRECFILTER

Parameters

RecordRef

Type: RecordRef

The RecordRef used to identify the record on which you want to place a filter.

Remarks

This function works the same as the SETRECFILTER Function (Record).

Example

The following example opens the Customer table as a RecordRef variable that is named MyRecordRef. The SETRECFILTER function sets the values in the current key of the current record as a record filter. The GETFILTERS Function (RecordRef) retrieves the filters that have been set and displays them in a message box. No. is displayed because the filter is set on the No. field, which is the current key. This example requires that you create the following variables and text constant and text constants in the C/AL Globals window.

Variable name | DataType
MyRecordRef | RecordRef
varFilters | Test

Text constant name | ENU value
Text000 | The filter is set on the %1 field.
Copy Code
MyRecordRef.OPEN(DATABASE::Customer);
MyRecordRef.SETRECFILTER;
varFilters := MyRecordRef.GETFILTERS;
MESSAGE(Text000, varFilters);

See Also

Reference

RecordRef Data Type


SETTABLE Function (RecordRef)

Sets the table to which a Record variable refers as the same table as a RecordRef variable.

RecordRefVar.SETTABLE(RecordVar)

Parameters

RecordRefVar

Type: RecordRef

The RecordRef for the table you want to the RecordVar to refer to.

RecordVar

Type: Record

The Record for which you want to specify a table.

Remarks

Any filters that are applied to the RecordRef are also applied to the Record. If you change the filter that is applied to the RecordRef, you must call SETTABLE again to apply the new filter to the Record.

Example

This example shows that if you have a RecordID data type, you can get a RecordRef for the table that the RecordID refers to. Then you can use the RecordRef to set the table to which a Record variable refers.

This example requires that you create the following variables in the C/AL Globals or C/AL Locals window.

Variable name | DataType | Subtype
InvtEventBuf | Record | Inventory Event Buffer
RecID | RecordID | Not applicable
RecRef | RecordRef | Not applicable
ProdOrderComp | Record | Prod. Order Component
Copy Code
InvtEventBuf.FIND('-');
RecID := InvtEventBuf."Source Line ID";
RecRef := RecID.GETRECORD;
RecRef.SETTABLE(ProdOrderComp);

See Also

Reference

GETTABLE Function (RecordRef)
RecordRef Data Type


SETVIEW Function (RecordRef)

Sets the current sort order, key, and filters on a table.

RecordRef.SETVIEW(String)

Parameters

RecordRef

Type: RecordRef

The RecordRef that refers to the table on which you want to set the current sort order, key, and filters.

String

Type: Text or code

The string format is the same as the SourceTableView Property on pages.

Remarks

The value of the String parameter can be returned by the GETVIEW Function (RecordRef).

If the SETVIEW function is executed with an empty string, all the filters are removed and the primary key is used.

If no table is selected, the SETVIEW function fails.

This function works the same as the SETVIEW Function (Record).

Example

The following example opens the Customer (18) table as a RecordRef variable that is named CustomerRecRef. The SETVIEW function sets the sort key to the Name field, sort order to Ascending and sets a filter that selects records between 1000 and 2000. The GETVIEW Function (RecordRef) retrieves the sort order, key and filters that have been set and stores the value in the ViewString variable. The value in the ViewString variable is displayed in a message box. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
CustomerRecRef | RecordRef
ViewString | Text

Text constant name | DataType | ENU value
Text000 | Text | The following is the current sort order, key, and filters that are set: %1
Copy Code
CustomerRecRef.OPEN(18);
CustomerRecRef.SETVIEW('SORTING(Name) ORDER(Ascending) WHERE(No.=CONST(10000..20000))');
ViewString := CustomerRecRef.GETVIEW;
MESSAGE(Text000, ViewString);

See Also

Reference

RecordRef Data Type


WRITEPERMISSION Function (RecordRef)

Determines if you can write to a table.

Ok := RecordRef.WRITEPERMISSION

Parameters

RecordRef

Type: RecordRef

The RecordRef that refers to a record in the table for which you want to know if you have write permission.

Property Value/Return Value

Type: Boolean

Specifies if you have permission to write to the table using any of the following RecordRef functions:

  • INSERT Function (RecordRef)

  • DELETE Function (RecordRef)

  • MODIFY Function (RecordRef)

  • DELETEALL Function (RecordRef)

true if you can write to some or all of the table; otherwise, false.

Remarks

This function can test for both full write permission and a partial write permission that has been granted with a security filter. A write permission consists of Insert, Delete, and Modify permissions.

This function uses the filter that is currently applied to the RecordRef to determine whether you have write permission. If no filter is applied, the function tests for full write permission. If a filter has been set, the function only tests for write permission in the range of the filter.

To determine whether the user has partial write permission, because a security filter has been applied, view the Permissions page. For more information, see How to: Set Security Filters.

If you do not have permission to write to a table and you attempt to write, a run-time error occurs. This function lets you determine in advance if you have write permission. When the permissions are checked, the combination of permissions in the license file and the user's permissions in the Permission table is considered.

This function works the same as the WRITEPERMISSION Function (Record).

Example

The following example opens table 18 (Customer) and creates a RecordRef variable that is named MyRecordRef for the table. The WRITEPERMISSION function determines whether the table has write permission and stores the return value in the varHasWritePerm variable. The Customer table has write permission, so the message displays Yes. You can initialize the varTableNo variable with any table number. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
MyRecordRef | RecordRef
varHasWritePerm | Boolean
varTableNo | Integer

Text constant name | DataType | ENU value
Text000 | Text | Does the %1 table have write permission? %2
Copy Code
varTableNo := 18;
MyRecordRef.OPEN(varTableNo);
varHasWritePerm := MyRecordRef.WRITEPERMISSION;
MESSAGE(Text000, MyRecordRef.NAME, varHasWritePerm);

See Also

Reference

RecordRef Data Type


Report Data Type

This complex data type stores reports.

Remarks

Reports contain a number of simpler elements called controls. Controls are used to display information to the user or receive information from the user.

See Also

Reference

BREAK Function (Report, XMLport)
DEFAULTLAYOUT Function
EXECUTE Function
PREVIEW Function (Report)
PRINT Function
PRINTONLYIFDETAIL Function (Report)
QUIT Function (Report, XMLport)
RDLCLAYOUT Function
REPORT.RUN Function
REPORT.RUNMODAL Function
RUN Function (Report)
RUNMODAL Function (Report)
RUNREQUESTPAGE Function
SAVEAS Function
SAVEASEXCEL Function (Report)
SAVEASPDF Function (Report)
SAVEASWORD Function (REPORT)
SAVEASXML Function (Reports)
SETTABLEVIEW Function (Page, Report, XMLport)
SKIP Function (Report, XMLport)
WORDLAYOUT Function
WORDXMLPART Function


BREAK Function (Report, XMLport)

Exits from a loop or a trigger in a data item trigger of a report or XMLport.

BREAK

Remarks

BREAK causes the current trigger to end. When used inside a loop, such as a WHILE-DO or REPEAT-UNTIL construction, BREAK interrupts the loop and causes the current trigger to end.

Compare this with the QUIT Function (Report, XMLport).

Example

This example of code in a trigger on a report object requires that you create the following variable and text constant in the C/AL Globals window.

Variable name | DataType
MyVar | Integer

Text constant | ENU value
Text000 | The variable is now %1.
Copy Code
MyVar := 0;
REPEAT
  MyVar := MyVar + 1;
  IF MyVar = 5 THEN
    CurrReport.BREAK;
  MESSAGE(Text000,MyVar);
UNTIL Myvar = 10;
MESSAGE('After REPEAT-UNTIL loop'); //This statement is never called.

When you run the previous code, the loop will end when MyVar is 5 and the execution of the current trigger ends. Statements after the loop are not executed.

See Also

Reference

Report Data Type
XMLport Data Type


CREATETOTALS Function (Report)

Microsoft Dynamics NAV Documentation
CREATETOTALS Function (Report)
See Also

Maintains totals for a variable in C/AL.

CREATETOTALS(Var1 [, Var2] ,...)

Parameters

Var1, Var2, …

Type: Decimal

Remarks

CREATETOTALS maintains group and grand totals. The totals can be printed by placing controls that have the variable or variables that are the arguments of CREATETOTALS as their source expressions in the appropriate sections. The group totals are printed in GroupFooter sections, and the grand totals are printed in Footer sections.

This function is not supported on client report definition (RDLC) report layouts. In most cases, when you create a layout suggestion for a Classic report layout that uses the CREATETOTALS function, a SUM expression is created instead and no action is required.

Example

This example shows how to use the CREATETOTALS function to maintain totals for the two variables Amount and Quantity.

Copy Code
CurrReport.CREATETOTALS(Amount, Quantity);

See Also

Reference

Report Data Type


DEFAULTLAYOUT Function

Gets the default built-in layout type that is used on a specified report.

DefaultLayout := REPORT.DEFAULTLAYOUT(Number)

Parameters

Number

Type: Integer

The ID of the report that you want to save. To specify the report from a list, on the View menu, choose Symbols.

If the report that you specify does not exist, then a run-time error occurs.

Property Value/Return Value

Type: Option

The default layout type. The value can be either None, RDLC, or Word.

Remarks

The default layout for a report is specified by the report's DefaultLayout Property.

See Also

Tasks

How to. Specify the Default Built-in Report Layout

Concepts

Reports
Designing Report Layouts from the Microsoft Dynamics NAV Development Environment


EXECUTE Function

Runs a report in preview or processing only mode without running the request page. The function gets the request page parameter values as an input parameter string from a RUNREQUESTPAGE Function call.

REPORT.EXECUTE (Number, Parameters[,RecordRef])

Parameters

Number

Type: Integer

The ID of the report that you want to run. To specify the report from a list, on the View menu, choose Symbols.

If the report that you specify does not exist, then a run-time error occurs.

Parameters

Type: Text or Code

A string of request page parameters as XML to use to run the report. The parameter string is typically retrieved from the return value a RUNREQUESTPAGE Function function call.

RecordRef

Type: RecordRef

The RecordRef that refers to a record in a table.

Remarks

You typically use this function together with the RUNREQUESTPAGE Function function. The RUNREQUESTPAGE function runs a report request page without actually running the report, but instead, returns the parameters that are set on the request page as a string. You can then call the EXECUTE function to get the parameter string and run the report.

For a simple example that illustrates how to use the EXECUTE function, see example in the RUNREQUESTPAGE Function function topic.

See Also

Reference

SAVEAS Function
PRINT Function

Concepts

Reports
Request Pages


PREVIEW Function (Report)

Indicates whether a report is being printed in preview mode.

IsPreview := PREVIEW

Property Value/Return Value

Type: Boolean

true if the report is run in preview mode; otherwise, false.

Remarks

You must use the return value. A compile error is generated if this value is not used.

In the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Web client, if you run a client report definition (RDLC) report layout in preview mode and then call the CurrReport.PREVIEW function, then the Print icon, Print Layout icon, Page Setup icon, and Save As icon are not displayed.

If you run a client report definition (RDLC) report layout in preview mode and do not call the CurrReport.PREVIEW function, then you can print from the Print Preview window.

The following illustration shows the Print icon in the Microsoft Dynamics NAV Windows client Print Preview window.

RDLC report print icon

Example

This example shows how to use the PREVIEW function. You can use this function in an application that stores a count of how many times a document has been printed in the database. This number must be updated from inside the report that is used to print the document. To avoid updating the number when the report is run in preview mode, add a construct to the OnPreDataItem trigger that resembles the one that is shown in this example when you add the code that updates the count.

Copy Code
IF CurrReport.PREVIEW THEN
... // Preview-specific processing.
ELSE
... // Processing that is not preview specific:
... // Update the print count.

See Also

Reference

Report Data Type


PRINTONLYIFDETAIL Function (Report)

Gets or sets the current settings of the PrintOnlyIfDetail Property.

[IsPrintOnlyIfDetail :=] PRINTONLYIFDETAIL([SetPrintOnlyIfDetail])

Parameters

SetPrintOnlyIfDetail

Type: Boolean

The new setting of PrintOnlyIfDetail Property.

Property Value/Return Value

Type: Boolean

true if the PrintOnlyIfDetail Property is set to true; otherwise, false.

Example

The following example is from the OnAfterGetRecord trigger of a report. If the PrintOnlyIfDetail property is true and if a GLEntryPage record exists, given the current filters, then the PageGroupNo is incremented. This example requires that you create the following variables.

Variable name | DataType | Subtype
GLEntryPage | Record | G/L Entry
PageGroupNo | Integer | Not applicable
Copy Code
IF CurrReport.PRINTONLYIFDETAIL AND GLEntryPage.FIND('-') THEN
  PageGroupNo := PageGroupNo + 1;

Example

The following example sets the value of the PrintOnlyIfDetail Property to true. It requires that you create a Report variable named Report111. The Subtype of the variable is report 111, Customer - Top 10 List.

Copy Code
IsPrintOnlyIfDetail := Report111.PRINTONLYIFDETAIL(true);

See Also

Reference

PrintOnlyIfDetail Property
Report Data Type


PRINT Function

Prints a specified report without running the request page. Instead of using the request page to obtain parameters at runtime, the function gets the parameter values as an input parameter string, typically from a RUNREQUESTPAGE Function call.

REPORT.PRINT(Number, Parameters[,PrinterName][, RecordRef])

Parameters

Number

Type: Integer

The ID of the report that you want to print. To specify the report from a list, on the View menu, choose Symbols.

If the report that you specify does not exist, then a run-time error occurs.

Parameters

Type: Text or Code

A string of request page parameters as XML to use to run the report. The parameter string is typically retrieved from the return value a RUNREQUESTPAGE Function function call.

PrinterName

Type: Text constant or code

The name of the printer to use to print the report. The printer must be set up on the Microsoft Dynamics NAV client computer. If you do not set this variable, the printer that is set as the default printer is used.

RecordRef

Type: RecordRef

The RecordRef that refers to the table in which you want to find a record.

Remarks

You typically use this function together with the RUNREQUESTPAGE Function function. The RUNREQUESTPAGE function runs a report request page without actually running the report, but instead, returns the parameters that are set on the request page as a string. You can then call the PRINT function to get the parameter string and print the report.

For a simple example that illustrates how to use the PRINT function, see example in the RUNREQUESTPAGE Function function topic.

See Also

Reference

SAVEAS Function
EXECUTE Function

Concepts

Reports
Request Pages


QUIT Function (Report, XMLport)

Aborts the processing of a report or XMLport.

QUIT

Remarks

When you use the QUIT function, the report or XMLport is exited without committing any changes that were made to the database during the execution. The OnPostReport Trigger or OnPostXMLport Trigger trigger will not be called.

Example

The following example shows how to use the QUIT function to abort an execution without committing any changes that were made during the processing.

Copy Code
// Do some database processing.
CurrReport.QUIT;

See Also

Reference

Report Data Type
XMLport Data Type


RDLCLAYOUT Function

Gets the RDLC layout that is used on a report and returns it as a data stream.

The function has an instance call and a static call. The following code shows the syntax of the RDLC function. The first line of code is the syntax for an instance function call. The second line of code is the syntax for a static function call.

[Ok :=] ReportVariable.RDLCLAYOUT(InStream)
[Ok :=] REPORT.RDLCLAYOUT(Number, InStream)

Parameters

ReportVariable

Type: Report

A variable that specifies the report object.

Number

Type: Integer

The ID of the report object for which you want to get the RDLC layout.

InStream

Type: ISequentialStream

The variable in which to return the RDLC layout.

Return Value

Type: Boolean

true if the RDLC layout was retrieved successfully; otherwise, false.

Remarks

Using the return value is optional. When you use the return value, if the RDLC layout cannot be retrieved at run-time, then the system returns false and no error recorded. When you omit the return value, if the RDLC layout cannot be retrieved at run-time, then an error occurs, which states that the layout could not be retrieved.

See Also

Concepts

Designing Word Report Layouts


REPORT.RUN Function

Loads and runs the report that you specify.

REPORT.RUN(Number [, ReqWindow] [, SystemPrinter] [, Record])

Parameters

Number

Type: Integer

The ID of the report that you want to run. To specify the report from a list, on the View menu, choose Symbols.

If the report that you specify does not exist, then a run-time error occurs.

ReqWindow

Type: Boolean

Specifies whether the request window for the report will be displayed. The request window is part of the report object.

Specify true to display the request window before you run the report. Specify false to run the report without displaying the request window.

This parameter overrides the setting of the UseRequestPage Property of the report. If you do not provide a value for the ReqWindow parameter, then the setting of the UseRequestPage property is used.

Important
Client-side printing is not supported by Microsoft Dynamics NAV Web client. If you set this parameter to false and the report will be run on Microsoft Dynamics NAV Web client, you must set up the report to print from Microsoft Dynamics NAV Server, otherwise an error occurs at runtime. For more information, see How to: Specify Printer Selection for Reports and STARTSESSION Function (Sessions).

SystemPrinter

Type: Boolean

Specifies whether to use the default Windows printer or use table 78, Printer Selection, to find the correct printer for this report. For example, if the report prints on continuous pages, you can set up an entry in the Printer Selection table to specify to always print this report on a specific printer.

Specify true to use the printer that is defined as the system printer. Specify false, which is the default value, to use the printer that is defined in the Printer Selection table.

Record

Type: Record

Specifies which record to use in the report. Any filters that are attached to the record that you specify are used.

Remarks

If you do not know the specific report that you want to run when you are designing the report, then use this function or the REPORT.RUNMODAL Function. If you do know the specific report that you want to run, then you can use the RUN Function (Report) or the RUNMODAL Function (Report). When you use these functions, the request page runs modally. However, when you choose Preview on the request page, the Print Preview page does not run modally.

Example

This example shows how to run a report. This example displays the request window and sends the report to the printer that is selected in the Printer Selection table.

Copy Code
REPORT.RUN(1001);

Example

This example shows how to run a report. This example skips the request window, starts the report immediately, and sends the report to the printer that is selected in the Printer Selection table.

Copy Code
REPORT.RUN(1001, FALSE);

Example

This example shows how to run a report. This example skips the request window and starts the report immediately. It sends the report to the system printer instead of the printer that is selected in the Printer Selection table.

Copy Code
REPORT.RUN(1001, FALSE, TRUE);

Example

This example shows how to run a report for which you specify a record. This example displays the request window and sends the report to the system printer. This example requires that you create the following variable in the C/AL Globals window.

Variable name | DataType | Subtype
MyRec | Record | Customer
Copy Code
MyRec.FINDLAST;
MyRec.SETRECFILTER;
Report.RUN(101, TRUE, TRUE, MyRec);

See Also

Reference

Report Data Type


REPORT.RUNMODAL Function

Loads and runs the report that you specify. The report is run modally.

REPORT.RUNMODAL(Number [, ReqWindow] [, SystemPrinter] [, Record])

Parameters

Number

Type: Integer

The ID of the report that you want to run. To select the report from a list, on the View menu, choose Symbols.

If the report that you specify does not exist, then a run-time error occurs.

ReqWindow

Type: Boolean

Specifies whether the request window for the report will be displayed. The request window is part of the report object.

Specify true, which is the default value, to display the request window before you run the report. Specify false to run the report without displaying the request window.

This parameter overrides the setting of the UseRequestPage Property of the report. If you do not provide a value for the ReqWindow parameter, then the setting of the UseRequestPage property is used.

Important
Client-side printing is not supported by Microsoft Dynamics NAV Web client. If you set this parameter to false and the report will be run on Microsoft Dynamics NAV Web client, you must set up the report to print from Microsoft Dynamics NAV Server, otherwise an error occurs at runtime. For more information, see How to: Specify Printer Selection for Reports and STARTSESSION Function (Sessions).

SystemPrinter

Type: Boolean

Specifies whether to use the default Windows printer or use table 78, Printer Selection, to find the correct printer for this report. For example, if the report prints on continuous forms, then you can set up an entry in the Printer Selection table to specify to always print this report on a specific printer.

Specify true to use the printer defined as the system printer. Specify false, which is the default value, to use the printer that is defined in the Printer Selection table.

Record

Type: Record

Specifies which record to use in the report. Any filters that are attached to the record that you specify are used.

Remarks

If you do not know the specific report that you want to run when you are designing your application, then use this function or the REPORT.RUN Function. If you do know the specific report that you want to run, then you can use the RUN Function (Report) or the RUNMODAL Function (Report). When you use these functions the request page runs modally. However, when you choose Preview on the request page, the Print Preview page does not run modally.

The request page is run modally when you use this function.

Example

This example shows how to run a report. This example displays the request window and sends the report to the printer selected through the Printer Selection table.

Copy Code
REPORT.RUNMODAL(1001);

This example shows how to run a report. This example skips the request window, starts the report immediately, and sends the report to the printer that is selected in the Printer Selection table.

Copy Code
REPORT.RUNMODAL(1001, FALSE);

This example shows how to run a report. This example skips the request window and starts the report immediately. It sends the report to the system printer instead of the printer that is selected in the Printer Selection table.

Copy Code
REPORT.RUNMODAL(1001, FALSE, TRUE);

See Also

Reference

Report Data Type


RUN Function (Report)

Loads and executes the report that you specify.

Report.RUN

Parameters

Report

Type: Report

After you define this variable, you can run this function or the Report.RUNMODAL function on the variable. The variable is automatically cleared after it executes this function.

Remarks

Use this function or the RUNMODAL Function (Report) if you know at design time the exact report that you want to run. Otherwise, use the REPORT.RUNMODAL Function or REPORT.RUN Function.

If the report you specify does not exist, then a compile error occurs.

Example

This example requires that you create the following variables.

Variable name | DataType | Subtype
CustomerRec | Record | Customer
SomeReport | Report | Salesperson - Sales Statistics
Copy Code
CustomerRec.SETCURRENTKEY("No.");
CustomerRec.SETFILTER("Salesperson Code", 'JR|PS');
SomeReport.SETTABLEVIEW(CustomerRec);
SomeReport.RUN

See Also

Reference

Report Data Type


RUNMODAL Function (Report)

Loads and executes the report that you specify.

Report.RUNMODAL

Parameters

Report

Type: Report

After you define this variable, you can run this function or the Report.RUN function on the variable. As opposed to the Report.RUN function, the system does not automatically clear the variable after it executes this function. You must handle clearing the variable.

Remarks

Use this function or the RUN Function (Report) if you know at design time the exact report you want to run. Otherwise, use the REPORT.RUNMODAL Function or REPORT.RUN Function.

If the report you specify does not exist, then a compile error occurs.

The request page is run modally when you use this function.

Example

This example requires that you create the following variables.

Variable name | DataType | Subtype
CustomerRec | Record | Customer
SomeReport | Report | Chart of Accounts
Copy Code
…
CLEAR(CustomerRec);
CustomerRec.SETRECFILTER;
SomeReport.XXX; // Any user-defined function.
SomeReport.SETTABLEVIEW(CustomerRec);
SomeReport.RUNMODAL()

See Also

Reference

Report Data Type


RUNREQUESTPAGE Function

Runs the request page for a report without running the report. Returns an XML string that contains the request page parameters that are entered on the request page.

Parameters := REPORT.RUNREQUESTPAGE(Number[, Parameters])

Parameters

Number

Type: Integer

The ID of the report for which you want to run the request page. To specify the report from a list, on the View menu, choose Symbols.

If the report that you specify does not exist, then a run-time error occurs.

Parameters

Type: Text or Code

A string of request page parameters as XML to use to run the report.

Property Value/Return Value

Type: Text or Code

A string of the request page parameters as XML.

Remarks

This function opens the request page for the specified report, where the user can provide parameters for the report. When the user closes the request page by choosing the OK button, a string that contains the parameter values that were set by the user is returned. When the user chooses the Cancel button, an empty string will be returned. The returned parameter string can be picked up by calling one of the following functions:

  • EXECUTE Function

  • PRINT Function

  • SAVEAS Function

Note
You can use these functions to schedule reports in the job queue.

Example

This example illustrates how to use the RUNREQUESTPAGE function to run the request page for report ID 206 Sales Invoice. The request page parameters are saved to a table, and then uses the parameters with the EXECUTE, SAVEAS, and PRINT functions to preview the report, save it as a PDF file, and print it.

This example requires that you create a table for holding parameters that are entered on the report request page and a codeunit that runs the report functions.

Create a table called Request Parameters that has the following fields.

Field Name | Data Type | Length
ReportId | Integer |
UserId | Code | 100
Parameters | BLOB |

Create a codeunit and add the following variables in the C/AL Globals window.

Variable name | DataType | Subtype | Length
ReportParameters | Record | Report Parameters |
XmlParameters | Text |  |
OStream | OutStream |  |
IStream | InStream |  |
CurrentUser | Code |  | 100
Content | File |  |
TempFileName | Text |  |

Add the following code to the OnRun trigger of the codeunit.

Copy Code
// Use the REPORT.RUNREQUESTPAGE function to run the request page to get report parameters
XmlParameters := REPORT.RUNREQUESTPAGE(206);
CurrentUser := USERID;
// Save the request page parameters to the database table
WITH ReportParameters DO BEGIN
    // Cleanup
    IF GET(206,CurrentUser) THEN
    DELETE;
    SETAUTOCALCFIELDS(Parameters);
    ReportId := 206;
    UserId := CurrentUser;
    Parameters.CREATEOUTSTREAM(OStream,TEXTENCODING::UTF8);
    MESSAGE(XmlParameters);
    OStream.WRITETEXT(XmlParameters);
    INSERT;
END;
CLEAR(ReportParameters);
XmlParameters := '';
// Read the request page parameters from the database table
WITH ReportParameters DO BEGIN
    SETAUTOCALCFIELDS(Parameters);
    GET(206,CurrentUser);
    Parameters.CREATEINSTREAM(IStream,TEXTENCODING::UTF8);
    IStream.READTEXT(XmlParameters);
END;
// Use the REPORT.SAVEAS function to save the report as a PDF file
Content.CREATE('TestFile.pdf');
Content.CREATEOUTSTREAM(OStream);
REPORT.SAVEAS(206,XmlParameters,REPORTFORMAT::Pdf,OStream);
Content.CLOSE;
// Use the REPORT.EXECUTE function to preview the report
REPORT.EXECUTE(206,XmlParameters);
// Use the REPORT.Print function to print the report
REPORT.PRINT(206,XmlParameters);

See Also

Concepts

Reports
Request Pages


SAVEAS Function

Runs a specific report without a request page and saves the report as a PDF, Excel, Word, or XML file. Instead of using the request page to obtain parameters at runtime, the function gets the parameter values as an input parameter string, typically from the return value of a RUNREQUESTPAGE Function call.

[Ok:=] REPORT.SAVEAS(Number, Parameters, Format, OutStream[, RecordRef])

Parameters

Number

Type: Integer

The ID of the report that you want to save. To specify the report from a list, on the View menu, choose Symbols.

If the report that you specify does not exist, then a run-time error occurs.

Parameters

Type: Text or Code

A string of request page parameters as XML to use to run the report. The parameter string is retrieved from the return value a RUNREQUESTPAGE Function function call.

Format

Type: Option

The type of file to save the report as. The following options are supported: Pdf, Excel, Word, and XML.

OutStream

Type: OutStream

The stream to which to write a report.

RecordRef

Type: RecordRef

The RecordRef that refers to the table in which you want to find a record.

Return Value

Type: Boolean

If you omit this optional return value and if the report cannot be saved as a file, then a run-time error occurs that states that the report cannot be saved. If you include a return value, then it is assumed that you will handle any errors and no run-time error occurs, even though the report is not saved.

true if the report was saved to a file; otherwise, false.

Remarks

You typically use this function together with the RUNREQUESTPAGE Function function. The RUNREQUESTPAGE function runs a report request page without actually running the report, but instead, returns the parameters that are set on the request page as a string. You can then call the SAVEAS function to get the parameter string and save the report to a file of the specified format.

For a simple example that illustrates how to use the SAVEAS function, see example in the RUNREQUESTPAGE Function function topic.

Note
By default, when a report uses an RDLC report layout at runtime, fonts are embedded in the generated PDF. You can specify whether fonts are embedded in the PDF for RDLC reports by changing the Report PDF Font Embedding setting in the Microsoft Dynamics NAV Server instance configuration or changing the PDFFontEmbedding property in report objects. For more information, see Configuring Microsoft Dynamics NAV Server and PDFFontEmbedding Property.

See Also

Reference

EXECUTE Function
PRINT Function

Concepts

Reports
Request Pages


SAVEASEXCEL Function (Report)

Saves a report on the computer that is running Microsoft Dynamics NAV Server as a Microsoft Excel (.xls) workbook.

[Ok :=] REPORT.SAVEASEXCEL(Number, FileName[, Record])
[Ok :=] ReportVariable.SAVEASEXCEL(FileName)

Parameters

Number

Type: Integer

The ID of the report that you want to run. From the C/AL Editor, on the View menu, choose C/AL Symbol Menu to select the report from a list.

If the report you specify does not exist, then a run-time error occurs.

FileName

Type: Text

The path and the name of the file that you want to save the report as. The path must exist, the file must not be being used, and the Microsoft Dynamics NAV Server process must have permission to write to the file. Otherwise, you will get errors.

Record

Type: Record

Specifies which record to use in the report. Any filters that have been applied to the record that you specify will be used.

ReportVariable

The report that you want to run.

Property Value/Return Value

Type: Boolean

If you omit this optional return value, then run-time errors can occur. If you include a return value, then it is assumed that you will handle any errors.

true if the report was saved; otherwise, false.

Remarks

You can use the SAVEASEXCEL function on the global REPORT object and on Report variables. If, at design time, you do not know the specific report that you want to run, then use the global REPORT object and specify the report number in the Number parameter. If you do know which report you want to run, then create a Report variable, set the Subtype of the variable to a specific report, and use this variable when you call the SAVEASEXCEL function.

When you call the SAVEASEXCEL function, the report is generated and saved to "FileName." The request page is not shown.

If the destination folder that you specify in FileName does not exist, then you get the following error:

The specified path is invalid.

If the file that you specify in FileName is being used, then you get the following error:

An I/O exception occurred during the operation.

If the Microsoft Dynamics NAV Server process does not have permission to write to the file that you specify in FileName, then you get the following error:

Either the caller does not have the required permission or the specified path is read-only.

Example

This example shows how to use the SAVEASEXCEL function to save the Excel workbook on the computer that is running Microsoft Dynamics NAV Server and then download the file to a different computer that is running the Microsoft Dynamics NAV Windows client. It requires that you create the following variables.

Variable name | DataType | Length
TempFile | File | Not applicable
Name | Text | 250
NewStream | InStream | Not applicable
ToFile | Text | 250
ReturnValue | Boolean | Not applicable
Copy Code
// Specify that TempFile is opened as a binary file.
TempFile.TEXTMODE(FALSE);
// Specify that you can write to TempFile.
TempFile.WRITEMODE(TRUE);
Name := 'C:\Temp\TempReport.xls';
// Create and open TempFile.
TempFile.CREATE(Name);
// Close TempFile so that the SAVEASEXCEL function can write to it.
TempFile.CLOSE;
REPORT.SAVEASEXCEL(406,Name);
TempFile.OPEN(Name);
TempFile.CREATEINSTREAM(NewStream);
ToFile := 'Report.xls';
// Transfer the content from the temporary file on Microsoft Dynamics NAV
// Server to a file on the client.
ReturnValue := DOWNLOADFROMSTREAM(
  NewStream,
  'Save file to client',
  '',
  'Excel File *.xls| *.xls',
  ToFile);
// Close the temporary file.
TempFile.CLOSE();

You can create an action on a page and set the action to run this code. When you run the action, the Export File dialog box opens. Choose Save to save the file to the client.

See Also

Reference

Report Data Type


SAVEASPDF Function (Report)

Saves a report as a .pdf file.

[Ok :=] REPORT.SAVEASPDF(Number, FileName[, Record])
[Ok :=] ReportVariable.SAVEASPDF(FileName)

Parameters

Number

Type: Integer

The ID of the report that you want to run. From the C/AL Editor, on the View menu, choose C/AL Symbol Menu to select the report from a list.

FileName

Type: Text

The path and name of the file that you want to save the report as.

Record

Type: Record

Specifies which record to use in the report. Any filters that have been applied to the record that you specify will be used.

ReportVariable

The report that you want to run.

Property Value/Return Value

Type: Boolean

true if the report was saved; otherwise, false.

If you omit this optional return value, then run-time errors can occur. If you include a return value, it is assumed that you will handle any errors.

Remarks

You can use the SAVEASPDF function on the global REPORT object or on Report variables. If, at design time, you do not know the specific report that you want to run, then use the global REPORT object and specify the report number in the Number parameter. If you do know which report you want to run, then create a Report variable, set the Subtype of the variable to a specific report, and use this variable when you call the SAVEASPDF function.

When you call SAVEASPDF, the report is generated and saved to "FileName." A Saving to PDF window shows the status of the process. Note that the request page will not be shown.

The FileName parameter specifies a location on the computer that is running Microsoft Dynamics NAV Server. If you call this function from a client, such as from an action on a page, then use the DOWNLOAD Function (File) to download the .pdf file from the computer that is running Microsoft Dynamics NAV Server to the computer that is running the client.

Note
By default, when a report uses an RDLC report layout at runtime, fonts are embedded in the generated PDF. You can specify whether fonts are embedded in the PDF for RDLC reports by changing the Report PDF Font Embedding setting in the Microsoft Dynamics NAV Server instance configuration or changing the PDFFontEmbedding property in report objects. For more information, see Configuring Microsoft Dynamics NAV Server and PDFFontEmbedding Property.

Example

This example shows how to use the SAVEASPDF function to save a specific report as a PDF file on the computer that is running Microsoft Dynamics NAV Server. It requires that you create the following variables.

Variable name | DataType | Subtype
Filename | Text | Not applicable
ReturnValue | Boolean | Not applicable
Report206 | Report | Sales - Invoice
Copy Code
Filename := 'C:\MyReports\report206.pdf';
ReturnValue := Report206.SAVEASPDF(Filename);

See Also

Reference

Report Data Type


SAVEASWORD Function (REPORT)

Saves a report on the computer that is running Microsoft Dynamics NAV Server as a Microsoft Word (.doc) document.

[Ok :=] REPORT.SAVEASWORD(Number, FileName[, Record])
[Ok :=] ReportVariable.SAVEASWORD(FileName)

Parameters

Number

Type: Integer

The ID of the report that you want to run. From the C/AL Editor, on the View menu, choose C/AL Symbol Menu to select the report from a list.

If the report you specify does not exist, then a run-time error occurs.

FileName

Type: Text

The path and the name of the file that you want to save the report as. The path must exist, the file must not be being used, and the Microsoft Dynamics NAV Server process must have permission to write to the file. Otherwise, you will get errors.

Record

Type: Record

Specifies which record to use in the report. Any filters that have been applied to the record that you specify will be used.

ReportVariable

The report that you want to run.

Property Value/Return Value

Type: Boolean

true if the report was saved; otherwise, false.

If you omit this optional return value, then run-time errors can occur. If you include a return value, then it is assumed that you will handle any errors.

Remarks

You can use the SAVEASWORD function on the global REPORT object or on Report variables. If, at design time, you do not know the specific report that you want to run, then use the global REPORT object and specify the report number in the Number parameter. If you do know which report you want to run, then create a Report variable, set the Subtype of the variable to a specific report, and use this variable when you call the SAVEASWORD function.

When you call the SAVEASWORD function, the report is generated and saved to "FileName." The request page is not shown.

If the destination folder that you specify in FileName does not exist, then you get the following error:

The specified path is invalid.

If the file that you specify in FileName is being used, then you get the following error:

An I/O exception occurred during the operation.

If the Microsoft Dynamics NAV Server process does not have permission to write to the file that you specify in FileName, then you get the following error:

Either the caller does not have the required permission or the specified path is read-only.

Example

This example shows how to use the SAVEASWORD function to save the Word document on the computer that is running Microsoft Dynamics NAV Server and then download the file to a different computer that is running the Microsoft Dynamics NAV Windows client. It requires that you create the following variables.

Variable name | DataType | Length
TempFile | File | Not applicable
Name | Text | 250
NewStream | InStream | Not applicable
ToFile | Text | 250
ReturnValue | Boolean | Not applicable
Copy Code
// Specify that TempFile is opened as a binary file.
TempFile.TEXTMODE(FALSE);
// Specify that you can write to TempFile.
TempFile.WRITEMODE(TRUE);
Name := 'C:\Temp\TempReport.doc';
// Create and open TempFile.
TempFile.CREATE(Name);
// Close TempFile so that the SAVEASWORD function can write to it.
TempFile.CLOSE;
REPORT.SAVEASWORD(406,Name);
TempFile.OPEN(Name);
TempFile.CREATEINSTREAM(NewStream);
ToFile := 'Report.doc';
// Transfer the content from the temporary file on Microsoft Dynamics NAV
// Server to a file on the client.
ReturnValue := DOWNLOADFROMSTREAM(
  NewStream,
  'Save file to client',
  '',
  'Word File *.doc| *.doc',
  ToFile);
// Close the temporary file.
TempFile.CLOSE();

You can create an action on a page and set the action to run this code. When you run the action, the Export File dialog box opens. Choose Save to save the file to the client.


SAVEASXML Function (Reports)

Saves a report as an .xml file on the computer that is running Microsoft Dynamics NAV Server.

[Ok :=] REPORT.SAVEASXML(Number, FileName[, Record])
[Ok :=] ReportVariable.SAVEASXML(FileName)

Parameters

Number

Type: Integer

The ID of the report that you want to run. From the C/AL Editor, on the View menu, choose C/AL Symbol Menu to select the report from a list.

If the report you specify does not exist, then a run-time error occurs.

FileName

Type: Text

The path and the name of the file that you want to save the report as. The path must exist, the file must not be being used, and the Microsoft Dynamics NAV Server must have permission to write to the file. Otherwise, you will get errors.

Tip
If you call this function from a Microsoft Dynamics NAV client, such as from an action on a page, then you can use the DOWNLOAD Function (File) to send the .xml file from the computer that is running Microsoft Dynamics NAV Server to the computer that is running the Microsoft Dynamics NAV client.

Record

Type: Record

Specifies which record to use in the report. Any filters that have been applied to the record that you specify will be used.

ReportVariable

The report that you want to run.

Property Value/Return Value

Type: Boolean

If you omit this optional return value, then run-time errors can occur. If you include a return value, then it is assumed that you will handle any errors.

true if the report was saved; otherwise, false.

Remarks

You can use the SAVEASXML function on the global REPORT object and on Report variables. If, at design time, you do not know the specific report that you want to run, then use the global REPORT object and specify the report number in the Number parameter. If you know which report you want to run, then create a Report variable, set the Subtype of the variable to a specific report, and then use this variable when you call the SAVEASXML function.

When you call the SAVEASXML function, the report is generated and saved to "FileName." The request page is not shown.

If the destination folder that you specify in FileName does not exist, then you get the following error:

The specified path is invalid.

If the file that you specify in FileName is being used, then you get the following error:

An I/O exception occurred during the operation.

If the Microsoft Dynamics NAV Server does not have permission to write to the file that you specify in FileName, then you get the following error:

Either the caller does not have the required permission or the specified path is read-only.

To resolve this issue, verify that the service account that is running the Microsoft Dynamics NAV Server instance has write permissions on the path.

Example

This example shows how to use the SAVEASXML function to save a report as an .xml file on the computer that is running Microsoft Dynamics NAV Server and then download the file to a different computer that is running the Microsoft Dynamics NAV Windows client. This example requires that you create the following variables.

Variable name | DataType | Length
TempFile | File | Not applicable
Name | Text | 250
NewStream | InStream | Not applicable
ToFile | Text | 250
ReturnValue | Boolean | Not applicable
Copy Code
// Specify that TempFile is opened as a binary file.
TempFile.TEXTMODE(FALSE);
// Specify that you can write to TempFile.
TempFile.WRITEMODE(TRUE);
Name := 'C:\Temp\TempReport.xml';
// Create and open TempFile.
TempFile.CREATE(Name);
// Close TempFile so that the SAVEASXML function can write to it.
TempFile.CLOSE;
REPORT.SAVEASXML(406,Name);
TempFile.OPEN(Name);
TempFile.CREATEINSTREAM(NewStream);
ToFile := 'Report.xml';
// Transfer the content from the temporary file on Microsoft Dynamics NAV
// Server to a file on the client.
ReturnValue := DOWNLOADFROMSTREAM(
  NewStream,
  'Save file to client',
  '',
  'Excel File *.xml| *.xml',
  ToFile);
// Close the temporary file.
TempFile.CLOSE();

You can create an action on a page and set the action to run this code. When you run the action, the Export File dialog box opens. Choose Save to save the file to the client.

See Also

Reference

Report Data Type


SKIP Function (Report, XMLport)

Skips the current iteration of the current report or XMLport.

Record.SKIP

Remarks

The SKIP Function (Report, XMLport) allows you to conditionally skip processing of the current report or XMLport. If the processing occurs inside a loop, the processing continues with the next record after the SKIP Function (Report, XMLport) is called.

A typical situation in which you will use SKIP is when you want to retrieve records from a related table by using values in the current record for forming a filter. If the values in the current record already indicate that no records from the related table will be retrieved, there is no need to perform this processing and you can use SKIP to avoid the processing.

Example

The following example shows how to use the SKIP Function (Report, XMLport) to skip processing the current record if the balance field of the record is zero. Processing of records will continue until a record that has a balance of 0 is encountered. This example requires that you create the following variable in the C/AL Globals window.

Variable | DataType
Balance | Decimal
Copy Code
IF Balance = 0 THEN
  CurrReport.SKIP
ELSE
  ... // Do some processing.

See Also

Reference

OnAfterGetRecord (Data Items) Trigger
OnAfterGetRecord (XMLports) Trigger
Report Data Type
XMLport Data Type


WORDLAYOUT Function

Gets the Word report layout that is used on a report and returns it as a data stream.

The function has an instance call and a static call. The following code shows the syntax of the WORDLAYOUT function. The first line of code is the syntax for an instance function call. The second line of code is the syntax for a static function call.

[Ok :=] ReportVariable.WORDLAYOUT(InStream)
[Ok :=] REPORT.WORDLAYOUT(Number, InStream)

Parameters

ReportVariable

Type: Report

A variable that specifies the report object.

Number

Type: Integer

The ID of the report object for which you want to get the Word report layout.

InStream

Type: ISequentialStream

The variable in which to return the Word report layout.

Return Value

Type: Boolean

true if the Word report layout was retrieved successfully; otherwise, false.

Remarks

Using the return value is optional. When you use the return value, if the Word report layout cannot be retrieved at run-time, then the system returns false and no error recorded. When you omit the return value, if the Word report layout cannot be retrieved at run-time, then an error occurs, which states that the Word report could not be retrieved.

See Also

Concepts

Designing Word Report Layouts


WORDXMLPART Function

Returns the report data structure as structured XML that is compatible with Microsoft Word custom XML parts.

The function has an instance call and a static call. The following code shows the syntax of the WORDXMLPART function. The first line of code is the syntax for an instance function call. The second line of code is the syntax for a static function call.

String := ReportVariable.WORDXMLPART([ExtendedFormat])
String := REPORT.WORDXMLPART(Number[, ExtendedFormat])

Parameters

ExtendedFormat

Type: String

If you set this variable to true, then XML elements will include the following attributes attributes:

  • ElementType="Parameter|Column|DataItem"

    Specifies the element type as defined for the report in Report Designer. Parameter is typically used for elements, such as captions.

  • ElementId="ID"

    Specifies the ID that is assigned to the element by its ID Property.

  • DataType="Type"

    Specifies the Microsoft Dynamics NAV data type of the element.

If you omit this parameter or set it to false, then the element attributes are not included in the XML. This is the recommended setting when you will use the Word XML part in Word for modifying the report layout because the XML is simpler.

The following example illustrates an XML element that has the ExtendedFormat set to false:

<CompanyName ElementType="Column" ElementId="3" DataType="OemText">

The following example illustrates the same XML with the ExtendedFormat set to true:

<CompanyName>

Number

Type: Integer

The ID of the report that you want to run. From the C/AL Editor, on the View menu, choose C/AL Symbol Menu to select the report from a list.

If the report you specify does not exist, then a run-time error occurs.

Return Value

Type: Text

You must use the return value; otherwise you cannot compile the object.

Remarks

This function returns the data structure of the report as structured XML that complies with custom XML parts in Microsoft Word 2013. The following table provides a simplified overview of the XML that is returned by the function.

XML Description

<?xml version="1.0" encoding="utf-16"?>

Header

<NavWordReportXmlPart xmlns="urn:microsoft-dynamics-nav/report/<reportname>/<id>/"

XML namespace specification. <reportname> is the name assigned to the report object in Microsoft Dynamics NAV Development Environment. <id> is the ID that is assigned to the report.

..<Labels>

....<ColumnNameCaption>ColumnNameCaption</ColumnNameCaption>

....<LabelName>LabelCaption</LabelName>

..</Labels>

Contains all the labels for the report. Labels are listed in alphabetical. The element includes labels that are related to columns that have the IncludeCaption Property set to Yes and labels that are defined in Report Label Designer.

  • Label elements that are related to columns have the format <ColumnNameCaption>ColumnNameCaption</ColumnNameCaption>, where ColumnName is determined by the column's Name Property.

  • Label elements from Report Label Designer have the format <LabelName>LabelCaption</LableName, where LabelName is determined by the label's Name Property and LabelCaption is determined by the label's Caption Property.

..<DataItem1>

....<DataItem1Column1>DataItem1Column1</DataItem1Column1>

Top-level data item and columns. Columns are listed in alphabetical order.

The element names and values are determined by the Name property of the data item or column.

....<DataItem2>

......<DataItem2Column1>DataItem2Column1</DataItem2Column1>

....</DataItem2>

....<DataItem3>

......<DataItem3Column1>DataItem3Column1</DataItem3Column1>

....</DataItem3>

Data items and columns that are nested in the top-level data item. Columns are listed in alphabetical order under the respective data item.

..</DataItem1>

</NavWordReportXmlPart>

Closing elements.

Word custom XML parts enable you to integrate business data into Word documents. For example, the WORDXMLPART function is used internally by Microsoft Dynamics NAV when you are creating report layouts in Word. You can use this function to create a custom XML part, and then, together with the SAVEASXML Function (Reports) function and additional data merging tools, you can implement your own functionality for mapping and laying out report data in Word documents. To create a custom XML part, you can save the return value to an .xml file that is encoded in UTF-16 (16-bit Unicode Transformation Format). The resultant file can be added to Word documents as a custom XML part to map the report data set as XML data.

Example

The following example uses the WORDXMLPART function to save the data structure of Report 112 Sales Statistics in an XML file in a predefined folder C:\Report Documents. The resultant file can be used in Word as a custom XML part. To complete the example, you must also create the following variables in the C/AL Globals window.

Variable | DataType
ReportAsString | Text
SalesStatsReport | File

Copy Code
ReportAsString := REPORT.WORDXMLPART(112);
SalesStatsReport.TEXTMODE(TRUE);
SalesStatsReport.WRITEMODE(TRUE);
SalesStatsReport.CREATE('C:\Report Documents\SalesStatsReport.xml', TextEncoding::UTF16);
SalesStatsReport.WRITE(ReportAsString);
SalesStatsReport.CLOSE;

The code generates the report structure as XML, and then writes the XML to the file C:\Report Documents\SalesStatsReport.xml.

See Also

Concepts

Designing Word Report Layouts


Sessions

Use the session functions to manage Microsoft Dynamics NAV sessions.

See Also

Reference

STARTSESSION Function (Sessions)
STOPSESSION Function (Sessions)
CURRENTEXECUTIONMODE Function (Sessions)
USERID Function (Sessions)


CURRENTEXECUTIONMODE Function (Sessions)

Specifies the mode in which the session is running.

ExecutionMode := CURRENTEXECUTIONMODE

Property Value/Return Value

Type: ExecutionMode

The execution mode is one of the following:

  • Debug

  • Standard

Remarks

If you start the Microsoft Dynamics NAV Windows client at a command prompt and use the -debug parameter, then the execution mode is Debug. Otherwise, the execution mode is Standard.

Example

This example requires that you create a variable named Mode that has a DataType of ExecutionMode.

Copy Code
Mode := CURRENTEXECUTIONMODE;
MESSAGE('Current execution mode is %1.', Mode);

See Also

Concepts

Sessions
Debugging


STARTSESSION Function (Sessions)

Starts a Microsoft Dynamics NAV session without a UI and runs the specified codeunit.

[OK :=] STARTSESSION(VAR SessionID, CodeunitID [, CompanyName] [,Record])

Parameters

SessionID

Type: Integer

The ID of the new session that is started. The ID is assigned to the SessionID variable after the session is started successfully.

This parameter is passed by reference to the function. For more information about passing parameters by reference, see C/AL Function Calls.

CodeunitID

Type: Integer

The ID of the codeunit to run when the session is started.

CompanyName

Type: Text

The company in which to start the session. By default, the session is started in the same company as the calling session.

This parameter is optional.

Record

Type: Record

A record that is passed to the OnRun trigger of the codeunit that runs when the session is started.

This parameter is optional.

Property Value/Return Value

Type: Boolean

true if the session started successfully and no errors occurred; otherwise false.

If you omit this optional return value and the session is not started successfully, then a run-time error occurs. If you include the return value, then you must handle any errors.

Remarks

The session is started on the same Microsoft Dynamics NAV Server instance from which the function is called. The session that is started is a background session and therefore has no UI. The session executes using the same user credentials as the calling C/AL code.

The following table describes how dialog boxes are handled in a background session, which has no UI.

Function that creates the dialog box Behavior

CONFIRM Function (Dialog)

  • Dialog box is suppressed.

  • The following error occurs on the Microsoft Dynamics NAV Server instance: Microsoft Dynamics NAV Server attempted to issue a client callback to show a confirmation dialog box.

ERROR Function (Dialog)

  • Dialog box is suppressed.

  • C/AL code execution ends.

  • The error is logged to the event log of the Microsoft Dynamics NAV Server instance.

  • The error is added to the Comments field of the Session Event table.

MESSAGE Function (Dialog)

  • Dialog box is suppressed.

  • The message is recorded in the event log of the computer that is running Microsoft Dynamics NAV Server instance. The log entry has type Information and includes the context of the message.

OPEN Function (Dialog)

  • Dialog box is suppressed.

  • Dialog box text is not displayed or logged.

Each background session has the same impact on resources as a regular user session. In addition, it takes time and resources to start each background session. Therefore, we recommend that you consider when and how you use background sessions. For example, do not use background sessions for small tasks that occur often because the cost of starting the session for each tasks is high.

Example

This example requires that you create the following variables.

Variable name | DataType | Subtype
OK | Boolean | Not applicable
SessionID | Integer | Not applicable
CacheStressTestRec | Record | Customer

In this example, the Cache Stress Test codeunit is a custom codeunit.

Copy Code
OK := STARTSESSION(SessionId, CODEUNIT::"Cache Stress Test", COMPANYNAME, CacheStressTestRec);
IF OK THEN
  STOPSESSION(SessionId, 'Logoff cache stress test session')
ELSE
  ERROR('The session was not started successfully.');

See Also

Tasks

How to: Debug a Background Session

Concepts

Printing Reports from a Background Session


STOPSESSION Function (Sessions)

Stops a Microsoft Dynamics NAV session.

[OK :=] STOPSESSION(SessionID[,Comment]);

Parameters

SessionID

Type: Integer

The ID of the session that you want to stop.

The session can be any of the following:

  • Microsoft Dynamics NAV Windows client session

  • Microsoft Dynamics NAV Web client session

  • NAS services session

  • SOAP web services client session

  • OData web services client session

  • Background session

Comment

Type: Text

An optional comment about the session event. The comment is stored in Table 2000000111, the Session Event table.

Property Value/Return Value

Type: Boolean

true if the session is stopped successfully and no errors occurred; otherwise false.

If you omit this optional return value and the session is not stopped successfully, then a run-time error occurs. If you include the return value, then you must handle any errors.

Remarks

The session that you want to stop and the session that calls STOPSESSION must be running on the same instance of Microsoft Dynamics NAV Server. The session is stopped before the next C/AL statement executes. Open transactions are rolled back.

Note
If the current executing statement is the SLEEP function, then the session is stopped immediately.

When a session is executing C/AL that does not interact with the server connection or the access lock used by the connection, STOPSESSION cannot terminate the connection. STOPSESSION can terminate connections that are inactive, idle, or using the database but not blocked.

You cannot stop the current, active session in which you are executing the STOPSESSION call.

Example

This example requires that you create the following variables, and assumes that you have a table named CacheStressTest that you use for testing.

Variable name | DataType | Subtype
SessionId | Integer | Not applicable
CacheStressTestRec | Record | CacheStressTest
Copy Code
STARTSESSION(SessionId, CODEUNIT::"Cache Stress Test", COMPANYNAME, CacheStressTestRec);
STOPSESSION(SessionId, 'Logoff cache stress test session');


CURRENTCLIENTTYPE Function

Gets the Microsoft Dynamics NAV client type that is running in current session.

[ClientType :=] CURRENTCLIENTTYPE

Property Value/Return Value

Type: ClientType

The Microsoft Dynamics NAV client type for the current session, which can be one of the following values:

Value | Description
Windows | Microsoft Dynamics NAV Windows client
Web | Microsoft Dynamics NAV Web client
Tablet | Microsoft Dynamics NAV Tablet client
Desktop | Microsoft Dynamics NAV Web client running the app
Phone | Microsoft Dynamics NAV Phone client

Remarks

You can use CURRENTCLIENTTYPE as a parameter in GETURL Function to get the URL of the current client.

Example

In the following example, CURRENTCLIENTTYPE is used to get the Microsoft Dynamics NAV client type for the session and return a message if the session uses the Microsoft Dynamics NAV Windows client.

Copy Code
IF CURRENTCLIENTTYPE = CLIENTTYPE::Windows THEN
  Message('The session is running the Microsoft Dynamics NAV Windows client');

In the following example, CURRENTCLIENTTYPE is used as a parameter of the GETURL Function to return the URL of the Microsoft Dynamics NAV client that invokes the code.

Copy Code
url := GETURL(CURRENTCLIENTTYPE);
MESSAGE('The URL is %1.', url);

See Also

Concepts

Sessions


DEFAULTCLIENTTYPE Function

Gets the default Microsoft Dynamics NAV client that is configured for the Microsoft Dynamics NAV Server instance that is used by the current session.

[ClientType :=] DEFAULTCLIENTTYPE

Property Value/Return Value

Type: ClientType

The default Microsoft Dynamics NAV client, which be one of the following values:

Value | Description
Windows | Microsoft Dynamics NAV Windows client
Web | Microsoft Dynamics NAV Web client
Tablet | Microsoft Dynamics NAV Tablet client
Desktop | Microsoft Dynamics NAV Web client running the app
Phone | Microsoft Dynamics NAV Phone client

Remarks

The default Microsoft Dynamics NAV client is specified by the DefaultClient setting in the CustomSettings.config file for the Microsoft Dynamics NAV Server instance. You can view and change the setting by opening the CustomSettings.config file directly or using the Microsoft Dynamics NAV Server Administration tool. For more information, see Configuring Microsoft Dynamics NAV Server.

You can use DEFAULTCLIENTTYPE in a GETURL Function call to get the URL of the default Microsoft Dynamics NAV client.

Example

In the following example, DEFAULTCLIENTTYPE is used to return the default Microsoft Dynamics NAV client type that is configured for the Microsoft Dynamics NAV Server instance that is used by the current session.

Copy Code
IF CURRENTCLIENTTYPE = CLIENTTYPE::Windows THEN
  Message('The default client is Microsoft Dynamics NAV Windows client');

In the following example, DEFAULTCLIENTTYPE is used as a parameter in the GETURL function to return the URL of the default Microsoft Dynamics NAV client that is configured for the Microsoft Dynamics NAV Server instance.

Copy Code
url := GETURL(DEFAULTCLIENTTYPE);
MESSAGE('The URL is %1.', url);

See Also

Concepts

Sessions


BINDSUBSCRIPTION Function

Binds the event subscriber functions in the codeunit to the current codeunit instance for handling the events that they subscribe to. This essentially activates the subscriber functions for the codeunit instance.

[OK:=] BINDSUBSCRIPTION(Codeunit)

Parameters

Codeunit

Type: Codeunit

The codeunit that contains the event subscribers.

Property Value/Return Value

Type: Boolean

true if the event subscriber functions bind successfully to the codeunit instance and no errors occurred; otherwise false.

If you omit this optional return value and the binding is not successful, then a run-time error occurs. If you include the return value, then you must handle any errors.

Remarks

You can only call this function on codeunits that have the EventSubscriberInstance Property set to Manual.

The codeunit instance to which event subscribers bind will be this exact instance and events will be raised on this instance. You cannot bind the same instance more than once, but you can bind multiple instances of the same codeunit. This will result in an event subscriber call on each bound instance when a given event is raised.

Example

The following code illustrates a typical use of the BINDSUBSCRIPTION function.

Copy Code
Function MyFunction(….)
LocalVar
  SubScriberCodeunit5000;
BEGIN
  // Set global information on the subscriber codeunit if required
  // You can rely on the instance being the same as the one receiving the event subscriber call
  SubScriberCodeunit5000.MySetGlobalInfo(<info you can later test in the subscriber event method>)
  BINDSUBSCRIPTION(SubscriberCodeunit5000);
  DoSomething(…);  // After binding, all subscriptions on SubscriberCodeunit5000 are “active”.
END; // Notice, that when SubScriberCodeunit888 goes out of scope, all bindings are removed.

See Also

Reference

UNBINDSUBSCRIPTION

Concepts

Events in Microsoft Dynamics NAV
Subscribing to Events
Raising Events
Publishing Events


UNBINDSUBSCRIPTION

Unbinds the event subscriber functions from in the codeunit instance. This essentially deactivates the subscriber functions for the codeunit instance.

[OK:=] UNBINDSUBSCRIPTION(Codeunit)

Parameters

Codeunit

Type: Codeunit

The codeunit that contains the event subscribers.

Property Value/Return Value

Type: Boolean

true if the event subscriber functions unbind successfully to the codeunit instance and no errors occurred; otherwise false.

If you omit this optional return value and the operation is not successful, then a run-time error occurs. If you include the return value, then you must handle any errors.

Remarks

You can only call this function on codeunits that have the EventSubscriberInstance Property set to Manual.

Calling this function on a codeunit that has not been bound (by the BINDSUBSCRIPTION Function) will result in an error. If the call to this function is successfull, all bindings are removed.

The codeunit instance that is unbound will be the same instance that previously was bound.

Example

The following code illustrates a typical use of the BINDSUBSCRIPTION function.

Copy Code
Function MyFunction(….)
LocalVar
  SubScriberCodeunit5000;
BEGIN
  // Set global information on the subscriber codeunit if required
  // You can rely on the instance being the same as the one receiving the event subscriber call
  SubScriberCodeunit5000.MySetGlobalInfo(<info you can later test in the subscriber event method>)
  BINDSUBSCRIPTION(SubscriberCodeunit5000);
  DoSomething(…);  // After binding, all subscriptions on SubscriberCodeunit5000 are “active”.
  UNBINDSUBSCRIPTION(SubscriberCodeunit888);  // Now deactivating again
  DoStuff(…);  // This time no events are raised inside SubscriberCodeunit888;
END;

See Also

Reference

BINDSUBSCRIPTION Function

Concepts

Events in Microsoft Dynamics NAV
Subscribing to Events
Raising Events
Publishing Events


Strings

This section contains the following topics:

  • BigText Data Type

  • Code Data Type

  • Text Data Type

  • BigText Functions

  • String Functions

We recommend the following guidelines for using the BigText, Code, and Text data types:

  • Use the BigText data type for large documents.

  • If a text field is part of a primary key, then use the Code data type.

  • If a text field has a TableRelation, then use the Code data type.

  • If the field is assigned values from a Code field, then use the Code data type. For example, if the Document No. field in the G/L Entry table is copied from the primary key field No. in the Sales Header or Purchase Header table, then use the Code data type for the Document No. field.

  • For all other text fields, use the Text data type.

In addition to the system functions that are available for string data types, you can also use C/AL operators on strings. For example, to concatenate two strings, use the + operator. For more information, see C/AL Operators.


BigText Data Type

This complex data type handles large text documents.

Remarks

This data type cannot be shown in a message window or be seen in the Debugger.

The maximum length of a BigText variable is 2,147,483,647 characters and this corresponds to 2 GB.

You can use the BigText functions to manipulate a BigText variable, for example to extract part of a BigText variable or to add a text string to a BigText variable.

The normal string functions cannot be used with a BigText variable.

See Also

Reference

ADDTEXT Function (BigText)
GETSUBTEXT Function (BigText)
LENGTH Function (BigText)
READ Function (BigText)
TEXTPOS Function (BigText)
WRITE Function (BigText)


Code Data Type

This simple data type denotes a special type of string that is converted to uppercase and removes any trailing or leading spaces.

Remarks

The length of a Code variable equals the number of characters in the text without leading or trailing spaces.

You must specify the length of a Code variable or field. The maximum length of a Code variable is 1024 characters. The maximum length of a Code field in a table is 250 characters.

A Code variable cannot be null.

The Code data type supports Unicode.

You can index any character position in a string, such as A[65]. The resulting value will be a Char Data Type.

Fields that contain a date formula must not have data type Code. Instead, use the DateFormula Data Type. All fields that contain a date formula with data type Code must be converted into data type DateFormula.

You cannot assign a char to a position in the code variable greater than the current length of the variable +1. For more information, see Char Data Type.

Example

This example shows some typical examples of code string assignments. In these examples, assume that the variable c is a code variable with a maximum length of 4.

Copy Code
c := 'ABC';
// Results in variable c, which contains 'ABC'
// and is 3 characters in length.
c := '1';
// Results in variable c, which contains '1'
// and is 1 character in length.
c := '';
// Results in variable c, which contains '' (empty string)
// and is zero (0) characters in length.
c := ' 2 ';
// Results in variable c, which contains '2'
// and is 1 character in length.

See Also

Reference

CONVERTSTR Function (Code, Text)
COPYSTR Function (Code, Text)
DELCHR Function (Code, Text)
DELSTR Function (Code, Text)
FORMAT Function (Code, Text)
INCSTR Function (Code, Text)
INSSTR Function (Code, Text)
LOWERCASE Function (Code, Text)
MAXSTRLEN Function (Code, Text)
PADSTR Function (Code, Text)
SELECTSTR Function (Code, Text)
STRCHECKSUM Function (Code, Text)
STRLEN Function (Code, Text)
STRPOS Function (Code, Text)
STRSUBSTNO Function (Code, Text)
UPPERCASE Function (Code, Text)


Text Data Type

This simple data type denotes a text string.

Remarks

Microsoft Dynamics NAV 2016 does not enforce a limit on the length of a Text variable. You can specify a maximum length in the C/AL Globals or C/AL Locals window when you create the variable, but it is not required. There is no performance impact if you do not specify a length. The maximum length of a Text field in a table is 250 characters. The length of a text variable equals the number of characters in the string. An empty text string has a length of zero (0). A text string cannot be null.

You can index any character position in a text string, for example A[65]. The resulting value will be a Char Data Type.

You cannot assign a char to a position in the code variable greater than the current length of the variable +1. For more information, see Char Data Type.

The Text data type supports Unicode.

Example

This example shows some typical examples of text strings. In these examples, the text variable has a maximum length of 6.

Copy Code
text := 'ABC';
// Results in a text variable which contains 'ABC'.
text := '123456abc';
// Results in a run-time error because the length (9)
// exceeds the maximum length of 6.

See Also

Reference

CONVERTSTR Function (Code, Text)
COPYSTR Function (Code, Text)
DELCHR Function (Code, Text)
DELSTR Function (Code, Text)
FORMAT Function (Code, Text)
INCSTR Function (Code, Text)
INSSTR Function (Code, Text)
LOWERCASE Function (Code, Text)
MAXSTRLEN Function (Code, Text)
PADSTR Function (Code, Text)
SELECTSTR Function (Code, Text)
STRCHECKSUM Function (Code, Text)
STRLEN Function (Code, Text)
STRPOS Function (Code, Text)
STRSUBSTNO Function (Code, Text)
UPPERCASE Function (Code, Text)


BigText Functions

This section contains the following topics:

  • ADDTEXT Function (BigText)

  • GETSUBTEXT Function (BigText)

  • LENGTH Function (BigText)

  • READ Function (BigText)

  • TEXTPOS Function (BigText)

  • WRITE Function (BigText)


ADDTEXT Function (BigText)

Adds a text string to a BigText variable.

BigText.ADDTEXT(Variable[, Position])

Parameters

BigText

Type: BigText

The BigText to which the text string will be added.

Variable

Type: BigText, Code, or Text

The string that will be added to the BigText variable. If this parameter is empty, then the BigText variable is not modified.

Position

Type: Integer

This is an optional parameter that defines the position in the BigText variable where the string is inserted. If this parameter is omitted, then the string is added at the end of the BigText variable. If this parameter is less than one, then a run-time error occurs. If this parameter is greater than the length of the BigText variable, then the string is added at the end of the BigText variable.

Remarks

Variable can be inserted anywhere in BigText or added at the end of the BigText.

The first character in a BigText variable is position 1.

To delete the content in a BigText variable, use the CLEAR Function. The following code shows the syntax for the function: CLEAR(BigText)

Note
If you use ADDTEXT to add multiple BigText strings to what is presented as a single string, you can experience performance problems. The same applies to other repetitive uses of ADDTEXT. This is due to the implementation of the BigText data type, which relies on a String object that is immutable. You can avoid this issue by refactoring the code to reduce the number of additions or deletions. Alternatively, you can change your implementation to use the System.Text.StringBuilder class instead. For more information, see Immutability and the StringBuilder Class in the MSDN Library.

Example

The following examples show how to use the ADDTEXT function. The specified text is inserted into the BigText string at the specified position. In these examples, the initial content of the BigText variable is ABCDEFG. These examples require that you create the following variables.

Variable name | DataType
MyBigText | BigText

The following example inserts the string 'ZZZ' after the character B in the MyBigText variable because 3 is specified for Position.

Copy Code
// Example 1
MyBigText.ADDTEXT('ABCDEFG');
MyBigText.ADDTEXT('ZZZ', 3); // Returns the subtext ABZZZCDEFG.

Example

The following example appends the string 'ZZZ' at the end of the MyBigText variable because the number specified for Position is greater than the length of the MyBigText variable.

Copy Code
// Example 2
MyBigText.ADDTEXT('ABCDEFG');
MyBigText.ADDTEXT('ZZZ', 15); // Returns the subtext ABCDEFGZZZ.

Example

In the following example, the content of the MyBigText variable is unchanged because the specified variable is an empty string.

Copy Code
// Example 3
MyBigText.ADDTEXT('ABCDEFG');
MyBigText.ADDTEXT('', 1); // Returns the subtext ABCDEFG.

Example

In the following example, the function returns an error because 0 is specified for Position.

Copy Code
// Example 4
MyBigText.ADDTEXT('ABCDEFG');
MyBigText.ADDTEXT('ZZZ', 0); // Returns an error.

See Also

Reference

BigText Data Type
ADDTEXT Function (BigText)


GETSUBTEXT Function (BigText)

Gets part of a BigText variable.

[RetLength :=] BigText.GETSUBTEXT(Variable, Position[, Length])

Parameters

Variable

Type: Text or BigText

The subtext of the BigText that is retrieved. This is the actual text that is returned.

Position

Type: Integer

The position in the BigText variable that the subtext is to be retrieved from. If this parameter is less than one, then a run-time error occurs. If this parameter is greater than the length of the BigText variable, then an empty string is returned. If the value of this parameter plus the value of the Length parameter is greater than the length of the BigText variable, then the remainder of the BigText variable from the position specified by this parameter is returned.

Length

Type: Integer

The length of the subtext that should be retrieved. This parameter is optional. If this parameter is omitted the function retrieves a subtext that starts at Position and runs to the end of the BigText variable. If this parameter is less than 0, then a run-time error occurs. If the value of the Position parameter plus the value of this parameter is greater than the length of the BigText variable, then the remainder of the BigText variable from the position specified by this parameter is returned.

Property Value/Return Value

Type: Integer

The length of the string that is retrieved from the variable.

Remarks

The first character in a BigText variable is position 1.

To delete the content in a BigText variable use the CLEAR Function. The following code snippet shows the syntax for the clear function. CLEAR(BigText).

Example

The following examples demonstrate how to use the GETSUBTEXT function. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable Name | DataType
MyBigText | BigText
VarSubText | Text

Text Constant Name | ENU Value
Text000 | VarSubText = %1

The following example initializes the content of the MyBigText variable with the text ABCDEFG. The function starts from the third position (the character C) in the MyBigText variable and retrieves two characters. The result is the subtext CD. This is because the number 2 is specified for Length .

Copy Code
MyBigText.ADDTEXT('ABCDEFG');
MyBigText.GETSUBTEXT(VarSubText, 3, 2); // Returns CD.
MESSAGE(Text000, VarSubText);

Example

The following example initializes the content of the MyBigText variable with the text ABCDEFG. The function returns an error because zero is specified for Position.

Copy Code
MyBigText.ADDTEXT('ABCDEFG');
MyBigText.GETSUBTEXT(VarSubText, 0, 4); // Returns an error.
MESSAGE(Text000, VarSubText);

Example

The following example initializes the content of the MyBigText variable with the text ABCDEFG. The function returns an error because a negative number is specified for Length.

Copy Code
MyBigText.ADDTEXT('ABCDEFG');
MyBigText.GETSUBTEXT(VarSubText, 5, -2); // Returns an error.
MESSAGE(Text000, VarSubText);

Example

The following example initializes the content of the MyBigText variable with the text ABCDEFG. The function returns an empty string because the number specified for position is greater than the length of the MyBigText variable.

Copy Code
MyBigText.ADDTEXT('ABCDEFG');
MyBigText.GETSUBTEXT(VarSubText, 15, 4); // Returns an empty string.
MESSAGE(Text000, VarSubText);

Example

The following example initializes the content of the MyBigText variable with the text ABCDEFG. The function starts from the forth position (the character D) and retrieves all the characters in the MyBigText string. The result is the subtext DEFG. This is because the number specified for Length is greater than the length of the MyBigText variable.

Copy Code
MyBigText.ADDTEXT('ABCDEFG');
MyBigText.GETSUBTEXT(VarSubText, 4, 15); // Returns DEFG.
MESSAGE(Text000, VarSubText);

See Also

Reference

BigText Data Type

Concepts

BigText Functions


LENGTH Function (BigText)

Retrieves the length of a BigText variable.

Length := BigText.LENGTH

Property Value/Return Value

Type: Integer

The length of the BigText variable.

Remarks

To delete the content in a BigText variable use the CLEAR Function. The syntax for the CLEAR function is shown in the following code snippet: CLEAR(BigText).

Example

The following example demonstrates how to retrieve the length of a BigText variable. This example requires that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
MyBigText | BigText
VarLength | Integer

Text constant name | ENU value
Text000 | VarLength = %1

In this example, the BigText variable is initialized with the text ‘ABCDEFG’. The length, which is 7, is stored in the VarLength variable and displayed in a message box.

Copy Code
 MyBigText.ADDTEXT('ABCDEFG');
 VarLength := MyBigText.LENGTH;
 MESSAGE(Text000, VarLength);

See Also

Reference

BigText Data Type


READ Function (BigText)

Streams a BigText object that is stored as a BLOB in a table to a BigText variable.

[Ok := ] BigText.READ(InStream)

Parameters

BigText

Type: BigText

The BigText variable into which you stream the BLOB.

InStream

Type: InStream

The InStream object type that you use to stream a BLOB to a BigText variable.

Property Value/Return Value

Type: Boolean

true if the read transaction was successful; otherwise, false.

Remarks

To delete the content in a BigText variable, use the CLEAR function.

Copy Code
CLEAR(BigText)

Example

This example shows how to stream a BigText that is stored as a BLOB in a table to a BigText variable.

This example requires that you define the following variables.

Variable | DataType | Subtype
Bstr | BigText | Not applicable
EmployeeRec | Record | Employee
Istream | InStream | Not applicable
Copy Code
EmployeeRec.FIND('-');
EmployeeRec.CALCFIELDS(Picture);
EmployeeRec.Picture.CREATEINSTREAM(Istream);
Bstr.READ(Istream);

Use the CALCFIELDS Function (Record) to calculate the BlobField. A BlobField is a binary large object (maximum size 2 GB) and must be calculated if you want to use it in C/AL or display it in the application.

See Also

Reference

BigText Data Type


TEXTPOS Function (BigText)

Gets the position at which a specific string first occurs in a BigText.

Position := BigText.TEXTPOS(String)

Parameters

String

Type: Text

The text string to search for in the BigText variable. If this parameter is empty, then 0 is returned.

Property Value/Return Value

Type: Integer

This return value indicates the position where the first occurrence of the string starts in the BigText variable.

If String is not found in the BigText variable, then 0 is returned.

Remarks

The first character in a BigText variable is position 1.

Example

The following examples show how to use the TEXTPOS function. These examples require that you create the following variables and text constant in the C/AL Globals window.

Variable name | DataType
MyBigText | BigText
VarPosition | Integer

Text constant name | ENU value
Text000 | VarPosition = %1

The following examples first initialize the content of the BigText variable with the text ABCDEFG.

In this example, the first occurrence of the character B (the first character of the specified text) is found in the second position in the MyBigText variable so the function returns 2. The return value is stored in the variable VarPosition and displayed in a message box.

Copy Code
MyBigText.ADDTEXT('ABCDEFG');
VarPosition := MyBigText.TEXTPOS('BCD'); // Returns 2.
MESSAGE(Text000, VarPosition);

Example

In the following example, the function returns 0 because the specified string is not found in the MyBigText variable. The return value is stored in the variable VarPosition and displayed in a message box.

Copy Code
MyBigText.ADDTEXT('ABCDEFG');
VarPosition := MyBigText.TEXTPOS(''); // Returns 0.
MESSAGE(Text000, VarPosition);

Example

In the following example, the function returns 0 because the specified string is not found in the MyBigText variable. The return value is stored in the variable VarPosition and displayed in a message box.

Copy Code
MyBigText.ADDTEXT('ABCDEFG');
VarPosition := MyBigText.TEXTPOS('XYZ'); // Returns 0.
MESSAGE(Text000, VarPosition);

See Also

Reference

BigText Data Type

Concepts

BigText Functions


WRITE Function (BigText)

Streams a BigText object to a BLOB field in a table.

[Ok := ] BigText.WRITE(OutStream)

Parameters

BigText

Type: BigText

The BigText that you want to write to a BLOB field.

OutStream

Type: OutStream

The stream to which you write a BigText.

Property Value/Return Value

Type: Boolean

This optional return value specifies whether the write transaction was successful.

Remarks

To delete the content in a BigText variable, use the CLEAR function.

Copy Code
CLEAR(BigText)

Example

This example shows how to stream a BigText to a BLOB field in a table.

This example requires that you define the following variables.

Variable name | DataType | Subtype
Bstr | BigText | Not applicable
ItemRec | Record | Item
Ostream | OutStream | Not applicable
Copy Code
Bstr.ADDTEXT('This is the text string that we want to store in a BLOB field.');
ItemRec.Picture.CREATEOUTSTREAM(Ostream);
Bstr.WRITE(Ostream);
ItemRec.INSERT;

See Also

Reference

BigText Data Type


String Functions

This section contains the following topics:

  • CONVERTSTR Function (Code, Text)

  • COPYSTR Function (Code, Text)

  • DELCHR Function (Code, Text)

  • DELSTR Function (Code, Text)

  • FORMAT Function (Code, Text)

  • INCSTR Function (Code, Text)

  • INSSTR Function (Code, Text)

  • LOWERCASE Function (Code, Text)

  • MAXSTRLEN Function (Code, Text)

  • PADSTR Function (Code, Text)

  • SELECTSTR Function (Code, Text)

  • STRCHECKSUM Function (Code, Text)

  • STRLEN Function (Code, Text)

  • STRPOS Function (Code, Text)

  • STRSUBSTNO Function (Code, Text)

  • UPPERCASE Function (Code, Text)


CONVERTSTR Function (Code, Text)

Converts some characters in a string.

NewString := CONVERTSTR(String, FromCharacters, ToCharacters)

Parameters

String

Type: Text constant or code

The string that you want to convert.

FromCharacters

Type: Text constant or code

The characters that you want to replace. This function is case-sensitive.

ToCharacters

Type: Text constant or code

The new characters with which you want to replace the FromCharacters. This function is case-sensitive.

The length of this string must correspond to the length of FromCharacters.

Each character in FromCharacters is replaced with the corresponding character in ToCharacters.

Property Value/Return Value

Type: Text constant or code

The converted string.

Remarks

The characters in the FromCharacters parameter are replaced by the characters in the ToCharacters parameter.

If the lengths of the FromCharacters and ToCharacters strings are not equal, then a run-time error occurs.

If either the FromCharacters or the ToCharacters strings are empty, then the source is returned unchanged.

Example

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Length
OriginalString | Text | 30
FromChars | Text | 30
ToChars | Text | 30
NewString | Text | 30

Text constant | ENU value
Text000 | Do you want to leave without saving?
Text001 | lws
Text002 | LWS
Text003 | The original sentence is:\ %1
Text004 | The sentence is converted to:\ %1
Copy Code
OriginalString := Text000;
FromChars := Text001;
ToChars := Text002;
NewString := CONVERTSTR(OriginalString, FromChars, ToChars);
MESSAGE(Text003, OriginalString);
MESSAGE(Text004, NewString);

The first message window shows:

The original sentence is:

Do you want to leave without saving?

The second message window shows:

The sentence is converted to:

Do you Want to Leave Without Saving?

See Also

Reference

Code Data Type
Text Data Type


COPYSTR Function (Code, Text)

Copies a substring of any length from a specific position in a string (text or code) to a new string.

NewString := COPYSTR(String, Position[, Length])

Parameters

String

Type: Text constant or code

The string that you want to copy from.

Position

Type: Integer

The position of the first character to copy. If the value of Position is less than 1, then the COPYSTR function returns an error. If Position is greater than the length of the string, then the COPYSTR function returns an empty string.

Length

Type: Integer

The number of characters to copy. If the value of Length is less than 0, then the COPYSTR function returns an error. If the value of Length causes Position + Length to be > (total length of the string), then the result includes all the characters from Position to the end of the string. If you omit Length, then the resulting string includes all the characters from Position to the end of the string.

Property Value/Return Value

Type: Text constant or code

The resulting string or substring.

Remarks

If Position combined with Length exceeds the length of the string, all the characters from Position to the end of the string are returned.

Example

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Length
Str | Text | 30
Position | Integer | Not applicable
Length | Integer | Not applicable
NewStr | Text | 30

Text constant | ENU value
Text000 | Using the COPYSTR function
Text001 | The original string is:\>%1<
Text002 | The copied string is:\>%1<
Copy Code
Str := Text000;
Position := 7;
Length := 8;
MESSAGE(Text001, Str);
NewStr := COPYSTR(Str, Position, Length);
MESSAGE(Text002, NewStr);

The first message window shows the original string:

The original string is:

>Using the COPYSTR function<

The second message window shows the copied string:

The copied string is:

>the COPY<

See Also

Reference

Code Data Type
Text Data Type


DELCHR Function (Code, Text)

Deletes one or more characters in a string.

NewString := DELCHR(String[, Where][, Which])

Parameters

String

Type: Text constant or code

The input string.

Where

Type: Text constant or code

Specifies where to delete characters.

You can include one or more of the following characters in the Where string:

  • = To delete any character in String that matches a character in Which (default)

  • < To delete any leading character in String that matches a character in Which

  • > To delete any trailing character in String that matches a character in Which

Which

Type: Text or code

Specifies the characters that you want to delete.

The default is a space character.

Property Value/Return Value

Type: Text constant or code

The resulting string.

Remarks

The DELCHR function is case-sensitive.

If you omit the Which parameter, then the function deletes spaces from String based on the contents of the Where parameter as follows:

  • If Where contains =, then all the spaces are deleted from String.

  • If Where contains <, then all the spaces at the start of String are deleted.

  • If Where contains >, then all the spaces at the end of String are deleted.

  • If Where contains any other character, then an error is returned.

  • If Where is empty, then String is returned unchanged.

If you use the Where and the Which parameters, then the function deletes from String the characters that are contained in the Which parameter based on the contents of the Where parameter as follows:

  • If Where contains =, then every occurrence of the characters in Which are deleted from String.

  • If Where contains <, then the characters in Which are only deleted if they occur at the start of String.

  • If Where contains >, then the characters in Which are deleted only if they occur at the end of String.

  • If Where contains any other character, then an error is returned.

  • If Where is empty, then String is returned unchanged.

  • If Which is empty, then String is returned unchanged.

The Which parameter contains an array of the characters that you want to delete. The order of the characters is of no significance. If String contains a character that is specified in Which, it is deleted from String.

Example

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
String | Text
Where | Text
Which | Text
NewString | Text

Text constant name | ConstValue
Text000 | Windy West Solutions
Text001 | >%1< is transformed to >%2<
Copy Code
String := Text000;
Where := '<>';
Which := 'Ws';
NewString := DELCHR(String, Where, Which);
MESSAGE(Text001, String,NewString);

The message window displays the following:

>Windy West Solutions< is transformed to >indy West Solution<

The function deletes every W and s that is either the first or last character in String.

Example

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
String | Text
Where | Text
Which | Text
NewString | Text

Text constant name | ConstValue
Text000 | This is an example
Text001 | >%1< is transformed to >%2<
Copy Code
String := Text000;
Where := '=';
Which := 'sx';
NewString := DELCHR(String, Where, Which);
MESSAGE(Text001, String,NewString);

The message window displays the following:

>This is an example< is transformed to >Thi i an eample<

The function deletes every s and x from String.

Example

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
String | Text
Where | Text
Which | Text
NewString | Text

Text constant name | ConstValue
Text000 | This is an example
Text001 | >%1< is transformed to >%2<
Copy Code
String := Text000;
Where := '>';
Which := 'Tely';
NewString := DELCHR(String, Where, Which);
MESSAGE(Text001, String,NewString);

The message window displays the following:

>This is an example< is transformed to >This is an examp<

If T, e, l, or y is the last character in String, the function deletes them.

Example

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
String | Text
Where | Text
Which | Text
NewString | Text

Text constant name | ConstValue
Text000 | This is an example
Text001 | >%1< is transformed to >%2<
Copy Code
String := Text000;
Where := '<';
Which := 'This';
NewString := DELCHR(String, Where, Which);
MESSAGE(Text001, String,NewString);

The message window displays the following:

>This is an example< is transformed to >an example<

If T, h, s, i, or space is the first character in String, the function deletes them.

Example

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
String | Text
Where | Text
Which | Text
NewString | Text

Text constant name | ConstValue
Text000 | This is an example
Text001 | >%1< is transformed to >%2<
Copy Code
String := Text000;
Where := '<';
NewString := DELCHR(String, Where);
MESSAGE(Text001, String,NewString);

The message window displays the following:

> This is an example< is transformed to >This is an example<

The function removes any spaces from the start of String.

See Also

Reference

Code Data Type
Text Data Type


DELSTR Function (Code, Text)

Deletes a substring inside a string (text or code).

NewString := DELSTR(String, Position[, Length])

Parameters

String

Type: Text constant or code

The input string.

Position

Type: Integer

The position of the first character that you want to delete. Position must be greater than zero (0).

If Position exceeds the length of String, DELSTR returns the original string, unchanged.

Length

Type: Integer

Specifies how many characters to delete. Length must be greater than zero (0).

Property Value/Return Value

Type: Text constant or code

The resulting string.

Remarks

If you omit Length, all the characters starting with Position are deleted until the end of the string.

If you omit Length and Position is less than 1, then an error is returned.

If you omit Length and Position is greater than the length of String, then String is returned unchanged.

Example

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Length
Str | Text | 40
Position | Integer | Not applicable
Length | Integer | Not applicable
NewStr | Text | 40

Text constant | ENU value
Text000 | Adjusting prices - Please wait.
Text001 | The original string:\>%1<
Text002 | The modified string:\>%2<
Copy Code
Str := Text000;
Position := 11; // Remove the word 'prices' and a blank.
Length := 7;
NewStr := DELSTR(Str, Position, Length);
MESSAGE(Text001, Str);
MESSAGE(Text002, NewStr);

The first message window displays the following:

The original string:

>Adjusting prices - Please wait.<

The second message window displays the following:

The modified string:

>Adjusting - Please wait.<

See Also

Reference

Code Data Type
Text Data Type


FORMAT Function (Code, Text)

Formats a value into a string.

String := FORMAT(Value[, Length][, FormatStr/FormatNumber])

Parameters

Value

Type: Any

This is a C/AL variable (expression) of any simple data type, such as Option, Integer, BigInteger, Decimal, Char, Text, Code, Date, Time, DateTime, Boolean, or GUID.

If, when the system formats Value, the result is a value larger than the maximum length MAXSTRLEN Function (Code, Text) of String, a run-time error occurs.

Length

Type: Integer

This optional parameter specifies the length of String. The following rules apply:

  • If Length = 0 then the entire value is returned (default).

  • If Length > 0 then the returned string will be exactly Length characters.

    If Value is less than Length characters, then either leading or trailing spaces are inserted, depending on the format that you select.

    If Value exceeds Length characters, then String is truncated to Length characters.

  • If Length < 0 then the returned string will not have leading or trailing spaces.

    If Value is less than Length characters, the length of String will equal the length of Value.

    If Value exceeds Length characters, then String is truncated to Length characters.

FormatStr

Type: String

A literal string that defines a format as in the Format Property.

FormatNumber

Type: Integer

This optional parameter specifies the format that you want to use. The basic options for the Decimal data type are as follows:

  • <Sign><Integer Thousand><Decimals> is Format 0

  • <Sign><Integer><Decimals> is Format 1

  • <Sign><Integer><Decimals><Comma,.> is Format 2

  • <Integer Thousand><Decimals><Sign,1> is Format 3

  • <Integer><Decimals><Sign,1> is Format 4

Note
You cannot use both FormatNumber and FormatStr at the same time.

Property Value/Return Value

Type: Text or code

The formatted output string.

Remarks

For more information about the formats that are used by the various data types, see Format Property. This topic describes the various predefined formats in detail, and how to create customized formats.

Format 9 is designed to be used when importing data with an XMLport and converts data from XML format to the corresponding C/SIDE formats.

Example

This example requires that you create the following text constant in the C/AL Globals window.

Text constant | ENU value
Text000 | The formatted value: >%1<
Copy Code
MESSAGE(Text000, FORMAT(-123456.78, 12, 3));
MESSAGE(Text000, FORMAT(-123456.78, 12, '<Standard Format,3>'));
MESSAGE(Text000, FORMAT(-123456.78, 12, '<Integer Thousand><Decimals><Sign,1>'));

The Regional and Language settings on the computer on which you run the code affect how the string is displayed. For example, on a computer that has the regional format set to English (United States), the message window displays the following:

The formatted value: > 123,456.78-<

The formatted value: > 123,456.78-<

The formatted value: > 123,456.78-<

On a computer that has the regional format set to Danish (Denmark), the message window displays the following:

The formatted value: > 123.456,78-<

The formatted value: > 123.456,78-<

The formatted value: > 123.456,78-<

Example

This example shows how to use a string to build a format.

This example requires that you create the following text constant in the C/AL Globals window.

Text constant | ENU value
Text000 | Today is %1.
Copy Code
MESSAGE(Text000, FORMAT(TODAY,0,'<Month Text> <Day>'));

The message window displays the following:

Today is April 15.

See Also

Reference

Format Property
EVALUATE Function
Code Data Type
Text Data Type


INCSTR Function (Code, Text)

Increases a positive number or decrease a negative number inside a string by one (1).

NewString := INCSTR(String)

Parameters

String

Type: Text constant or code

The string that you want to increase or decrease.

Property Value/Return Value

Type: Text constant or code

The result after increasing or decreasing String.

Remarks

If String contains more than one number, then only the number closest to the end of the string is changed. For example, 'A10B20' is changed to 'A10B21' and 'a12b12c' to 'a12b13c'.

If String contains a negative number, then it is decreased by one. For example, '-55' is changed to '-56'.

Zero (0) is considered a positive number. Therefore, it is increased it by one. For example, 'A0' is changed to 'A1'.

When String contains a number such as 99, it is increased to 100 and the length of the output string is: LEN(String) + 1. For example, 'a12b99c' is changed to 'a12b100c'.

If String does not contain any number, the output string is an empty string. For example, 'aaa' is changed to ''.

INCSTR only increments integer numbers within strings, not decimals. For example, if you call INCSTR on the string a99.99b then the result is a99.100b.

Example

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Length
Account | Text | 60
NegAccount | Text | 60
EmptyAccount | Text | 60
MyAccount | Text | 60
ResultAccount | Text | 60
ResultNegAccount | Text | 60
ResultEmptyAccount | Text | 60
ResultMyAccount | Text | 60

Text constant | ENU value
Text000 | Account no. 99 does not balance.
Text001 | Account no. 2342 shows a total of $-452.
Text002 | My bank account is empty.
Text003 | My bank account shows a total of $0.
Text004 | The text strings before INCSTR is called:\%1\%2\%3\%4
Text005 | The text strings after INCSTR is called:\%1\%2\%3\%5
Copy Code
Account := Text000;
NegAccount := Text001;
EmptyAccount := Text002;
MyAccount := Text003;
MESSAGE(Text004, Account, NegAccount, EmptyAccount, MyAccount);
ResultAccount := INCSTR(Account);
ResultNegAccount := INCSTR(NegAccount);
ResultEmptyAccount := INCSTR(EmptyAccount);
ResultMyAccount := INCSTR(MyAccount);
MESSAGE(Text005, ResultAccount, ResultNegAccount, ResultEmptyAccount, ResultMyAccount);

The first message displays the following:

The text strings before INCSTR is called:

Account no. 99 does not balance.

Account no. 2342 shows a total of $ -452.

My bank account is empty.

My bank account shows a total of $ 0.

The second message displays the following:

The text strings after INCSTR has been called:

Account no. 100 does not balance.

Account no. 2342 shows a total of $ -453.

My bank account shows a total of $ 1.

The example shows that if the string contains more than one number, only the last number is changed. Furthermore, positive numbers and zero are increased and negative numbers are decreased. Finally, if there are no numbers in the string, then an empty string is returned.

See Also

Reference

Code Data Type
Text Data Type


INSSTR Function (Code, Text)

Inserts a substring into a string.

NewString := INSSTR(String, SubString, Position)

Parameters

String

Type: Text constant or code

The string into which you want to insert a substring.

SubString

Type: Text constant or code

The substring that you want to insert into String.

Position

Type: Integer

Specifies where to insert SubString. Position must be greater than or equal to 1.

If Position is greater than the length of String, then the result is concatenated and copied to NewString.

Property Value/Return Value

Type: Text constant or code

The result after SubString is inserted into String.

Remarks

If SubString is empty, then String is returned unchanged.

If Position is less than 1, an error is returned.

If Position is greater than the length of String, SubString is added at the end of String. For example, INSSTR("Thomas","AAA",999) returns 'ThomasAAA'.

Example

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Subtype
Str | Text | 60
SubString | Text | 60
NewString | Text | 60

Text constant | ENU value
Text000 | Press ENTER to continue.
Text001 | or ESC
Text002 | The test string before INSSTR is called:\>%1<
Text003 | The resulting string after INSSTR is called:\>%1<
Copy Code
Str := Text000;
SubString := Text001;
MESSAGE(Text002, Str);
NewString := INSSTR(Str, SubString, 13);
MESSAGE(Text003, NewString);

The first message window displays the following:

The test string before INSSTR is called:

>Press ENTER to continue.<

The second message window displays the following:

The resulting string after INSSTR is called:

>Press ENTER or ESC to continue.<

See Also

Reference

Code Data Type
Text Data Type


LOWERCASE Function (Code, Text)

Converts all letters in a string to lowercase.

NewString := LOWERCASE(String)

Parameters

String

Type: Text constant or code

The string that you want to convert to lowercase. Only letters in the range A to Z and, if applicable, special language characters are converted.

Property Value/Return Value

Type: Text constant or code

The resulting string after it has been converted to lowercase.

Example

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Length
Str | Text | 60
Lower | Text | 60

Text constant | ENU value
Text000 | The Entries are Sorted by Name.
Text001 | The string before LOWERCASE is:\>%1<
Text002 | The string after LOWERCASE is:\>%1<
Copy Code
Str := Text000;
MESSAGE(Text001, Str);
Lower := LOWERCASE(Str);
MESSAGE(Text002, Lower);

The first message window displays the following:

The string before LOWERCASE is:

>The Entries are Sorted by Name.<

The second message window displays the following:

The string after LOWERCASE is:

>the entries are sorted by name.<

See Also

Reference

Code Data Type
Text Data Type


MAXSTRLEN Function (Code, Text)

Gets the maximum defined length of a string variable.

MaxLength := MAXSTRLEN(String)

Parameters

String

Type: Text constant or code

The string variable for which you want to find the maximum length.

Property Value/Return Value

Type: Integer

The maximum length of the string variable.

Remarks

If you call this function on a Variant, it returns an error.

Example

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Length
City | Text | 30
MaxLength | Integer | Not applicable
Length | Integer | Not applicable

Text constant | ENU value
Text000 | Vedbaek
Text001 | The MAXSTRLEN function returns %1,\
Text002 | whereas the STRLEN function returns %2
Copy Code
City := Text000;
MaxLength := MAXSTRLEN(City);
Length := STRLEN(City);
MESSAGE(Text001 + Text002, MaxLength, Length);

The message window displays the following:

The MAXSTRLEN function returns 30,

whereas the STRLEN function returns 7.

See Also

Reference

Code Data Type
Text Data Type


PADSTR Function (Code, Text)

Changes the length of a string to a length that you define.

NewString := PADSTR(String, Length[, FillCharacter])

Parameters

String

Type: Text constant or code

The string that you want to increase or decrease.

Length

Type: Integer

The new length of the output string.

If Length is less than the length of String, then String is truncated. Otherwise String is expanded with filler characters.

If Length is less than 0, then an error is returned.

FillCharacter

Type: Text constant or code

This is a string of length 1. This character is used to fill empty spaces at the end of the output string. If not specified, spaces are used as default. If the length of FillCharacter is not 1, an error is returned.

Property Value/Return Value

Type: Text constant or code

The output string. The length of the return value is Length characters. If the maximum (defined) length of NewString is less than Length, a run-time error occurs.

Remarks

If you omit FillCharacter and String is shorter than Length, then spaces are added at the end of String to match Length.

If you omit FillCharacter and String is longer than Length, then String is truncated.

Example

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Length
Str1 | Text | 30
Str2 | Text | 30
Len1 | Integer | Not applicable
Len2 | Integer | Not applicable

Text constant | ENU value
Text000 | 13 characters
Text001 | Four
Text002 | Before PADSTR is called:\
Text003 | >%1< has the length %2\
Text004 | >%3< has the length %4\
Text005 | After PADSTR is called:\
Copy Code
Str1 := Text000;
Str2 := Text001;
Len1 := STRLEN(Str1);
Len2 := STRLEN(Str2);
MESSAGE(Text002 + Text003 + Text004, Str1, Len1, Str2, Len2);
Str1 := PADSTR(Str1, 5); // Truncate the length to 5
Str2 := PADSTR(Str2, 15, 'w'); // Concatenate w until length = 15
Len1 := STRLEN(Str1);
Len2 := STRLEN(Str2);
MESSAGE(Text005 + Text003 + Text004, Str1, Len1, Str2, Len2);

The first message window displays the following:

Before PADSTR is called:

>13 characters< has the length 13

>Four< has the length 4

The second message window displays the following:

After PADSTR is called:

>13 ch< has the length 5

>Fourwwwwwwwwwww< has the length 15

See Also

Reference

Code Data Type
Text Data Type


SELECTSTR Function (Code, Text)

Retrieves a substring from a comma-separated string.

NewString := SELECTSTR(Number, CommaString)

Parameters

Number

Type: Integer

Specifies which substring to retrieve. The substrings in the comma-separated string are numbered 1, 2, 3, and so on.

If Number is greater than the actual number of substrings, then a run-time error occurs.

CommaString

Type: Option

A string that contains substrings separated by commas. The maximum length of this string is 391 characters.

Property Value/Return Value

Type: Option

The substring that is retrieved from CommaString.

Remarks

SELECTSTR treats string values as OPTIONS. This means that identical values in different strings are not allowed.

Any trailing commas are removed before the operation starts.

If Number is less than 1 or greater than the number of real values (excluding trailing commas) in the string, then an error is returned.

Quotes are not supported. For example, a,b,"c,d",e is treated as a five-element substring where substring 4 is d".

Example

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Length
CommaStr | Text | 60
CommaStr2 | Text | 60
SubStr1 | Text | 60
SubStr2 | Text | 60
SubStr3 | Text | 60
SubStr4 | Text | 60

Text constant | ENU value
Text000 | This,is a comma,separated,string
Text001 | The calls to SELECTSTR return:\
Text002 | 11,22,33,,55,,,
Copy Code
CommaStr := Text000;
CommaStr2 := Text002;
SubStr1 := SELECTSTR(2, CommaStr); // Pick out the 2nd substring.
SubStr2 := SELECTSTR(4, CommaStr); // Pick out the 4th substring.
SubStr3 := SELECTSTR(1, CommaStr2);
SubStr4 := SELECTSTR(3, CommaStr2);
MESSAGE(Text001 + '>%1<\' + '>%2<\' + '>%3<\' + '>%4<\', SubStr1, SubStr2, SubStr3, SubStr4);

The message window displays the following text:

The calls to SELECTSTR return:

>is a comma<

>string<

>11<

>33<

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Length
CommaStr2 | Text | 60
SubStr5 | Text | 60

Text constant | ENU value
Text002 | 11,22,33,,55,,,
Copy Code
CommaStr2 := Text002;
SubStr5 := SELECTSTR(6,CommaStr2);
MESSAGE('>%1<\', SubStr5);

This example returns an error.

See Also

Reference

Code Data Type
Text Data Type


STRCHECKSUM Function (Code, Text)

Calculates a checksum for a string that contains a number.

CheckNumber :=STRCHECKSUM(String[, WeightString][, Modulus])

Parameters

String

Type: Text constant or code

This string contains the number for which you want to calculate a checksum. You can only enter the numeric characters 0-9 in this string. If you enter anything else, a run-time error will occur. If String is empty, 0 is returned.

WeightString

Type: Text constant or code

This string contains numbers that you want to use as weights when calculating the checksum. The default value is a string that contains STRLEN(String) '1'-characters.

You can only enter the numeric characters 0-9 in this string. If you enter anything else, then a run-time error occurs.

If String is longer than WeightString, then a string is concatenated that contains STRLEN(String) - STRLEN(WeightString) '1'-characters to the end of WeightString. If WeightString is longer than String, then a run-time error occurs.

Modulus

Type: Integer

The number that you want to use in the checksum formula. The default value is 10.

Property Value/Return Value

Type: Integer

The checksum, which is calculated using this formula:

Example

This example shows how to use the STRCHECKSUM function to calculate a checksum.

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Length
StrNumber | Text | 30
Weight | Text | 30
Modulus | Integer | Not applicable

Text constant | ENU value
Text000 | The number: %1\
Text001 | has the checksum: %2
Copy Code
StrNumber := '4378';
Weight := '1234';
Modulus := 7;
CheckSum := STRCHECKSUM(StrNumber, Weight, Modulus);
MESSAGE(Text000 + Text001, StrNumber, CheckSum);

The formula is:

(7 - (4x1 + 3x2 + 7x3 + 8x4) MOD 7) MOD 7=0

The message window displays the following:

The number: 4378

has the checksum: 0

Example

This example shows how to use the STRCHECKSUM function to calculate a modulus 10 checksum for a bar code.

The STRCHECKSUM function can be used to calculate checksums for 13- and 8-digit European Article Number (EAN) and EAN-compatible bar codes such as a Universal Product Code (UPC) or Japanese Article Number (JAN).

A 13-digit EAN code has the following format:

  1. The 12 digits in positions 13 to 2 are used to calculate the checksum at position 1.

  2. Starting with position 2, all even values are totaled. The result is then multiplied by three. This value is called Even.

  3. Starting with position 3, all odd values are totaled. The result is called Odd.

  4. Total=Even + Odd.

  5. The modulus 10 checksum is then (10 - Total MOD 10) MOD 10.

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Length
StrNumber | Text | 30
Weight | Text | 30
Modulus | Integer | Not applicable

Text constant | ENU value
Text000 | The EAN code: %1\
Text001 | has the checksum: %2
Copy Code
StrNumber := '577622135746';
Weight := '131313131313';
CheckSum := STRCHECKSUM(StrNumber, Weight);
MESSAGE(Text000 + Text001, StrNumber, CheckSum);

The message window displays the following:

The EAN code: 577622135746

has the checksum: 3

See Also

Reference

Code Data Type
Text Data Type


STRLEN Function (Code, Text)

Gets the length of a string you define.

Length := STRLEN(String)

Parameters

String

Type: Text constant or Code

The string for which you want to determine the length.

Property Value/Return Value

Type: Integer

The length of String.

Remarks

The difference between the STRLEN function and the MAXSTRLEN Function (Code, Text) is that the STRLEN returns the actual number of characters in the input string, whereas MAXSTRLEN returns the maximum defined length of the input string.

In Microsoft Dynamics NAV 2016, if you call STRLEN on a Variant, then you get an error that the contents of the parameter are not valid. In earlier versions of Microsoft Dynamics NAV, if you call STRLEN on a Variant, then 0 is returned.

Example

This example shows the difference between the STRLEN and the MAXSTRLEN functions.

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Length
City | Text | 30
MaxLength | Integer | Not applicable
Length | Integer | Not applicable

Text constant | ENU value
Text000 | Atlanta
Text001 | The MAXSTRLEN function returns: %1,\
Text002 | whereas the STRLEN function returns: %2
Copy Code
City := Text000;
MaxLength := MAXSTRLEN(City);
Length := STRLEN(City);
MESSAGE(Text001 + Text002, MaxLength, Length);

The message window displays the following:

The MAXSTRLEN function returns: 30

whereas the STRLEN function returns: 7

This shows that the MAXLENGTH function returns the maximum possible length according to the definition of the string variable, whereas STRLEN returns the actual length of the text.

See Also

Reference

Code Data Type
Text Data Type


STRPOS Function (Code, Text)

Searches for the first occurrence of substring inside a string.

Position := STRPOS(String, SubString)

Parameters

String

Type: Text constant or code

The string in which you want to search.

SubString

Type: Text constant or code

The substring for which you want to search.

The STRPOS function is case-sensitive.

Property Value/Return Value

Type: Integer

The position of SubString in String.

Remarks

The STRPOS function returns the position of the first occurrence of the substring.

If SubString cannot be found, then the function returns zero.

If String or SubString is empty, then the function returns zero.

Example

This example shows how to use the STRPOS function.

This example requires that you create the following text constants in the C/AL Globals window.

Text constant | ENU value
Text000 | 'ABC abc abc xy'
Text001 | 'abc'
Text002 | 'The search for the substring: >%1<\'
Text003 | 'in the string: >%2<,\'
Text004 | 'returns the position: %3'
Copy Code
String := Text000;
SubStr := Text001
Pos := STRPOS(String, SubStr);
MESSAGE(Text002 + Text003 + Text004, SubStr, String, Pos);
// The STRPOS function is case-sensitive. Furthermore, it only
// returns the position of the 1st occurrence of the substring.

The message window displays the following:

The search for the substring: >abc<

in the string: >ABC abc abc xy<

returns the position: 5

Copy Code
Pos1 := StrPos("abc",""); // Returns 0.
Pos2 := StrPos("abc","c"); // Returns 3.
Pos3 := StrPos("abc","bc"); // Returns 2.
Pos4 := StrPos("abc","x"); // Returns 0.

See Also

Reference

Code Data Type
Text Data Type


STRSUBSTNO Function (Code, Text)

Replaces %1, %2, %3... and #1, #2, #3... fields in a string with the values you provide as optional parameters.

NewString := STRSUBSTNO(String [,Value1, …])

Parameters

String

Type: Text constant or Code

A string containing '#' and/or '%' fields.

The % fields are replaced by the values with their full lengths, and # fields are replaced by the values that are truncated to the length of the # field.

If this parameter is an expression that evaluates to Text or Code that is 512 or more characters, then a run-time error occurs.

Value1, …

Type: Any

One or more values (expressions) that you want to insert into String. You can specify up to 10 values.

Property Value/Return Value

Type: Text constant or Code

The resulting string, after the corresponding values have been substituted into the '#' and '%' fields.

Remarks

This function replaces the numbered specifiers in a string with a string representation of the equivalent numbered value.

The specifiers in the string can be either %n or #######n, where n represents a 1-based number. When you use the # specifier, the number can be anywhere in the specifier. For example, ###2#### is allowed.

The %n specifier is replaced with the string representation of the value with their full lengths.

The ##n specifier is replaced with the same number of characters as the length of the specifier (including the number). The values are truncated to the length of the # field.

If the string representation is shorter than the length of the specifier, then it is left aligned.

For example, StrSubstNo('Test %1 >#2##< >#3<', 1,2,3) returns "Test 1 >2 < >3 <".

In this example, the following substitutions are made:

  • %1 is replaced by '1' because a % field is replaced by the specified value in its full length.

  • '#2##' is replaced by '2 space space space' because the value is shorter than the field and therefore, the 2 is left aligned and the field is four characters long.

  • #3 is replaced by '3 space' because the 3 is left aligned and the field is two characters long

If the string is longer, then asterisks are inserted to indicate overflow.

For example, StrSubstNo('Test %1 >###2< >#3<', 'Thomas','Thomas',0) returns "Test Thomas >****< >0 <".

In this example the following substitutions are made:

  • %1 is replaced by 'Thomas' because a %1 field is replaced by the specified value in its full length.

  • '###2' is replaced by '****' because the string 'Thomas' is longer than the ###2 field. Each character in the field is replaced by an asterisk.

  • #3 is replaced by '0 space' because the 0 is left aligned and the field is two characters long.

You can have several references to the same value.

For example, StrSubstNo('Test %1 %3 %1', 555, 666, 777) returns "Test 555 777 555".

If one of the values is null, then it is treated as an empty string.

For more information about the STRSUBSTNO function in a multilanguage-enabled application, see Developing Multilanguage-Enabled Applications.

Example

The following example shows how to use the STRSUBSTNO function.

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | Data type | Length
Str | Text | 1024
AccountNo | Integer | Not applicable
Balance | Decimal | Not applicable

Text constant | ENU value
Text000 | The balance of account %1 is $ %2
Text001 | The string before STRSUBSTNO has been called:\%1
Text002 | The string after STRSUBSTNO has been called:\%1
Copy Code
Str := Text000;
AccountNo := 3452;
Balance := 2345 + 5462;
MESSAGE(Text001, Str);
Str := STRSUBSTNO(Str, AccountNo, Balance);
MESSAGE(Text002, Str);

The first message window displays the following text:

The string before STRSUBSTNO has been called:

The balance of account %1 is $ %2

The second message window displays the following text:

The string after STRSUBSTNO has been called:

The balance of account 3452 is $ 7,807

Note
This example is run on a computer that has the regional format set to English (United States).

See Also

Reference

Code Data Type
Text Data Type


UPPERCASE Function (Code, Text)

Converts all letters in a string to uppercase.

NewString := UPPERCASE(String)

Parameters

String

Type: Text constant or code

The string that you want to convert to uppercase.

Property Value/Return Value

Type: Text constant or code

The resulting string after it has been converted to uppercase.

Example

The following example shows how to use the UPPERCASE function.

This example requires that you create the following text constants in the C/AL Globals window.

Text constant | ConstValue
Text000 | Outstanding Order Status
Text001 | The test string before UPPERCASE is called:\%1
Text002 | The string after UPPERCASE is called:\%1
Copy Code
Lower := Text000;
MESSAGE(Text001, Lower);
Upper := UPPERCASE(Lower);
MESSAGE(Text002, Upper);

The first message window displays the following:

The test-string before UPPERCASE is called:

Outstanding Order Status

The second message window displays the following:

The string after UPPERCASE is called:

OUTSTANDING ORDER STATUS

See Also

Reference

Code Data Type
Text Data Type


System

This section contains the following topics:

  • Array Functions

  • Error Handling

  • Language Functions

  • Operating System Functions

  • Variable Functions

  • Encryption Functions

See Also

Concepts

C/AL Functions
Technical Reference


Array Functions

This section contains the following topics:

  • ARRAYLEN Function

  • COMPRESSARRAY Function

  • COPYARRAY Function


ARRAYLEN Function

Returns the total number of elements in an array or the number of elements in a specific dimension.

Length := ARRAYLEN(Array[, Dimension])

Parameters

Array

Type: Any

The array that you want to investigate.

Dimension

Type: Integer

If you omit this optional argument, the function returns the total number of elements in the array. To get the number of elements in a specific dimension, use Dimension with a valid value. The valid values are determined by the number of dimensions of the input array. For example, the valid values for a three-dimensional array would be 1, 2, and 3.

Property Value/Return Value

Type: Integer

The number of elements in the array, or the number of elements in a specific dimension.

Remarks

If you use ARRAYLEN with an input parameter that is not an array, a run-time error occurs.

Example

This example shows how to use the ARRAYLEN function.

This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Dimension
Array1 | Integer | 2
Array2 | Integer | 3;4
Copy Code
MESSAGE('Array1, Total number of elements: %1', ARRAYLEN(Array1));
MESSAGE('Array2, Dimension 1 size: %1', ARRAYLEN(Array2,1));
MESSAGE('Array2, Dimension 2 size: %1', ARRAYLEN(Array2,2));
MESSAGE('Array2, Total number of elements: %1', ARRAYLEN(Array2));

The following messages are displayed.

Array1, Total number of elements: 2

Array2, Dimension 1 size: 3

Array2, Dimension 2 size: 4

Array2, Total number of elements: 12

See Also

Reference

COMPRESSARRAY Function
COPYARRAY Function


COMPRESSARRAY Function

Moves all non-empty strings (text) in an array to the beginning of the array. The resulting StringArray has the same number of elements as the input array, but empty entries appear at the end of the array.

[Count := ] COMPRESSARRAY(StringArray)

Parameters

StringArray

Type: Array of strings

The string array that you want to compress.

Property Value/Return Value

Type: Integer

The number of non-empty strings that were compressed.

Remarks

When compressing an array of strings, the non-empty strings in the resulting array are sorted just like in the original array.

The COMPRESSARRAY function is useful for printing names and addresses. For instance, you can use this function to remove blank lines in account statements.

This function compresses an array of Text or Code, but not BigText. The compression is performed by moving empty strings to the end of the array.

For example, "Redmond", "Copenhagen", "", "Fargo", "Paris" is changed to "Redmond", "Copenhagen", "Fargo", "Paris", "".

In Microsoft Dynamics NAV 2016, it is not supported to use the COMPRESSARRAY function on multidimensional arrays. In earlier versions, COMPRESSARRAY works for arrays of arrays.

Example

This example shows how to use the COMPRESSARRAY function. The input array has the following values.

Joe Raybon

One Meca Way

Atlanta

The output StringArray has the following values.

Joe Raybon

One Meca Way

Atlanta

All non-empty entries have been moved to the beginning of the array.

This example requires that you create the following variable in the C/AL Globals window.

Variable | DataType | Dimension
CustomerData | Text | 6
Copy Code
CustomerData[1] := 'Joe Raybon';
CustomerData[2] := ''; // Empty string.
CustomerData[3] :='One Meca Way';
CustomerData[4] := '  '; // A non-empty string that contains blanks.
CustomerData[5] := 'Atlanta';
CustomerData[6] := ''; // Empty string.
MESSAGE('Before compression the address is: \%1\%2\%3\%4\%5\%6', CustomerData[1], CustomerData[2], CustomerData[3], CustomerData[4], CustomerData[5], CustomerData[6]);
COMPRESSARRAY(CustomerData); // The empty lines (strings) are removed.
MESSAGE('After compression the address is: \%1\%2\%3\%4\%5\%6', CustomerData[1], CustomerData[2], CustomerData[3], CustomerData[4], CustomerData[5], CustomerData[6]);

The first message window displays the following:

Before compression, the address is:

Joe Raybon

One Meca Way

Atlanta

The second message window displays the following:

After compression, the address is:

Joe Raybon

One Meca Way

Atlanta

All empty strings, which cause blank lines, are moved to the end of the array.

Note
Empty lines are not printed if they occur on the first or last line in a message window.

See Also

Reference

ARRAYLEN Function
COPYARRAY Function


COPYARRAY Function

Copies one or more elements in an array to a new array.

COPYARRAY(NewArray, Array, Position[, Length])

Parameters

NewArray

Type: Array

The array to copy to; the destination array.

Array

Type: Array

The array to copy from; the source array.

Position

Type: Integer

The position of the first array element to copy.

Length

Type: Integer

The number of array elements to copy. If you do not specify Length, all array elements are copied from Position to the last element. Use the following equation to determine valid values.

1 =< LENGTH =< MAXLEN(ARRAY) - POSITION + 1

Remarks

You can only copy from one-dimensional arrays. Repeat the COPYARRAY function to copy two-dimensional and three-dimensional arrays.

You cannot copy an array if the data type of the array is a complex data type. For more information about complex data types, see C/AL Data Types.

Example

The following example assigns values to Array1 and copies values from Array1 to Array2. Array1 is an integer array with the Dimensions Property set to 10. It contains integers from 1 to 10. The example code copies the numbers 6, 7, 8, 9, and 10 to Array2, an integer array with the Dimensions property set to 5. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Dimension
Array1 | Integer | 10
Array2 | Integer | 5
Copy Code
Array1[1] := 1;
Array1[2] := 2;
Array1[3] := 3;
Array1[4] := 4;
Array1[5] := 5;
Array1[6] := 6;
Array1[7] := 7;
Array1[8] := 8;
Array1[9] := 9;
Array1[10] := 10;
COPYARRAY(Array2,Array1,6,5);

If Array1 is an integer array with dimension 10, and it contains the numbers from 1 to 10, and Array2 is an integer array with dimension 5, then the following command causes a run-time error.

Copy Code
COPYARRAY(Array2,Array1,3);

The error occurs because the code attempts to copy eight elements from Array1 to Array2, and Array2 has room for only five elements.

See Also

Reference

ARRAYLEN Function
COMPRESSARRAY Function


Error Handling

This section contains the following topics:

  • CLEARLASTERROR Function

  • GETLASTERRORCALLSTACK Function

  • GETLASTERRORCODE Function

  • GETLASTERROROBJECT Function

  • GETLASTERRORTEXT Function

See Also

Reference

ERROR Function (Dialog)


CLEARLASTERROR Function

Removes the last error message from memory.

CLEARLASTERROR

Remarks

You can use the GETLASTERRORTEXT Function to determine whether an error has occurred and to see the text in the last error message that was generated. You can then use the CLEARLASTERROR function to remove the last error message from memory. If you subsequently call the GETLASTERRORTEXT function, an empty string is returned.

See Also

Concepts

Error Handling


GETLASTERRORCALLSTACK Function

Gets the call stack from where the last error occurred.

String := GETLASTERRORCALLSTACK

Property Value/Return Value

Type: Text

A text string that contains the call stack from where the error occurred.

The format of the string is:

<codeunit name>(Codeunit <number>).<function name> line <line number>\[<calling codeunit name>(Codeunit <number>).<calling function name> line <line number>\...]

The string cannot exceed the maximum string length that is specified in Microsoft Dynamics NAV, which is 1,024 characters.

If no error has occurred, then the function returns an empty string.

Remarks

For some errors, such as divide by zero errors and overflow errors, GETLASTERRORCALLSTACK does not return every call in the stack. To get the complete call stack for these types of errors, use the debugger and specify that you want to break on errors. On the Debugger page, in the Call Stack FactBox, you can view all the function calls that led to the error. For more information, see How to: Break on Errors.

Example

In this example, an error occurs in codeunit 50003. The text of the MESSAGE includes a call to the GETLASTERRORCALLSTACK function.

Copy Code
// Codeunit 50001, TestErrors1
// OnRun trigger
ERROR('Some error message')
// Codeunit 50002, TestErrors2
// OnRun trigger
CLEARLASTERROR;
IF NOT Codeunit.RUN(50001) THEN
  MESSAGE('The call stack for the last error is:\' + GETLASTERRORCALLSTACK);

When you run codeunit 50002, the message window displays the following:

The call stack for the last error is:

TestErrors1(CodeUnit 50001).OnRun(Trigger) line 1

TestErrors2(CodeUnit 50002).OnRun(Trigger) line 2

See Also

Concepts

Error Handling


GETLASTERRORCODE Function

Gets the classification of the last error that occurred.

String := GETLASTERRORCODE

Property Value/Return Value

Type: Text

A string that contains the error code of the last error. The error code is a classification of the error.

If no error has occurred, then the function returns an empty string.

Remarks

You use the GETLASTERRORCODE function to identify the type of the last error that occurred. You use the GETLASTERRORTEXT Function to get the details of the last error.

The result of the GETLASTERRORCODE function is not translated into the local language. The result of the GETLASTERRORTEXT function is translated into the local language.

Example

This example opens a file and then causes an error to occur by trying to open the file again. If the code for the error that occurred is not the expected error code, then an error message is displayed.

This example requires that you create the following text constant and variables.

Text constant | ENU value
Text001 | The error code is not valid. Expected: %1. Actual: %2. Error message: %3

Variable name | DataType | Length
ErrorCode | Text | 1024
ExpectedErrorCode | Text | 1024
FileObj1 | File | Not applicable
FileObj2 | File | Not applicable
Copy Code
ExpectedErrorCode := 'StreamIO';
FileObj1.CREATETEMPFILE;
ASSERTERROR FileObj2.CREATE(FileObj1.NAME);
ErrorCode := GETLASTERRORCODE;
IF ErrorCode <> ExpectedErrorCode THEN
  ERROR(Text001, ExpectedErrorCode, ErrorCode, GETLASTERRORTEXT);

See Also

Concepts

Error Handling


GETLASTERROROBJECT Function

Gets the last System.Exception object that occurred.

DotNet := GETLASTERROROBJECT

Property Value/Return Value

Type: DotNet

A System.Exception object that contains the last exception that occurred.

If no exception has occurred, then function returns a NULL object.

Remarks

You use this function to retrieve and handle the last exception that occurred in the application. The System.Exception object exposes several members that enable you to get detailed information about the exception, such Exception.InnerException and Exception.Message.

Example

This example uses the GETLASTERROROBJECT function to get an exception object that occurs. In this example, the Microsoft .NET Framework objects are executed by MyCodeunit. The C/AL code uses the InnerException property of the System.Exception object to identify whether the inner exception has the type WebException and returns an exception message accordingly.

This example requires that you create the following variables.

Variable name constant | Data Type | SubType
MyCodeunt | Codeunit | MyCodeunit
Exception | DotNet | 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Exception
WebException | DotNet | 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.System.Net.WebException
Copy Code
IF NOT MyCodeunit.RUN THEN BEGIN
    Exception := GETLASTERROROBJECT;
    IF NOT Exception.InnerException.GetType.Equals(WebException.GetType) THEN
        ERROR(Exception.Message);
    WebException := Exception.InnerException;
    ERROR(WebException.Message);
END;

See Also

Concepts

Error Handling


GETLASTERRORTEXT Function

Gets the text that was included in the last error message that was generated.

String := GETLASTERRORTEXT

Property Value/Return Value

Type: Text

The text string that was contained in the last error message that was generated by Microsoft Dynamics NAV.

If no error has occurred, then the function returns an empty string.

Remarks

If you call the GETLASTERRORTEXT function immediately after you call the CLEARLASTERROR function, then an empty string is returned.

The result of the GETLASTERRORCODE Functionis not translated into the local language. The result of the GETLASTERRORTEXT function is translated into the local language.

Example

If you call the Codeunit.RUN function to run a codeunit and an error occurs in the codeunit, then the error is displayed. However, if you also use the return value of the Codeunit.RUN function, then the error is not displayed. In this case, you can use the GETLASTERRORTEXT function to determine whether an error has occurred and to see the text of the last error message that was generated. This example shows how to use the GETLASTERRORTEXT function. This example requires that you create two codeunits. Codeunit 50001 generates an error. Codeunit 50002 runs codeunit 50001 and if an error occurs, then it displays the text of the error.

Copy Code
// Codeunit 50001
// OnRun trigger
ERROR(‘Some error message.’);
// Codeunit 50002
// OnRun trigger
CLEARLASTERROR();
IF NOT Codeunit.RUN(50001) THEN
  MESSAGE(‘The last error was: ’ + GETLASTERRORTEXT);

In this example, because the IF statement uses the return value of the Codeunit.RUN function, the error from codeunit 50001 is not displayed. Instead, you use the GETLASTERRORTEXT function to display the error.

When you run codeunit 50002, the message window displays the following:

The last error was: Some error message.

See Also

Concepts

Error Handling


Language Functions

This section contains the following topics:

  • GLOBALLANGUAGE Function

  • WINDOWSLANGUAGE Function


GLOBALLANGUAGE Function

Gets and sets the current global language setting.

[LanguageID :=] GLOBALLANGUAGE([NewLanguageID])

Parameters

NewLanguageID

Type: Integer

Property Value/Return Value

Type: Integer

Remarks

The LanguageID is a standard Windows language ID. The Windows Language virtual table contains a list of these IDs and the corresponding names and short names.

For more information, see Multilanguage Development.

See Also

Reference

WINDOWSLANGUAGE Function


WINDOWSLANGUAGE Function

Gets the current Windows language setting.

LanguageID := WINDOWSLANGUAGE

Property Value/Return Value

Type: Integer

Remarks

The LanguageID is a standard Windows language ID. The Windows Language virtual table contains a list of these IDs and the corresponding names and short names.

For more information, see Multilanguage Development.

See Also

Reference

GLOBALLANGUAGE Function


Operating System Functions

This section contains the following topics:

  • APPLICATIONPATH Function

  • GUIALLOWED Function

  • HYPERLINK Function

  • SLEEP Function

  • TEMPORARYPATH Function


APPLICATIONPATH Function

Returns the path of the directory where the executable file for Microsoft Dynamics NAV is installed.

APPLICATIONPATH

Remarks

This function returns a string that contains the path of the directory where the executable file for Microsoft Dynamics NAV is installed. This string ends with a backslash ('\') and does not contain the name of the executable file.

The string cannot contain more than 255 characters.

If this function is called from an application that is running on a Microsoft Dynamics NAV Application Server, it returns the path of the directory where the Microsoft Dynamics NAV Application Server is installed.

See Also

Reference

GUIALLOWED Function
HYPERLINK Function
SLEEP Function
TEMPORARYPATH Function


GETURL Function

Generates a URL for the specified client target that is based on the configuration of the Microsoft Dynamics NAV Server instance.

If the code runs in a multitenant deployment architecture, the generated URL will automatically apply to the tenant ID of the current user.

[String :=] GETURL(ClientType[, Company][, Object Type][, Object Id][, Record/RecordRef][, UseFilters])

Parameters

ClientType

Value: CURRENTCLIENTTYPE (or Current), DEFAULTCLIENTTYPE (or Default), Windows, Web, SOAP, or OData

Specifies the client that you want to generate the URL for. This parameter is required. If you want to generate a URL that depends on the client that the user is accessing the URL from, choose Current. The following table describes the options.

Option Description

CURRENTCLIENTTYPE

or

ClientType::Current

The URL is generated based on the client that invokes the code, provided that this is one of the client types that are specified in this list. If the URL is requested by another client type, such as a NAS session, Microsoft Dynamics NAV generates a URL based on the default client that is specified for the relevant Microsoft Dynamics NAV Server instance.

Note
If you specify current as the client type, the URL cannot be consumed by an OData web service.

DEFAULTCLIENTTYPE

or

ClientType::Default

The URL is generated based on the default client that is specified for the relevant Microsoft Dynamics NAV Server instance.

ClientType::Windows

The URL is generated based on a request from the Microsoft Dynamics NAV Windows client.

ClientType::Web

The URL is generated based on a request from the Microsoft Dynamics NAV Web client.

ClientType::Desktop

The URL is generated based on a request from the Microsoft Dynamics NAV Web client running the Microsoft Dynamics NAV Universal App.

ClientType::Tablet

The URL is generated based on a request from the Microsoft Dynamics NAV Tablet client.

ClientType::Phone

The URL is generated based on a request from the Microsoft Dynamics NAV Phone client.

ClientType::SOAP

The URL is generated based on a request from a SOAP web service.

ClientType::OData

The URL is generated based on a request from an OData web service.

Warning
A runtime error occurs if the ClientType is set to SOAP or OData but the specified object type and ID has not been published as a web service.

Company

Type: Text

Specifies the company that the URL must contain. If you do not specify a company, the URL will run in the user’s current company.

ObjectType

Value: Table, Page, Report, Codeunit, Query, or XMLport

Specifies the object type that the URL must open. If you specify an object type, you must also specify an object ID in the ObjectId parameter. Otherwise, the user will see a runtime error.

If you set the ObjectType parameter to Page, you can also specify a record variable in the Record parameter.

ObjectId

Type: Integer

Specifies the ID of the specified object type that the URL must open.

Record/RecordRef

Type: Record or RecordRef variable

The Record or RecordRef variable that specifies which record to open.

UseFilters

Type: Boolean

Specifies whether to include filters that are defined on the object as a text string in the URL.

Property Value/Return Value

Type: String

Remarks

The GETURL function generates a URL to open a specific page, for example, or to read Microsoft Dynamics NAV data from a web service. The generated URL includes settings from the configuration of the Microsoft Dynamics NAV Server instance which the code that uses the function runs in. This means that you can use the GETURL function to generate URLs that are generic. The URLs are generated based on the Microsoft Dynamics NAV Server configuration for the user who is accessing the code that generates the URL. If you specify a company, then the URL applies to that company only. Also, in a multitenant deployment, the URLs are tenant-specific. The URL will only allow access to the requested object if the user has permission to access to the object.

Warning
GETURL returns an empty string if the specified parameters result in values that are not valid, and if the URL cannot be generated for other reasons. If the function returns an empty string, you can use the GETLASTERRORTEXT function to troubleshoot. For more information, see GETLASTERRORTEXT Function.

For example, you can write code that will open page 21 in the Microsoft Dynamics NAV Web client. In that case, you call the GETURL function that has the relevant parameters, and when the code runs, the name of the Microsoft Dynamics NAV Server instance and the server name are extracted automatically. The following table describes the basic URLs that you get with the simplest use of the GETURL function by writing url := GETURL(ClientType::Default), 'CRONUS International Ltd.';.

Client | URL
Microsoft Dynamics NAV Windows client | DynamicsNAV://server:port/instance//CRONUS International Ltd.
Microsoft Dynamics NAV Web client | https://server:port/instance/WebClient?company='CRONUS International Ltd.'/
Microsoft Dynamics NAV Tablet client | ms-dynamicsnav://server:port/instance?company=’ CRONUS International Ltd.’
Microsoft Dynamics NAV Phone client | ms-dynamicsnav://server:port/instance?company=’ CRONUS International Ltd.’
Microsoft Dynamics NAV Desktop client | ms-dynamicsnav://server:port/instance?company=’ CRONUS International Ltd.’
OData | https://server:port/instance/OData/Company('CRONUS International Ltd.')/
SOAP | https://server:port/instance/WS/CRONUS International Ltd.

In the example, an empty string for the company name is included for clarity. But an even simpler use of GETURL is to only specify the client type as in url := GETURL(ClientType::Default);.

URLs for opening a page or a report are available from the About this Page windows. For more information, see Using About This Page and About This Report.

Example

The following code example illustrates how you can use the GETURL function to generate a URL that will open page 21 in the client that the current user is using.

Copy Code
Cust.Get(10000);
url := GETURL(CURRENTCLIENTTYPE, 'COMPANYNAME', ObjectType::Page, 21, Cust);
// Alternatively, you can use the following code:
//Cust.Get(10000);
//url := GETURL(ClientType::OData, COMPANYNAME, ObjectType::Page, 21, Cust);

When the code runs, a different URL is generated, depending on the client that is using the URL. If the code is run in the context of a SOAP web service, it has a different syntax than if it runs in the context of the Microsoft Dynamics NAV Windows client. The following table describes the syntax of the generated URL for each client type.

Client | URL
Microsoft Dynamics NAV Windows client | DynamicsNAV://server:port/instance/company/runpage?page=21&bookmark=bookmark
Microsoft Dynamics NAV Web client | https://server:port/instance/WebClient?company&page=21&bookmark=bookmark
OData | Not applicable because the client type is set to Current, which is not supported for Odata web services.
SOAP | Not applicable because the URL for SOAP web services does not support filtering for the record.

The current version of Microsoft Dynamics NAV cannot generate a URL for an OData client if the client type is set to Current. However, the following code example illustrates a similar scenario for opening page 21 and specifying the record so that the URL can be consumed by an OData web service:

Copy Code
Cust.Get(10000);
url := GETURL(ClientType::OData, COMPANYNAME, ObjectType::Page, 21, Cust);

In this example, the following URL is generated for OData web services:

https://server:port/instance/OData/Company('company')/Customer('10000')

In this example, it is assumed that page 21 is published as an OData web service with the name Customer.

The following code example illustrates a similar scenario for opening page 21 and not specifying the record so the URL can be consumed by a SOAP web service:

Copy Code
url := GETURL(CURRENTCLIENTTYPE, COMPANYNAME, ObjectType::Page, 21);
// Alternatively, you can use the following code:
//url := GETURL(ClientType::Current, COMPANYNAME, ObjectType::Page, 21);

In this example, the following URL is generated for SOAP web services:

https://server:port/instance/WS/company/Page/Customer

See Also

Tasks

How to: Copy the URL to Open a Page or Report
How to: Publish a Web Service

Reference

HYPERLINK Function
CURRENTCLIENTTYPE Function
DEFAULTCLIENTTYPE Function

Concepts

Creating and Running Hyperlinks


GUIALLOWED Function

Checks whether the C/AL code can show any information on the screen.

[Ok :=] GUIALLOWED

Property Value/Return Value

Type: Boolean

If the return value is true, then the GUI is available.

If the return value is false, then the C/AL code is running on Microsoft Dynamics NAV Application Server and no GUI is available.

Remarks

User Portal Application Server accepts GUIALLOWED.

Example

This example shows how to use the GUIALLOWED function.

This example requires that you create the following text constant in the C/AL Globals window.

Text constant | ENU value
Text000 | Code is running on a client.
Copy Code
IF GUIALLOWED THEN
 MESSAGE(Text000);

If the code runs on a client, which means that the user interface is available, a message box will appear with the following message.

Code is running on a client

If the code runs on Microsoft Dynamics NAV Application Server, then the message will not be displayed.

Note
If the MESSAGE Function (Dialog) or the ERROR Function (Dialog) is called when the code is running on Microsoft Dynamics NAV Application Server, then the message is written to the event log of the operating system.

See Also

Reference

APPLICATIONPATH Function
HYPERLINK Function
SLEEP Function
TEMPORARYPATH Function


HYPERLINK Function

Passes a URL as an argument to an Internet browser, such as Windows Internet Explorer.

HYPERLINK(URL)

Parameters

URL

Type: Text

A URL that is passed to the Internet browser as an argument.

Remarks

The syntax must be a valid URL, such as http://www.microsoft.com, or file path, such as c:\temp\myfile.txt. If you want the URL to be configurable, you can get the URL from a field or a variable instead. If you pass an empty string, then no browser window is opened.

If you use this function for an application that runs on the Microsoft Dynamics NAV Windows client, then the default Internet browser that is based on the setting in the system registry is used. If the browser is already running, then a new tab opens in the browser window. If you use this function for an application that runs on the Microsoft Dynamics NAV Web client, then a new tab in the same browser window that is currently hosting the Microsoft Dynamics NAV Web client is opened.

The HYPERLINK function works with different protocols and file types as along as the syntax is valid.

The HYPERLINK function does not work on NAS services.

Example

The following example shows two uses of the HYPERLINK function to open the specified URL in the default browser. In the first line of code, the URL is specified in code. The second line of code illustrates how you can get a URL that is stored in a field on the current table.

Copy Code
HYPERLINK('http://www.microsoft.com');
...
HYPERLINK(Rec.UrlField);

See Also

Reference

APPLICATIONPATH Function
GUIALLOWED Function
SLEEP Function
TEMPORARYPATH Function


SLEEP Function

Returns control to the operating system for a specified time.

SLEEP(Duration)

Parameters

Duration

Type: Integer

The number of milliseconds to return control to the operating system.

Remarks

When you use the SLEEP function, control is guaranteed to return to the operating system for at least Duration milliseconds.

Note
The period may be longer than Duration milliseconds, depending on what the operating system is doing at the time that control is to return to the caller.

See Also

Reference

APPLICATIONPATH Function
GUIALLOWED Function
HYPERLINK Function
TEMPORARYPATH Function


TEMPORARYPATH Function

Gets the path of the directory where the temporary file for Microsoft Dynamics NAV is stored.

TEMPORARYPATH

Remarks

This function returns a string that contains the path of the directory where the temporary file for Microsoft Dynamics NAV is stored. This string ends with a backslash ('\') and does not contain the name of the temp file.

The string cannot contain more than 255 characters.

If this function is called from an application that is running on a Microsoft Dynamics NAV Application Server, it returns the path of the directory where the Microsoft Dynamics NAV Application Server is installed.

See Also

Reference

APPLICATIONPATH Function
GUIALLOWED Function
HYPERLINK Function
SLEEP Function


Variable Functions

This section contains the following topics:

  • CANLOADTYPE Function

  • CLEAR Function

  • CLEARALL Function

  • EVALUATE Function

See Also

Concepts

System
Technical Reference
C/SIDE Reference Guide


CANLOADTYPE Function

Tests if the specified .NET Framework type can be loaded by Microsoft Dynamics NAV.

You can use the CANLOADTYPE function to test the availability of assemblies that are expected to be present on the Microsoft Dynamics NAV client computer or on the Microsoft Dynamics NAV Server computer.

Ok := CANLOADTYPE(DotNet)

Parameters

DotNet

Type: A variable of the DotNet data type to represent the .NET Framework type.

Property Value/Return Value

Returns true if the specified type can be accessed by Microsoft Dynamics NAV; otherwise false.

Example

The following code example is based on codeunit 5300 in the CRONUS International Ltd. demonstration database. This example requires that you create the following variable and text constant in the C/AL Globals window.

Variable name | DataType | Subtype
OObjLibrary | DotNet | Microsoft.Dynamics.NAV.OLSync.OLSyncSupplier.OutlookObjectLibrary.'Microsoft.Dynamics.NAV.OLSync.OLSyncSupplier, Version=7.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

Text constant name | ConstValue
MyError | Cannot access the specified type.
Copy Code
IF NOT CANLOADTYPE(OObjLibrary) THEN
   ERROR(MyError);

See Also

Concepts

Calling .NET Framework Members from C/AL


CLEAR Function

Clears the value of a single variable. Also clears all the filters that were set if the variable is a record and resets the key to the primary key.

CLEAR(Variable)

Parameters

Variable

Type: Any

The identifier (variable) of any C/AL data type, including simple and composite data types. The following rules apply when you run the CLEAR function:

  • A number variable is set to 0 (zero)

  • A string variable is set to empty string

  • A date variable is set to 0D (undefined date)

  • A time variable is set to 0T (undefined time)

  • A Boolean variable is set to FALSE

Remarks

Use the CLEARALL Function to clear all internal variables, keys, and filters in the object and in any associated objects such as reports, pages, and codeunits that contain C/AL code. Note, however, that CLEARALL does not affect or change values for variables in single instance codeunits.

For a composite data type, such as a record or an array, all elements are cleared. Furthermore, all fields in a record will be initialized with the InitValue Property of the field.

CLEAR can also be used on the GUID Data Type. It converts the GUID to zeros. Use the CREATEGUID Function (GUID) to create a new unique GUID.

For an Automation object, CLEAR releases the Automation object and decreases the reference count. The Automation server determines if this should cause a shutdown. After CLEAR, you can use the CREATE Function (Automation) on the Automation variable to create a new instance of the object.

If you use CLEAR on a codeunit, only the reference to the codeunit is deleted and not the codeunit itself, as with Automation objects. This means that the content of the codeunit stays intact.

If you have an array of controls, the whole array is destroyed when the array variable goes out of scope.

If you have an array of automation servers, you may clear the whole array at once, or clear each element individually.

Example

This example shows how to use the CLEAR function.

This example requires that you create the following text constants in the C/AL Globals window

Text constant | ConstValue
Text000 | Joe Raybon
Text001 | Initially the variable "Name" contains: >%1<
Text002 | After using CLEAR, the variable "Name" contains: >%1<
Copy Code
Name := Text000;
MESSAGE(Text001, Name);
CLEAR(Name);
MESSAGE(Text002, Name);

The first message window displays the following:

Initially the variable "Name" contains: >Joe Raybon<

The second message window displays the following:

After using CLEAR, the variable "Name" contains: ><

Example

In the following example you will declare two variables:

Copy Code
MyTextVar, data type: "text".
GuidVar, data type: "GUID".

These variables will be declared and cleared, first by using CLEAR and then by using CLEARALL.

This example requires that you create the following text constants in the C/AL Globals window

Text constant | ENU value
Text000 | My Text
Text001 | Initially the variable "MyTextVar" contains >%1< and "GuidVar" is defined as >%2<
Text002 | After using CLEAR(MyTextVar), the variable "MyTextVar" contains >%1< and "GuidVar" is still defined as >%2<
Text003 | After using CLEAR(GuidVar) the variable "GuidVar" becomes undefined
Text004 | Giving the "MyTextVar" variable the initial value again and creating a new "GuidVar" results in >%1< and >%2<
Text005 | Using CLEARALL results in an empty "MyTextVar" >%1< and an undefined "GuidVar"
Copy Code
MyTextVar := Text000;
GuidVar := CREATEGUID();
MESSAGE(Text001,MyTextVar,GuidVar);
CLEAR(MyTextVar);
MESSAGE(Text002,MyTextVar,GuidVar);
CLEAR(GuidVar);
MESSAGE(Text003,GuidVar);
MyTextVar := Text000;
GuidVar := CREATEGUID();
MESSAGE(Text004,MyTextVar,GuidVar);
CLEARALL;
MESSAGE(Text005,MyTextVar,GuidVar);

The first message window displays the following:

Initially the variable "MyTextVar" contains: >My Text< and "GuidVar" is defined as >12345678-1234-1234-1234-1234567890AB<

The second message window displays the following:

After using CLEAR(MyTextVar), the variable "MyTextVar" contains: >< and GuidVar is still defined as >12345678-1234-1234-1234-1234567890AB<

The third message window displays the following:

After using CLEAR(GuidVar) the variable "GuidVar" becomes undefined

The fourth message window displays the following:

Giving the "MyTextVar" variable the initial value again and creating a new "GuidVar" results in >My Text< and >87654321-4321-4321-4321-BA0987654321<

The fifth message window displays the following:

Using CLEARALL results in an empty "MyTextVar" >< and an undefined "GuidVar"

See Also

Reference

CLEARALL Function
COPYSTREAM Function
EVALUATE Function


CLEARALL Function

Clears all internal variables (except REC variables), keys, and filters in the object and in any associated objects, such as reports, pages, codeunits, and so on that contain C/AL code.

CLEARALL

Remarks

CLEARALL works by calling the CLEAR Function repeatedly on each variable. However, this is not the case with codeunits, where the CLEARALL function works by calling CLEARALL inside the codeunit. It deletes the contents of the codeunit, whereas CLEAR only deletes the reference to the codeunit.

CLEARALL does not affect or change values for variables in single instance codeunits.

When a function is called repeatedly in the same transaction, the system retains all values for variables and filters in memory between calls. For example, this is used to assign numbers to entry numbers when posting. When you do not want to retain the values in memory, use the CLEARALL function to clear them.

For information about the initial values of cleared variables, see the CLEAR Function. Take into consideration that fields in a record will be initialized with the InitValue Property of the field.

See Also

Reference

CLEAR Function
COPYSTREAM Function
EVALUATE Function


EVALUATE Function

Evaluates a string representation of a value into its typical representation. The result is assigned to a variable.

[Ok :=] EVALUATE(Variable, String[, Number])

Parameters

Variable

Type: Any type of variable

The value of the string is assigned to the variable.

String

Type: Text constant or code

A string that contains a value of any simple C/AL data type.

Number

Type: Integer

This optional value can be used when exporting data with an XMLport. The only valid value is 9, which indicates that the data must be converted from XML format to C/SIDE format.

Property Value/Return Value

Type: Boolean

Specifies whether an error occurred during the evaluation of the string.

If the return value is true, then no errors occurred during the evaluation of the string and the value was assigned to Variable.

If the return value is false, then errors occurred during the evaluation of the string and the original value of Variable was not modified.

Example

This example shows how to use the EVALUATE function when it is called with four different types of variables.

This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
VarInteger | Integer
VarDate | Date
VarYesNo | Boolean
VarDuration | Duration
Value | Text
Ok1 | Boolean
Ok1 | Boolean
Ok3 | Boolean
Ok4 | Boolean

Text constant | ENU value
Text000 | VarInteger = #1######. The return code is: %2.\
Text001 | VarDate = #3######. The return code is: %4.\
Text002 | VarYesNo = #5######. The return code is: %6.\
Text003 | VarDuration = %7. The return code is: %8.
Copy Code
Value := '010196';
Ok1 := EVALUATE(VarInteger, Value);
Ok2 := EVALUATE(VarDate, Value);
Ok3 := EVALUATE(VarYesNo, Value);
Value := '2days 4hours 3.7 seconds 17.3 milliseconds';
Ok4 := EVALUATE(VarDuration, Value);
MESSAGE(Text000 + Text001 + Text002 + Text003, VarInteger, Ok1, VarDate, Ok2, VarYesNo, Ok3, VarDuration, Ok4);

The message window displays the following:

VarInteger = 10196 . The return code is: Yes.

VarDate = 01/01/96. The return code is: Yes.

VarYesNo = No . The return code is: No.

VarDuration = 2 days 4 hours 3 seconds 717 milliseconds. The return code is: Yes.

This example shows that although Value ('010196') can be interpreted as both an integer and a date expression, it cannot be interpreted as a Boolean expression. This causes an error, shown in the return code Ok3 (=FALSE).

This example also shows that when you evaluate a string as a duration data type, you can use certain words in the string to describe the duration. The following words or abbreviations are supported:

  • day, days, d

  • hour, hours, h

  • minute, minutes, min, m

  • second, seconds, sec, s

  • millisecond, milliseconds, milli, millis

You can include decimal values in the string that you evaluate as a duration. Decimal values for milliseconds are ignored; only the whole number is evaluated.

See Also

Reference

CLEAR Function
CLEARALL Function
COPYSTREAM Function


CAPTIONCLASSTRANSLATE Function

Returns a translated version of the caption string. The string is translated to the current local language.

String := CAPTIONCLASSTRANSLATE(CaptionClassText)

Parameters

CaptionClassText

Type: String

A literal string that defines the caption.

Return Value

Type: Text

The caption string in the current local language of the client.

Remarks

You can use the SELECTLATESTVERSION Function (Database) to clear the current session's cache for the CaptionClassTranslate strings. The strings will then be reevaluated by the CaptionClassTranslate function trigger (ID 15) in codeunit 1.

See Also

Concepts

CaptionClass Functionality


Encryption Functions

This section contains the following topics:

  • ENCRYPT

  • DECRYPT

  • IMPORTENCRYPTIONKEY

  • EXPORTENCRYPTIONKEY

  • CREATEENCRYPTIONKEY

  • DELETEENCRYPTIONKEY

  • ENCRYPTIONKEYEXISTS

  • ENCRYPTIONENABLED

See Also

Concepts

System
Technical Reference
C/SIDE Reference Guide


ENCRYPT

Takes a string as input and returns the encrypted value of the string.

String := ENCRYPT(Str)

Parameters

Str

Value: Text or Code

The input string that will be encrypted.

Important
The input string cannot exceed a length of 215 plain characters. If the input string includes special characters the length is even more reduced.

Property Value/Return Value

Value: Text or Code

The output string that is encrypted.

Exceptions

If encryption is not enabled or the encryption key is not found, the following error will be displayed: An encryption key is required to complete the request.

Remarks

Example

The code example requires that you create the following text constant in the C/AL Globals window.

Text Text000

Copy Code
Text000 := ‘ABC123’;
MESSAGE(‘Value: ‘ + Text000)
Text000 := ENCRYPT(Text000);
MESSAGE(‘Value: ‘ + Text000);

This code example takes the string value ABC123 and outputs the encrypted value of the string. The encrypted value will vary from system to system due to differences in the encryption key.

See Also

Concepts

System
Technical Reference
C/SIDE Reference Guide


DECRYPT

Takes a string as input and returns the decrypted value of the string.

String := DECRYPT(Str)

Parameters

Str

Value: Text or Code

The input string that will be decrypted.

Property Value/Return Value

Value: Text or Code

The output string that is decrypted.

Exceptions

If encryption is not enabled or the encryption key does not exist, the following error will be displayed: An encryption key is required to complete the request. If decryption failed because input data could not be decrypted, the following error will be displayed: Unable to decrypt data. The data was encrypted using a different key.

Example

This code example checks whether the tenant is configured to allow encryption using the ENCRYPTIONENABLED function, and then it decrypts an encrypted text string.

This example requires that you create the following text constants: EncryptedText and PlainText.

Copy Code
IF NOT ENCRYPTIONENABLED THEN
        ERROR('Encryption has not been enabled.');
      PlainText := DECRYPT(EncryptedText);

See Also

Concepts

System
Technical Reference
C/SIDE Reference Guide


IMPORTENCRYPTIONKEY

Points to a password protected file that contains the key on the current server.

When encrypting or decrypting data in Microsoft Dynamics NAV, an encryption key is used. Microsoft Dynamics NAV uses a single key per tenant and every tenant will have a different key. Keys can be created or imported if one exists already, as may be the case if upgrading or migrating a system from one set of hardware to another. The IMPORTENCRYPTIONKEY function allows an administrator to specify a file (password protected) which contains a key and imports it to the current Microsoft Dynamics NAV Server.

Note
In systems with multiple Microsoft Dynamics NAV Server instances, you must run the IMPORTENCRYPTIONKEY function for each instance.

Important
Use the System Restore permission set in Microsoft Dynamics NAV to allow importing the encryption key.

IMPORTENCRYPTIONKEY(filename, pwd)

Parameters

filename

Value: String

The file that contains the encryption key.

pwd

Value: String

The password that protects the file.

Return Value

Type: Boolean

true if the encryption key was imported; otherwise, false.

If you omit this optional return value and the encryption key cannot be imported successfully, then a run-time error occurs. If you include the return value, then you must handle any errors.

Exceptions

If the import key file cannot be imported, the following error will be displayed: Import Failed. The provided encryption key file contains invalid data and could not be imported.

Example

This code example uses the ENCRYPTIONENABLED and ENCRYPTIONKEYEXISTS functions to do a check before importing the encryption key.

This example requires that you create a text constant ServerFileName.

Copy Code
IF ENCRYPTIONENABLED THEN
        IF ENCRYPTIONKEYEXISTS THEN
          IF NOT CONFIRM('Encryption has been enabled and the server already contains an encryption key.\'
          + 'Importing a key will overwrite any existing key and may result in lost data.\\'
          + 'Do you wish to continue?') THEN
            EXIT
        ELSE
          IF NOT CONFIRM('Importing a key different from the already configured key will result in data corruption.\\'
          + 'Do you wish to continue?') THEN
            EXIT
      IF NOT UPLOAD('Upload encrypted key','','Encrypted Key File (*.ekey)|*.ekey','ExportedKey.ekey',ServerFileName) THEN
        EXIT;
      IMPORTENCRYPTIONKEY(ServerFileName,'This is my personal secret');
      ERASE(ServerFileName);

See Also

Reference

EXPORTENCRYPTIONKEY

Concepts

Encryption Key Management
Encryption Functions


EXPORTENCRYPTIONKEY

Returns a password protected temporary filepath containing the encryption key.

When encrypting or decrypting data in Microsoft Dynamics NAV, an encryption key is used. Microsoft Dynamics NAV uses a single key per tenant and every tenant will have a different key. Keys can be exported to a file which may be necessary in the case of upgrading or migrating a system from one set of hardware to another. The EXPORTENCRYPTIONKEY function allows an administrator to specify a destination file for the key and specify a password protection for the file.

Important
Use the System Restore permission set in Microsoft Dynamics NAV to allow importing the encryption key.

TempFile EXPORTENCRYPTIONKEY(pwd)

Parameters

pwd

Value: String

Specifies the password for the encryption key file.

Property Value/Return Value

Value: Text

A temporary filepath to where the key is exported.

Exceptions

If encryption is not enabled or the encryption key is not found, the following error will be displayed: An encryption key is required to complete the request.

Example

This code example uses the EXPORTENCRYPTIONKEY function to return a password protected file that contains an encryption key. With the DOWNLOAD function the file is sent from the Microsoft Dynamics NAV Server computer to the client computer.

This example requires that you create the following text constants: ExportFileName and ClientFileName.

Copy Code
IF NOT ENCRYPTIONENABLED THEN
        ERROR('Encryption has not been enabled.');
      ExportFileName := EXPORTENCRYPTIONKEY('This is my personal secret');
      ClientFileName := 'ExportedKey.ekey';
      DOWNLOAD(ExportFileName,'Save the encrypted key file','','Encrypted Key File (*.ekey)|*.ekey',ClientFileName);
      ERASE(ExportFileName);

See Also

Concepts

System
Technical Reference
C/SIDE Reference Guide
Encryption Key Management


CREATEENCRYPTIONKEY

Creates an encryption key for the current Microsoft Dynamics NAV tenant.

CREATEENCRYPTIONKEY()

Return Value

Type: Boolean

true if the encryption key was created; otherwise, false.

If you omit this optional return value and the encryption key cannot be created successfully, then a run-time error occurs. If you include the return value, then you must handle any errors.

Exceptions

If a key already exists, the following error will be displayed: Unable to create a new encryption key. An encryption key already exists.

Example

This code example creates an encryption key for the current tenant. It uses the ENCRYPTIONENABLED function to perform a check.

Copy Code
IF NOT ENCRYPTIONENABLED THEN
        CREATEENCRYPTIONKEY();

See Also

Concepts

System
Technical Reference
C/SIDE Reference Guide


DELETEENCRYPTIONKEY

Deletes the encryption key for the current Microsoft Dynamics NAV tenant.

Important
Use the System Restore permission set in Microsoft Dynamics NAV to allow importing the encryption key.

DELETEENCRYPTIONKEY()

Example

This code example checks if encryption is configured for the tenant using the ENCRYPTIONENABLED function and if so, it performs the deletion of the encryption key.

Copy Code
IF NOT ENCRYPTIONENABLED THEN
  ERROR('Encryption has not been enabled.');
  DELETEENCRYPTIONKEY();

See Also

Concepts

System
Technical Reference
C/SIDE Reference Guide


ENCRYPTIONKEYEXISTS

Checks whether an encryption key for the current tenant is present on the server tenant.

Bool ENCRYPTIONKEYEXISTS()

Property Value/Return Value

Value: Boolean

Returns true if the encryption key exists, otherwise false.

Example

This code example performs checks to determine if an encryption key already exists.

Copy Code
IF ENCRYPTIONENABLED THEN
        IF ENCRYPTIONKEYEXISTS THEN
          MESSAGE('Encryption has been enabled and the encryption key is present in this server instance')
        ELSE
          MESSAGE('Encryption has been enabled but the encryption key is not present on this server instance')
      ELSE
        MESSAGE('Encryption has not been enabled')

See Also

Concepts

System
Technical Reference
C/SIDE Reference Guide


ENCRYPTIONENABLED

Checks if the tenant is configured to allow encryption.

Note
This does not mean that an encryption key is present on the Microsoft Dynamics NAV Server, only that the system is expecting to use one. This situation can arise if multiple servers are in use but the encryption key has not yet been deployed to each of them.

Bool ENCRYPTIONENABLED()

Property Value/Return Value

Value: Boolean

Returns true if the tenant is configured to allow encryption, otherwise false.

Example

This code example checks if the tenant is configured for encryption.

Copy Code
IF ENCRYPTIONENABLED THEN
        MESSAGE('Encryption has been enabled')
      ELSE
        MESSAGE('Encryption has not been enabled')

See Also

Concepts

System
Technical Reference
C/SIDE Reference Guide


Test Pages

You can use test pages to mimic actual pages so that you can test the code the page. There are two types of test pages:

  • TestPage

  • TestRequestPage

You use the TestPage Functions to:

  • Open and close test pages.

  • Navigate among records to display on the test page.

  • Navigate among fields on the test page.

  • Expand and collapse rows on a test page.

  • Create a new record from a test page.

  • Get the options and option count for an option field.

  • Get validation errors and error counts.

You use the TestPage Field Functions to:

  • Set the focus on a specific field.

  • Set the value of a field.

  • Compare the value of a field.

  • Simulate the drop-down arrow, drill-down, and lookup buttons on a field.

You use the TestPage Filter Functions to set filter parameters, such as current key, and direction to display the results, such as ascending or descending.

You use the TestPage Action Functions to invoke an action on a page. This includes both actions that you define in Page Designer and built-in actions, such as Yes, No, OK, and Cancel.

See Also

Reference

TestPage Data Type
TestRequestPage Data Type


TestPage Data Type

Stores test pages. A test page is a logical representation of a page that does not display a user interface (UI). The subtype of a test page is the page that it is used to test.

A test page can be any page type. For more information about types of pages, see Pages Overview.

Remarks

You can use test pages only within test codeunits.

See Also

Reference

TestRequestPage Data Type


TestRequestPage Data Type

This data type stores test request pages. A test request page part is a logical representation of a request page on a report. A test request page does not display a user interface (UI). The subtype of a test request page is the report whose request page you want to test.

Remarks

You can use test request pages only within test codeunits.

See Also

Reference

TestPage Data Type


SAVEASEXCEL Function (TestRequestPage)

Saves a report as a Microsoft Excel (.xls) file.

TestRequestPage.SAVEASEXCEL(Filename)

Parameters

TestRequestPage

Type: TestRequestPage

The TestRequestPage from which you want to test saving the report as an Excel file.

Filename

Type: Text

The path and file name to which the report is saved. The file name extension should be .xls.

Remarks

All filters and options that have been set on the TestRequestPage are respected in the saved report.

After you run this function, you cannot continue to interact with the TestRequestPage. If you want to continue to use the TestRequestPage variable, you must run a report again.

Example

The following example shows the code for a test function to run a report and a request page handler function to test the request page. This example requires that you create the following:

  • A test codeunit called SaveAsExcel. For more information, see How to: Create Test Codeunits and Test Functions.

  • A test function in the test codeunit called TestSaveAsExcel. For more information, see How to: Create Test Codeunits and Test Functions.

  • A handler function of type RequestPageHandler called ReqPageHandler. This handler function has one parameter called RequestPage of Type TestRequestPage and Subtype Customer - Top 10 List. The RequestPage parameter is specified as VAR and is passed by reference to the handler function. For more information, see How to: Create Handler Functions.

This example also requires that you create the following variable in the C/AL Globals window of the SaveAsExcel codeunit.

Variable name | DataType
Filename | Text
Copy Code
//Test function: TestSaveAsExcel
Filename := TEMPORARYPATH + 'MyRep.xls';
MESSAGE(Filename);
IF NOT FILE.ERASE(Filename) THEN
  ERROR('Cannot erase %1',Filename);
REPORT.RUN(111);
IF NOT FILE.EXISTS(Filename) THEN
  ERROR('File should exist!');
//Request Page Handler function
RequestPage.Customer.SETFILTER("No.", '20000');
RequestPage.ChartType.VALUE('Pie chart');
RequestPage.SAVEASEXCEL(Filename);

See Also

Reference

SAVEASPDF Function (TestRequestPage)
SAVEASWORD Function (TestRequestPage)

Concepts

Testing the Application


SAVEASPDF Function (TestRequestPage)

Saves a report as an Adobe Acrobat (.pdf) file.

TestRequestPage.SAVEASPDF(Filename)

Parameters

TestRequestPage

Type: TestRequestPage

The TestRequestPage from which you want to test saving the report as a PDF file.

Filename

Type: Text

The path and filename to which the report is saved. The file name extension should be .pdf.

Remarks

All filters and options that have been set on the TestRequestPage are respected in the saved report.

After you run this function, you cannot continue to interact with the TestRequestPage. If you want to continue to use the TestRequestPage variable, you must run a report again.

Example

The following example shows the code for a test function to run a report and a request page handler function to test the request page. This example requires that you create the following:

  • A test codeunit called SaveAsPDF. For more information, see How to: Create Test Codeunits and Test Functions.

  • A test function in the test codeunit called TestSaveAsPDF. For more information, see How to: Create Test Codeunits and Test Functions.

  • A handler function of type RequestPageHandler called ReqPageHandler. This handler function has one parameter called RequestPage of Type TestRequestPage and Subtype Customer - Top 10 List. The RequestPage parameter is specified as VAR and is passed by reference to the handler function. For more information, see How to: Create Handler Functions.

This example also requires that you create the following variable in the C/AL Globals window of the SaveAsPDF codeunit.

Variable name | DataType
Filename | Text
Copy Code
//Test function: TestSaveAsPDF
Filename := TEMPORARYPATH + 'MyRep.pdf';
MESSAGE(Filename);
IF NOT FILE.ERASE(Filename) THEN
  ERROR('Cannot erase %1',Filename);
REPORT.RUN(111);
IF NOT FILE.EXISTS(Filename) THEN
  ERROR('File should exist!');
//Request Page Handler function
RequestPage.Customer.SETFILTER("No.", '20000');
RequestPage.ChartType.VALUE('Pie chart');
RequestPage.SAVEASPDF(Filename);

See Also

Reference

SAVEASEXCEL Function (TestRequestPage)
SAVEASWORD Function (TestRequestPage)

Concepts

Testing the Application


SAVEASWORD Function (TestRequestPage)

Saves a report as a Microsoft Word (.doc) file.

TestRequestPage.SAVEASWORD(Filename)

Parameters

TestRequestPage

Type: TestRequestPage

The TestRequestPage from which you want to test saving the report as a Word file.

Filename

Type: Text

The path and filename to which the report is saved. The file name extension should be .doc.

Remarks

All filters and options that have been set on the TestRequestPage are respected in the saved report.

After you run this function, you cannot continue to interact with the TestRequestPage. If you want to continue to use the TestRequestPage variable, you must run a report again.

Example

The following example shows the code for a test function to run a report and a request page handler function to test the request page. This example requires that you create the following:

  • A test codeunit called SaveAsWord. For more information, see How to: Create Test Codeunits and Test Functions.

  • A test function in the test codeunit called TestSaveAsWord. For more information, see How to: Create Test Codeunits and Test Functions.

  • A handler function of type RequestPageHandler called ReqPageHandler. This handler function has one parameter called RequestPage of Type TestRequestPage and Subtype Customer - Top 10 List. The RequestPage parameter is specified as VAR and is passed by reference to the handler function. For more information, see How to: Create Handler Functions.

This example also requires that you create the following variable in the C/AL Globals window of the SaveAsWord codeunit.

Variable name | DataType
Filename | Text
Copy Code
//Test function: TestSaveAsWord
Filename := TEMPORARYPATH + 'MyRep.doc';
MESSAGE(Filename);
IF NOT FILE.ERASE(Filename) THEN
  ERROR('Cannot erase %1',Filename);
REPORT.RUN(111);
IF NOT FILE.EXISTS(Filename) THEN
  ERROR('File should exist!');
//Request Page Handler function
RequestPage.Customer.SETFILTER("No.", '20000');
RequestPage.ChartType.VALUE('Pie chart');
RequestPage.SAVEASEXCEL(Filename);


SAVEASXML Function (TestRequestPage)

Saves a report dataset and the labels on a report as two XML (.xml) files.

TestRequestPage.SAVEASXML(Filename_Labels, Filename_Dataset)

Parameters

TestRequestPage

Type: TestRequestPage

The TestRequestPage from which you want to test saving the report dataset and labels as XML files.

Filename_Labels

Type: Text

The path and file name to which the report labels are saved. The file name extension should be .xml.

Filename_Dataset

Type: Text

The path and file name to which the report dataset is saved. The file name extension should be .xml.

Remarks

All filters and options that have been set on the TestRequestPage are respected in the saved report.

After you run this function, you cannot continue to interact with the TestRequestPage. If you want to continue to use the TestRequestPage variable, you must run a report again.

Example

The following example shows the code for a test function to run a report and a request page handler function to test the request page. This example requires that you create the following:

  • A test codeunit called SaveAsXML. For more information, see How to: Create Test Codeunits and Test Functions.

  • A test function in the test codeunit called TestSaveAsXML. For more information, see How to: Create Test Codeunits and Test Functions.

  • A handler function of type RequestPageHandler called ReqPageHandler. This handler function has one parameter called RequestPage of Type TestRequestPage and Subtype Customer - Top 10 List. The RequestPage parameter is specified as VAR and is passed by reference to the handler function. For more information, see How to: Create Handler Functions.

This example also requires that you create the following variables in the C/AL Globals window of the SaveAsXML codeunit.

Variable name | DataType
LabelsFilename | Text
DatasetFilename | Text
Copy Code
// Add the following code to the TestSaveAsXML test function.
LabelsFilename := TEMPORARYPATH + 'MyLabels.xml';
DatasetFilename := TEMPORARYPATH + 'MyDataset.xml';
REPORT.RUN(111);
IF NOT FILE.EXISTS(LabelsFilename) THEN
  ERROR('Labels file should exist!');
IF NOT FILE.EXISTS(DatasetFilename) THEN
  ERROR('Dataset file should exist!');
// Add the following code to the ReqPageHandler function.
RequestPage.Customer.SETFILTER("No.", '20000');
RequestPage.ChartType.VALUE('Pie chart');
RequestPage.SAVEASXML(LabelsFilename,DatasetFilename);

See Also

Reference

TestRequestPage Data Type


TestPage Functions

You can use the TestPage functions for the following purposes.

To do the following Use these functions

Open and close test pages.

  • OPENEDIT Function (TestPage)

  • OPENNEW Function (TestPage)

  • OPENVIEW Function (TestPage)

  • CLOSE Function (TestPage)

  • TRAP Function (TestPage)

Navigate among records to display on the test page.

  • FIRST Function (TestPage)

  • LAST Function (TestPage)

  • NEXT Function (TestPage)

  • PREVIOUS Function (TestPage)

  • GOTOKEY Function (TestPage)

  • GOTORECORD Function (TestPage)

Navigate among fields on the test page.

  • FINDFIRSTFIELD Function (TestPage)

  • FINDNEXTFIELD Function (TestPage)

  • FINDPREVIOUSFIELD Function (TestPage)

  • GETFIELD Function (TestPage)

Expand and collapse rows on a test page.

EXPAND Function (TestPage)

Create a new record from a test page.

NEW Function (TestPage)

Get the options and option count for an option field.

  • GETOPTION Function (TestPage Field)

  • OPTIONCOUNT Function (TestPage Field)

Get validation errors and error counts.

  • GETVALIDATIONERROR Function (TestPage, TestPage Field)

  • VALIDATIONERRORCOUNT Function (TestPage, TestPage Field)

See Also

Concepts

Test Pages


CAPTION Function (TestPage)

Gets the caption of the test page.

Caption := TestPage.CAPTION

Parameters

TestPage

Type: TestPage

The test page that the caption belongs to.

Property Value/Return Value

Type: Text or Code

The caption of the test page.

See Also

Concepts

TestPage Functions


CLOSE Function (TestPage)

Closes an open test page.

TestPage.CLOSE

Parameters

TestPage

Type: TestPage

The test page that you want to close.

Remarks

If TestPage has never been opened or is already closed, then a run-time error occurs, and the outcome of the test function is FAILURE.

Example

This example requires that you create a TestPage variable named CustTestPage with a Subtype of Customer List and that the codeunit in which you write the code is a test codeunit.

Copy Code
// Open the test page.
CustPage.OPENEDIT;
// Add code to test the Customer List page.
// …
// Close the Customer Card
CustPage.CLOSE;

See Also

Concepts

TestPage Functions


EXPAND Function (TestPage)

Expands rows on a test page.

MyTestPage.EXPAND(Expand);

Parameters

TestPage

Type: TestPage

The test page that contains the rows that you want to expand.

Expand

Type: row

The rows that you want to expand on the test page.

See Also

Concepts

TestPage Functions


FINDFIRSTFIELD Function (TestPage)

Finds the first field in the dataset that is displayed on a test page.

[Ok :=] TestPage.FINDFIRSTFIELD(Field, Value);

Parameters

TestPage

Type: TestPage

The test page that contains the dataset that you want to find.

Field

Type: Field

The field to find.

Value

Type: Any

The value of the field.

Property Value/Return Value

Type: Boolean

true if the first field is found; otherwise, false. The return value is optional.

See Also

Concepts

TestPage Functions


FINDNEXTFIELD Function (TestPage)

Finds the next field in the dataset that is displayed on a test page.

[Ok :=]TestPage.FINDNEXTFIELD(Field, Value);

Parameters

TestPage

Type: TestPage

The test page that contains the dataset that you want to find.

Field

Type: Field

The field to find.

Value

Type: Any

The value of the field.

Property Value/Return Value

Type: Boolean

true if the first field is found; otherwise, false. The return value is optional.

See Also

Concepts

TestPage Functions


FINDPREVIOUSFIELD Function (TestPage)

Finds the previous field in the dataset that is displayed on a test page.

[Ok :=] TestPage.FINDPREVIOUSFIELD(Field, Value);

Parameters

TestPage

Type: TestPage

The test page that contains the dataset.

Field

Type: Field

The field to find.

Value

Type: Any

The value of the field.

Property Value/Return Value

Type: Boolean

true if the previous field is found; otherwise, false. The return value is optional.

See Also

Concepts

TestPage Functions


FIRST Function (TestPage)

Sets the current row of the test page as the first row in the dataset.

OK := TestPage.FIRST

Parameters

TestPage

The test page variable that you use to refer to the test page.

Property Value/Return Value

Type: Boolean

true if a record exists in the dataset and the current row was successfully set to the first row in the dataset; otherwise, false.

Remarks

If TestPage is closed or has never been opened, then the function call fails.

Example

This example sets the current row to the first customer in the dataset. It requires that you create a TestPage variable named CustomerList with a Subtype of Customer List.

Copy Code
CustomerList.OPENVIEW;
CustomerList.FIRST;
MESSAGE(CustomerList.Name.Value);

See Also

Concepts

TestPage Functions


GETACTION Function (TestPage)

Gets the action that the test page invokes.

[Action :=] TestPage.GETACTION(id);

Parameters

TestPage

Type: TestPage

The test page variable that you use to refer to the test page.

id

Type: Integer

The ID of the action that the test page invokes.

Property Value/Return Value

Type: Text

The action that the test page invokes. This return value is optional.

See Also

Concepts

TestPage Functions


GETFIELD Function (TestPage)

Gets a field on a test page.

[Field] := TestPage.GETFIELD(Id)

Parameters

TestPage

Type: TestPage

The test page for which you want to get a field.

Id

Type: Integer

The ID of the field that you want to get. This ID is from Page Designer.

Property Value/Return Value

Type: TestField

The field on the test page.

You cannot declare a variable of type TestField. Instead, you use the Value property and assign the value of the field to a variable.

Remarks

To find the ID of a field, in Page Designer, select the field, and then on the View menu, choose Properties.

You can use this function if you have a function or a property on a test page with the same name as a field on the page. If you use the <TestPage>.<Field> notation but the Field name is also a function name, then the function takes precedence. To access the field, use the GETFIELD function.

Example

This example requires that you create the following variables and text constants.

Variable name | DataType | Subtype | Length
CustomerCard | TestPage | Customer Card | Not applicable
AddressField | Text | Not applicable | 200

Text constant | ENU value
Text001 | 612 South Sunset Drive
Copy Code
CustomerCard.OPENEDIT;
AddressField := CustomerCard.GETFIELD(6).Value;
IF AddressField <> Text001 THEN
  ERROR('Incorrect address');

See Also

Concepts

TestPage Functions


GETVALIDATIONERROR Function (TestPage, TestPage Field)

Gets the validation error that occurred on a test page.

OemText := TestPage.GETVALIDATIONERROR(index);

Parameters

TestPage

Type: TestPage

The test page that you want to get the validation error from.

index

Type: Integer

The index of the validation error that occurred on the test page.

Property Value/Return Value

Type: Text

The validation error that occurred on the test page.

See Also

Concepts

TestPage Functions


GOTOKEY Function (TestPage)

Finds the row in a dataset on the test page that is identified by the specified values.

[Ok :=]TestPage.GOTOKEY([Value],...);

Parameters

TestPage

Type: TestPage

The test page that contains the dataset.

Value

Type: Text or Integer

The value or list of values to use to find the row. If this parameter is omitted, the primary key value is used.

Property Value/Return Value

Type: Boolean

true if the specified row is found; otherwise, false. The return value is optional.

See Also

Concepts

TestPage Functions


GOTORECORD Function (TestPage)

Finds the specified record in a dataset on a test page.

[Ok :=]TestPage.GOTORECORD(Rec);

Parameters

TestPage

Type: TestPage

The test page that contains the dataset.

Rec

Type: Record

The record to find.

Property Value/Return Value

Type: Boolean

true if the specified record is found; otherwise, false. The return value is optional.

See Also

Concepts

TestPage Functions


ISEXPANDED Function (TestPage)

Specifies if rows on a test page are expanded.

Ok := TestPage.ISEXPANDED;

Parameters

TestPage

Type: TestPage

The test page that contains the dataset.

Property Value/Return Value

Type: Boolean

true if the rows are expanded; otherwise, false.

See Also

Concepts

TestPage Functions


LAST Function (TestPage)

Sets the current row of the test page as the last row in the dataset.

OK := TestPage.LAST

Parameters

TestPage

The test page variable that you use to refer to the test page.

Property Value/Return Value

Type: Boolean

true if a record exists in the dataset and the current row was successfully set to the last row in the dataset; otherwise, false.

Remarks

If TestPage is closed or has never been opened, then the function call fails.

Example

This example sets the current row to the last customer in the dataset. It requires that you create a TestPage variable named CustomerList with a Subtype of Customer List.

Copy Code
CustomerList.OPENVIEW;
CustomerList.LAST;
MESSAGE(CustomerList.Name.Value);


NEW Function (TestPage)

Sets the current row of the test page to an empty row in a dataset.

TestPage.NEW

Parameters

TestPage

Type: TestPage

The test page that contains the dataset.

See Also

Concepts

TestPage Functions


NEXT Function (TestPage)

Sets the current row of the test page as the next row in the dataset.

OK := TestPage.NEXT

Parameters

TestPage

Type: TestPage

The test page variable that you use to refer to the test page.

Property Value/Return Value

Type: Boolean

true if the current row was set to the next row in the dataset successfully; otherwise, false.

Remarks

If TestPage is closed or has never been opened, then the function call fails.

Example

This example requires that you create a TestPage variable named CustomerList with a Subtype of Customer List.

Copy Code
CustomerList.OPENVIEW;
// Loops through all customers and displays the customer name.
IF CustomerList.FIRST THEN
  REPEAT
    MESSAGE(CustomerList.Name);
UNTIL NOT CustomerList.NEXT;


OPENEDIT Function (TestPage)

Opens a test page in edit mode.

TestPage.OPENEDIT

Parameters

TestPage

Type: TestPage

The test page variable that you use to refer to the test page.

Remarks

If TestPage is already open, then a run-time error occurs, and the outcome of the test function is FAILURE.

If the page to which TestPage refers is a card page, then the data that is loaded on the page is from the first row in the dataset.

Example

This example requires that you create a TestPage variable named CustTestPage with a Subtype of Customer List and that the codeunit in which you write the code is a test codeunit.

Copy Code
// Opens the TestPage in edit mode.
CustTestPage.OPENEDIT()


OPENNEW Function (TestPage)

Opens a blank test page in edit mode.

TestPage.OPENNEW

Parameters

TestPage

Type: TestPage

The test page variable that you use to refer to the new test page.

Remarks

If TestPage is already open, then a run-time error occurs, and the outcome of the test function is FAILURE.

Example

This example requires that you create a TestPage variable named CustTestPage with a Subtype of Customer List and that the codeunit in which you write the code is a test codeunit.

Copy Code
// Opens a blank Customer Card test page.
CustTestPage.OPENNEW;


OPENVIEW Function (TestPage)

Opens a test page in view mode.

TestPage.OPENVIEW

Parameters

TestPage

Type: TestPage

The test page variable that you use to refer to the test page.

Remarks

If TestPage is already open, then a run-time error occurs, and the outcome of the test function is FAILURE.

If the page to which TestPage refers is a card page, then the data that is loaded on the page is from the first row in the dataset.

Example

This example requires that you create a variable named CustTestPage with a Subtype of Customer List and that the codeunit in which you write the code is a test codeunit.

Copy Code
// Opens the Customer Card on the first Customer in the dataset.
CustTestPage.OPENVIEW;


PREVIOUS Function (TestPage)

Sets the current row of the test page as the previous row in the dataset.

OK := TestPage.PREVIOUS

Parameters

TestPage

Type: TestPage

The test page variable that you use to refer to the test page.

Property Value/Return Value

Type: Boolean

true if the current row was set to the previous row in the dataset successfully; otherwise, false.

Remarks

If TestPage is closed or has never been opened, then the function call fails.

Example

This example requires that you create a TestPage variable named CustomerList with a Subtype of Customer List.

Copy Code
CustomerList.OPENVIEW;
…
IF CustomerList.LAST THEN REPEAT
  MESSAGE(CustomerList.Name);
UNTIL NOT CustomerList.PREVIOUS;


TRAP Function (TestPage)

Traps the next test page that is invoked and assigns it to the test page variable.

TestPage.TRAP

Parameters

TestPage

Type: TestPage

The test page variable that you use to refer to the test page.

Remarks

You can trap only nonmodal pages with the TRAP function. To trap modal pages that you invoke with the RUNMODAL Function (Page) or the PAGE.RUNMODAL Function, you must use the ModalFormHandler function. For more information, see How to: Create Handler Functions.

Example

This example shows how to use the TRAP function to trap a call to open a test page so that the opened page is assigned to a variable.

This example requires that you create the following variables.

Variable name | DataType | Subtype
CustomerCard | TestPage | Customer
CustomerStatistics | TestPage | Customer Statistics
Copy Code
CustomerCard.OPENEDIT;
CustomerStatistics.TRAP; // The next page that is invoked will be trapped and assigned to the CustomerStatistics variable.
CustomerCard."Page Customer Statistics".INVOKE; // Invokes an action from the Customer Card page.
CustomerStatistics."Balance (LCY)".ASSERTEQUALS(0); // Now that the CustomerStatistics test page is open, you can use the variable to test the page.


VALIDATIONERRORCOUNT Function (TestPage, TestPage Field)

Gets the number of validation errors that occurred on the test page.

Count := TestPage.VALIDATIONERRORCOUNT

Parameters

TestPage

Type: TestPage

The test page variable that you use to refer to the test page.

Property Value/Return Value

Type: Integer

The number of validation errors that occurred on the test page.

See Also

Concepts

TestPage Functions


TestPage Field Functions

The field functions enable you to view or change the value of a field on a test page.

See Also

Concepts

Testing Pages


ACTIVATE Function (TestPage Field)

Activates a field on a test page.

TestPage.ACTIVATE

Parameters

TestPage

Type: TestPage

The test page variable that you use to refer to the test page.

See Also

Concepts

TestPage Field Functions


ASBOOLEAN Function (TestPage Field)

Converts the value in a field on a test page to a Boolean data type.

Boolean := TestPage.Field.ASBOOLEAN

Parameters

TestPage

Type: TestPage

The test page variable that you use to refer to the test page.

Field

Type: Field

The field that contains the value that you want to convert.

Property Value/Return Value

Type: Boolean

The converted value.

See Also

Concepts

TestPage Field Functions


ASDECIMAL Function (TestPage Field)

Converts the value in a field on a test page to a DECIMAL data type.

Decimal := TestPage.Field.ASDECIMAL

Parameters

TestPage

Type: TestPage

The test page variable that you use to refer to the test page.

Field

Type: Field

The field that contains the value that you want to convert.

Property Value/Return Value

Type: Decimal

The converted value.

See Also

Concepts

TestPage Field Functions


ASINTEGER Function (TestPage Field)

Converts the value in a field on a test page to an Integer data type.

Integer := TestPage.Field.ASINTEGER

Parameters

TestPage

Type: TestPage

The test page variable that you use to refer to the test page.

Field

Type: Field

The field that contains the value that you want to convert.

Property Value/Return Value

Type: Integer

The converted value.

See Also

Concepts

TestPage Field Functions


ASSISTEDIT Function (TestPage Field)

Provides assist-edit functionality to a field on a test page.

TestPage.Field.ASSISTEDIT

Parameters

TestPage

Type: TestPage

The test page variable that you use to refer to the test page.

Field

Type: Field

The field that you want to add assist-edit functionality to.

See Also

Concepts

TestPage Field Functions


ASSERTEQUALS Function (TestPage Field)

Asserts that the value in a field on a test page equals a specified value.

TestPage.Field.ASSERTEQUALS(value)

Parameters

TestPage

Type: TestPage

The test page variable that you use to refer to the test page.

Field

Type: Field

The field that contains the value that you want to assert.

Value

Type: Any

Specifies the value that the field should equal.

See Also

Concepts

TestPage Field Functions


DRILLDOWN Function (TestPage Field)

Applies drill-down capability for a field on a test page.

TestPage.Field.DRILLDOWN

Parameters

TestPage

Type: TestPage

The test page variable that you use to refer to the test page.

Field

Type: Field

The field that you want to apply the drill-down to.

See Also

Concepts

TestPage Field Functions


GETOPTION Function (TestPage Field)

Gets the options for a field on a test page.

Text := TestPage.Field.GETOPTION([Index]);

Parameters

TestPage

Type: TestPage

The test page variable that you use to refer to the test page.

Field

Type: Field

The field for which you to get the options.

Index

Type: Integer

The index of the field that you want to get the options from. This parameter is optional.

Property Value/Return Value

Type: Text

The options in the field.


LOOKUP Function (TestPage Field)

Provides a lookup window for a text box on a test page.

TestPage.Field.LOOKUP

Parameters

TestPage

Type: TestPage

The test page variable that you use to refer to the test page.

Field

Field

The field that you want to provide a lookup window for.

See Also

Concepts

TestPage Field Functions


OPTIONCOUNT Function (TestPage Field)

Gets the number of options in a field on a test page.

Integer := TestPage.Field.OPTIONCOUNT

Parameters

TestPage

Type: TestPage

The test page variable that you use to refer to the test page.

Field

Type: Field

The field that contains the options.

Property Value/Return Value

Type: Integer

The number of options in a field.

See Also

Concepts

TestPage Field Functions


SETVALUE Function (TestPage Field)

Sets a value for a field on a test page.

TestPage.Field.SETVALUE(Value)

Parameters

TestPage

Type: TestPage

The test page variable that you use to refer to the test page.

Field

Type: Field

The field that you want to set a value for.

Value

Type: Any

The value to set.

See Also

Concepts

TestPage Field Functions


TestPage Filter Functions

The filter functions enable you to filter data that can be accessed on a test page. You use the Filter property in combination with the filter functions to perform filter operations.

See Also

Concepts

Test Pages


ASCENDING Function (TestPage Filter)

Gets or sets the order in which to search through a dataset on a test page.

[IsAscending :=] TestPage.Part.Filter.ASCENDING([SetAscending]);

Parameters

TestPage

Type: TestPage

The test page that displays the dataset to search.

Part

Type: Part

The control that contains the dataset you want to search.

Filter

Type: Filter

The filter that is applied to the dataset.

SetAscending

Type: Boolean

The order in which the dataset will be searched. This parameter is optional.

IsAscending

Type: Boolean

The sort order of the dataset.

Property Value/Return Value

Type: Boolean

true if the search is performed in ascending order; otherwise, false.

See Also

Concepts

TestPage Filter Functions


CURRENTKEY Function (TestPage Filter)

Gets the current key of a dataset that is displayed on a test page.

CurrentKey := TestPage.Part.Filter.CURRENTKEY

Parameters

TestPage

Type: TestPage

The test page that displays the dataset.

Part

Type: Part

The control on the test page that contains the dataset.

Filter

Type: Filter

The filter that is applied to the dataset.

Property Value/Return Value

Type: Text

Returns a string that contains the current key.

See Also

Concepts

TestPage Filter Functions


GETFILTER Function (TestPage Filter)

Gets the filter that is applied to the specified field in a dataset that is displayed on a test page.

String := TestPage.Part.Fiter.GETFILTER(Field);

Parameters

TestPage

Type: TestPage

The test page that displays the dataset that contains the specified field.

Part

Type: Part

The control on the test page that contains the dataset.

Filter

Type: Filter

The filter that is applied to the dataset.

Field

Type: Field

The field that you want to get the filter from.

Property Value/Return Value

Type: Text

The filter that is applied to the specified field.

See Also

Concepts

TestPage Filter Functions


SETCURRENTKEY Function (TestPage Filter)

Sets the specified fields in a dataset on a test page as the current key.

[Ok :=] TestPage.Filter.SETCURRENTKEY(Field1 [, Field2] ,...);

Parameters

TestPage

Type: TestPage

The test page that displays the dataset that contains the specified field.

Part

Type: Part

The control on the test page that contains the dataset.

Filter

Type: Filter

The filter that is applied to the dataset.

Field1

Type: Field

The field that you want to set as the current key.

Field2

Type: Field

Additional field that you want to set as the current key. This parameter is optional.

Property Value/Return Value

Type: Boolean

true if the current key was set; otherwise, false. This return value is optional.

Remarks

You can select additional fields to be included as the current key.

See Also

Concepts

TestPage Filter Functions


SETFILTER Function (TestPage Filter)

Applies a filter to the specified field on a test page.

TestPage.Part.Fiter.SETFILTER(Field, String);

Parameters

TestPage

Type: TestPage

The test page that displays the dataset that contains the specified field.

Part

Type: Part

The control on the test page that contains the dataset.

Filter

Type: Filter

The filter that is applied to the dataset.

Field

Type: Field

The field that you want to apply the filter to.

String

Type: Text

The filter to apply to the specified field.

See Also

Concepts

TestPage Filter Functions


TestPage Action Functions

Access page actions by using the dot notation and the INVOKE Function (TestPage Action).

See Also

Concepts

Test Pages


INVOKE Function (TestPage Action)

Invokes an action on a test page.

TestPage.Action.INVOKE

Parameters

TestRequestPage

Type: TestPage

The test page from which you want to invoke the action.

Action

Type: Text

The action to invoke from the test page.

Remarks

All actions that are available on the page are also available on the test page.

See Also

Concepts

Test Pages
TestPage Functions


TableFilter Data Type

Applies a filter to another table. Currently, this data type can only be used when you are setting security filters from the Permission table.


Variant Data Type

The C/AL variant data type can contain many C/AL data types or any variants from OCX and Automation objects. However, not all these values can be mapped to C/AL values. For more information, see Using COM Technologies in Microsoft Dynamics NAV.

The variant data type can contain the following C/AL data types:

  • Action

  • Automation

  • BigInteger

  • BigText

  • Boolean

  • Byte

  • Char

  • Code

  • Codeunit

  • Date

  • DateFormula

  • DateTime

  • Decimal

  • Duration

  • FilterPageBuilder

  • GUID

  • InStream

  • Integer

  • Option

  • OutStream

  • Record

  • RecordRef

  • Text

  • Time

  • TransactionType

You can use the variant data type to pass Automation variants from one external component (Automation or OCX) to another. This requires that the recipient component can accept the original variant. You can also assign a C/AL variable to a variant and pass it to an external component. When you pass C/AL variants ByRef to an external COM component, small conversion differences may occur. Therefore, we recommend that you pass C/AL variants ByVal if you do not have to assign a new value to the C/AL variant in your external component.

Returning Variants in Internal Function Calls

The C/AL variant is a complex data type. To return C/AL variants in function calls, you must pass them in a parameter ByVar (called ByRef in COM).

Passing DateTime variables to Automation

It is not possible to pass a C/AL DateTime variable to Automation. However, you can convert the C/AL DateTime to a variant, and then pass it to Automation. The following examples shows how to pass a DateTime to Automation. This example requires that you create the following variables.

Variable | Data type
varAutomation | Automation
varVariant | Variant
varDateTime | DateTime
Copy Code
varDateTime := CURRENTDATETIME;
varVariant := varDateTime;
varAutomation.MethodDateData(varVariant);

Variants and Approximation

A C/AL variant contains two allocation areas: one for C/AL variables and one for Automation and OCX variants. This means every time that you assign a C/AL variable to a variant, the variant will contain the same data as the original variable. The conversion process does not change the data in any way. However, this is not the case with DATI2VARIANT because it is a VT_VARIANT. When you assign an external variable to a variant, the variant will also contain the same data as the original external variable.

Assigning Automation Variants to FieldRef Values

In Microsoft Dynamics NAV 2016, if an Automation method returns a byte string (bstr) in a variant, you cannot assign that variant to a field that is a Code data type. Instead, you must first assign the variant to a code variable, and then assign the code variable to the FieldRef value. For example, the following code assigns a variant from an Automation method to a variable, and then assigns the variable to a field.

Copy Code
CodeVariable := AutomationMetodReturningBStrInVariant();
FieldRef.Value := CodeVariable;

In earlier versions of Microsoft Dynamics NAV, you could assign the variant to a Code FieldRef value.

See Also

Reference

DATI2VARIANT Function (Date, Variant)
ISACTION Function (Variant)
ISAUTOMATION Function (Variant)
ISBINARY Function (Variant)
ISBOOLEAN Function (Variant)
ISCHAR Function (Variant)
ISCODE Function (Variant)
ISCODEUNIT Function (Variant)
ISDATE Function (Variant)
ISDATEFORMULA Function (Variant)
ISDECIMAL Function (Variant)
ISFILE Function (Variant)
ISINSTREAM Function (Variant)
ISINTEGER Function (Variant)
ISOPTION Function (Variant)
ISOUTSTREAM Function (Variant)
ISRECORD Function (Variant)
ISTEXT Function (Variant)
ISTIME Function (Variant)
ISTRANSACTIONTYPE Function (Variant)
VARIANT2DATE Function (Date, Variant)
VARIANT2TIME Function (Date, Variant)


ISACTION Function (Variant)

Indicates whether a C/AL variant contains an Action variable.

Ok := Variant.ISACTION

Parameters

Variant

Type: Variant

Property Value/Return Value

Type: Boolean

true if the C/AL variant contains an Action variable; otherwise, false.

See Also

Reference

Variant Data Type


ISAUTOMATION Function (Variant)

Indicates whether a C/AL variant contains an Automation variable.

Ok := Variant.ISAUTOMATION

Parameters

Variant

Type: Variant

Property Value/Return Value

Type: Boolean

true if the C/AL variant contains an Automation variable; otherwise, false.

Example

The following example determines whether a C/AL variant contains an Automation variable. The MyAutomation variable is assigned to the variant variable that is named MyVariant. The ISAUTOMATION function determines whether the variant contains an Automation variable and stores the return value in the varResult variable. In this case, the variant contains an Automation variable so Yes is returned and displayed in a message box. The ISCODE Function (Variant) determines whether the variant contains a code variable. The return value is No because the variant does not contain a code. This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Subtype
MyAutomation | Automation | AFormAut 1.0 Type Library
MyVariant | Variant | Not applicable
varResult | Boolean | Not applicable

Text constant name | ConstValue
Text000 | Does the variant contain an Automation variable? %1
Text001 | Does the variant contain a code variable? %1
Copy Code
MyVariant := MyAutomation;
varResult := MyVariant.ISAUTOMATION;
MESSAGE(Text000,varResult);
varResult := MyVariant.ISCODE;
MESSAGE(Text001, varResult);

See Also

Reference

Variant Data Type


ISBINARY Function (Variant)

Indicates whether a C/AL variant contains a Binary variable.

Ok := Variant.ISBINARY

Parameters

Variant

Type: Variant

Property Value/Return Value

Type: Boolean

true if the C/AL variant contains a Binary variable; otherwise, false.

See Also

Reference

Variant Data Type


ISBOOLEAN Function (Variant)

Indicates whether a C/AL variant contains a Boolean variable.

Ok := Variant.ISBOOLEAN

Parameters

Variant

Type: Variant

Property Value/Return Value

Type: Boolean

true if the C/AL variant contains a Boolean variable; otherwise, false.

Example

The following example determines whether a C/AL variant contains a Boolean variable. The code initializes the MyBoolean variable with a Boolean value. The MyBoolean variable is assigned to the variant variable that is named MyVariant. The ISBOOLEAN function determines whether the variant contains a Boolean variable and stores the return value in the varResult variable. In this case, the variant contains a Boolean variable so Yes is returned and displayed in a message box. The Boolean value is obtained from the Critical field in the Item table. The ISCODE Function (Variant) determines whether the variant contains a code variable. The return value is No because the variant does not contain a code. This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Subtype
ItemRec | Record | Item
MyBoolean | Boolean | Not applicable
MyVariant | Variant | Not applicable
varResult | Boolean | Not applicable

Text constant name | ConstValue
Text000 | Does the variant >%1< contain a Boolean variable? %2
Text001 | Does the variant >%1< contain a code variable? %2
Copy Code
MyBoolean := ItemRec.Critical;
MyVariant := MyBoolean;
varResult := MyVariant.ISBOOLEAN;
MESSAGE(Text000,MyVariant,varResult);
varResult := MyVariant.ISCODE;
MESSAGE(Text001,MyVariant,varResult);

See Also

Reference

Variant Data Type


ISCHAR Function (Variant)

Indicates whether a C/AL variant contains a Char variable.

Ok := Variant.ISCHAR

Parameters

Variant

Type: Variant

Property Value/Return Value

Type: Boolean

true if the C/AL variant contains a Char variable; otherwise, false.

See Also

Reference

Variant Data Type


ISCODE Function (Variant)

Indicates whether a C/AL variant contains a Code variable.

Ok := Variant.ISCODE

Parameters

Variant

Type: Variant

Property Value/Return Value

Type: Boolean

true if the C/AL variant contains a Code variable; otherwise, false.

Example

The following example determines whether a C/AL variant contains a code variable. The code initializes the MyCode variable with a string value. The MyCode variable is assigned to the variant variable that is named MyVariant. The ISCODE function determines whether the variant contains a code variable and stores the return value in the varResult variable. In this case, the variant contains a code variable so Yes is returned and displayed in a message box. The ISTEXT Function (Variant) determines whether the variant contains a text variable. The return value is No because the variant does not contain a text. This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Length
MyCode | Code | 100
MyVariant | Variant | Not applicable
varResult | Boolean | Not applicable

Text constant name | ConstValue
Text000 | Does the variant >%1< contain a code variable? %2.
Text001 | Does the variant >%1< contain a text variable? %2.
Copy Code
MyCode := 'A1297';
MyVariant :=  MyCode;
varResult := MyVariant.ISCODE;
MESSAGE(Text000,MyVariant,varResult);
varResult := MyVariant.ISTEXT;
MESSAGE(Text001,MyVariant,varResult);

See Also

Reference

Variant Data Type


ISCODEUNIT Function (Variant)

Indicates whether a C/AL variant contains a Codeunit variable.

Ok := Variant.ISCODEUNIT

Parameters

Variant

Type: Variant

Property Value/Return Value

Type: Boolean

true if the C/AL variant contains a Codeunit variable; otherwise, false.

See Also

Reference

Variant Data Type


ISDATE Function (Variant)

Indicates whether a C/AL variant contains a Date variable.

Ok := Variant.ISDATE

Parameters

Variant

Type: Variant

Property Value/Return Value

Type: Boolean

true if the C/AL variant contains a Date variable; otherwise, false.

Example

The following example determines whether a C/AL variant contains a Date variable. The code initializes the MyDate variable with a Date value. The MyDate variable is assigned to the variant variable that is named MyVariant. The ISDATE function determines whether the variant contains a Date variable and stores the return value in the varResult variable. In this case, the variant contains a Date variable so Yes is returned and displayed in a message box. The ISCODE Function (Variant) determines whether the variant contains a Code variable. The return value is No because the variant does not contain a code. This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
MyDate | Date
MyVariant | Variant
varResult | Boolean

Text constant name | Enu value
Text000 | Does the variant >%1< contain a date variable? %2.
Text001 | Does the variant >%1< contain a code variable? %2.
Copy Code
MyDate := TODAY;
MyVariant :=  MyDate;
varResult := MyVariant.ISDATE;
MESSAGE(Text000,MyVariant,varResult);
varResult := MyVariant.ISCODE;
MESSAGE(Text001,MyVariant,varResult);

See Also

Reference

Variant Data Type


ISDATEFORMULA Function (Variant)

Indicates whether a C/AL variant contains a DateFormula variable.

Ok := Variant.ISDATEFORMULA

Parameters

Variant

Type: Variant

Property Value/Return Value

Type: Boolean

true if the C/AL variant contains a DateFormula variable; otherwise, false.

See Also

Reference

Variant Data Type


ISDECIMAL Function (Variant)

Indicates whether a C/AL variant contains a Decimal variable.

Ok := Variant.ISDECIMAL

Parameters

Variant

Type: Variant

Property Value/Return Value

Type: Boolean

true if the C/AL variant contains a Decimal variable; otherwise, false.

See Also

Reference

Variant Data Type


ISFILE Function (Variant)

Indicates whether a C/AL variant contains a File variable.

Ok := Variant.ISFILE

Parameters

Variant

Type: Variant

Property Value/Return Value

Type: Boolean

true if the C/AL variant contains a File variable; otherwise, false.

See Also

Reference

Variant Data Type


ISFILTERPAGEBUILDER Function (Variant)

Indicates whether a C/AL variant contains a FilterPageBuilder variable.

Ok := Variant.ISFILTERPAGEBUILDER

Parameters

Type: Variant

Return Value

Type: Boolean

true if the C/AL variant contains a FilterPageBuilder variable; otherwise, false.

Example

The following example uses the ISFILTERPAGEBUILDER function on a filter page object that includes a filter control for the Date system table.

This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | SubType
varDateItem | Text |
varFilterPageBuilder | FilterPageBuilder |
myVariant | Variant |
Copy Code
varDateItem := 'Date record';
varFilterPageBuilder.ADDTABLE(varDateItem + ‘ 1’,DATABASE::Date);
myVariant := varFilterPageBuilder;
IF not myVariant.ISFILTERPAGEBUILDER THEN
  ERROR(‘This variant should contain a FilterPageBuilder variable’);

See Also

Reference

Variant Data Type
FilterPageBuilder Data Type
ADDFIELD Function
ADDFIELDNO Function
ADDRECORD Function
ADDRECORDREF Function
ADDTABLE Function
GETVIEW function (FilterPageBuilder)
SETVIEW Function
COUNT Function (FilterPageBuilder)
NAME Function (FilterPageBuilder)
RUNMODAL Function (FilterPageBuilder)


ISINSTREAM Function (Variant)

Indicates whether a C/AL variant contains an InStream variable.

Ok := Variant.ISINSTREAM

Parameters

Variant

Type: Variant

Property Value/Return Value

Type: Boolean

true if the C/AL variant contains an InStream variable; otherwise, false.

See Also

Reference

Variant Data Type


ISINTEGER Function (Variant)

Indicates whether a C/AL variant contains an Integer.

Ok := Variant.ISINTEGER

Parameters

Variant

Type: Variant

Property Value/Return Value

Type: Boolean

true if the C/AL variant contains an Integer; otherwise, false.

See Also

Reference

Variant Data Type


ISOPTION Function (Variant)

Indicates whether a C/AL variant contains an Option variable.

Ok := Variant.ISOPTION

Parameters

Variant

Type: Variant

Property Value/Return Value

Type: Boolean

true if the C/AL variant contains an Option variable; otherwise, false.

See Also

Reference

Variant Data Type


ISOUTSTREAM Function (Variant)

Indicates whether a C/AL variant contains an OutStream variable.

Ok := Variant.ISOUTSTREAM

Parameters

Variant

Type: Variant

Property Value/Return Value

Type: Boolean

true if the C/AL variant contains an OutStream variable; otherwise, false.

See Also

Reference

Variant Data Type


ISRECORD Function (Variant)

Indicates whether a C/AL variant contains a Record variable.

Ok := Variant.ISRECORD

Parameters

Variant

Type: Variant

Property Value/Return Value

Type: Boolean

true if the C/AL variant contains a Record variable; otherwise, false.

Example

The following example determines whether a C/AL variant contains a record variable. The GET function gets customer number 10000 from the Customer table. The record is stored in the MyRecord variable. The MyRecord variable is assigned to the variant variable that is named MyVariant. The ISRECORD function determines whether the variant contains a Record variable and stores the return value in the varResult variable. In this case, the variant contains a Record variable so Yes is returned and displayed in a message box. The ISCODE Function (Variant)determines whether the variant contains a code variable. The return value is No because the variant does not contain a code. This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Subtype
MyRecord | Record | Customer
MyVariant | Variant | Not applicable
varResult | Boolean | Not applicable

Text constant name | ConstValue
Text000 | Does the variant >%1< contain a record variable? %2.
Text001 | Does the variant >%1< contain a code variable? %2.
Copy Code
MyRecord.GET('10000');
MyVariant := MyRecord;
varResult := MyVariant.ISRECORD;
MESSAGE(Text000,MyVariant,varResult);
varResult := MyVariant.ISCODE;
MESSAGE(Text001,MyVariant,varResult);

See Also

Reference

Variant Data Type


ISTEXT Function (Variant)

Indicates whether a C/AL variant contains a Text variable.

Ok := Variant.ISTEXT

Parameters

Variant

Type: Variant

Property Value/Return Value

Type: Boolean

true if the C/AL variant contains a Text variable; otherwise, false.

Example

The following example determines whether a C/AL variant contains a text variable. The code initializes the MyText variable with a text value. The MyText variable is assigned to the variant variable that is named MyVariant. The ISTEXT function determines whether the variant contains a text variable and stores the return value in the varResult variable. In this case, the variant contains a text variable so Yes is returned and displayed in a message box. The ISCODE function determines whether the variant contains a code variable. The return value is No because the variant does not contain a code. This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType | Length
MyText | Text | 50
MyVariant | Variant | Not applicable
varResult | Boolean | Not applicable

Text constant name | Enu value
Text000 | Does the variant >%1< contain a text variable? %2.
Text001 | Does the variant >%1< contain a code variable? %2.
Copy Code
MyText := 'This is some text';
MyVariant :=  MyText;
varResult := MyVariant.ISTEXT;
MESSAGE(Text000,MyVariant,varResult);
varResult := MyVariant.ISCODE;
MESSAGE(Text001,MyVariant,varResult);

See Also

Reference

Variant Data Type


ISTIME Function (Variant)

Indicates whether a C/AL variant contains a Time variable.

Ok := Variant.ISTIME

Parameters

Variant

Type: Variant

Property Value/Return Value

Type: Boolean

true if the C/AL variant contains a Time variable; otherwise, false.

Example

The following example determines whether a C/AL variant contains a time variable. The code initializes the MyTime variable with a Time value. The MyTime variable is assigned to the variant variable that is named MyVariant. The ISTIME function determines whether the variant contains a Time variable and stores the return value in the varResult variable. In this case, the variant contains a Time variable so Yes is returned and displayed in a message box. The ISCODE Function (Variant) determines whether the variant contains a Code variable. The return value is No because the variant does not contain a code. This example requires that you create the following variables and text constants in the C/AL Globals window.

Variable name | DataType
MyTime | Time
MyVariant | Variant
varResult | Boolean

Text constant name | Enu value
Text000 | Does the variant >%1< contain a time variable? %2.
Text001 | Does the variant >%1< contain a code variable? %2.
Copy Code
MyTime := TIME;
MyVariant := MyTime;
varResult := MyVariant.ISTIME;
MESSAGE(Text000,MyVariant,varResult);
varResult := MyVariant.ISCODE;
MESSAGE(Text001,MyVariant,varResult);

See Also

Reference

Variant Data Type


ISTRANSACTIONTYPE Function (Variant)

Indicates whether a C/AL variant contains a Transaction\Type variable.

Ok := Variant.ISTRANSACTIONTYPE

Parameters

Variant

Type: Variant

Property Value/Return Value

Type: Boolean

true if the C/AL variant contains a TransactionType variable; otherwise, false.

See Also

Reference

Variant Data Type


XMLport Data Type

You use XMLports to import and export data in .xml, .csv, or .txt format. XMLports make the process of exchanging data in XML between systems more simple and streamlined. You only need a basic knowledge of XML and you do not have to create XML documents using external products.

XMLports support multiple languages with the CaptionML Property.

XMLports support UTF-8, UTF-16, and ISO-8859-2 formats for XML.

Remarks

For more information about how to design XMLports, see XMLports.

See Also

Reference

BREAK Function (Report, XMLport)
EXPORT Function (XMLport)
FILENAME Function (XMLport)
IMPORT Function (XMLport)
QUIT Function (Report, XMLport)
RUN Function (XMLport)
SETTABLEVIEW Function (Page, Report, XMLport)
SKIP Function (Report, XMLport)


BREAKUNBOUND Function (XMLport)

Exits from a loop on records in an XMLport trigger.

BREAKUNBOUND

Remarks

BREAKUNBOUND causes the current trigger to end. If you are looping over columns in an export where the Unbound property is set to Yes, use BREAKUNBOUND to indicate when the record is fully processed.

For example, your XMLport supports two different file formats. One format contains 5 columns, and the other contains 10 columns. Instead of duplicating the maximum number of columns and writing code that skips any redundant columns, you can set up a single column, make it unbound, and then specify in code when to break to the next element.

See Also

Reference

Unbound Property


EXPORT Function (XMLport)

Creates an XML data stream (XML document) and sends it to a chosen destination.

[Ok :=] XMLPORT.EXPORT(Number, OutStream[, Record])

Parameters

Number

Type: Integer

The ID of the XMLport that you want to run.

Instead of the ID number, you can specify the name of the XMLport by using the following syntax: XMLPORT.EXPORT(XMLPORT::CustomerXMLport, XmlStream). For more information, see Walkthrough: Exporting Data from Tables to XML Documents.

OutStream

Type: ISequentialStream

Where the XMLport object will write the XML data stream.

Record

Type: Record

The record to use in the XMLport. Any filters attached to the record will be used.

This parameter is optional. If this parameter is omitted, all records in the table are exported.

Example

The following example exports data from a table to an XML document. The code uses the CREATE Function (File) to create an XML file named CustXmlFile.xml in a folder named xmlData on the C drive. The CREATEOUTSTREAM Function (File) opens a data stream to output the data from the table to the XML file. The EXPORT Function (XMLport) then exports the data and saves it at the specified location. The CLOSE Function (File) closes the data stream. This example assumes that you have created a folder named xmlData on the C drive. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType | Subtype
CustXmlFile | File | Not applicable
XmlStream | OutStream | Not applicable
varXmlPort | XMLport | 50002 This inserts the name of the XMLport.
Copy Code
CustXmlFile.CREATE('C:\XmlData\Customer.xml');
CustXmlFile.CREATEOUTSTREAM(XmlStream);
XMLPORT.EXPORT(50002, XmlStream);
CustXmlFile.CLOSE;

See Also

Reference

XMLport Data Type

Concepts

Designing XMLports


FILENAME Function (XMLport)

Gets the current value of the FileName Property of an XMLport and sets this property to a new value.

[CurrFileName] := FILENAME([NewFileName])

Parameters

NewFileName

Type: Text

The new value of the FileName property.

Property Value/Return Value

Type: Text

The current value of the FileName property.

See Also

Reference

XMLport Data Type


IMPORT Function (XMLport)

Reads and parses an incoming XML data stream (XML document).

[Ok :=] XMLPORT.IMPORT(Number, InStream[, Record])

Parameters

Number

Type: Integer

The ID of the XMLport that you want to run.

If the XMLport that you specify does not exist, a run-time error occurs.

InStream

Type: ISequentialStream

The source from which the import XMLport object will read the XML data stream.

Record

Type: Record

The record to use in the XMLport. Any filters that are attached to the record will be used.

This parameter is optional. If this parameter is omitted, all records in the table are imported.

For example, you can use this parameter to change the values of properties such as FieldSeparator or TextEncoding, depending on each record that is imported.

Example

The following example imports data from an XML document to a table. The code uses the OPEN Function (File) to open the XML document named NewCustomer.xml from a folder named Import on the C: drive. The CREATEINSTREAM Function (File) creates a data stream to get the data from the XML document to the table. The IMPORT Function (XMLport) then imports, parses the data and adds it as a record to the table by using an XMLport (50004). The CLOSE Function (File) then closes the data stream. This example assumes that you have created a NewCustomer.xml file in a folder named Import on the C drive and you have created an XMLport and given it ID 50004. This example requires that you create the following variables in the C/AL Globals window.

Variable name | DataType
ImportXmlFile | File
XmlINStream | InStream
Copy Code
ImportXmlFile.OPEN('C:\Import\NewCustomer.xml');
ImportXmlFile.CREATEINSTREAM(XmlINStream);
XMLPORT.IMPORT(50004, XmlINStream);
ImportXmlFile.CLOSE;

See Also

Reference

XMLport Data Type

Other Resources

XMLport Walkthroughs


RUN Function (XMLport)

Loads and executes the XMLport that you specify.

XMLport.RUN (Number [, ReqWindow] [, Import] [, Record])

Parameters

XMLport

Type: XMLport

The variable is automatically cleared after this function runs.

Number

Specifies the XMLport to run.

ReqWindow

Specify true to show request page; specify false to run the report and skip the request page.

This parameter overrides the setting of the UseRequestPage Property of the XMLPort. If you do not provide a value for the ReqWindow parameter, then the setting of the UseRequestPage property is used.

Important
Microsoft Dynamics NAV Web client does not support request pages with XMLports. If the XMLPort will appear in the Microsoft Dynamics NAV Web client, you should set the value to false; otherwise, you will get an error at runtime.

Import

Specifies whether the XMLPort imports or exports data. Specify true to run the XMLport and import data; specify false to export data.

This parameter is most relevant when the XMLport does not use a request page and the Direction Property of the XMLport is set to Both. In this instance, you use the parameter to specify the direction of the data. If the XMLport uses a request page, then a direction option appears on the request page that enables the user can choose to import or export data. The Import parameter specifies the default value in the direction on option on the request page.

If the Direction property is set to Import or Export, then you must set this parameter to match the direction that is set by the Direction property; otherwise, you will get an error at runtime.

The default is true.

Record

The record to use in the XMLport. The system will use any filters that are attached to the specified record.

Example

The following example creates a codeunit that runs the XMLport that has ID 50002, runs a request page that lets the user set filters, and exports data from the Customer table. On the request page, you can either open the file and view it or save it as an XML document on your computer. This example assumes that you have created an XMLport and saved it with ID 50002. For more information about how to create an XMLport, see How to: Create XMLports. This example requires that you create the following variable in the C/AL Globals window.

Variable name | DataType | Subtype
varRec | Record | Customer

Copy Code
XMLPORT.RUN (50002, TRUE, FALSE, varRec);

See Also

Tasks

How to: Create XMLports

Reference

XMLport Data Type


Properties

View the table of contents to see the complete list of properties that are available in Microsoft Dynamics NAV 2016.

You can set the value of each property in the Value field. When you leave this field (by pressing Enter or by moving with the arrow keys), the property is updated. Default values are displayed in angle brackets (<>). If a property has a default value, then you can reset the property to the default value by deleting the current value and then moving out of the field.

Note
A bold property value indicates that the property value is not set to its default value.

See Also

Tasks

How to: View or Modify Properties on a Table or Field

Concepts

C/AL Functions
Triggers


Codeunit Properties

This topic lists properties that apply to the Codeunit object, variables, text constants, functions, parameters, and return values.

Codeunit Object Properties

The following properties apply to the Codeunit object.

  • ID Property

  • Name Property

  • Permissions Property

  • SingleInstance Property

  • SubType Property (Codeunit)

  • TableNo Property

  • TestIsolation Property

C/AL Globals Variables Properties

The following properties apply to Variables in the C/AL Globals window of codeunit objects.

  • Dimensions Property

  • ID Property

  • IncludeInDataSet Property

  • OptionString Property

  • WithEvents Property

C/AL Globals Text Constants Properties

The following properties apply to Text Constants in the C/AL Globals window of codeunit objects.

  • ConstValue Property

  • ConstValueML Property

  • ID Property

C/AL Globals Functions Properties

The following properties apply to Functions in the C/AL Globals window of codeunit objects.

  • ID Property

  • Local Property

  • FunctionType Property (Upgrade Codeunits)

  • FunctionType Property (Test Codeunits)

  • HandlerFunctions Property

  • TransactionModel Property

  • TryFunction Property

  • Event Property

  • EventFunction Property

  • EventPublisherObject Property

  • EventType Property

  • GlobalVarAccess Property

  • IncludeSender Property

  • OnValidateEventField Property

C/AL Locals Variables Properties

The following properties apply to Variables in the C/AL Locals window of codeunit objects.

  • Dimensions Property

  • ID Property

  • OptionString Property

  • RunOnClient Property

  • SuppressDispose Property

  • Temporary Property

C/AL Locals Text Constants Properties

The following properties apply to Text Constants in the C/AL Locals window of codeunit objects.

  • ConstValue Property

  • ConstValueML Property

  • ID Property

C/AL Locals Parameters Properties

The following properties apply to Parameters in the C/AL Locals window of codeunit objects.

  • Dimensions Property

  • ID Property

C/AL Locals Return Values Properties

The following properties apply to Return Values in the C/AL Locals window of codeunit objects.

  • Dimensions Property

  • ID Property


MenuSuite Properties

This topic lists properties that apply to the MenuSuite object.

Menu Properties

The following properties apply to menus on a MenuSuite object.

  • Bitmap Property

  • Caption Property

  • CaptionML Property

Menu Item Properties

  1. AccessByPermission Property

  2. Caption Property

  3. CaptionML Property

See Also

Concepts

Properties
MenuSuites


Page Properties

This topic lists properties that apply to the page object, controls, and actions on a page.

Page Object Properties

The following properties apply to a Page object.

  • AutoSplitKey Property

  • Caption Property

  • CaptionML Property

  • CardPageID Property

  • DataCaptionExpr Property

  • DataCaptionFields Property

  • DelayedInsert Property

  • DeleteAllowed Property

  • Description Property

  • Editable Property

  • InsertAllowed Property

  • ID Property

  • InstructionalTextML Property

  • LinksAllowed Property

  • ModifyAllowed Property

  • MultipleNewLines Property

  • Name Property

  • PageType Property

  • Permissions Property

  • PopulateAllFields Property

  • PromotedActionCategoriesML Property

  • RefreshOnActivate

  • SaveValues Property

  • ShowFilter Property

  • SourceTable Property

  • SourceTableTemporary Property

  • SourceTableView Property

Container Control Properties

The following properties apply to Container controls on a page.

  • Caption Property

  • CaptionML Property

  • ContainerType Property

  • Description Property

  • ID Property

  • Name Property

Group Control Properties

The following properties apply to Group controls on a page.

  • Caption Property

  • CaptionML Property

  • Description Property

  • Editable Property

  • Enabled Property

  • FreezeColumnID Property

  • GroupType Property

  • ID Property

  • IndentationColumnName Property

  • IndentationControls Property

  • InstructionalTextML Property

  • Layout Property

  • Name Property

  • ShowAsTree Property

  • Visible Property

Field Control Properties

The following properties apply to Field controls on a page.

  • AccessByPermission Property

  • AssistEdit Property

  • AutoFormatExpr Property

  • AutoFormatType Property

  • BlankNumbers Property

  • BlankZero Property

  • Caption Property

  • CaptionClass Property

  • CaptionML Property

  • CharAllowed Property

  • ClosingDates Property

  • ColumnSpan Property

  • ControlAddin Property

  • DateFormula Property

  • DecimalPlaces Property

  • Description Property

  • DrillDown Property

  • DrillDownPageID Property

  • Editable Property

  • Enabled Property

  • ExtendedDataType Property

  • HideValue Property

  • ID Property

  • Importance Property

  • Lookup Property

  • LookupPageID Property

  • MaxValue Property

  • MinValue Property

  • MultiLine Property

  • Name Property

  • NotBlank Property

  • Numeric Property

  • OptionCaption Property

  • OptionCaptionML Property

  • QuickEntry Property

  • RowSpan Property

  • ShowCaption Property

  • ShowMandatory Property

  • SourceExpr Property

  • Style Property

  • StyleExpr Property

  • TableRelation Property

  • Title Property

  • ToolTip Property

  • ToolTipML Property

  • ValuesAllowed Property

  • Visible Property

  • Width Property

Part Control Properties

The following properties apply to Part controls on a page.

  • AccessByPermission Property

  • Caption Property

  • CaptionML Property

  • ChartPartID Property

  • Description Property

  • Editable Property

  • Enabled Property

  • ID Property

  • Name Property

  • PagePartID Property

  • PartType Property

  • ProviderID Property

  • ShowFilter Property

  • SubPageLink Property

  • SubPageView Property

  • SystemPartID Property

  • ToolTip Property

  • ToolTipML Property

  • UpdatePropagation Property

  • Visible Property

ActionContainer Properties

The following properties apply to ActionContainer on a page.

  • Caption Property

  • CaptionML Property

  • Description Property

  • ID Property

  • Name Property

ActionGroup Properties

The following properties apply to ActionGroups.

  • Caption Property

  • CaptionML Property

  • Description Property

  • Enabled Property

  • ID Property

  • Image Property

  • Name Property

  • Visible Property

Action Properties

The following properties apply to Actions.

  • AccessByPermission Property

  • Caption Property

  • CaptionML Property

  • Description Property

  • Ellipsis Property

  • Enabled Property

  • ID Property

  • Image Property

  • InFooterBar Property

  • Name Property

  • Promoted Property

  • PromotedCategory Property

  • PromotedIsBig Property

  • RunPageLink Property

  • RunPageMode Property

  • RunPageOnRec Property

  • RunPageView Property

  • RunObject Property

  • Scope Property

  • ShortCutKey Property

  • ToolTip Property

  • ToolTipML Property

  • Visible Property

Separator Properties

The following properties apply to Separators.

  • Caption Property

  • CaptionML Property

  • ID Property

  • IsHeader

See Also

Concepts

Properties


Query Properties

This topic lists properties that apply to the query object.

Query Object Properties

The following properties apply to the query object as a whole.

  • Caption Property

  • CaptionML Property

  • Description Property

  • ID Property

  • Name Property

  • OrderBy Property

  • Permissions Property

  • TopNumberOfRows Property

  • ReadState Property

Query Data Item Properties

The following properties apply to the DataItem control of a query.

  • DataItemTable Property

  • DataItemLink Property (Query)

  • DataItemLinkType Property

  • Description Property

  • DataItemTableFilter Property

  • ID Property

  • Indentation Property (Query)

  • Name Property

Query Column Properties

The following properties apply to the Column control of a query.

  • Caption Property

  • CaptionML Property

  • ColumnFilter Property

  • DataSource Property

  • Description Property

  • ID Property

  • Indentation Property (Query)

  • Method Property

  • MethodType Property

  • Name Property

  • ReverseSign Property

Query Filter Control Properties

The following properties apply to the Filter control of a query.

  • Caption Property

  • CaptionML Property

  • ColumnFilter Property

  • DataSource Property

  • Description Property

  • ID Property

  • Indentation Property (Query)

  • Name Property


Report Properties

This topic lists properties of the report object.

Report Object Properties

The following properties apply to the report object.

  • Caption Property

  • CaptionML Property

  • Description Property

  • EnableExternalAssemblies Property

  • EnableExternalImages Property

  • EnableHyperlinks Property

  • ID Property

  • Name Property

  • PaperSourceDefaultPage Property

  • PaperSourceFirstPage Property

  • PaperSourceLastPage Property

  • Permissions Property

  • ProcessingOnly Property

  • ShowPrintStatus Property

  • TransactionType Property

  • UseRequestPage Property

  • UseSystemPrinter Property

  • PDFFontEmbedding Property

DataItem Properties

The following properties apply to DataItem controls of a report object.

  • CalcFields Property

  • DataItemLink Property (Reports)

  • DataItemLinkReference Property

  • DataItemTable Property

  • DataItemTableView Property

  • ID Property

  • Indentation Property (Reports)

  • MaxIteration Property

  • Name Property

  • PrintOnlyIfDetail Property

  • ReqFilterFields Property

  • ReqFilterHeading Property

  • ReqFilterHeadingML Property

  • Temporary Property (Reports)

Column Properties

The following properties apply to Column controls of a report object.

  • AutoCalcField Property

  • AutoFormatExpr Property

  • AutoFormatType Property

  • DecimalPlaces Property

  • Description Property

  • ID Property

  • IncludeCaption Property

  • Indentation Property (Reports)

  • Name Property

  • OptionCaption Property

  • OptionCaptionML Property

  • OptionString Property

  • SourceExpr Property

Report Label Properties

The following properties apply to Report Labels of a report object.

  • Caption Property

  • CaptionML Property

  • Description Property

  • ID Property

  • Name Property

See Also

Concepts

Properties


Table Properties

The following topic lists properties that apply to the table object.

Table Object Properties

The following properties apply to a Table object.

  • Caption Property

  • CaptionML Property

  • DataCaptionFields Property

  • DataPerCompany Property

  • Description Property

  • DrillDownPageID Property

  • ID Property

  • LinkedObject Property

  • LookupPageID Property

  • Name Property

  • PasteIsValid Property

  • Permissions Property

  • TableType Property

BLOB Properties

The following properties apply to the BLOB field of a table object.

  • AccessByPermission Property

  • Caption Property

  • CaptionML Property

  • Compressed Property

  • Data Type Property

  • Description Property

  • Enabled Property

  • Field No. Property

  • Name Property

  • Owner Property

  • SubType Property (BLOB)

BigInteger Properties

The following properties apply to the BigInteger field of a table object.

  • AccessByPermission Property

  • AltSearchField Property

  • AutoFormatExpr Property

  • AutoFormatType Property

  • AutoIncrement Property

  • BlankNumbers Property

  • BlankZero Property

  • Caption Property

  • CaptionClass Property

  • CaptionML Property

  • Data Type Property

  • Description Property

  • Editable Property

  • Enabled Property

  • ExtendedDataType Property

  • Field No. Property

  • FieldClass Property

  • InitValue Property

  • MaxValue Property

  • MinValue Property

  • Name Property

  • NotBlank Property

  • SignDisplacement Property

  • TableRelation Property

  • TestTableRelation Property

  • ValidateTableRelation Property

  • ValuesAllowed Property

  • Width Property

Boolean Properties

The following properties apply to the Boolean field of a table object.

  • AccessByPermission Property

  • AltSearchField Property

  • AutoFormatExpr Property

  • AutoFormatType Property

  • BlankNumbers Property

  • BlankZero Property

  • Caption Property

  • CaptionClass Property

  • CaptionML Property

  • Data Type Property

  • Description Property

  • Editable Property

  • Enabled Property

  • ExtendedDataType Property

  • Field No. Property

  • FieldClass Property

  • InitValue Property

  • MaxValue Property

  • MinValue Property

  • Name Property

  • NotBlank Property

  • SignDisplacement Property

  • TableRelation Property

  • TestTableRelation Property

  • ValidateTableRelation Property

  • ValuesAllowed Property

Code Properties

The following properties apply to the Code field of a table object.

  • AccessByPermission Property

  • AltSearchField Property

  • AutoFormatExpr Property

  • AutoFormatType Property

  • Caption Property

  • CaptionClass Property

  • CaptionML Property

  • CharAllowed Property

  • Data Type Property

  • DataLength Property

  • DateFormula Property

  • Description Property

  • Editable Property

  • Enabled Property

  • ExtendedDataType Property

  • Field No. Property

  • FieldClass Property

  • InitValue Property

  • Name Property

  • NotBlank Property

  • Numeric Property

  • SQL Data Type Property

  • TableRelation Property

  • TestTableRelation Property

  • ValidateTableRelation Property

  • ValuesAllowed Property

  • Width Property

Date Properties

The following properties apply to the Date field of a table object.

  • AccessByPermission Property

  • AltSearchField Property

  • AutoFormatExpr Property

  • AutoFormatType Property

  • BlankNumbers Property

  • Caption Property

  • CaptionClass Property

  • CaptionML Property

  • ClosingDates Property

  • Data Type Property

  • Description Property

  • Editable Property

  • Enabled Property

  • ExtendedDataType Property

  • Field No. Property

  • FieldClass Property

  • InitValue Property

  • MaxValue Property

  • MinValue Property

  • Name Property

  • NotBlank Property

  • SignDisplacement Property

  • TableRelation Property

  • TestTableRelation Property

  • ValidateTableRelation Property

  • ValuesAllowed Property

DateFormula Properties

The following properties apply to the DateFormula field of a table object.

  • AccessByPermission Property

  • AltSearchField Property

  • AutoFormatExpr Property

  • AutoFormatType Property

  • Caption Property

  • CaptionClass Property

  • CaptionML Property

  • Data Type Property

  • Description Property

  • Editable Property

  • Enabled Property

  • ExtendedDataType Property

  • Field No. Property

  • FieldClass Property

  • InitValue Property

  • Name Property

  • NotBlank Property

  • TableRelation Property

  • TestTableRelation Property

  • ValidateTableRelation Property

  • ValuesAllowed Property

DateTime Properties

The following properties apply to the DataTime field of a table object.

  • AccessByPermission Property

  • AltSearchField Property

  • AutoFormatExpr Property

  • AutoFormatType Property

  • BlankNumbers Property

  • Caption Property

  • CaptionClass Property

  • CaptionML Property

  • Data Type Property

  • Description Property

  • Editable Property

  • Enabled Property

  • ExtendedDataType Property

  • Field No. Property

  • FieldClass Property

  • InitValue Property

  • MaxValue Property

  • MinValue Property

  • Name Property

  • NotBlank Property

  • SignDisplacement Property

  • TableRelation Property

  • TestTableRelation Property

  • ValidateTableRelation Property

  • ValuesAllowed Property

Decimal Properties

The following properties apply to the Decimal field of a table object.

  • AccessByPermission Property

  • AltSearchField Property

  • AutoFormatExpr Property

  • AutoFormatType Property

  • BlankNumbers Property

  • BlankZero Property

  • Caption Property

  • CaptionClass Property

  • CaptionML Property

  • Data Type Property

  • Description Property

  • Editable Property

  • Enabled Property

  • ExtendedDataType Property

  • Field No. Property

  • FieldClass Property

  • InitValue Property

  • MaxValue Property

  • MinValue Property

  • Name Property

  • NotBlank Property

  • SignDisplacement Property

  • TableRelation Property

  • TestTableRelation Property

  • ValidateTableRelation Property

  • ValuesAllowed Property

  • Width Property

Duration Properties

The following properties apply to the Duration field of a table object.

  • AccessByPermission Property

  • AltSearchField Property

  • AutoFormatExpr Property

  • AutoFormatType Property

  • BlankNumbers Property

  • BlankZero Property

  • Caption Property

  • CaptionClass Property

  • CaptionML Property

  • Data Type Property

  • Description Property

  • Editable Property

  • Enabled Property

  • ExtendedDataType Property

  • Field No. Property

  • FieldClass Property

  • InitValue Property

  • MaxValue Property

  • MinValue Property

  • Name Property

  • NotBlank Property

  • SignDisplacement Property

  • Standard Day/Time Unit Property

  • TableRelation Property

  • TestTableRelation Property

  • ValidateTableRelation Property

  • ValuesAllowed Property

  • Width Property

GUID Properties

The following properties apply to the GUID field of a table object.

  • AccessByPermission Property

  • AltSearchField Property

  • AutoFormatExpr Property

  • AutoFormatType Property

  • Caption Property

  • CaptionClass Property

  • CaptionML Property

  • Data Type Property

  • Description Property

  • Editable Property

  • Enabled Property

  • ExtendedDataType Property

  • Field No. Property

  • FieldClass Property

  • InitValue Property

  • Name Property

  • NotBlank Property

  • TableRelation Property

  • TestTableRelation Property

  • ValidateTableRelation Property

  • ValuesAllowed Property

Integer Properties

The following properties apply to the Integer field of a table object.

  • AccessByPermission Property

  • AltSearchField Property

  • AutoFormatExpr Property

  • AutoFormatType Property

  • BlankNumbers Property

  • BlankZero Property

  • Caption Property

  • CaptionClass Property

  • CaptionML Property

  • Data Type Property

  • Description Property

  • Editable Property

  • Enabled Property

  • ExtendedDataType Property

  • Field No. Property

  • FieldClass Property

  • InitValue Property

  • MaxValue Property

  • MinValue Property

  • Name Property

  • NotBlank Property

  • SignDisplacement Property

  • TableRelation Property

  • TestTableRelation Property

  • ValidateTableRelation Property

  • ValuesAllowed Property

  • Width Property

OemCode Properties

The following properties apply to the OemCode field of a table object.

  • AccessByPermission Property

  • AltSearchField Property

  • AutoFormatExpr Property

  • AutoFormatType Property

  • Caption Property

  • CaptionClass Property

  • CaptionML Property

  • CharAllowed Property

  • Data Type Property

  • DataLength Property

  • DateFormula Property

  • Description Property

  • Editable Property

  • Enabled Property

  • ExtendedDataType Property

  • Field No. Property

  • FieldClass Property

  • InitValue Property

  • Name Property

  • NotBlank Property

  • Numeric Property

  • TableRelation Property

  • TestTableRelation Property

  • ValidateTableRelation Property

  • ValuesAllowed Property

  • SQL Data Type Property

  • Width Property

OemText Properties

The following properties apply to the OemText field of a table object.

  • AccessByPermission Property

  • AltSearchField Property

  • AutoFormatExpr Property

  • AutoFormatType Property

  • Caption Property

  • CaptionClass Property

  • CaptionML Property

  • CharAllowed Property

  • Data Type Property

  • DataLength Property

  • DateFormula Property

  • Description Property

  • Editable Property

  • Enabled Property

  • ExtendedDataType Property

  • Field No. Property

  • FieldClass Property

  • InitValue Property

  • Name Property

  • NotBlank Property

  • Numeric Property

  • TableRelation Property

  • TestTableRelation Property

  • Title Property

  • ValidateTableRelation Property

  • ValuesAllowed Property

  • Width Property

Option Properties

The following properties apply to the Option field of a table object.

  • AccessByPermission Property

  • AltSearchField Property

  • AutoFormatExpr Property

  • AutoFormatType Property

  • BlankNumbers Property

  • BlankZero Property

  • Caption Property

  • CaptionClass Property

  • CaptionML Property

  • Data Type Property

  • Description Property

  • Editable Property

  • Enabled Property

  • ExtendedDataType Property

  • Field No. Property

  • FieldClass Property

  • InitValue Property

  • MaxValue Property

  • MinValue Property

  • Name Property

  • NotBlank Property

  • OptionCaption Property

  • OptionCaptionML Property

  • OptionString Property

  • SignDisplacement Property

  • TableRelation Property

  • TestTableRelation Property

  • ValidateTableRelation Property

  • ValuesAllowed Property

RecordID Properties

The following properties apply to the RecordID field of a table object.

  • AccessByPermission Property

  • AltSearchField Property

  • AutoFormatExpr Property

  • AutoFormatType Property

  • Caption Property

  • CaptionClass Property

  • CaptionML Property

  • Data Type Property

  • Description Property

  • Editable Property

  • Enabled Property

  • ExtendedDataType Property

  • Field No. Property

  • FieldClass Property

  • InitValue Property

  • Name Property

  • NotBlank Property

  • TableRelation Property

  • TestTableRelation Property

  • ValidateTableRelation Property

  • ValuesAllowed Property

TableFilter Properties

The following properties apply to the TableFilter field of a table object.

  • AccessByPermission Property

  • Caption Property

  • CaptionML Property

  • Data Type Property

  • Description Property

  • Enabled Property

  • Field No. Property

  • Name Property

  • TableIDExpr Property

Text Properties

The following properties apply to the Text field of a table object.

  • AccessByPermission Property

  • AltSearchField Property

  • AutoFormatExpr Property

  • AutoFormatType Property

  • Caption Property

  • CaptionClass Property

  • CaptionML Property

  • CharAllowed Property

  • Data Type Property

  • DataLength Property

  • DateFormula Property

  • Description Property

  • Editable Property

  • Enabled Property

  • ExtendedDataType Property

  • Field No. Property

  • FieldClass Property

  • InitValue Property

  • Name Property

  • NotBlank Property

  • Numeric Property

  • TableRelation Property

  • TestTableRelation Property

  • ValidateTableRelation Property

  • ValidateTableRelation Property

  • ValuesAllowed Property

  • Width Property

Time Properties

The following properties apply to the Time field of a table object.

  • AccessByPermission Property

  • AltSearchField Property

  • AutoFormatExpr Property

  • AutoFormatType Property

  • BlankNumbers Property

  • Caption Property

  • CaptionClass Property

  • CaptionML Property

  • Data Type Property

  • Description Property

  • Editable Property

  • Enabled Property

  • ExtendedDataType Property

  • Field No. Property

  • FieldClass Property

  • InitValue Property

  • MaxValue Property

  • MinValue Property

  • Name Property

  • NotBlank Property

  • SignDisplacement Property

  • TableRelation Property

  • TestTableRelation Property

  • ValidateTableRelation Property

  • ValuesAllowed Property

See Also

Concepts

Properties


XMLport Properties

This topic lists properties of the XMLport object, element, and attribute.

XMLport Object Properties

The following properties apply to the XMLport object.

  • Caption Property

  • CaptionML Property

  • CurrentPath Property

  • DefaultFieldsValidation Property

  • DefaultNamespace Property

  • Direction Property

  • Encoding Property

  • FileName Property

  • Format Property

  • Format/Evaluate Property

  • ID Property

  • InlineSchema Property

  • Name Property

  • NamespacePrefix Property

  • Namespaces Property

  • Permissions Property

  • PreserveWhiteSpace Property

  • TextEncoding Property (XMLports)

  • TransactionType Property

  • UseDefaultNamespace Property

  • UseLax Property

  • UseRequestPage Property

  • XMLVersionNo Property

Text Element Properties

The following properties apply to Text elements of an XMLport object.

  • Indentation Property (XMLports)

  • MaxOccurs Property

  • MinOccurs Property

  • NodeName Property

  • NodeType Property

  • SourceType Property

  • TextType Property

  • Unbound Property

  • VariableName Properties

  • Width Property (XMLport)

Table Element Properties

The following properties apply to Table elements of an XMLport object.

  • AutoReplace Property

  • AutoSave Property

  • AutoUpdate Property

  • CalcFields Property

  • Indentation Property (XMLports)

  • LinkFields Property

  • LinkTable Property

  • LinkTableForceInsert Property

  • MaxOccurs Property

  • MinOccurs Property

  • NodeName Property

  • NodeType Property

  • ReqFilterFields Property

  • ReqFilterHeading Property

  • ReqFilterHeadingML Property

  • SourceTable Property (XMLports)

  • SourceTableView Property (XMLports)

  • SourceType Property

  • Temporary Property (XMLports)

  • VariableName Properties

  • Width Property (XMLport)

Field Element Properties

The following properties apply to Field elements of an XMLport Object.

  • AutoCalcField Property

  • FieldValidate Property

  • Indentation Property (XMLports)

  • MaxOccurs Property

  • MinOccurs Property

  • NodeName Property

  • NodeType Property

  • SourceField Property

  • SourceType Property

  • Unbound Property

  • Width Property (XMLport)

Text Attribute Properties

The following properties apply to Text attributes of an XMLport object.

  • Indentation Property (XMLports)

  • NodeName Property

  • NodeType Property

  • Occurrence Property

  • SourceType Property

  • TextType Property

  • VariableName Properties

  • Width Property (XMLport)

Table Attribute Properties

The following properties apply to Table attributes of an XMLport object.

  • AutoReplace Property

  • AutoSave Property

  • AutoUpdate Property

  • CalcFields Property

  • Indentation Property (XMLports)

  • LinkFields Property

  • LinkTable Property

  • LinkTableForceInsert Property

  • NodeName Property

  • NodeType Property

  • Occurrence Property

  • ReqFilterFields Property

  • ReqFilterHeading Property

  • ReqFilterHeadingML Property

  • SourceTable Property (XMLports)

  • SourceTableView Property (XMLports)

  • SourceType Property

  • Temporary Property (XMLports)

  • VariableName Properties

  • Width Property (XMLport)

Field Attribute Properties

The following properties apply to Field attributes of an XMLport object.

  • AutoCalcField Property

  • FieldValidate Property

  • Indentation Property (XMLports)

  • NodeName Property

  • NodeType Property

  • Occurrence Property

  • SourceField Property

  • SourceType Property

  • Width Property (XMLport)

See Also

Concepts

Properties


Page Properties Not Supported by Microsoft Dynamics NAV Web Client

Most page properties that are supported in the Microsoft Dynamics NAV Windows client are also supported in the Microsoft Dynamics NAV Web client. There are some properties that are not supported by Microsoft Dynamics NAV Web client and other properties that are either partially supported or behave differently in the Microsoft Dynamics NAV Windows client.

Unsupported Properties

This section lists the properties that are not supported by the Microsoft Dynamics NAV Web client. When a page that contains an unsupported property is displayed in a browser, the property is ignored. You do not receive an error but the property does not affect the page.

  • ChartPartID Property

  • ColumnSpan Property

  • RowSpan Property

  • RefreshOnActivate Property

  • ShowAsTree Property

  • SystemPartID Property

Partially Supported Properties

This section lists the properties that either do not have all the capabilities in the Microsoft Dynamics NAV Web client as they do in Microsoft Dynamics NAV Windows client or they behave differently than in the Microsoft Dynamics NAV Windows client.

  • AssistEdit Property

  • DrillDown Property

  • DrillDownPageID Property

  • GroupType Property

  • Importance Property

  • IndentationControls Property

  • PageType Property

  • PartType Property

See Also

Concepts

Feature Limitations of the Microsoft Dynamics NAV Web Client
Properties
Pages
Microsoft Dynamics NAV Web Client


AccessByPermission Property

Sets a value for a table field or UI element that determines the permission mask for an object that a user must have to see and access the related page fields or UI element in the client. The UI element will be removed at runtime if the user does not have permissions to a certain object as specified in the Access By Permission window. For more information, see How to: Remove UI Elements Using the AccessByPermission Property.

All types of UI elements will be removed if they relate to an object to which the user does not have the required permissions:

  • Fields on pages, including FactBoxes

  • Actions on pages, including toolbars and navigation panes

  • Page parts, such as Lines FastTabs

Note
To use this property, the UI Elements Removal field in the Microsoft Dynamics NAV Server Administration tool must be set to LicenseFile or LicenseFileAndUserPermissions. For more information, see How to: Specify When UI Elements Are Removed.

Applies To

  • Fields in tables (affecting all related fields on pages)

  • Fields on pages

  • Actions on pages

  • MenuSuite items

  • Page parts, such as a Lines FastTab

Property Value

When you choose the AssistEdit button, the Access By Permission window opens. Fill the fields as described in the following table.

Field | Description
Object Type | Specify the type of object to which permission is required to display the UI element.
Object ID | Specify the object to which permission is required to display the UI element.
Read | Specify if Read permission is required to display the UI element.
or Insert | Specify if Insert permission is required to display the UI element.
or Modify | Specify if Modify permission is required to display the UI element.
or Delete | Specify if Delete permission is required to display the UI element.
or Execute | Specify if Execute permission is required to display the UI element.
Note
If multiple permissions are selected, then one or the other applies.

Example: Remove the Unit Price field if the user does not have permission to the Sales Price table

  1. Open table 27, Item Card, with the Table Designer.

  2. View the properties of field 18, Unit Price.

  3. For the AccessByPermission property, choose the AssistEdit button in the Value field.

  4. In the Access By Permission window, fill the fields as described in the following table.

    Field Description

    Object Type

    TableData

    Object ID

    Sales Price

    Read

    Select

    Insert

    Select

    Modify

    Leave blank

    Delete

    Leave blank

    Execute

    Leave blank

  5. Close the Access By Permission window and save the changes on table 27.

All instances of the Unit Price field on pages are now removed if the user does have Read or Insert permission to the Sales Price table.

Important
If you defined the property for a table field, then all instances of the field on pages are removed. To override the property on an individual page field, delete the permission value after the = sign in the Value field. Do NOT delete the whole string as that will be replicated on the property of the table field.

Note
To use the LicenseFileAndUserPermissions option in the UI Elements Removal field, you must assign the special FOUNDATION permission set to the user along with the relevant application permission sets that define which application objects the user will access. Unlike the BASIC permission set, the FOUNDATION permission set only grants access to application setup and system tables and requires that other assigned permission sets define which specific application objects can be accessed. For more information, see Special Permission Sets.

Not all of the 167 default permission sets that are provided with Microsoft Dynamics NAV are ready to support the FOUNDATION permission set to remove UI elements according to user permissions. You must therefore edit the relevant permission sets as explained in the following procedures.

To experience how UI elements are removed for a user performing the task to create and edit a new customer, you can create a sample user interface based on default permission sets provided with Microsoft Dynamics NAV. For more information, see How to: Try Out the UI Elements Removal Feature Based on Demonstration Permission Sets.

See Also

Tasks

How to: Remove UI Elements Using the AccessByPermission Property
How to: Specify When UI Elements Are Removed
How to: Try Out the UI Elements Removal Feature Based on Demonstration Permission Sets
How to: Define Permissions for Users

Reference

Access By Permission

Concepts

Removing Elements from the User Interface According to Permissions
Properties

Other Resources

Managing Permissions and Permission Sets


AltSearchField Property

Sets the Name Property of an alternative field used to perform lookups on the current field.

Applies To

Fields

Remarks

This property makes it easier for users to use search and lookup in a table. For example, if a table's primary key is a numeric identifier that is also used as a foreign key in another table, users must know this identifier to perform a lookup into this table. Using this property, you can link a different search field that is easy to remember (for example, a name or address field) to the numeric primary key field.

See Also

Concepts

Properties


AssistEdit Property

Sets assist-edit capabilities for a text box.

Applies To

  • Page Fields

Property Value

Yes if assist-edit capabilities and an AssistEdit button are provided; otherwise, No. The default value is No.

Remarks

You can add C/AL code in the OnAssistEdit Trigger to change the default assist-edit behavior.

In the Microsoft Dynamics NAV Web client, the AssistEdit button does not appear on the field when the page is in the view mode or if the field has the data type of Option.

See Also

Reference

Lookup Property
DrillDown Property


AutoCalcField Property

Sets whether FlowFields should be automatically calculated.

Applies To

  • Report columns

  • XMLports

Property Value

Yes if the FlowField is automatically calculated; otherwise, No. The default is Yes.

See Also

Concepts

FlowFields


AutoFormatExpr Property

Sets a C/AL expression that specifies how to format data.

Applies To

Fields (or columns) of the decimal data type in the following objects:

  • Tables

  • Pages

  • Reports

Remarks

The C/AL expression is evaluated when the expression performs updates. Together with the AutoFormatType Property, this property determines how data is formatted. These two properties are only used to format decimal data types, such as amounts that can be stated in a foreign currency or ratios.

For more information, see Formatting the Data in a Field.

See Also

Reference

AutoFormatType Property
DecimalPlaces Property


AutoFormatType Property

Sets a value that determines how data is formatted, together with the C/AL expression in the AutoFormatExpr Property.

Applies To

Fields of the decimal data type in the following objects:

  • Tables

  • Pages

  • Reports

Remarks

These two properties are only used to format decimal data types, such as amounts that can be stated in a foreign currency or ratios.

For more information, see Formatting the Data in a Field.

See Also

Reference

AutoFormatExpr Property


AutoIncrement Property

Sets whether the field value should be automatically incremented.

Applies To

Fields of Integer Data Type and BigInteger Data Type

Property Value

Yes if the field value is automatically incremented; otherwise, No. The default value is Yes.

Note
If you want to manually assign a value to a field that has the AutoIncrement property set to Yes, you must be member of the SQL Server db_owner database permission set.

Remarks

A table can only contain one auto-increment field. The numbers assigned to this field will not always be consecutive for the following reasons:

  • If you delete some records from a table, the numbers used for these records are not reused.

  • If several transactions are performed at the same time, they will each be assigned a different number. However, if one of these transactions is rolled back, the number that it was assigned is not reused.

If you add an auto-increment field to an existing table, the field automatically generates consecutive values and inserts them into the table. If you enable the AutoIncrement property for a field that already contains data, there must be no zero values in the field.

The AutoIncrement property is designed to always assign numbers automatically. If you want to insert a record, be sure that the value in this field is blank before you insert the record.

The AutoIncrement property does not work with Microsoft Dynamics NAV temporary tables.

See Also

Concepts

Properties


AutoReplace Property

Sets whether imported records automatically replace existing records with the same primary key.

Applies To

Data items in XMLports.

Property Value

Yes if the records are replaced; otherwise, No. The default value is No.

Remarks

If a record with the same primary key is found in the database, then the record is initialized with the initial value for each field and then populated with the values in the imported record. Any field in the record that is not present in the imported record retains its initial value. For more information about initial values, see InitValue Property.

Warning
If this property is set to Yes, then the AutoUpdate Property has no effect.

See Also

Reference

AutoUpdate Property
AutoSave Property


AutoSave Property

Sets whether imported records are automatically written to the table.

Applies To

Data items in XMLports

Property Value

Yes if the record is written to the table automatically; otherwise, No. The default value is Yes.

Remarks

This property applies to new records that are inserted into the table and existing records that are modified.

If AutoSave is set to No, then an imported record is not automatically written to the appropriate table. To insert or modify records manually, add code to the OnBeforeInsertRecord Trigger and the OnBeforeModifyRecord Trigger. For example, set the AutoSave property to No, create a new function that evaluates the records, does some calculations, or retrieves additional data, and then call your new function from the OnBeforeInsertRecord and OnBeforeModifyRecord triggers. Use the OnAfterInitRecord trigger if you must evaluate the records before inserting or modifying them, or if you want to calculate or retrieve additional data before inserting or modifying the record.

If a record already exists and AutoSave is set to Yes, then the values of the AutoReplace Property and the AutoUpdate Property determine whether the imported record overwrites or updates the existing record. If the record already exists and the values of the AutoReplace property and the AutoUpdate property are both No, then an error occurs.

See Also

Reference

AutoReplace Property
AutoUpdate Property


AutoSplitKey Property

Sets whether a key is automatically created for a new record placed between the current record and the previous record.

Applies To

  • Pages

Property Value

Yes if the key is automatically created for the new record; otherwise, No. The default value is No.

Remarks

To set this property to a value of Yes, the following conditions must be met:

  • The current key must be the primary key.

  • The last field in the primary field must be an Integer Data Type, BigInteger Data Type, GUID Data Type, or Decimal Data Type field.

See Also

Concepts

Properties


AutoUpdate Property

Sets whether a record in the database with the same primary key as the record in the imported XMLport is updated with values from the imported record.

Applies To

Data items in XMLports.

Property Value

Yes if the records are updated; otherwise, No. The default value is No.

Remarks

When AutoUpdate is set to Yes, if a record exists in the database with the same primary key as a record in the imported XMLport, then the record in the database is updated with the values in the record from the XMLport. Fields that are not defined in the record from the XMLport remain the same in the record in the database.

Set AutoUpdate to Yes when you import a file with partial information. For example, you can use this property if you create new prices for an item list in an external file where this file only contains item numbers and prices. In this case, you would want to update the price field, while retaining the information in the other fields.

Warning
If this property is set to Yes, then the AutoReplace Property has no effect.

See Also

Reference

AutoReplace Property
AutoSave Property


BackupKey Property

This property is used by the backup/restore system. Under normal circumstances, you do not need to set this property.

Applies To

Keys

Property Value

Yes if the enabled property of secondary keys will be restored during restore; otherwise, No. The default value is No.

Remarks

During backup, secondary keys where the Enabled Property is set to a value of Yes are marked with a BackupKey value of Yes, and the secondary indexes are not stored in the backup. When the backup is restored, the BackupKey value is checked to see whether it reenables secondary keys where BackupKey = Yes, and the indexes are recreated.

You will normally only see the BackupKey set to No (the default), as it is only set to Yes during backup. If a backup restore is suspended during key creation (to be resumed at a later time), you can see and set the BackupKey property.

See Also

Reference

Enabled Property


Bitmap Property

Sets a bitmap icon to be shown with a department on the Department page of the RoleTailored client.

Applies To

  • MenuSuite buttons

Remarks

You can choose among eleven predefined bitmap icons. To specify a file, you enter an ID number from 0 to 15.

See Also

Tasks

How to: Change Department Icons in the Windows Client
How to: Modify a Department Menu in a MenuSuite

Reference

Menu Properties
Create Menu


BitmapList Property

Sets a list of bitmaps from which the correct bitmap to display is selected.

Applies To

Picture boxes

Remarks

Specify the bitmap list using a comma-separated list of file names, such as c:\pictures\<example1>.bmp,c:\pictures\<example2>.bmp. There are 44 predefined bitmaps. They can be chosen by entering a number from 1 to 44. You can mix external bitmaps that are stored in files, with the internal bitmaps in this list.

The SourceExpr Property of the control is used to choose which bitmap to display. The first bitmap in the list is number 1, the second bitmap is number 2, and so on.

The bitmaps are imported. If you change one or more of the bitmaps, you have to re-import them to update the versions that are used. You can do this by reentering this property value.

The size limit for all the user-defined bitmaps included in the list is 32 KB.

See Also

Reference

Bitmap Property
BitmapPos Property


BitmapPos Property

Sets the position of a bitmap.

Applies To

  • Check boxes

  • Command buttons

  • Menu buttons

  • Option buttons

Property Value

Value | Description
None | None (the bitmap is not displayed)
Left (default for command buttons, check boxes, option buttons) | On the left
Right (default for menu buttons) | On the right
Top | At the top
Bottom | At the bottom
Center | In the center

See Also

Reference

Bitmap Property
BitmapList Property


BlankNumbers Property

Indicates whether the system will clear a range of numbers as it formats them.

Applies To

  • Page Fields

Property Value

Value | Description
DontBlank (default) | Not clear any numbers
BlankNeg | Clear negative numbers
BlankNegAndZero | Clear negative numbers and zero
BlankZero | Clear numbers equal to zero
BlankZeroAndPos | Clear positive numbers and zero
BlankPos | Clear positive numbers

See Also

Reference

BlankZero Property


BlankZero Property

Indicates whether the system displays zeros (0) and No.

Applies To

  • Page Fields

Property Value

Yes if zeros and No are displayed; otherwise, No. The default is No.

See Also

Reference

BlankNumbers Property


CalcFields Property

Sets a list of FlowFields to automatically calculate.

Applies To

  • Reports

  • XMLports

Remarks

Use the AssistEdit button to select the FlowFields.

See Also

Concepts

FlowFields
Properties


CalcFormula Property

Sets the calculation for FlowFields.

Applies To

Table Fields

Remarks

You can choose from several methods of calculations including sum (total), average, maximum value, minimum value, record count, lookup, and whether a record exists. Use the AssistEdit button to set up the calculation formula. The AssistEdit window lets you reverse the calculation, choose a table and fields, and create filters.

See Also

Concepts

FlowFields


Caption Property

Sets the text string that displays with the object, control, or other element in user interface for the current language.

Applies To

  • Codeunit objects

  • XMLport objects

  • Pages, including general page properties, Container, Group, Part, and Field controls.

  • Query objects and query columns

  • Reports

  • Tables and table fields

  • XMLport objects

Remarks

A caption is the text used to show the identity of a control (for example, in the caption bar of a page or a label for another control).

The Caption property value is taken from the value of the CaptionML Property for the current user language if the CaptionML Property is set. If you enter a value for the Caption Property, then the value is included in CaptionML property for the current language. For example, if the current system language is Danish, then a value of DAN =<value> is placed in the CaptionML field.

Note
For query columns, when you run the query from Object Designer, the About This Query window that opens in the RoleTailored client displays the value for the Name Property of the query column, not the Caption property or CaptionML Property.

See Also

Reference

ShowCaption Property

Concepts

Multilanguage Development


CaptionClass Property

Controls the caption that is used in the label of a field in a database table or in the label of a control on a page.

Applies To

  • Table Fields

  • Page Fields

Remarks

The data type of the C/AL expression must be either Text (maximum length 80) or Code.

Because this property lets you enter an expression, Microsoft Dynamics NAV must be able to differentiate between a literal string like 'DIM1' and a variable or function called DIM1. Every text string that you enter must be enclosed in ' ' or it will be interpreted as a variable or function. You must enter a value that results in a string. For example, if you want to enter 1 + 5, you must either enter '1+ 5', or FORMAT(1 + 5), which results in '6'.

The expression is then interpreted by trigger 15 in codeunit 1.

C/AL expression | Comments
DIM1 | This value produces an error unless a text variable exists with the name DIM1.
'DIM1' | OK. The caption is 'DIM1.'
'DIM'+FORMAT(2) | OK. The caption is 'DIM2.'
1+5 | Error. The data type is Integer

See Also

Concepts

CaptionClass Functionality


CaptionML Property

Sets the string that is used to identify a control or other object in the user interface.

Applies To

  • Codeunit objects

  • XMLport objects

  • Menu objects, menu buttons, menu groups, and menu items

  • Pages, including general page properties and Group, Part, and Field controls.

  • Query objects and query columns

  • Report objects

  • Table objects and table fields

  • XMLport objects

Remarks

The CaptionML property is multilanguage enabled, so it can contain a list of text strings in different languages. The string that is used is selected according to the user's language settings. For more information, see Multilanguage Development.

The CaptionML property has the following format.

<Language ID>=<caption>

<Language ID> is the standard Windows three-letter language ID, and <caption> is the caption text for this language. Use semicolons to separate entries.

The following example shows a CaptionML value.

DAN=Navn;DEU=Name;ESP=Nombre;FRA=Nom

In this example, values are set for Danish (DAN), German Standard (DEU), Spanish Traditional Sort (ESP), and French Standard (FRA).

You can enter values for the CaptionML property in two ways:

  • If you enter a value for the Caption Property, then the CaptionML property is set to the value of the current language. For example, if the current system language is Danish, then a value of DAN =<value> is placed in the CaptionML field.

  • If you choose the AssistButton in the CaptionML value field, then the Multilanguage Editor opens and displays two columns: Language and Value. The Language column is populated with all languages that are defined by Windows. You specify the CaptionML value for a language by entering a value in the Value field for that language. You must close the Multilanguage Editor by choosing OK. If you press ESC to close the Multilanguage Editor, then the CaptionML field is not updated.

When you export objects as XML, the CaptionML property values are included.

Note
For query columns, when you run the query from Object Designer, the About This Query window that opens in the RoleTailored client displays the value for the Name Property of the query column, not the CaptionML Property.

Default Values

The following table shows how the default caption is determined for the various objects in Microsoft Dynamics NAV.

Object, control, or other element | Default caption
Table object | Name property
Table Field | Name property
Report | Name property
XMLport | Name property
Codeunit | Name property
Menu button and menu item | Name property
Page objects and page controls (container, group, part, and field) | Name property
Query objects | Name property
Query columns | CaptionML property of the underlying table field for the column

See Also

Reference

Caption Property
Name Property


CardPageID Property

Sets the card page that is associated with items in the current list page.

Applies To

Pages

Remarks

Use this property on a list page to specify the card page that should be displayed when an end user double-clicks an item on the list page..

For an example of how the CardPageID property is used, see Walkthrough: Creating a Customer List in Page Designer.

See Also

Tasks

Walkthrough: Creating a Customer List in Page Designer


CharAllowed Property

Sets the range of characters the user can enter into this field or control.

Applies To

  • Page Fields

  • Table Fields

Remarks

If you want users to only enter uppercase letters in this field, enter AZ. This ensures that only uppercase characters in the range of A-Z are accepted. If you want both uppercase and lowercase characters, leave this value blank.

You can specify multiple ranges of characters by entering the parameters in pairs. For example, a value of admpzz indicates that only the following characters are accepted: a, b, c, d, m, n, o, p, and z. If you only want to allow a single character, then enter that character twice to specify a starting and ending range.

The setting for the field is checked during validation. Validation occurs only if the field or control value is updated through the UI, for example, if a value is updated on a page or if a field is updated in a table directly. If a field is updated through application code, then the CharAllowed property is not validated.

See Also

Concepts

Properties


ChartPartID Property

Sets the ID of the chart to add to the page.

Applies To

  • Part control on a page

Important
This property is not supported by Microsoft Dynamics NAV Web client. When the page displays in Microsoft Dynamics NAV Web client, the property is ignored and the chart does not appear.

Remarks

To set this property, you need to first set the value of the PartType Property to Chart. The ChartPartID property creates a link to the selected chart in the Chart table.

See Also

Reference

PartType Property
PagePartID Property
SystemPartID Property


ClearOnLookup Property

Sets a value that determines whether the current contents of the field are deleted before the value that is selected via the lookup is added.

Applies To

  • Fields

Property Value

Yes if current contents of the field are replaced; otherwise, No if the contents are pasted. The default value is Yes for all fields except FlowFilters fields.

See Also

Concepts

FlowFilter Overview


ClosingDates Property

Sets a value that determines whether users can enter a closing date in this field. The default value is No.

Applies To

  • Table Fields

  • Page Fields

Remarks

All dates have a corresponding closing date. A closing date is a period following the given date, but before the next date. Closing dates are sorted immediately after the corresponding date but before the next date.

For fields, this property only applies to Date and Time Functions.

See Also

Concepts

Date and Time Functions


Clustered Property

Sets a value that indicates whether the index is clustered.

Applies To

Keys

See Also

Concepts

Properties


ColumnFilter Property

Sets a filter on the column filter row of a query.

Applies to

Query columns and filter rows

Property Value

Filter expression.

The filter expression must follow the required syntax. For more information, see Entering Criteria in Filters.

Remarks

In a query, Columns and Filter rows specify fields of the underlying table of the parent DataItem. Columns appear in the resulting dataset, whereas Filter rows do not. You use a ColumnFilter property to apply a condition on a field to limit the records in query’s resulting dataset. The ColumnFilter property resembles the DataItemTableFilter Property of the DataItem, but there are differences. The ColumnFilter property has the following behavior:

  • Unlike filters that are set by the DataItemTableFilter property, filters that are set by the ColumnFilter property can be overwritten at runtime by calling the SETFILTER Function (Query) and SETRANGE Function (Query) from C/AL code.

    There can be multiple calls to the SETFILTER and SETRANGE functions in C/AL, but it is the first call in the function that overwrites the ColumnFilter property.

  • If the ColumnFilter property specifies a filter on the same field as the DataItemTableFilter property, then the filters of the two properties are combined. In SQL SELECT statements, this combination corresponds to an AND operator. To be included in the query dataset, records must meet the condition of both the filters. For example, if the DataItemTableFilter property sets a filter on a field to include values less than fifty (<50) and the ColumnFilter property sets a filter on the same field to include values greater than twenty (>20), then the resultant filter on the field includes values that are greater than twenty and less than fifty (20< value <50). However, if the same field is also set with a filter from C/AL code by calling the SETFILTER or SETRANGE functions, then only the DataItemTableFilter property filter is applied because, even though the function overwrites the ColumnFilter property filter, the function filter is ignored.

  • You can set the ColumnFilter property on any Column or Filter row in the query, this includes columns that are set with the totaling method using the Method Property.

  • In an SQL SELECT statement, a filter that is set by the ColumnFilter property that is not applied a totaling method would correspond to a WHERE clause. A filter on a column that is applied a totaling method would correspond to a HAVING clause.

Example

The following example sets a filter on the ColumnFilter property of the Quantity column of a query so that the resulting dataset will only include records where the value of the Quantity column is between 20 and 50.

Copy Code
Quantity=FILTER(>20&<50)

See Also

Tasks

How to: Set Up Filter Rows in Query Designer
How to: Create Queries

Concepts

Understanding Query Filters
Queries


ColumnSpan Property

Sets the number of columns that a field spans in a GridLayout control.

Applies To

Field controls in a GridLayout control on a page.

Property Values

An integer that specifies the number of columns to span the field.

Remarks

When you set a field to span several columns, the field occupies the cells to its right, and existing fields in the occupied cells are moved to the right. For example, the following figure illustrates a GridLayout control that consists of four fields arranged in two rows.

GridLayout of 4 fields in 2 rows and 2 columns

If you set Field 1 to span two columns, then the following layout is displayed:

GridLayout showing column span
Important
The ColumnSpan property is not supported by the Microsoft Dynamics NAV Web client. If the page displays in the Microsoft Dynamics NAV Web client, the property is ignored and the field will not span any columns.

See Also

Tasks

How to: Arrange Fields in Rows and Columns Using the GridLayout Control


Compressed Property

Sets a value that specifies whether a BLOB is compressed.

Applies To

Fields of the BLOB Data Type

Remarks

If you want to access BLOB data with an external tool, for example to display a bitmap, you must set this property to No.

The RoleTailored client can access BLOBs without using this property.

See Also

Reference

BLOB Data Type


ConstValue Property

Sets the value of the C/AL text constant for the current application language of the development environment.

Applies To

Local and global text constants in the C/AL code of objects.

Remarks

The ConstValue property sets the text string in the ConstValueML Property for the current application language of the development environment. For example, if the application language of the development environment is set to English (United States) and you set the ConstValue property to test, then the value ENU=test is included in the ConstValueML property.

See Also

Tasks

How to: Change the Language in the User Interface

Concepts

Multilanguage Development


ConstValueML Property

Sets the values of a C/AL text constant for the different languages that are available in Microsoft Dynamics NAV.

Applies To

Local and global text constants in the C/AL code of objects.

Remarks

The ConstValue property is enabled for multiple languages. It contains a list of text values for the languages that are available in Microsoft Dynamics NAV. The value that is used in the RoleTailored client is selected according to the user's language settings. For more information, see Multilanguage Development.

The ConstValueML property has the following format.

<Language ID>=<string>

  • <Language ID> is the Windows three-letter language ID.

  • <string> is the text string for the language.

If you have more than one language entry, then separate each consecutive entry with a semicolon.

The following example illustrates a ConstValueML property value.

DAN=Navn;ENU=Name;ESP=Nombre;FRA=Nom

In this example, values are set for Danish (DAN), English (United States), Spanish Traditional Sort (ESP), and French Standard (FRA).

To specify values for languages

  1. In the ConstValueML value field, choose the AssistEdit button.

    The Multilanguage Editor opens and displays two columns: Language and Value. The Language column is populated with all languages that are defined by Windows.

  2. To specify the value for a language, enter the value in the Value column for that language.

  3. To save the changes, choose the OK button.

See Also

Tasks

How to: Change the Language in the User Interface

Concepts

Multilanguage Development


ContainerType Property

Sets the container type in Page Designer when you want to add one of the following controls to a page:

  • Container

  • Group

  • Field

  • Part

Applies To

  • Container controls on Pages

Remarks

A Container control functions as a high-level container for other page controls. You can choose from one of the following subtypes:

Value | Description
ContentArea | Specifies the main content area of the page. A page can only have one ContentArea control. Except for Role Center pages, pages will have a ContentArea container as the first control in Page Designer.
FactBoxArea | Specifies a FactBox area on the page. A FactBox is an area that is located along the right-side of the page that contains one or page parts.
RoleCenterArea | Specifies the main content area for a RoleCenter page type.

You can change ContainerType property in the Properties window for the Container control or from the SubType column in Page Designer.

See Also

Concepts

Properties


ControlAddin Property

Sets the Microsoft Dynamics NAV Windows client control add-in to use on the field control.

Applies To

  • Page Fields

Property Value

The name and public token key of the control add-in as registered in the Control Add-in table (ID 2000000069). For more information, see How to: Register a Windows Client Control Add-in.

Remarks

A control add-in is a custom control, or visual element, for displaying and modifying data on Microsoft Dynamics NAV Windows client pages.

See Also

Tasks

Walkthrough: Creating and Using a Windows Client Control Add-in

Concepts

Extending Any Microsoft Dynamics NAV Client Using Control Add-ins
Windows Client Control Add-in Overview
Installing and Configuring Windows Client Control Add-ins on Pages
Developing Windows Client Control Add-ins


ControlType Property

Use this property when you select a control type in Page Designer.

Applies To

This property displays the following control types for you to choose from:

  • Container

  • Group

  • Field

See Also

Concepts

Properties


CurrentPath Property

Returns the path of the current node as a text string.

Applies To

  • XMLports

Remarks

You set the CurrentPath property in C/AL code on a function or trigger. For example, you can write code such as the following:

currXMLport.CURRENTPATH

Each node in the path is separated by a ‘/’, for example, /Root/Vendors/Vendor/Name.

For an example of how to use this property, see XMLPort 1232, Exp. Bank Data Conv. Serv.-CT, in the CRONUS International Ltd. demonstration database and refer to the LOCAL GetValue(PostExchNo : Integer;LineNo : Integer) : Text function.

See Also

Concepts

Properties


Data Type Property

Sets the data type of a table field.

Applies To

Table Fields

See Also

Concepts

Properties


DataCaptionExpr Property

Sets a C/AL expression that is evaluated and displayed to the left of the page caption.

Applies To

  • Pages

Remarks

The expression is evaluated each time the user switches from one record to another or when one of the fields in the record changes.

See Also

Concepts

Properties


DataCaptionFields Property

Sets the fields that appear to the left of the caption on pages that display the contents of this table.

Applies To

  • Pages

  • Tables

Remarks

Card Pages

Card pages display one record at a time. For this object, the value of the underlying table's DataCaptionFields property is used; the value of this property on the page is ignored. If the DataCaptionFields property is not defined on the table, the primary key is used.

Tabular Pages

Tabular pages show multiple records at a time. The following data caption rules are applied:

  • A data caption is only displayed if a filter containing the fields defined in the DataCaptionFields property for the page evaluate to one value. In this case, two situations are possible:

    • There is a table relation (as defined by the TableRelation Property) on one or more of the fields. In this case, the DataCaptionFields from the underlying table are used. If this table does not have a value for the DataCaptionFields property, the primary key for that table is used.

    • There is no table relation. In this case, the (single) value that results from evaluating the filter is used directly.

Example of DataCaptionFields Use

The following is an example of how the DataCaptionFields property is used. The Customer Card page (21) is based on the Customer table (18). Using the Navigate menu on this page, users can open other pages, including the Customer Ledger Entry page (25).

In the Customer table, the DataCaptionFields property is set to No., Name. On the Customer Ledger Entry page, the DataCaptionFields property is set to CustomerNo.. When the Customer Ledger Entry page (25) is opened from the Customer Card page (21), a filter is set on Customer No. field of the Customer Ledger Entries table, selecting only those entries related to the currently displayed customer on the Customer Card. This relationship is accomplished by setting the RunPageLink property of the menu item that invokes the Customer Ledger Entry page to Customer No.=FIELD(No.).

If you view the Customer Ledger Entry page with a filter applied, the customer name and number appear to the left of the caption on the Customer Ledger Entry page. If you remove the filter, the caption disappears.

The important point is that the DataCaptionFields property on a page does not directly put any caption on the page, but only works when used with appropriate settings of DataCaptionFields at the table level.

See Also

Concepts

Properties


DataItemLink Property (Reports)

Sets the corresponding fields from two data items that are linked by the DataItemLinkReference Property. The link is defined as a property of the indented (child) data item.

Applies To

  • Data items

  • Reports

Remarks

The following syntax shows the DataItemLink property.

<field>=FIELD(<reference field>)

The following table describes field and reference field.

Syntax | Description
<field> | A field from the child data item
<reference field> | A field from the less indented (parent) data item that is identified by the DataItemLinkReference Property

The DataItemLink property sets a filter on the child data item. This filter selects records that contain the same field value in both the parent and child data items. Use the AssistButton to select the fields from field name lookups for the parent and child data items.

The following example illustrates using this property. You have two data items, a parent and child. The parent data item is a list of customers, called Customer. The child data item contains a record of all sales orders. In the customer table, the primary key is the customer number, which is stored in the No. field. In the table that contains sales data, each record contains this customer number as a foreign key in a field called Sell-to Customer No. You set the value of the DataItemLinkReference Property on the child data item to the parent data item. You set the DataItemLink property of the child data item to the following value.

Sell-to Customer No.=FIELD(No.)

You now have a filter on the records in the child data item. This filter only displays records that pertain to the currently selected customer record. You can also accomplish the same task by placing the following C/AL statement in the OnPreDataItem Trigger for the child data item.

Copy Code
SETRANGE("Sell-to Customer No.",Customer."No.");

See Also

Reference

OnPreDataItem Trigger
DataItemLinkReference Property


DataItemLink Property (Query)

Sets a reference between one or more fields of the data item table and data item or data items above it in Query Designer.

Applies To

  • Query data items

Property Value

Field=Table.ReferenceField

  • Field is the name of the field in the table of the lower data item.

  • Table is the name of the table of the upper data item.

  • ReferenceField is the name of the field in the table of the upper data item.

Note
You can link to more than one column. Separate multiple column links with a comma.

Remarks

The DataItemLink property works together with the DataItemLinkType property to combine records from tables into a dataset. The DataItemLink property sets up "equal to" (=) comparison between two fields of the data item tables. When the query is run, the query compares each row of the two data items to find records that having matching values for the fields. Records that have a matching field values are combined into a row in the resulting dataset. In some cases, there will be records that do not have matching values. You use the DataItemLinkType Property to include records that do not have matching values. For more information about data item links, see Understanding Data Item Links.

When setting up a data item link between two data items, you always set up the DataItemLinkType property on the lower data item in Query Designer. To set the DataItemLink property, you can choose the AssistButton to select the fields from field name lookups to data item tables or you can type the syntax directly in the Value column.

Note
If the DataItemLinkType property is set to SQL Advanced Options and the SQLJoinType Property is set to Cross Join, then you cannot set the DataItemLink property. For more information about cross joins, see SQL Advanced Options for Data Item Link Types.

Example

A Salesperson table and a Sales Header table have the Code column and Salesperson_Code field in common, respectively. To create a link between these two tables, you add the following value in the DataItemLink property of the Sales Header data item.

Copy Code
Salesperson Code=Salesperson.Code

For a detailed step-by-step example of the DataItemLink property, see Walkthrough: Creating a Query to Link Two Tables.

See Also

Tasks

How to: Create Queries

Reference

DataItemLinkType Property

Concepts

Understanding Data Item Links


DataItemLinkType Property

Sets the data item link type between data items in a query to determine the records that are included in the resulting dataset.

Applies To

  • Query data items

Property Value

The DataItemLinkType property has the following values.

Value | Description
Use Default Values If No Match | The resulting dataset contains all the records from the upper data item or data items; even if a record does not have a matching value in the linked field of lower data item as specified by the DataItemLink Property (Query).
Exclude Row If No Match | The resulting dataset contains only records from data item tables that have matching values for the fields that are linked by the DataItemLink property.
SQL Advanced Options | Provide alternatives to Use Default Values If No Match and Exclude Row If No Match for generating a dataset that correspond to joins in SQL SELECT statements. When you set the property to SQL Advanced Options, the SQLJoinType Property appears where you can select the SQL join types. For more information, see SQL Advanced Options for Data Item Link Types.

Remarks

When setting up a data item link between two data items, you always set up the DataItemLinkType property on the lower data item in Query Designer.

The DataItemLinkType property works together with the DataItemLinkType property to combine records from tables into a dataset. The DataItemLink property sets up "equal to" (=) comparison between two or more fields of the data item tables. When the query is run, the query compares each row of the two data items to find records that have matching values for the fields. Records that have matching field values are combined into a row in the resulting dataset. In some cases, there will be records that do not have matching values. You use the DataItemLinkType Property to include records that do not have matching field values.

Note
If the DataItemLinkType property is set to SQL Advanced Options and the SQLJoinType Property is set to Cross Join, then you cannot set the DataItemLink property because there is no relationship between table fields. For more information about cross joins, see SQL Advanced Options for Data Item Link Types.

For more information about data item links, see Understanding Data Item Links.

For a step-by-example of using the DataItemLinkType, see Walkthrough: Creating a Query to Link Two Tables.


DataItemLinkReference Property

Sets the parent data item to which a child (indented) data item is linked. After you specify the DataItemLinkReference value, use the DataItemLink Property (Reports) to specify a field from each data item on which to base the link.

Applies To

  • Data items

  • Reports

Remarks

The value of the DataItemLinkReference property must be specified as the Name of a parent data item.

The default value is the name of the last preceding data item in the report with lower indentation. You can set DataItemLinkReference and DataItemLink properties for a data item that is not a child of another data item, however, this will not have any effect.


DataItemTable Property

Sets the Microsoft Dynamics NAV database table that is associated with a data item.

Applies To

  • Queries

  • Reports

Remarks

Queries and reports retrieve data from one or more tables. You specify tables in these objects by defining a data item. You can associate the same table with more than one data item. However, each data item must have a unique name in the object. If you have data items with the same name, you can change the names by setting the Name Property or Name column on the DataItem.

The DateItemTable property is set automatically when you use Query Designer or Report Dataset Designer to create data items.


DataItemTableFilter Property

Sets filters on fields of the underlying table of a query.

Applies to

DataItems of queries

Property Value

Filter expression.

The filter expression must follow the required syntax. For more information, see Entering Criteria in Filters.

Remarks

In a query, a DataItem specifies a table from which to retrieve data. You use the DataItemTableFilter property to apply conditions on one or more fields of the table to limit the records in the resulting dataset of the query. You can filter on any field in the table, not just those fields that are included as columns in the resulting dataset.

To set up filters, you can either enter the filter syntax directly in the Value column for the DataItemTableField property in the Properties window or choose the Value column, and then use the Table Filter window to set up the filters. If you are entering filters manually, then you must separate filters for different fields by using a comma.

In addition to the DataItemTableField property, you can also filter on the same field by setting the ColumnFilter Property on a Column or Filter row in Query Designer or by calling the SETFILTER Function (Query) and SETRANGE Function (Query) from C/AL. A filter that is set by the ColumnFilter property, SETFILTER function, or SETRANGE function is joined to the filter that is set by the DataItemTableFilter property. In logical terms, and in SQL SELECT statements, this combination corresponds to an "AND" operator. For example, if the DataItemTableFilter property sets a filter on a field to include values less than fifty (<50) and the ColumnFilter property sets a filter on the same field to include values greater than twenty (>20), then the resultant filter includes values that are greater than twenty and less than fifty (20< value <50). Using the same example, if the SETFILTER function is called from C/AL code and sets a filter to include values greater than ten (>10), then the SETFILTER function overwrites the ColumnFilter property and the resultant filter on the field includes values that are greater than ten and less than fifty (10< value <50).

Note
In an SQL SELECT statement, a filter that is set by the DataItemTableFilter property would correspond to a WHERE clause.


DataItemTableView Property

Sets the key on which to sort, the sort order, and the filters for the data item.

Applies To

Data items on reports.

Remarks

Choose the AssistEdit button to open the Table View window, where you can set the key field or fields on which to sort, the sort order, and the filters that you want to use.

  • If you set a key in the Table View window, then the data item does not have a FastTab on the request page and the end users cannot select a key for sorting, sort order, or filters for the data item.

  • If you set a sort order in the Table View window, then this sort order is used for the report, regardless of the sort order that the end user selects on the request page.

  • If you set a filter in the Table View window, then this filter is not displayed on the request page but it is used along with any filters that the end user specifies on the request page.

  • Setting a sort order, a filter, or both in the Table View window does not prevent end users from selecting a sort field on the request page. The default sort field that is displayed in the request page is the primary key. The list of fields on which you can sort includes all keys for the data item. To add fields to the list, you must add keys to the table.

See Also

Concepts

Request Pages


DataLength Property

Sets the maximum length of data stored in this field.

Applies To

Fields

Remarks

For Text Data Type and Code Data Type fields, enter the maximum length of the field. The database only stores the actual content of the field—not the maximum length you specify.

This field does not apply to the other data types because they have fixed lengths.

See Also

Reference

Text Data Type
Code Data Type


DataPerCompany Property

Sets a value that indicates whether the table data applies to all companies in the database or only the current company.

Applies To

Tables

Property Value

Yes if data is available only to this company; otherwise, No. The default value is Yes.

See Also

Concepts

Properties


DataSource Property

Sets the field to associate with a column of a query.

Applies to

Query columns and filter rows

Property Value

Field

You choose fields from the table that is specified by the DataItemTable Property of the column’s parent data item.

Remarks

A query retrieves data from fields of one or more tables. To specify a table in a query, you define a data item, and then set the DataItemTable Property of the data item to the table. After you define the data item, you can add columns under the data item, and then modify the DataSource properties of the columns to specify the fields to include in the query results. You can also set the column field by changing the Data Source column in Query Designer.

You can use the same field on different columns in your query. Each column in a query must a unique name, which is defined by the defined by the Name Property. By default, columns are given a name that is based on the field name. If the query has duplicate column names, then you use the Name Property to give columns unique names.

See Also

Tasks

How to: Set Up Filter Rows in Query Designer

Concepts

Understanding Query Filters


DateFormula Property

Sets a date formula used to verify that the date the user enters is correct.

Applies To

  • Table Fields

  • Page Fields

Remarks

The following table shows the syntax that is used to create the date formula.

Syntax | Description
30D | 30 days
2W | 2 weeks
CM+10D | Current month plus 10 days
CM+1M | Current month plus one month
CQ+1M+20D | Current quarter plus one month plus 20 days
CW+1W | Current week plus one week
D15 | On the 15th of each month

In Microsoft Dynamics NAV, weeks begin on Monday and end on Sunday.

For fields, this property only applies to text and code fields.

The field settings are checked during validation.

Note
We do not recommend that you use this property, but use the DateFormula Data Type instead.

See Also

Reference

DateFormula Data Type


DecimalPlaces Property

Sets display and storage requirements for the Decimal Data Type.

Applies To

  • Page Fields

  • Report Columns

Property Value

You can enter minimum, maximum, or both values for the number of decimal places, as shown in the following examples.

Value | Description
1 | A minimum of 1 and a maximum of 1 decimal place.
1:4 | A minimum of 1 and a maximum of 4 decimal places.
2: | At least 2 decimal places.
:2 | No more than 2 decimal places.

Remarks

For decimal fields, this property specifies the number of decimal places that you want to store. The default storage requirements for Decimal Data Type are two decimal places for amounts. Use this property to specify storage requirements that are different than the default.

This setting is evaluated on text boxes and fields during validation.

When you create a new field of Decimal Data Type, the value is automatically formatted as a currency. If your decimal field does not contain a currency value, then you can use this property to determine the number of decimal places that appear on the screen. For example, in the G/L Entry table, the DecimalPlaces property of field 42, Quantity, is set to 0:5. The minimum number of decimal places that you can enter is 0 and the maximum is 5.

See Also

Reference

Decimal Data Type

Concepts

Formatting the Data in a Field


DefaultFieldsValidation Property

Sets a value that indicates whether fields are validated.

Applies To

XMLports

Property Value

Yes if fields are validated; otherwise, No. The default value is Yes.

Remarks

This property sets the default value of the FieldValidate Property. Therefore, if you change the setting of the DefaultFieldsValidation property, the change is implemented for all fields. However, for fields for which the FieldValidate property has been set to Yes or No, no change is made.

If you change the value of the FieldValidate property, the change does not affect the value of the DefaultFieldsValidation property. This means that FieldValidate can override DefaultFieldsValidation, but that it can also inherit the default value of DefaultFieldsValidation.

See Also

Concepts

Properties


DefaultLayout Property

Specifies whether the report uses the built-in RDLC or Word report layout by default.

Applies to

  • Reports

Property Value

  • RDLC - specifies the built-in RDLC layout as the default layout.

  • Word - specifies the built-in Word layout as the default layout.

Remarks

A report object can include a built-in layout of either an RDLC type, Word type, or both. When you set the property to a type, then that layout type is used by default to view, save and print a report. Users can change a report to use another layout from the Microsoft Dynamics NAV client.

For more information, see Built-in and Custom Report Layouts.

See Also

Tasks

How to. Specify the Default Built-in Report Layout

Concepts

Designing Report Layouts from the Microsoft Dynamics NAV Development Environment


DefaultNamespace Property

Specifies the default namespace for both the IMPORT Function (XMLport) and EXPORT Function (XMLport) functions.

Applies To

  • XMLports

Remarks

This property specifies the default namespace for both import and export. The default value is unique for different XMLports. For example, the following string specifies a namespace: urn:microsoft-dynamics-nav/xmlports/x100, where 100 is the ID of the XMLport.

See Also

Concepts

Properties


DelayedInsert Property

Sets a value that specifies whether a user must leave a record before it is inserted into the database. By default, new records are inserted when the user leaves the control that shows the primary key in the table.

Applies To

  • Pages

Property Value

Yes if the record is inserted when the user leaves the record; otherwise, No if the record is inserted when the user leaves the control that shows the primary key. The default value is No.

See Also

Concepts

Properties


DeleteAllowed Property

Sets a value that specifies whether users can delete records while using the page.

Applies To

  • Pages

Property Value

Yes if the user can delete records; otherwise, No. The default value is Yes.

See Also

Concepts

Properties


Description Property

Sets the description of the table, field, page, report, or control. This description is for internal use and does not appear to end users.

Applies To

  • Tables

  • Reports

  • Pages

  • Queries

  • Labels

See Also

Concepts

Properties


Dimensions Property

Sets the dimensions of a variable that is to create a multi-dimensional variable (array).

Applies To

Variables

Remarks

Enter the dimensions as a semicolon-delimited list of integers, where each number defines the number of elements in that dimension. The maximum number of dimensions is 10 and the total number of elements in all dimensions is 1,000,000.

For example, to define an integer array with dimensions 3 x 3 x 4, start by creating an integer variable called A. In the Properties window, set the Dimensions property to a value of 3;3;4. To access the elements in the array, use either of the following:

  • A[2][3][2]

  • A[2,3,2]

Indexes start at a value of 1 (not 0 as in some programming languages).

See Also

Concepts

Array Functions


Direction Property

Sets the XMLport to import, export, or import and export data in XML format.

Applies To

XMLports

Property Value

Value Description

Import

The XMLPort only imports data.

Export

The XMLPort only exports data.

Both (default)

The XMLPort can import and export data.

If the XMLPort uses a request page, as specified by the UseRequestPage Property, then an option appears on the request page that enables the users to choose to import or export data. Note: request pages show when the XMLport is run from Object Designer, and action page, or the Run function in C/AL code. Dooes not show with Export Import finctions

If the XMLPort does not use a request, then XMLPort defaults to Import, unless you specify the direction by Import parameter of the run function.

Remarks

See Also

Concepts

Properties


DrillDown Property

Sets a drill-down for a field on a page.

Applies To

  • Page Fields

Important
This property is not supported on Repeater controls on pages when it is displayed in the Microsoft Dynamics NAV Web client.

Property Value

Yes if a drill-down for the field is provided; otherwise, No. The default value is No.

Remarks

Drill-downs are a system-wide feature of FlowFields that let you see the underlying transactions that make up the information shown in the FlowField. For example, if the FlowField shows an account balance, then providing a drill-down for this text box lets the user quickly see the various transactions that make up the balance shown in the field.

See Also

Reference

Page Properties

Concepts

Pages
Page Properties Not Supported by Microsoft Dynamics NAV Web Client


DrillDownPageID Property

Sets the ID of the page to use as a drill-down.

Applies To

  • Page Fields

  • Tables

Important
This property is not supported on Repeater controls on pages when it is displayed in the Microsoft Dynamics NAV Web client.

Remarks

Drill-downs are a system-wide feature of fields (normal fields and FlowFields) that let you see the underlying transactions that make up the information shown in the field. For example, the DrillDownID property is typically used to create a link from a Cue to an underlying page.

See Also

Concepts

Properties


Editable Property

Sets a value that indicates whether a field, page, or control can be edited through the UI.

Applies To

  • Pages and group, part, and field controls

  • Table fields

Property Value

Yes (true on pages) if the field, page, or control can be edited; otherwise, No (false on pages). The default value is Yes.

Remarks

For fields, use this property to make a field for display only.

For controls, if the Editable property for the container that contains this control is set to No, then that setting overrides what you enter here.

If a page has Editable set to No, then the controls on the page are not editable, even if the individual Editable properties are set to Yes.

The property setting is checked during validation. Validation occurs only if the field or control value is updated through the UI, for example, if a value is updated on a page or if a field is updated in a table. If a field is updated through application code, then the Editable property is not validated.

Note
When using CurrPage.Editable, the Editable property also reflects the page mode that the page was opened in. This applies to Edit, Create, and Delete modes, but not to View mode. If the page is editable, then CurrPage.Editable will return false.

On pages, you use the Editable property for group, part, field, and action controls. You can make them editable or non-editable either statically by setting the property to true or false, or dynamically by using a Boolean variable or a Boolean field on the page. The Boolean field on the page can be either a true/false Boolean or a Boolean expression, such as “Credit Limit > Sales YTD”.

Caution
Do not use CurrPage.Editable to prevent users from deleting entries. We recommend that you use permissions to control which users can delete data.

Example: Dynamic Property Change Using a Boolean Field

To make the Credit Limit (LCY) field on customer cards non-editable unless line discounts are allowed, follow these steps:

  1. Open page 21, Customer Card, with Page Designer.

  2. View the properties of field 22, Credit Limit (LCY).

  3. For the Visible property, enter “Allow Line Disc.” in the Value field.

    The Allow Line Disc. field is a Boolean field on page 21, Customer Card.

  4. Save the changes on page 21.

Now, when a user selects the Allow Line Disc. check box on a customer card, the Credit Limit (LCY) field is editable. Otherwise, the field is non-editable.

See Also

Reference

Page Properties

Concepts

Properties


Ellipsis Property

Sets a value that specifies whether an ellipsis (...) is appended to the caption on a command button or menu item. An ellipsis tells the user that other choices will appear if the command button or menu item are selected.

Applies To

  • Command buttons

  • Menu items

  • Pages

Property Value

Yes if the ellipsis is appended; otherwise, No. The default value is No.

See Also

Concepts

Properties


Enabled Property

Sets a value that indicates whether a field or key is enabled or disabled, or whether a control can respond to user-generated events.

Applies To

  • Group, part, and field controls on pages

  • Page actions

  • Keys

  • Table fields

Property Value

Yes (true on pages) if the field, key, or control is enabled; otherwise, No (false on pages). The default is Yes (true on pages).

Remarks

For keys, this property determines whether a key is maintained in the database. If you are not using the key or if you rarely use the key, you may want to mark it as disabled for performance reasons. When you want to use the key you can change this setting.

For fields, this property determines whether you can store data in the field. If the field is unused, disable it to conserve database space. In an XMLPort, a disabled field is read from the external file on import, but it is not inserted in the database.

For controls, the Enabled setting for the container that contains this control overrides what is entered here.

On pages, you use the Enabled property for group, part, field, and action controls. You can enable or disable the control either statically by setting the property to true or false, or dynamically by using a Boolean variable or a Boolean field on the page. The Boolean field on the page can be either a true/false Boolean or a Boolean expression, such as “Credit Limit > Sales YTD”.

Example: Dynamic Property Change Using a Boolean Field

To disable the Credit Limit (LCY) field on customer cards unless line discounts are allowed, follow these steps:

  1. Open page 21, Customer Card, with Page Designer.

  2. View the properties of field 22, Credit Limit (LCY).

  3. For the Visible property, enter “Allow Line Disc.” in the Value field.

    The Allow Line Disc. field is a Boolean field on page 21, Customer Card.

  4. Save the changes on page 21.

Now, when a user selects the Allow Line Disc. check box on a customer card, the Credit Limit (LCY) field is enabled. Otherwise, the field is disabled.

See Also

Concepts

Properties


EnabledIfError Property

Sets a value that specifies whether an action is enabled or disabled if it enters an error state.

Applies To

  • Actions

  • Pages

Property Value

Yes/No

See Also

Reference

EnabledIfInsertion Property
EnabledIfSelection Property


EnabledIfInsertion Property

Sets a value that indicates whether the action should be enabled or disabled if the record is undefined.

Applies To

  • Actions

  • Pages

Property Value

Yes/No

See Also

Reference

EnabledIfError Property
EnabledIfSelection Property


EnabledIfSelection Property

Sets a value that indicates whether the selected action is enabled or disabled.

Applies To

  • Actions

  • Pages

Property Value

Yes/No

See Also

Reference

EnabledIfError Property
EnabledIfInsertion Property


EnableExternalAssemblies Property

Sets whether external Microsoft .NET assemblies can be used on a report.

Applies To

Client report definition (RDLC) report layouts

Property Value

Yes if external assemblies can be used; otherwise, No. The default is No.

Remarks

When you use the Visual Studio Report Designer for creating reports for the RoleTailored client, you can reference external assemblies to add functionality to a report. The location of the assembly must be accessible from the RoleTailored client. To use external assemblies on a report, the EnableExternalAssemblies property must be set to Yes.

For more information about referencing assemblies, see Adding Custom Code to a Report (Visual Studio Report Designer).

Security Considerations

Microsoft Dynamics NAV cannot verify assemblies and protect against malicious sources that may be harmful to your computer. You should set the EnableExternalAssemblies property to Yes only if you can ensure that assemblies on the report come from a trusted source.

See Also

Concepts

Properties
Designing Reports


EnableExternalImages Property

Sets whether external images are allowed on a report.

Applies To

Client report definition (RDLC) report layouts

Property Value

Yes if external images are allowed; otherwise, No. The default is No.

Remarks

When you use the Visual Studio Report Designer for creating reports for the RoleTailored client, you can add images such as your company logo to a report. You can add either embedded or external images.

  • With an embedded image, the source file is compiled as part of the report. If a report only uses embedded images, then you can set the EnableExternalImages property to No. For an example of using embedded images, see How to add a Company Picture to a Report.

  • With an external image, the source file is stored outside of the report in a location that must be accessible from the RoleTailored client, such as on a file server or local computer. The image is referenced from the report and loads when the report opens. To use external images on a report, the EnableExternalImages property must be set to Yes.

    Note
    The EnableExternalImages property exposes the LocalReport.EnableExternalImages property of the Microsoft.ReportViewer.WebForms.LocalReport object, which is embedded in Microsoft Dynamics NAV 2016. The Microsoft.ReportViewer.WebForms.LocalReport object is part of the ReportViewer controls that are available in Visual Studio for adding reports to your application.

    Important
    To display an external image in the Microsoft Dynamics NAV Web client or, if the network uses a proxy, then you have to configure the client to bypass the proxy. To do this, you modify the web.config file of the website that is running the Microsoft Dynamics NAV Web Server components. For more information, see Adding Images to a Report (Visual Studio Report Designer).

For information about how to add images using Visual Studio Report Designer, see Adding Images to a Report (Visual Studio Report Designer).

Security Considerations

Microsoft Dynamics NAV 2016 cannot verify image sources and protect against malicious images or sources that may be harmful to your computer. You should set the EnableExternalImages property to Yes only if you can ensure that images on the report come from a trusted source.

See Also

Concepts

Properties
Designing Reports
Configuring Microsoft Dynamics NAV Web Client by Modifying the Web.config File


EnableHyperlinks Property

Sets whether hyperlinks to URLs are allowed on reports.

Applies To

Client report definition (RDLC) report layouts

Property Value

Yes if links to other URLs from the report are allowed; otherwise, No. The default is No.

Remarks

When you use the Visual Studio Report Designer for creating reports for the RoleTailored client, you can add hyperlinks on controls that target different URLs. This allows you set up a link from a field on a report to another report or page of the RoleTailored client for drilling down into data. To use hyperlinks on a report, the EnableHyperlinks property must be set to Yes. For examples that use this property, see Walkthrough: Creating a Link from a Report to a Report and Walkthrough: Creating a Link from a Report to a Page.

Note
The EnableHyperlinks property exposes the LocalReport.EnableHyperlinks Property of the Microsoft.ReportViewer.WebForms.LocalReport object, which is embedded in Microsoft Dynamics NAV 2016. The Microsoft.ReportViewer.WebForms.LocalReport object is part of the ReportViewer controls that are available in Visual Studio for adding reports to your application.

Security Considerations

Microsoft Dynamics NAV 2016 cannot verify URLs and protect against malicious sites that may be harmful to your computer. You should set the EnableHyperlinks property to Yes only if you can ensure that hyperlinks on the report target trusted sites.

See Also

Concepts

Properties
Designing Reports


Encoding Property

Sets a value that specifies which system is applied to the XMLport for character encoding.

Applies To

XMLports

Remarks

The two options available for this property are UTF8 and UTF16. UTF8 is the default setting. Information about the encoding system used is inserted into the header of the XML document. For example, <? XML version = 1.0 encoding=utf8 ?>.

See Also

Concepts

Properties


Event Property

Specifies whether the function is used to publish or subscribe to an event.

Applies to

  • C/AL functions.

Property Value

Value | Description
No | The function is a normal function that does not publish or subscribe to an event.
Publisher | The function is an event publisher, which is used to declare and raise a business or integration event in the application. For more information, see Publishing Events.
Subscriber | The function is an event subscriber, which is used to handle a published event. For more information, see Subscribing to Events.

Remarks

For more information about events, see Events in Microsoft Dynamics NAV.

See Also

Concepts

Raising Events
C/AL Function Statements


EventFunction Property

Specifies the event publisher function that the event subscriber function subscribes to.

Applies to

  • C/AL functions.

    This property is only available when the Event Property is set to Subscriber.

Property Value

An event publisher function in the object that is specified in the EventPublisherObject Property.

Remarks

You use this property to set up an event subscriber function to respond to the event that is declared by the event publisher function. When the event is raised in the application, the event subscriber function is called.

You add C/AL code to this function that defines the logic to handle the event when it is called.

For more information about events, see Subscribing to Events..

See Also

Concepts

Events in Microsoft Dynamics NAV
Publishing Events
Raising Events
C/AL Function Statements


EventPublisherObject Property

Specifies the object that contains the event publisher function that the event subscriber responds to.

Applies to

  • C/AL functions.

    This property is only available when the Event Property is set to Subscriber.

Property Value

Application object.

Remarks

You use this property to set up an event subscriber function to subscribe to a published event. There are three types of events: business, integration, and trigger.

  • Business and integration events are published by event publisher functions in objects such as codeunits, pages, or tables. To subscribe to a business or integration type event, you specify the object that contains the event publisher function for the event.

  • Trigger events are system events that are declared in tables. To subscribe to a trigger event, you specify the table.

After you set this property, you set the EventFunction Property to specify the event publisher function that you want the event subscriber to subscribe to.

For more information about events, see Event Types and Subscribing to Events.

See Also

Concepts

Publishing Events
Raising Events
Events in Microsoft Dynamics NAV
C/AL Function Statements


EventSubscriberInstance Property

Specifies how event subscriber functions in a codeunit are bound to codeunit instance and events that they subscribe to.

Applies to

  • Codeunits.

Property Value

Value Description

Static-Automatic

Subscribers are statically bound to events and the codeunit instances are controlled by the system. This is the default value.

Binding - Scope

All bindings are for the current tenant group. When NAV Apps are not used, tenant group 0 is used, which is the same as a static binding cross all current and future sessions in the system.

If the event subscription is part of a NAV App, it will be a static binding cross all current and future sessions within the tenant group(s) that has the NAV App installed and enabled.

Note
With this setting, you cannot call the BINDSUBSCRIPTION Function or UNBINDSUBSCRIPTION for any events in this codeunit; otherwise, an error occurs.

Instances

All codeunit instances are controlled by the system. If the subscriber codeunit is defined as single instance (as specified by the SingleInstance Property), the first call to a subscriber function will create the instance and it will be kept for the lifespan of the session.

If the codeunit is not declared as single instance, a new instance will automatically be created just before the call to the subscriber function, and immediately disposed afterwards - each subscriber function call will be run on its own instance.

Manual

Subscribers are bound to an event by calling the BINDSUBSCRIPTION function. This enables you to control which event subscriber instances are called when an event is raised. If the BINDSUBSCRIPTION function is not called, then nothing will happen when the event is raised.

Bindings - Scope

The binding of event subscribers to events is completely manual. To establish the binding, you must call the BINDSUBSCRIPTION function to pass an instance of a subscriber codeunit. Only then will the event subscriber functions be called.

You can stop (or unbind) the subscriber function calls by either calling the UNBINDSUBSCRIPTION function or by letting the previously bound instance go out of scope. For example, you declare a local variable, call BINDSUBSCRIPTION, and then eventually exit the function that declares the local variable. All bindings on the instance are automatically unbound.

Instances

By controlling the instance of the subscriber codeunit, you control the lifespan. If you store the instance on a single instance codeunit global variable, you are effectively creating a binding that lasts the whole session. However, it is still only bound for your session. Other sessions must also call BINDSUBSCRIPTION to establish the direct binding to the instance of the subscriber codeunit.

Remarks

On the event publisher side, the bindings are always considered static. For example, if you bind instance A of a given subscriber codeunit, all instances of publisher application objects will start calling the event subscribers. You cannot design it so that a specific instance of publisher table X calls only a specific instance of subscriber codeunit A. However, you can achieve the same by using/storing some global state on the subscriber.

For more information about events, see Events in Microsoft Dynamics NAV.

See Also

Concepts

Publishing Events
Raising Events
Subscribing to Events
C/AL Function Statements


EventType Property

Specifies the type of event that is published by the event publisher function.

Applies to

  • C/AL functions.

    This property is only available when the Event Property of a function is set to Publisher.

Property Value

Value | Description
Business | The event is a business event type. A business event has an implied promise or contract that it will not to change in future Microsoft Dynamics NAV releases. Business events are typically implemented by ISVs and Microsoft.
Integration | The event is an integration event type. An integration event is like a business event except that is does not have the same promise or contract of not changing. Therefore, it less restrictive. Integration events are typically for integrating Microsoft Dynamics NAV with other solutions, such as Microsoft Dynamics CRM.

For more information about the different event types, see Event Types

Remarks

For more information about events, see Events in Microsoft Dynamics NAV.

See Also

Concepts

Publishing Events
Raising Events
Subscribing to Events
C/AL Function Statements


ExtendedDataType Property

Sets the extended data type of a control.

Applies To

  • Page Fields

  • Table Fields

Remarks

The value of this property overrides the value of the table field and it converts a text field into one of the following:

  • None

  • Phone number

  • Email address

  • URL

  • Filter (used on reports)

  • Ratio (to monitor the progress bar)

  • Masked (displays the value as dots)

This property affects the layout and behavior of controls on a page. Use it to add an icon next to an input field to indicate whether the field relates to a telephone number, email address, or URL. This property applies validation to the field.

See Also

Concepts

Properties


Field No. Property

Sets a unique numeric ID for the field.

Applies To

Fields

Remarks

No two fields can have the same Field No. within a table. The Field No. is used for reference purposes and you can use the Name Property in code. The Name is automatically converted to the Field No. when C/AL code is compiled.

Usually, the Field No. is automatically assigned by Table Designer when you add fields to a table.

See Also

Reference

Name Property


FieldClass Property

Sets the class of the field.

Applies To

Fields

Property Value

Value | Description
Normal | A data entry field
FlowFilter | To compute the results of FlowFields
FlowField | A calculated field

Remarks

There are three classes of fields: Normal, FlowFields, and FlowFilters. For more information, see FlowFields and FlowFilter Overview.

See Also

Tasks

How to: Create a FlowField

Concepts

Properties


FieldDelimiter Property

Specifies the text delimiter for a field.

Applies To

  • XMLports

Remarks

The default value is “”, an empty string.

You can set the field delimiter in C/AL code so that the XMLport can import and export records with different delimiters. For example, if your XMLport must import from a file or stream where one record uses commas and another uses an empty string, you can change the field delimiter property at run time.

See Also

Concepts

Properties


FieldSeparator Property

Sets the string that is to be used to separate fields.

Applies To

  • XMLports

Property Value

Value | Description
<None> | There is no field separator.
<NewLine> | Any combination of CR and LF characters.
<CR/LF> | CR followed by LF.
<CR> | CR alone.
<LF> | LF alone.
<TAB> | Tabulator alone.
Other strings | The literal string entered.

Remarks

The strings in the preceding table must be entered literally, using the < and > characters. These special strings can be combined and can also be mixed with other characters.

The default value is a comma (<,>).

CR refers to the character with ASCII value 13.

LF refers to the character with ASCII value 10.

FieldSeparator is only used if the Format property is set to Variable Text. Otherwise, the setting is ignored.

You can set the field separator in C/AL code so that the XMLport can import and export records with different separators. For example, if your XMLport must import from a file or stream where one record uses commas and another uses TAB, you can change the field seperator property at run time.

See Also

Reference

Format Property (XMLports)

Concepts

Properties


FieldValidate Property

Sets a value that specifies whether the values in the source field are validated by the OnValidate (Fields) Trigger trigger for the field.

Applies To

XMLports

Property Value

Yes if the fields are validated; otherwise, No. The default value is Undefined.

Remarks

This property only applies to fields and works in combination with the DefaultFieldsValidation Property XMLport property.

The DefaultFieldsValidation property sets the value for the FieldValidate XMLport field property. Therefore, if you change the setting of the DefaultFieldsValidation property, the change is implemented for all fields. However, if the FieldValidate property of a field is set to Yes or No, no change will be made to this field.

If you change the value of the FieldValidate property, the change does not affect the value of the DefaultFieldsValidation property. This means that FieldValidate can override DefaultFieldsValidation, but that it can also inherit the default value of DefaultFieldsValidation.

See Also

Reference

DefaultFieldsValidation Property
OnValidate (Fields) Trigger


FileName Property

Sets the name of the external file to read data from or write data to an XMLport.

Applies To

  • XMLports

Remarks

The FileName property must be set to a valid file name or a run-time error occurs.

This property can be set dynamically by using the FILENAME Function (XMLport). Using this function together with the Import function, you can create XMLports that are dynamic. This means that they can determine whether data is input or output at run time, and the name of the external file to read from or write to can also be set at run time.

If FileName is blank, then a default request options page tab will be created, where this property can be set at run time. If no name is specified or the UseRequestPage Property is set to No, then a run-time error occurs.

See Also

Reference

IMPORT Function (XMLport)
FILENAME Function (XMLport)
UseRequestPage Property


Format Property

Sets the formats of the source expression for various data types.

Applies To

All data types in C/AL.

Remarks

You can set the Format property to a predefined format, or you can build your own format. For more information, see FORMAT Function (Code, Text).

Basic Settings

To choose a predefined format, use the syntax: <Standard Format,X>, where X is one of the entries in the Value column of the following table.

Value | Description
0 | Standard Display Format (the default for all data types)
1 | Standard Display Format 2 (edit)
2 | C/AL Code Constant Format
Note
You must enter the < and > angle brackets, such as <Standard Format,2>.

Building Formats

You can use the Format property to create your own formats. To create a format, use the following rules:

  • A format property consists of zero or more Chars, Fields, or Attributes.

  • Fields and Attributes are expressed by using an identifier enclosed in brackets (<>).

  • Attributes must contain a comma (,) and a parameter after the identifier.

  • Fields can optionally take a comma (,) and a FieldLen.

The following table shows the syntax.

FormatProperty := | [<Char> | <Field> | <Attribute>]
<Char> := | character with ASCII value [32..255]
<Field> := | '<' <FieldName> [',' <FieldLen>] '>' [, <Attribute>]
<FieldName> := | literal name of field (format component)
<FieldLen> := | length of field (0 or no entry means that the length is dynamic)
<Attribute> := | ['<' <AttributeName> ',' <Char> '>']
<AttributeName> := | [Standard Format | 1000Character | Comma | Overflow | Filler Character | Precision]

The 1000Character attribute specifies the character that separates the thousandths place digit from the hundredths place digit, the millionth place digit from the hundred thousandths place digit, and so on. The 1000Character attribute must be after the Integer or Integer Thousand field name and before the Decimals field name.

The Comma attribute specifies the character that separates the integer from the decimals. The Comma attribute must be after the Decimals field name.

Filler Character indicates the character that is used to fill empty spaces.

The FieldName is a component that you can use to build a format expression. Depending on the data type in the field, you can choose the appropriate FieldName from this list.

Data type FieldName values

Decimal

Sign, Integer, Decimals, Integer Thousand

Date

Day, Month, Month Text, Quarter, Year, Year4, Week, Week Year, Week Year4, Weekday, Weekday Text, Closing

Time

Hours24, Hours12, Minutes, Seconds, Thousands, AM/PM, Second dec

DateTime

Day, Month, Month Text, Quarter, Year, Year4, Week, Week Year, Week Year4, Weekday, Weekday Text, Hours24, Hours12, Minutes, Seconds, Thousands, AM/PM, Second dec

Note
"Second dec" specifies a fraction of a second, in decimal format.

Integer, BigInteger

Sign, Integer, Integer Thousand

Boolean

Text, Number

Option

Text, Number

Code

Text

Char

Char/Number, Char, Number

Text

Text

Example

The following examples demonstrate how to use the Format property:

  • Choosing a standard format.

    Use the Standard Format attribute to select one of the standard formats (these are listed at the end of this Help topic).

    For example, <Standard Format,5> selects Standard Format 5.

  • Using a standard format with an attribute.

    <Precision,2:3><Standard Format,0> will use Standard Format 0 and will format the data with a minimum of 2 and a maximum of 3 decimal places. For more information, see DecimalPlaces Property. If you do not specify a precision, then the page uses the precision that is specified in the DecimalPlaces Property of the corresponding field in the table.

  • Building a format.

    You can create your own formats using Chars (which are displayed literally), Fields (to choose specific components of a value, for example the year-part of a date) and Attributes (for example to select which character to use as a filler).

    For example, a field that is based on a source expression of the Date data type can use the following format string:

    <Weekday Text>, <Month Text> <Day>

    This expression displays the date as Monday, April 15.

    Note
    The settings that are specified under the Regional and Language Options in Windows determine how some separators are displayed.

Standard Formats

The following tables list the predefined formats for each data type. This table shows the standard Decimal formats with the regional setting of a European country/region.

Europe Decimal | Format | Example
<Sign><Integer Thousand><Decimals> | 0 | -76.543,21
<Sign><Integer><Decimals> | 1 | -76543,21
<Sign><Integer><Decimals><Comma,.> | 2 | -76543.21
<Integer Thousand><Decimals><Sign,1> | 3 | 76.543,21-
<Integer><Decimals><Sign,1> | 4 | 76543,21-
XML format | 9 | -76543.21

The following table shows the standard Decimal formats with the regional setting of English (US).

US Decimal | Format | Example
<Sign><Integer Thousand><Decimals> | 0 | -76,543.21
<Sign><Integer><Decimals> | 1 | -76543.21
<Sign><Integer><Decimals> | 2 | -76543.21
<Integer Thousand><Decimals><Sign,1> | 3 | 76,543.21-
<Integer><Decimals><Sign,1> | 4 | 76543.21-
XML format | 9 | -76543.21

The following table shows the standard Date formats with the regional setting of a European country/region.

Europe Date | Format | Example
<Closing><Day,2>-<Month,2>-<Year> | 0 | 05-04-03
<Closing><Day,2>-<Month,2>-<Year> | 1 | 05-04-03
<Day,2><Month,2><Year><Closing>D | 2 | 050403D
<Closing><Year>-<Month,2>-<Day,2> | 3 | 03-04-05
<Closing><Day>. <Month Text> <Year4> | 4 | 5. April 2003
<Closing><Day,2><Month,2><Year> | 5 | 050403
<Closing><Year><Month,2><Day,2> | 6 | 030405
<Day,2><Filler Character, >. <Month Text,3> <Year4> | 7 | 5. Apr 2003
XML format | 9 | 2003-04-05

The following table shows the standard Date formats with the regional setting of English (US).

US Date | Format | Example
<Closing><Month,2>/<Day,2>/<Year> | 0 | 04/05/03
<Closing><Month,2>/<Day,2>/<Year> | 1 | 04/05/03
<Month,2><Day,2><Year><Closing>D | 2 | 040503D
<Closing><Year>/<Month,2>/<Day,2> | 3 | 03/04/05
<Month Text> <Closing><Day>, <Year4> | 4 | April 5, 2003
<Closing><Month,2><Day,2><Year> | 5 | 040503
<Closing><Year><Month,2><Day,2> | 6 | 030405
<Day,2><Filler Character, >. <Month Text,3> <Year4> | 7 | 5. Apr 2003
XML format | 9 | 2003-04-05

The following table shows the standard Time formats with the regional setting of a European country/region.

Europe Time | Format | Example
<Hours24>.<Minutes,2>.<Seconds,2> | 0 | 4.35.55
<Hours24>.<Minutes,2>.<Seconds,2><Second dec.> | 1 | 4.35.55.553
<Hours24,2><Filler Character,0><Minutes,2><Seconds,2> <Second dec.><Comma,.>T | 2 | 043555.553T
XML format | 9 | 04:35:55.553

The following table shows the standard Time formats with the regional setting of English (US).

US Time | Format | Example
<Hours12>:<Minutes,2>:<Seconds,2><Second dec.> <AM/PM> | 0 | 4:35:55 AM
<Hours12>:<Minutes,2>:<Seconds,2><Second dec.> <AM/PM> | 1 | 4:35:55.553 AM
<Hours24,2><Filler Character,0><Minutes,2><Seconds,2> <Second dec.>T | 2 | 043555 .553T
XML format | 9 | 04:35:55.553

The following table shows the standard DateTime formats with the regional setting of a European country/region.

Europe DateTime Format Example

<Day,2>-<Month,2>-<Year> <Hours24>.<Minutes,2>

0

05-04-03 04:35

<Day,2>-<Month,2>-<Year> <Hours24>.<Minutes,2>.<Seconds,2><Second dec>

1

05-04-03 04:35:55,553

<Day,2>-<Month,2>-<Year> <Hours24>.<Minutes,2>

2

05-04-03 04:35

<Day,2>-<Month,2>-<Year> <Hours24>.<Minutes,2>.<Seconds,2>

3

05-04-03 04:35:55

XML format

Warning
A DateTime is stored in the database as Coordinated Universal Time (UTC). For example, on a computer in the (UTC+01:00) Brussels, Copenhagen, Madrid, Paris time zone, UTC is one hour earlier than local time on the computer and probably two hours earlier during summer time.

9

2003-04-05T03:35:55.553Z

The following table shows the standard DateTime formats with the regional setting of English (US).

US DateTime Format Example

<Month,2>/<Day,2>/<Year> <Hours12,2>:<Minutes,2> <AM/PM>

0

04/05/03 04:35 AM

<Month,2>/<Day,2>/<Year> <Hours12,2>:<Minutes,2>:<Seconds,2><Second dec> <AM/PM>

1

04/05/03 04:35:55.553 AM

<Month,2>/<Day,2>/<Year> <Hours12,2>:<Minutes,2> <AM/PM>

2

04/05/03 04:35 AM

<Month,2>/<Day,2>/<Year> <Hours12,2>:<Minutes,2>:<Seconds,2> <AM/PM>

3

04/05/03 04:35:55 AM

XML format

Warning
A DateTime is stored in the database as Coordinated Universal Time (UTC). For example, on a computer in the (UTC-08:00) Pacific Time zone, UTC is eight hours later than local time on the computer.

9

2003-04-05T12:35:55.553Z

Integer and BigInteger | Format | Example
<Sign><Integer> | 0 | -567
<Sign><Integer> | 1 | -567
<Sign><Integer> | 2 | -567
XML format | 9 | -567

Boolean | Format | Example
<Text> | 0 | Yes/No
<Text> | 1 | Yes/No
<Number> | 2 | 1/0
XML format | 9 | true/false

Option | Format | Example
<Text> | 0 | Blue
<Text> | 1 | Blue
<Number> | 2 | 1
XML format | 9 | 1

Standard format 9 is used to display the data in the standard XML formats.

For Chars, all formats should resemble the following: <Char/Number>.

For Text and Code, all formats should resemble the following: <Text>.

See Also

Reference

DecimalPlaces Property


Format Property (XMLports)

Determines the import and export format of the XMLPort.

Applies To

  • XMLports

Remarks

This property supports support CSV (comma separated values) export files and XML files. Available export options are as follows:

  • XML

  • Variable Text

  • Fixed Text

See Also

Concepts

Properties


Format/Evaluate Property

Sets the data that is being imported or exported as XML data types or as the standard C/SIDE data types.

Applies To

XMLports

Property Values

C/SIDE Format/Evaluate (default)

XML Format/Evaluate

Remarks

Importing

If the XML document that you want to import contains data that corresponds to the standard C/SIDE data types, use C/SIDE Format/Evaluate (default value). The data is then evaluated before being inserted into the database.

If the XML document that you want to import contains data that uses the standard XML data types, use the XML Format/Evaluate setting. This ensures that the data is evaluated and converted to the C/SIDE data types before being inserted into the database.

If the data that you want to import does not follow either the Standard C/SIDE formats or the XML formats, import the data into a temporary table in text format. You can then use C/AL code to convert the data before inserting it into the database.

Exporting

If you want to export data that uses the standard C/SIDE data types to an XML document and use these data types in the XML document, use C/SIDE Format/Evaluate (default value). The data from the database is then formatted according to the standard rules for C/SIDE data types.

If you want to export data in the standard XML formats to an XML document, use the XML Format/Evaluate setting. This ensures that the data you export from the database is formatted and exported in the standard XML formats.

The following XML Data types require evaluation.

XML Data Type | Microsoft Dynamics NAV Data Type
Decimal Float Double | Decimal
Boolean | Boolean
Datetime | DateTime
Time | Time
Date | Date
Integer | Integer
Duration | Duration

This is an XMLport property and therefore applies to all the data that is being streamed. It cannot be applied only to specific fields.

For more information about formatting C/SIDE data types, see Format Property. For more information about evaluating variables, see EVALUATE Function. For more information about using temporary tables, see Temporary Property (XMLports).

See Also

Reference

Format Property (XMLports)
EVALUATE Function
Temporary Property (XMLports)


FreezeColumnID Property

Specifies the columns in a list that remain in view on a page, even when you scroll right.

Applies To

  • Group controls on pages

Remarks

The property is useful when you have a list that has many columns that extend beyond the control’s boundaries, which require that you scroll right to see all columns. This property lets you specify columns that always remain in view, even when you scroll through the remaining columns. To set the property, you select a column. The column that you select and all columns before it remain in view on the page.


FunctionType Property (Test Codeunits)

Sets the type of function in a test codeunit.

Applies To

C/AL functions on test codeunits. A test codeunit is codeunit that has the SubType Property (Codeunit) set to Test.

Property Value

Value | Description
Normal | Acts as normal function.
Test | Tests the application.
MessageHandler | Handles MESSAGE functions.
ConfirmHandler | Handles CONFIRM functions.
StrMenuHandler | Handles STRMENU functions.
PageHandler | Handles specific pages that are not run modally.
ModalPageHandler | Handles specific pages that are run modally.
ReportHandler | Handles specific reports.
RequestPageHandler | Handles specific report request pages.
FilterPageHandler | Handles specific filter pages for filtering tables. For more information, see Creating Filter Pages for Filtering Tables
HyperlinkHandler | Handles specific hyperlinks.

Remarks

You create test codeunits to test your application. A test codeunit can consist of one or more test functions, handler functions, and normal functions.

  • You use test functions that include C/AL code that performs a test on an area of the application. For more information, see How to: Create Test Codeunits and Test Functions.

  • You use handler functions to automate tests by handling instances when user interaction is required by the code that is being tested by the test function. In these instances, the handler function is run instead of the requested user interface. The handler function should simulate the user interaction for the test case, such as validating messages, making selections, or entering values. For example, a test function that has a FunctionType of MessageHandler handles MESSAGE function calls. If the code that is being tested calls the MESSAGE function, then the MessageHandler function that is declared for that test function is called instead of the MESSAGE function. You write code in the MessageHandler function to verify that the expected message is displayed by the MESSAGE function.

    Note
    The parameters of the functions that are being handled are passed as parameters to the handler functions. The value of the parameter can be changed by the handler function.

    To set up handler function for use by a test function, you assign the handler function to the HandlerFunctions Property of the test function.

    For more information, see How to: Create Handler Functions.

  • You use normal functions to structure the test code by using the same design practices and principles as functions in other codeunits of the application.

See Also

Tasks

How to: Create Test Codeunits and Test Functions
How to: Create Handler Functions
Walkthrough: Testing Purchase Invoice Discounts

Concepts

Testing the Application


FunctionType Property (Upgrade Codeunits)

Sets the type of function in an upgrade codeunit.

Applies To

C/AL functions on upgrade codeunits. An upgrade codeunit is codeunit that has the SubType Property (Codeunit) set to Upgrade.

Property Value

Value | Description
Normal | Acts as normal function.
UpgradePerCompany | Provides instructions for upgrading data in a business data table. When you perform a data upgrade, these functions are run for all companies in the database, where each function is executed within its own system session on Microsoft Dynamics NAV Server that connects to the specific company. You typically use this type of function when the data in the table that you upgrading is company-specific, as specified by the table's DataPerCompany Property. For more information, see Upgrade Codeunits.
UpgradePerDatabase | Provides instructions for upgrading data in a business data table. These functions are executed once during an upgrade process, in a single system session on Microsoft Dynamics NAV Server that does not open any company. You typically use an UpgradePerDatabase function when the data in the table that you are upgrading is not company-specific. This can prevent locking issues when upgrade functions are run in parallel mode. For more information, see Upgrade Codeunits.
TableSyncSetup | Provides instructions about how to synchronize the table schemas in the business database with the table definitions.
CheckPrecondition | Provides logic that checks conditions that must be met in order for the data upgrade process to continue and start running the Upgrade functions.

Remarks

For more information about these functions and upgrade codeunits, see Upgrade Codeunits.

See Also

Concepts

Upgrading Data


GlobalVarAccess Property

Specifies whether global variables in the object that contains the event publisher function are accessible to event subscriber functions that subscribe to the published event.

Applies to

C/AL functions.

This property is only available when the Event Property is set to Publisher and the EventType Property is set to Integration.

Property Value

Yes to allow access from event subscriber functions to global variables in the object that contains the event publisher function; otherwise, No. The default value is No.

Remarks

When you set the GlobalVarAccess property to Yes, event subscriber functions that subscribe to an event can call the global variable parameters in the object that is specified by the EventPublisherObject Property, which contains the event publisher function that declares the event. You must add variable parameters to the event subscriber functions manually and use a name and type that matches the variable declaration in the event publisher object.

See Also

Reference

GlobalVarAccess Property

Concepts

Events in Microsoft Dynamics NAV
Publishing Events
Raising Events
Subscribing to Events
C/AL Function Statements


GroupType Property

Sets the subtype for a group control on a page, which determines how fields in a group layout on a page.

Applies To

  • Group type controls on pages

Property Values

Value Description For more information

Group

If the control is a top level control that does not have a child group of the subtype CueGroup, FixedLayout, or GridLayout, then the Group setting creates a FastTab of fields; otherwise, it is acts as a container for the child group.

How to: Add FastTabs to a Customer Card Page

Repeater

Arranges fields in a row and repeats the fields on subsequest lines in a table. This is used for displaying data in a list, such as Sales Orders or Customers.

Walkthrough: Creating a Customer List in Page Designer

CueGroup

Displays fields as a Cue on page. A Cue is a graphical representation of a total number of entities in a database table. This is typically only used on Role Center page types.

Walkthrough: Creating a Cue Based on a FlowField

FixedLayout

Arranges fields in rows and columns.

This value is not fully supported by the Microsoft Dynamics NAV Web client. You can experience misalignment of captions and fields in some setups.

Arranging Fields in Rows and Columns Using a FixedLayout Control

GridLayout

Arranges fields in rows and columns. GridLayout gives you more control than FixedLayout over how fields are displayed by letting you span rows and columns, specify labels for individual fields, and layout fields in a row-by-row or column-by-column basis.

This value is not fully supported by the Microsoft Dynamics NAV Web client. You cannot span rows and columns by setting the RowSpan Property and ColumnSpan Property on fields because these properties are not supported.

How to: Arrange Fields in Rows and Columns Using the GridLayout Control


HandlerFunctions Property

Specifies the handler functions that are used by the test function.

Applies To

C/AL test functions on test codeunits. A test function is a function that has the FunctionType Property (Test Codeunits) set to Test.

Property Value

The handler function name as specified on the Functions tab of the C/AL Global window for the test codeunit.

Note
If the test function uses more than one handler function, then you should separate the handler function names by a comma.

Remarks

You use test codeunits and test functions to test your application. A handler function allows you to automate tests by handling instances when user interaction is required by the code that is being tested. In these instances, the test function calls the handler function, which is run instead of the user interface.

The following is some important information about handler functions:

  • To be a handler function, the FunctionType Property (Test Codeunits) must set to one of the handler types: MessageHandler, ConfirmHandler, StrMenuHandler, PageHandler, ModalPageHandler, ReportHandler, RequestPageHandler, or FilterPageHandler.

  • A test function can only call handler functions that are defined in the same test codeunit as the test function.

  • A test function can call MessageHandler, ConfirmHandler, and StrMenuHandler type handlers only once. It can call PageHandler, ModalPageHandler, ReportHandler, RequestPageHandler, or FilterPageHandler type handlers multiple times but only once per application object ID.

  • Every handler function that you enter in the HandlerFunctions property must be called at least once in the test function. If you execute a test function that has a handler function listed that is not called, then the test fails.

For more information, see Testing the Application and How to: Create Handler Functions.

See Also

Tasks

How to: Create Test Codeunits and Test Functions
How to: Create Handler Functions
Walkthrough: Testing Purchase Invoice Discounts

Concepts

Testing the Application


HideValue Property

Sets whether to show or hide a value for the user based on an expression.

Applies To

Page Fields

Property Values

True if the value is hidden; otherwise, False. The default is False.

See Also

Concepts

Properties


ID Property

Sets a unique numeric ID for this codeunit, table, page, report, XMLport, or control.

Applies To

  • Codeunits

  • Menu items

  • Pages, including the page object, controls, and actions

  • Queries, including the query object, data items, columns, and filter rows

  • Tables

  • XMLports

Remarks

The ID must be unique within the scope of the object. For example, two code units, tables, or page cannot have the same ID, and no control can have the same ID as another control on that object.

The ID is used for reference purposes. As a result, you can use the value of the Name Property to reference objects in your code. The Name is automatically converted to the ID when the code is compiled.

If you do not set the ID property, you will be prompted for one when you save the object. For controls, a numeric ID is assigned based on the next available number for the page or the report. You can change this ID.

See Also

Reference

Name Property


Image Property

Specifies the icon that you want to associate with an action or an activity button. You can only choose from the icons that are available in the Image List window when you choose the AssistEdit button for the property. There are different icons that you can use on actions in the ribbon and activity buttons. If you want to view the different icons, see Action Icon Library.

Note
The image property is not valid on page link actions that are set up under activity buttons in the navigation pane. These actions use a default image that cannot be changed.

Applies To

  • Action and ActionGroup controls on pages

See Also

Tasks

How to: Promote Actions to the Ribbon on Pages
How to: Set an Icon on an Activity Button
How to: Set an Icon on an Action

Concepts

Properties


Image Property (Fields)

Specifies the image to display on a Cue.

Applies To

  • Field controls in a CueGroup control on a page.

    You can only use images on fields that have an integer data type.

Property Value

Select from the options that are available in the image list that appears when you choose the AssistEdit button. Select None if you do not want an image on the cue. The default value is Stack.

Remarks

If you want to view the different images, then see Microsoft Dynamics NAV Icon Collection.

See Also

Tasks

How to: Set Up an Image on a Cue
Walkthrough: Creating a Cue Based on a FlowField

Concepts

Properties


Importance Property

Sets the amount of information that is visible in a window or dialog box.

Applies To

Page Fields

Remarks

Different parts of a dialog box or window can be hidden by setting this property. The available options are:

  • Standard displays the field on the page by default.

  • Promoted displays the field on the page and also in the header of the FastTab when the FastTab is collapsed.

  • Additional hides the field by default. On a FastTab, to show the field, a user can choose Actions, and then choose Show more fields.

You can set the Importance property if you are an administrator or as a user personalization option.

See Also

Concepts

Properties


IncludeCaption Property

Sets whether to include the caption of a field in the dataset of a report.

Applies To

Columns on client report definition (RDLC) report datasets.

Property Value

Yes if the caption is included in the dataset; otherwise No. The default value is No.

Remarks

In Visual Studio Report Designer, if you want to use the Caption or CaptionML values of a field as a label on a report layout, then you must include the caption in the dataset. You design the dataset by using Report Dataset Designer. When you add table fields to the dataset with Report Dataset Designer, you can set the IncludeCaption property to Yes to specify that the caption for the field is also added to the dataset. If you do not include the caption in the dataset, then in a multilanguage application, you cannot use the multilanguage captions as labels in the report.

You can set the IncludeCaption property either in the Properties window of a data item or in the IncludeCaption column of Report Dataset Designer for a data item or a column. If you set the IncludeCaption column of a data item, then the IncludeCaption property is set to Yes for every child column of the data item.

See Also

Tasks

How to: Create Labels for a Report

Reference

Caption Property


IncludeInDataSet Property

Sets whether the C/AL variable's value is included in the dataset of the RoleTailored client.

Applies To

C/AL variables of Boolean Data Type or Integer Data Type on pages.

Property Value

Yes to include the variable's value in the dataset; otherwise, No. The default is No.

Remarks

You must set this property to Yes if the variable is used as the value of the Editable Property, Enabled Property, Visible Property, or StyleExpr Property.

See Also

Tasks

How to: Style Field Text on a Page


IncludeSender Property

Specifies whether global functions in the object that contains the event publisher function are exposed to event subscriber functions that subscribe to the event.

Applies to

  • C/AL functions.

    This property is only available when the Event Property is set to Publisher.

Property Value

Yes to expose the global functions in the object that contains the event publisher function to event subscriber functions; otherwise, No. The default value is No.

Remarks

Setting the property to Yes enables you to call global functions in the object that contains the event publisher function from event subscriber functions that subscribe to the published event.

When you set the property to Yes, the signature of event subscriber functions that subscribe to the published event automatically include a VAR parameter for the published event object, as shown in the following example:

LOCAL [EventSubscriber] CheckAddressLine(VAR Sender : Codeunit "My Publisher Object")

For more information about events, see Events in Microsoft Dynamics NAV.

See Also

Reference

GlobalVarAccess Property

Concepts

Publishing Events
Raising Events
Subscribing to Events
C/AL Function Statements


Indentation Property (Query)

Sets the indentation level of a data item, column, or filter row in a query in Query Designer.

Applies To

  • Query data items, columns, and filter rows

Property Value

Integer

0 sets no indentation, 1 indents the item one level, 2 indents the item two levels, and so on.

Remarks

In Query Designer, data items, columns, and filter rows are arranged in a hierarchy, as indicated by an indentation of the DataSource column of the item. Indentation is performed automatically as you add items in Query Designer, but you can also set the indentation by modifying the Indentation property The first data item in Query Designer is not indented, but each subsequent data item must be indented one level from the data item above it and every column must be indented one level from the data item to which it belongs.

See Also

Tasks

How to: Set Up Filter Rows in Query Designer

Concepts

Understanding Query Filters
Queries


Indentation Property (Reports)

Sets the indentation level of a data item or column on a report.

Applies To

  • Reports

Remarks

A value of <0> (zero) indicates no indentation. Data items can be indented ten levels deep. The largest possible value of this property is <10>. You can only indent a data item one level at a time, so the indentation level of a data item can be no more than one greater than the level of the preceding data item. Usually, you will set the indentation level property from the Report Dataset Designer, where you indent data items by clicking a button.

When a report is run, the first data item is processed. If there is an indented data item (second data item), it is processed each time a record is retrieved and processed in the first data item. This process is recursive, meaning that if there is a third data item with additional indentations after the second data item, then this third data item is processed in the same way as the second items was processed with regard to the top-level data item, and so on.


Indentation Property (XMLports)

Sets the indentation level of an element or an attribute in XMLport Designer.

Applies To

XMLports

Remarks

In XMLport Designer, specify the names of elements and their attributes in the Tag Name field.

When you are determining the indentation level of an element or an attribute, remember the following:

  • List the elements and their attributes in the order that they appear in the XML document.

  • List child elements and attributes under the parent element that they define.

  • Only indent each child one level more than its parent.

  • Only the first element can have an indentation of 0.

  • The indentation level that you set in the Properties window corresponds directly to the indentation level you can set in XMLport Designer. You can also use the buttons in XMLport Designer to change the indentation level of an element or an attribute.

See Also

Concepts

Properties


IndentationColumnName Property

Sets the name of the hidden column that controls row indentation in a List page.

Applies To

  • Pages (Type = Group, Subtype = Repeater)

Remarks

This property can be set to a field or variable of Integer Data Type. For an example of row indentation, see the page 16 Chart of Accounts.

See Also

Reference

IndentationControls Property


IndentationControls Property

Sets which columns (controls) are indented in a list.

Applies To

  • Repeater subtype controls on page

Remarks

To access the Indent Controls window, select a Group container in Page Designer and then view properties. The Indentation Controls property lets you choose which columns are indented under a group control on a List page. Choose the Assistbutton to open the Indent Controls window. In the Indent Controls window, you can see all the field controls that are under a Group container on a List page.

Define which columns you want to indent by selecting the appropriate field control in the Indentation column. Choose the OK button and the selected fields appear as comma-separated values in the Value column of the IndentationControls property in the Properties window.

Note
Microsoft Dynamics NAV Web clientsupports indentation on one column only. If you specify more than one column in the IndentationControls property, only the first column is used when the page is displayed in Microsoft Dynamics NAV Web client.

See Also

Reference

IndentationColumnName Property


InFooterBar Property

Sets whether an action should be viewed as an exit action in the lower part of the page.

Applies To

  • Actions

  • Pages

Remarks

Available options:

Yes/No (Boolean)

See Also

Concepts

Properties


InitValue Property

Sets the initial value of this field when a user creates a new record.

Applies To

Fields

Remarks

This attribute is only important if you create the record in a window or by using the C/AL functions InitValue Property, CLEAR Function, or CLEARALL Function. For example, this attribute is commonly used in Boolean fields when you want either Yes or No to be the default.

See Also

Reference

InitValue Property
CLEAR Function
CLEARALL Function


InlineSchema Property

Specifies whether an XML schema definition should be included inside an XML document.

Applies To

  • XMLports

Property Value

true if the XML schema definition should be included in the XML document; otherwise, false.

Remarks

Inline schemas are XML schema definitions that can be included inside XML instance documents instead of importing it from an external source. Like an external schema, an inline schema can be used to verify that the XML document instance matches the schema constraints.

Inline schemas can be useful in many situations. You can use inline schemas in the following situations:

  • When the architecture uses internal DTDs, and the developers wants to preserve that design pattern.

  • When it is difficult to access external files or URLs. For example, when there are security or platform restrictions.

  • When there is so much diversity in the XML document and the schema. The document is easier to process if the schema is inside the XML document.

See Also

Reference

XMLport Data Type

Concepts

Properties


InsertAllowed Property

Sets a value to specify whether users can add records while using a page.

Applies To

  • Pages

Property Value

Yes if you want to allow users to add records; otherwise, No. The default value is Yes.

See Also

Concepts

Properties


InstructionalTextML Property

Sets the multilanguage value of the InstructionalText of the object. Use this property as a label.

Applies To

Pages including:

  1. Page properties

  2. Group control

See Also

Concepts

Properties


Key Property

Use this property to identify the field or fields that make up this key.

Applies To

Keys

Remarks

You can select up to 20 fields for each key and you can have up to 40 keys for each table. The combination of the data in the fields that you select for the key must be unique. The first key that you create is the primary key for the table. If the key consists of more than one field, separate the fields with commas. For more information, see Table Keys.

Searching for specific data is usually easier if several keys are defined and maintained for the table. The indexes for each of the keys provide specific views that let the system quickly perform flexible searches. There are advantages and disadvantages to creating a large number of keys. For examples, see the following table.

Value | Performance increases | Performance slows
Increase the number of secondary keys marked as active | When you retrieve data in several different sorting sequences, because the data is already sorted. | When you enter data because indexes need to be maintained for each secondary key.
Decrease the number of secondary keys marked as active | When you enter data because there are fewer indexes to maintain. | When you retrieve data. You may have to define or reactivate the secondary keys to get the appropriate sorting. Depending on the size of the database, this can take some time, because the index must be rebuilt.

See Also

Concepts

Table Keys


Layout Property

Sets whether the fields in Group controls are arranged horizontally in a row or vertically in a column.

Applies To

  • Group controls, including Group, Repeater, CueGroup, FixedLayout, and GridLayout subtypes on pages.

Property Values

Value | Description
Rows | Arranges fields within Group controls in rows.
Columns | Arranges fields within Group controls in columns. This is the default setting.
Undefined | Same as the Columns setting.

Remarks

You use a Group control to arrange fields in rows and columns. To define the rows and columns of fields, you add SubType Group controls to the Group control. Each SubType control contains the fields that you want to display. You can use the Layout property to specify whether the fields in a group are arranged in rows or columns.

See Also

Tasks

How to: Arrange Fields in Rows and Columns Using the GridLayout Control


LinkedInTransaction Property

Gets and sets data from linked server data sources, such as Microsoft Office Excel, Access, or another SQL Server.

Applies To

Tables

Remarks

This property is available when the LinkedObject Property is set to Yes.

Set the LinkedInTransaction property to No when the Microsoft Dynamics NAV table description refers to an object outside the current database or on a linked server.

The access to linked server data sources is not under Microsoft Dynamics NAV transaction control. This means that if a Microsoft Dynamics NAV transaction is aborted, then any changes that were made to a linked object that is outside the current database or on a linked server during this transaction will remain in effect.

See Also

Reference

LinkedObject Property

Concepts

Creating Table Definitions from SQL Server Objects (Linked Objects)


LinkedObject Property

Use this property to link to SQL Server objects.

Applies To

Tables

Remarks

When you set the LinkedObject property to Yes, the LinkedInTransaction Property becomes available.

See Also

Reference

Table Properties


LinkFields Property

Specifies the fields that are linked between two tables using the LinkTable Property. This property is only available for XML items that have a table as their data source.

Applies To

XMLports

Property Value

Value | Description
<field> | A field from the table that is specified as the data source of this XML item
<reference field> | A field from the table that is specified in the LinkTable Property.

Remarks

The following syntax shows the LinkFields property.

Copy Code
<field>=FIELD(<reference field>)

This property works in combination with the LinkTable Property and the LinkTableForceInsert Property.

The property sets a filter on the table that is the data source for the XML item. The filter selects only those records that contain the same <field> value in source table as the <reference field> value from the table specified in LinkTable Property.

For example, you have defined two XML items—one based on the Customer table that contains a list of customers and one based on the Sales Header table that contains a record of each sales order that has been made.

In the Customer table, the primary key is the customer number and is stored in the No. field. In the Sales Header table that contains the sales data, each record contains this customer number as a foreign key in the field called Sell-to Customer No.

Setting the LinkTable Property of the second XML item to point to the Customer table and setting the Linkfields property of the first XML item to point to the Sell-to Customer No. field places a filter on the records in the Customer table. This means that only those records in the Sales Header table that refer to the current customer are selected.

The same result can be obtained by placing this C/AL statement in the OnPreXMLItem Trigger of the child data item.

Copy Code
SETRANGE("Sell-to Customer No.",Customer."No.");

See Also

Reference

LinkTable Property
LinkTableForceInsert Property


LinksAllowed Property

Sets whether links are allowed.

Applies To

  • Pages

Property Value

Yes if links are allowed; otherwise, No. The default value is Yes.

Remarks

If LinksAllowed is Yes, then you can add links or notes to a page. The links can be a links to web sites, files stored on the local computer or on a remote computer, or links to pages.

On a page, the links and notes are displayed in FactBoxes. If LinksAllowed is Yes, then the Actions menu has a Notes item and a Links item. You use these to create and modify notes and links.

See Also

Concepts

Properties


LinkTable Property

Sets the table that this XML item should be linked to. This property is only available for XML items that have a table as their data source.

Applies To

XMLports

Remarks

This property works in combination with the LinkFields Property and the LinkTableForceInsert Property.

Exporting

In this example, you are exporting data about specific customers and the orders that they placed. You create an XMLport based on the following database tables:

  • A Customer table that contains general information about the customer, such as address, telephone number, and so on.

  • A Sales Header table that contains information about the orders placed by these customers.

In the Customer table, the primary key is the customer number and is stored in the No. field. In the Sales Header table, each record contains this customer number as a foreign key in the Sell-to Customer No field.

Set the LinkTable property of the Sales Header XML item to point to the Customer table and set the LinkFields Property of the Sales Header XML item so that the Sell-to Customer No. field is equal to the No. field in the Customer table. This places a filter on the records in the Customer table and ensures that only those records in the Sales Header table that refer to the customers you specified are selected and exported by the XMLport.

This corresponds to placing the following C/AL code in the OnPreXMLItem Trigger of the indented data item.

Copy Code
SETRANGE("Sell-to Customer No.",Customer."No.");

Importing

In this example, you are importing XML data that contains information about new customers as well as details about their first orders. You create an XMLport based on the following database tables:

  • A Customer table that contains general information about the customer, such as address, telephone and so on.

  • A Sales Header table that contains information about the orders placed by these customers.

In the Customer table, the primary key is the customer number and is stored in the No. field. In the Sales Header table, each record contains this customer number as a foreign key in the field called Sell-to Customer No.

You must set the LinkTable property of the Sales Header XML item to point to the Customer table and set the LinkFields Property of the Sales Header XML item so that the Sell-to Customer No. field points to the No. field in the Customer table. This ensures that the customer numbers in the incoming data stream are inserted into both the Customer table and the Sales Header table. The incoming data stream must conform to the XML schema that you have defined for your XMLport.

In this example, the information you are importing has a header/line relationship—each customer can place many orders. The customer information is the parent of the sales header information. In this kind of relationship the parent information generally functions as a kind of wrapper that encapsulates the information about the children.

The schema typically starts by supplying some of the parent information, followed by the information about the children, and it finishes by supplying the last of the parent information.

When the XML stream is processed, it begins with the parent information, for example, the customer number is inserted into the No. field in the Customer table. Next comes the sales header information and the customer number is inserted into the Sell-to Customer No. field in the Sales Header table. The rest of the sales header information is then inserted into that table.

In this case, you must use the LinkTableForceInsert Property to ensure that the parent information is inserted before the child information. The customer information is inserted into the Customer table before you start processing the sales header information. This makes it possible to validate the sales header information against the customer information as it is inserted.

After the sales header information has been processed, the last of the customer information is inserted into the Customer table.

If the customer number already exists, you will receive an error. This means that you will probably have to insert the data into a temporary table, modify it, and then insert it into the correct tables.

See Also

Concepts

Properties


LinkTableForceInsert Property

Sets whether data from the linked table is forcibly modified or inserted into a table to prevent an error from being generated.

Applies To

XMLports

Property Value

Yes if you want to forcibly insert or modify data; otherwise, No. The default is Yes.

Remarks

This property works in combination with the LinkFields Property and the LinkTable Property.

Setting this property to Yes will forcibly insert or modify data from the linked table and run the OnAfterInitRecord Trigger on the main table.

This feature is useful if you have a header to line relationship in your XML document. The table and the header information must be inserted before you can insert the line information. As a result, you can use this property to ensure that the header information is inserted before the XMLport starts reading the line information.

See Also

Reference

LinkFields Property
LinkTable Property


Local Property

Specifies if a function is local to the object on which the function is defined. A local function cannot be accessed from outside the object.

Property Value

Yes to specify the function as local; otherwise, No.

When you add a function, the property is set to Yes by default. If the value is blank, then it defaults to No.

Remarks

When the property is set to Yes, the function definition in C/AL code includes the word Local.

If the property is set to No, then the function is considered to be global, which means that is can be called and accessed from other Microsoft Dynamics NAV objects.

Note
This property is not set to Yes when the function is in a test codeunit. Instead, the FunctionType Property (Test Codeunits) is set to Test. Functions in test codeunits are automatically global. For more information, see How to: Create Test Codeunits and Test Functions.

See Also

Concepts

Standard and User-Defined Functions


Lookup Property

Use this property to provide a lookup window for a text box.

Applies To

  • Page Fields

Property Value

Yes if you want a lookup for the field; otherwise, No. The default value is No.

Remarks

By default, a lookup provides a list of records in the table. Using this list, users can select a record and retrieve information from it into this control.

See Also

Reference

LookupPageID Property


LookupPageID Property

Sets the ID of the page you want to use as a lookup.

Applies To

  • Page Fields

  • Tables

Remarks

For tables, the default value LookUpPageID property is <Undefined>. By changing this value, you can determine which page is displayed when users press F6 (Lookup).

See Also

Reference

Lookup Property


MaintainSIFTIndex Property

Sets the value to determine whether SIFT structures should be created in SQL Server to support the corresponding SumIndexFields for the Microsoft Dynamics NAV key.

Applies To

Keys

Property Value

Yes to create the SIFT structures in SQL Server; otherwise, No. The default is Yes.

Remarks

SumIndexFields are created in Microsoft Dynamics NAV to support FlowField calculations and other fast summing operations. SQL Server can sum numeric data by scanning the table. If the SIFT structures exist for the SumIndexFields, summing the fields is faster, especially for large sets of records, but modifications to the table are slower because the SIFT structures must also be maintained.

In situations where SumIndexFields must be created on a key to enable FlowField calculations, but the calculations are performed infrequently or on small sets of data, you can disable this property to prevent slow modifications to the table.

See Also

Concepts

Properties


MaintainSQLIndex Property

Sets a value that indicates whether a SQL Server index that corresponds to the Microsoft Dynamics NAV key should be created.

Applies To

Keys

Property Value

Yes to create the SQL Server index; otherwise, No. The default is Yes.

Remarks

In Microsoft Dynamics NAV, you can use a key to sort data in a table by the set of fields specified in the key. SQL Server can sort data without an index on the fields to be sorted. However, if an index exists, sorting by the fields matching the index will be faster, but modifications to the table will be slower. The more indexes there are on a table, the slower the modifications become.

In situations where a key must be created to allow only occasional sorting (for example, when running infrequent reports), set this property to No to prevent slow modifications to the table.

Note
You cannot disable this property on the primary key of a table. This key is always created in SQL Server.

See Also

Concepts

Properties


MaxIteration Property

Sets a limit on the number of times that a data item will be iterated when the report is run.

Applies To

Data items

Remarks

Valid settings of this property are integers between 0 and the maximum value of an integer (2,147,483,647).

See Also

Concepts

Properties


MaxOccurs Property

Sets a value that indicates the maximum number of times an element can occur.

Applies To

XMLports

Property Value

SourceType | Default
Table | Unbounded
Text | Unbounded
Field | Once

Remarks

The default value of the MaxOccurs property varies depending on what you have selected as the SourceType Property of this element.

The minimum number of times an element can appear is determined by the value of the MinOccurs Property.

The MinOccurs and MaxOccurs properties conform to the standard occurrence constraints that are used when defining XML schemas.

The minimum number can be either 1 or 0.

The maximum number can be either 1 or infinite.

See Also

Concepts

Properties


MaxValue Property

Sets the maximum numeric value for a field.

Applies To

  • Page Fields

Property Value

Value | Description
9999 | Integers
9999.0 | Decimals
December 31, 9999 | Dates
23:59:59 | Time

Remarks

The field setting is checked during validation. Validation occurs only if the field or control value is updated through the UI, for example, if a value is updated on a page or if a field is updated in a table directly. If a field is updated through application code, then the MaxValue is not validated.

See Also

Reference

MinValue Property
NotBlank Property
Numeric Property


MenuItemType Property

Sets the value for the type of menu item.

Applies To

Menu items

Property Value

Value | Description
MenuItem (default) | If the menu item is a standard menu item
Separator | If the menu item separates other items

Remarks

Specify the menu item properties using the menu item editor, which is available by selecting the Menu Items option on the View menu.

See Also

Concepts

Properties


MenuLevel Property

Sets the menu level for a control. Levels are indicated by indentation.

Applies To

Menu items

Remarks

Usually you specify the menu item properties using the menu item editor, which you can display by selecting the Menu Items option on the View menu.

The number you enter indicates the relative level of the option. The default value is zero (0).

See Also

Concepts

Properties


MethodType Property

Sets a date or totals type method on the query column. The method is applied by the Method Property.

Applies to

Query columns

Property Value

Value | Description
None | No method type is applied. This is the default value.
Date | Applies the date method that is specified by the Method property to the query column. The available date methods retrieve the day, month, or year from the date expression of field values in the column.
Totals | Applies the totals method that is specified by the Method property to the query column. The available totals methods calculate the sum of field values in the column, the average, minimum, and maximum field value in a column, or the total number, or count, of records for a group in the resulting dataset.

Remarks

The Date method type can only be set in fields that have a data type of Date or DateTime. For more information about date methods, see Using the Date Method to Retrieve Day, Month, and Year Data.

Except when the Method property is set to Count, the Totals method type can only be used on fields that have a numeric data type of Decimal, Integer, BigInteger, or Duration.

When you set the MethodType property of a column to Totals, the rows in the resulting dataset are automatically grouped by the other columns in the query as indicated by a check mark in the Group By column in Query Designer. When grouped in the resulting dataset, rows that have similar column values are combined into a single record. Setting the MethodType property to Totals corresponds to using the SQL aggregate functions SUM, AVG, MIN, MAX, and COUNT in SQL SELECT statements. For more information, see Understanding Query Totals and Grouping.

See Also

Tasks

How to: Create Queries

Reference

Method Property

Concepts

Using the Date Method to Retrieve Day, Month, and Year Data
Understanding Query Totals and Grouping


Method Property

Sets either a date method for retrieving the year, month, or day from a date field or a totals method for performing calculations on field values.

Applies to

Query columns

Property Value

The values that are available for the Method property depend on whether the MethodType Property is set to Date or Totals. The following table describes the values for each setting.

MethodType property setting Method property value Description

Date

Day

Gets the day from the date expression for the field in the query column. The day is returned as an integer, in the range of 1 to 31, which represents the day of the month. If the day in the date expression is 0, then 1 is returned.

Month

Gets the month from the date expression for the field in the query column. The month is returned as an integer, in the range of 1 to 12, where 1 represents January and 12 represents December. If the month in the date expression is 0, then 1 is returned.

Year

Gets the year from the date expression for the field in the query column. The year is returned as an integer. If the year in the date expression is 0, then 1900 is returned.

Totals

Sum

Adds the values of all fields for the specified column within a group.

Count

Returns the number of rows that are included in the dataset within a group.

Note
The Count method is associated with the DataItem and not with a specific column, so the DataSource property must be blank.

Average

Calculates the average value of the fields in the column within a group.

When averaging fields that have an integer data type (such as Integer or BigInteger), integer division is used. This means that result is not rounded, and the remainder is discarded. For example, 5÷2=2 instead of 2.5 (or 2 1/2).

Min

Retrieves the lowest value of fields in the column within a group.

Max

Retrieves the highest value of fields in the column within a group.

Date Methods

You can only use the date methods on fields of the Date and DateTime data type.

When you set up a totals method on another column in the query, rows in the resulting dataset are grouped by the day, month, or year, depending on the Method property setting.

For more information about date methods, see Using the Date Method to Retrieve Day, Month, and Year Data.

Totals Methods and Groups

A totals method performs a calculation on fields in a column and returns a single value. When you set a totals method on a column, the retrieved records are automatically grouped by the other columns in the query, as indicated by a check mark in the Group By column in Query Designer. When grouped by a column, records that have similar values for the column are grouped together. The totals method is applied against the records in the group. A summary value is calculated for the group and returned in a single row for the group in the dataset. The Method property values correspond to the SQL aggregate functions SUM, AVG, MIN, MAX, and COUNT in SQL SELECT statements.

Except for the Count method, you can only use a totals method on a field that has a numeric data type of Decimal, Integer, BigInteger, or Duration. The totals method returns a decimal value that is calculated from values of all fields in a column.

Count is only associated with its parent DataItem, not a specific column. Therefore, when you set a column to Count, you leave the DataSource Property of the column blank. The Count method returns an integer value that corresponds to the number of rows that are returned from the table that is specified by the data item associated with the column.

For more information, see Understanding Query Totals and Grouping.

See Also

Tasks

How to: Create Queries

Reference

MethodType Property

Concepts

Using the Date Method to Retrieve Day, Month, and Year Data
Understanding Query Totals and Grouping


MinOccurs Property

Sets the minimum number of times that an element can occur.

Applies To

XMLports

Property Values

The possible values are Once and Zero (0). The default value is Once.

Remarks

The maximum number of times an element can appear is determined by the value of the MaxOccurs Property. The MinOccurs and MaxOccurs properties conform to the standard occurrence constraints that are used when defining XML schemas.

If you use Lazy API for XML (LAX), then the minimum number is 1. If you do not use LAX, then the minimum number is 0.

The maximum number can be either 1 or infinite.

See Also

Reference

MaxOccurs Property


MinValue Property

Sets the minimum value for a field.

Applies To

  • Page Fields

Property Value

Value | Description
0 | Integers
0.0 | Decimals
January 1, 0 | Dates
00:00:00 | Time

Remarks

The field setting is checked during validation. Validation occurs only if the field or control value is updated through the UI, for example, if a value is updated on a page or if a field is updated in a table directly. If a field is updated through application code, then the MinValue property is not validated.

See Also

Reference

MaxValue Property
NotBlank Property
Numeric Property


ModifyAllowed Property

Sets the value to determine whether users can modify records while using this page.

Applies To

  • Pages

Property Value

Yes if you want to allow the users to modify records; otherwise, No. The default is Yes.

See Also

Concepts

Properties


MultiLine Property

Sets the value that indicates whether a field can display multiple lines of text.

Applies To

  • Page Fields

Property Value

Yes if you want to display multiple lines; otherwise, No. The default is Yes.

See Also

Concepts

Properties


MultipleNewLines Property

Sets a value that determines whether users can add multiple new lines between records.

Applies To

  • Pages

Property Value

Yes if you want to allow users to add multiple new lines between records; otherwise, No. The default is No.

See Also

Reference

AutoSplitKey Property


Name Property

Sets the name of the object. The name is used for internal identification of the objects, controls, and other elements in C/AL code and the development environment.

Applies To

  • Codeunits

  • Fields

  • Menu items

  • Pages

  • Queries

  • Reports

  • Tables

  • XMLports

Remarks

Unlike the ID Property, the value of the Name property does not have to be unique; however, it is a good practice to use unique names. The Name can be up to 30 characters long. The name must comply with the Common Language Specification (CLS). For example, the first character must be a letter and subsequent characters can be any combination of letters, whole number, and underscores. For more information, see the "Naming" section in Common Language Specification in the MSDN Library.

When you use the Name in C/AL code, it is automatically converted to the value of the ID Property when the C/AL code is compiled.

For report, page, XMLport, and query objects, the name is the default for the Caption Property.

For controls, the default name is based on the ID.

See Also

Reference

ID Property
Caption Property


NamespacePrefix Property

Specifies the namespace prefix on an XMLport element.

Applies To

  • XMLports that have the Format Property (XMLports) set to Xml. The property applies only to Element node types. It is not supported on Attribute node types.

Remarks

You can only set the property to a prefix that is declared in the Namespaces Property of the XMLport.

For more information about namespaces with XMLports, see Using Namespaces with XMLports.

See Also

Tasks

How to: Create XMLports

Concepts

Designing XMLports


Namespaces Property

Specifies namespaces on the XMLport.

Applies To

  • XMLports that have the Format Property (XMLports) set to Xml.

Remarks

You can use this property to declare one or more namespaces on the XMLport. To add a namespace, you can choose the AssistEdit button or enter the namespaces directly in the field.

A namespace declaration consists of prefix and the namespace name, which has the format prefix=namespace. Separate multiple namespaces with a comma.

In the XML documents exported or imported by the XMLport, the namespaces declarations are only supported in the <root> element. For example, if an XMLport has the namespace mynavprefix=mynavnamepace and the default namespace urn:nav:schema:all, then the root element will be as follows:

<Root xmlns:mynavprefix="mynavnamespace" xmlns="urn:nav:schema:all">

To specify a default namespace, leave the Prefix field blank. You can also specify the default namespace by specifying the namespace in the DefaultNamespace Property and setting the UseDefaultNamespace Property to Yes. However, there can only be one default namespace. So if you want to specify a default namespace in the Namespace property, you must set the UseDefaultNamespace Property to No.

For more information about namespaces with XMLports, see see Using Namespaces with XMLports.

See Also

Tasks

How to: Create XMLports

Concepts

Designing XMLports


NodeName Property

Sets the name of a node in an XML document.

Applies To

XMLports

Remarks

The name that you specify is inserted in the NodeName field of the XMLport Designer of the element or attribute in question.

You must enter node names in the order that they appear in the XML document. Parent elements must precede their child elements. Indent the node names of child elements under their parent elements using one indentation per level. List attributes under the elements that they define and indent them to the child level.

See Also

Reference

NodeType Property


NodeType Property

Sets the value to specify whether an XML object is an element or an attribute.

Applies To

XMLports

Remarks

The possible values are as follows: Element and Attribute. The default value is Undefined. In an XML document, you can use the Element node to represent a record and the Attribute node to represent the fields in the record. For example, the following code defines a table with one record and the record contains two fields: <Record> <Field1>123</Field><Field2>456</Field2> </Record>

Value | Description
Element | Describes the data that it contains. The data could be record. For example, <Record> “Data 1” </Record> could represent an element that contains 1 record.
Attribute | An attribute could represent a field in the record. For example, the <Record></Record> Element could contain two fields, as shown in the code example. An attribute cannot contain other elements.

See Also

Reference

NodeName Property


NotBlank Property

Sets a value that specifies whether users must enter a value in the selected field or text box.

Applies to

  • Table Fields

  • Page Fields

Remarks

You can use this property together with the InitValue Property to make sure that an entry is made in this field. This setting is evaluated for controls and fields during validation. Validation occurs only if the field or control value is updated through the UI, for example, if a value is updated on a page or if a field is updated in a table directly. If a field is updated through application code, then the NotBlank property is not validated.

You can set the NotBlank property to Yes on primary fields in a table. Setting the NotBlank property to Yes on other fields in a table does not cause a red star marking on the UI.

If the NotBlank property is used on other fields than primary fields, the behavior is as follows:

  • If the field is blank, and never entered, the page can be closed.

  • If the field has been entered, and the user tries to enter a blank value, a validation error occurs.

See Also

Reference

MinValue Property
MaxValue Property
Numeric Property


Numeric Property

Sets a value that requires that users enter only numbers in the field.

Applies To

  • Table Fields

  • Page Fields

Remarks

This setting is checked during validation. Validation occurs only if the field or control value is updated through the UI, for example, if a value is updated on a page or if a field is updated in a table directly. If a field is updated through application code, then the Numeric property is not validated.

See Also

Reference

MinValue Property
MaxValue Property
NotBlank Property


Occurrence Property

Sets a value that specifies whether an attribute must occur in the data that is being imported or exported.

Applies To

XMLports

Property Value

Value | Description
Required (default) | If the attribute must be part of the data.
Optional | If the attribute does not have to be part of the data.

Remarks

This property is primarily used to ensure that the XML data that you are importing conforms to the data structure in Microsoft Dynamics NAV.

See Also

Concepts

Properties


OnMissingLicense Property

Specifies what happens to the event subscriber function call when the license of the Microsoft Dynamics NAV user account that is running the current session does not include the codeunit that contains the subscriber function.

Applies to

  • C/AL functions in codeunits.

    This property is only available when the Event Property is set to Subscriber.

Property Value

Value | Description
Error | An error is thrown and the code execution stops. This is the default value.
Skip | The subscriber call will be ignored, and execution will continue to the next subscriber.

Remarks

For more information about events, see Events in Microsoft Dynamics NAV.

See Also

Concepts

Publishing Events
Raising Events
Subscribing to Events
C/AL Function Statements


OnMissingPermission Property

Specifies what happens to the subscriber function call when the Microsoft Dynamics NAV user account that is running the current session does not have permission to the codeunit that contains the subscriber function. The permissions are defined by the permission sets on the user account.

Applies to

  • C/AL functions in codeunits.

    This property is only available when the Event Property is set to Subscriber.

Property Value

Value | Description
Error | An error is thrown and code execution will stop. This is the default value.
Skip | The subscriber function call is ignored and the execution continues the next subscriber.

Remarks

Before the permissions of the user account are evaluated, the user's license is evaluated to make sure that it includes the codeunit. If the license is not valid for the codeunit, the call to the subscriber is stopped and this property is irrelevant.

For more information about events, see Events in Microsoft Dynamics NAV.

See Also

Concepts

Publishing Events
Raising Events
Subscribing to Events
C/AL Function Statements


OnValidateEventField Property

Specifies the table field that the trigger event pertains to.

Applies to

  • C/AL functions.

    This property is only available on event subscriber functions that handle validation-type trigger events. The Event Property must be set to Subscriber, the EventPublisherObject Property must be set to a table, and the EventFunction Property must be set to a validate trigger event, such as OnAfterValidateEvent.

Property value

A field in the table that is specified by the EventPublisherObject Property.

Remarks

You use this property to set up an event subscriber function that will be called when the trigger event that is specified by the EventFunction Property is raised on the specified table field. For more information, see Subscribing to Events.

See Also

Reference

GlobalVarAccess Property
IncludeSender Property

Concepts

Publishing Events
Raising Events
Subscribing to Events
C/AL Function Statements


OptionCaption Property

Sets the text string options that are displayed to the user.

Applies To

  • Pages

  • Reports

  • Variables

Remarks

OptionCaption sets the text used to show the option values available for a variable or a field on a page or report. The OptionString Property contains the set of values that are acceptable choices. If you have set the OptionCaptionML Property, this overrides the OptionCaption setting.

See Also

Reference

OptionString Property
OptionCaptionML Property


OptionCaptionML Property

Sets the strings that are displayed to the user for selecting an option. OptionCaptionML is only used if the field or variable has an OptionString Property. The OptionString property contains the set of values that are acceptable choices, and it is one of these values that is saved in the database or used in C/AL code.

Applies To

  • Page Fields

  • Variables

Remarks

OptionCaptionML is multilanguage enabled so it can contain a list of text in different languages. The text that is displayed is selected according to the current language settings of the user. For more information, see Multilanguage Development.

The OptionCaptionML property has the following format.

Copy Code
<Language ID>=<optioncaption [,optioncaption]*>

<Language ID> is a Windows standard three-letter language ID and <optioncaption [,optioncaption]*> is the OptionCaption text(s) for this language. Semicolons are used to separate entries.

Although you can use OptionCaptionML to limit the number of options displayed to the user, it is recommended that you use OptionString Property to do this. You cannot expand the set of options. If you do, a run-time error will occur when the user selects an option that is outside the option set defined for the field or variable.

The following is an example of an OptionCaptionML value.

Copy Code
DAN=Resultatopgørelse,Balance;DEU=GuV,Bilanz;ESP=Comercial,Balance

In this example, values are set up for Danish (DAN), German Standard (DEU), and Spanish Traditional Sort (ESP).

How to Enter OptionCaptionML Values

When you choose the AssistEdit button in the OptionCaptionML Value field, the Multilanguage Editor opens. This editor has two columns: Language and Value. The Language column is populated with all languages defined by Windows. For your convenience, the names, not the abbreviated names, of the languages are displayed. The OptionCaptionML value for a language is added by entering a value in the Value field for that language. You must close the Multilanguage Editor by choosing OK. If you close it by pressing the ESC key, the OptionCaptionML field is not updated.

Examples of Using OptionCaptionML

The following examples demonstrate the relationship between the OptionString Property and the OptionCaptionML property on fields (or variables) and controls.

  1. An Option field in a table has the following OptionString Property value: opt1,opt2,op3. The value of OptionCaptionML is not set. A page based on this table contains a text box that is based on the Option field. OptionString and OptionCaptionML are not set for the text box.

    Result Users see opt1, opt2, and opt3 as the available choices.

  2. An OptionCaptionML property is added to the database field containing DAN=valg1,valg2,valg3;ENG=choice1,choice2,choice3.

    Result If a user selects DAN as the language, valg1, valg2, valg3 will be the available choices on the page. If a user selects ENG, choice1, choice2, choice3 will be available. For more information about what happens when the selected language is not available, see Multilanguage Development.

  3. An OptionCaptionML property is added to the text box containing DAN=valg nummer 1,valg nummer 2,valg nummer 3.

    Result If a user sets DAN as the language, the choices are valg nummer 1, valg nummer 2, valg nummer 3. If a user sets the language to ENG, the same set of choices are available.

  4. The OptionCaptionML is removed from the field. The OptionString Property is set on the field; the OptionCaptionML property on the text box is set to DAN. The text strings specified in the OptionCaptionML property are used for all languages.

    Result Same result as for example 3. As long as any OptionCaptionML property is set on the text box or the field, the OptionString Property is not used to display choices to the user.

See Also

Concepts

Multilanguage Development


OptionString Property

Sets the option values for a field, text box, or variable. OptionString is multilanguage enabled.

Applies to

  • Fields

  • Variables

Remarks

If the OptionCaptionML Property is set, then users see the OptionCaptionML values as the option values. However, the value that is used in C/AL code or that is stored in the database will be the corresponding value from the OptionString property.

This allows you to present strings to users in different languages. The strings that are displayed to users are selected according to the user's current language setting. For more information, see Multilanguage Development. If the OptionCaptionML Property is not set, then users will see the values from OptionString.

For other multilanguage enabled properties (Caption Property, ToolTip Property, and ReqFilterHeading Property), there is a relationship between the property itself and the multilanguage counterpart. The only connection between the OptionString and OptionCaptionML properties is that if the OptionCaptionML property is not set, then the strings displayed are taken from the OptionString property.

For Option fields and variables, use this property to list the options you want to be accepted (and displayed, if OptionCaptionML is not set). You can enter a maximum of 250 characters. Separate the options with a comma. For example: option1,option2,option3.

For controls, you can use this property to limit the number of options that the user can select. You cannot add options; if you do, a run-time error occurs when users select an option outside the set of options defined for the field or variable.

This property setting is checked recursively during validation.

See Also

Reference

OptionCaptionML Property


OrderBy Property

Sorts rows in the resulting dataset of a query in ascending or descending order by a column or columns.

Applies to

Query objects

Property Value

Column=Ascending|Descending

  • Column is the name of the query column as specified by its Name Property.

  • Ascending sorts the column from lowest value to the highest value (A to Z, 0 to 9).

  • Descending sorts the column from highest value to the lowest value (Z to A, 9 to 0).

Note
Separate multiple columns with a comma.

Remarks

To access the OrderBy property, in Query Designer, select the first blank line, and then, on the View menu, choose Properties.

To modify the OrderBy property, you can choose the AssistEdit button next to the property. In the Order By window, you add a column and set its direction to ascending or descending. You can sort on multiple columns by adding additional columns to the Order By window. The query will sort the results by the first column in the Order By window, then the second column, and so on.

You can also type values directly in the Value column of the OrderBy property in the Properties window. To sort on multiple columns, separate each column with a comma.

Note
You cannot sort on the same column more than once.

The OrderBy property corresponds to the Order By clause in SQL select statements.

Example

This following table shows the results of a query that retrieves the quantity of items in every open sales order for each customer.

Customer | Quantity
The Cannon Group | 50
New Concepts | 15
New Concepts | 30
Selangerian Ltd. | 20
Selangerian Ltd. | 60

To sort the Customer column in ascending order and the Quantity column to descending order, you set the OrderBy property to Name=Ascending,Quantity=Descending. The following table shows the results of the query after sorting.

Customer | Quantity
New Concepts | 30
New Concepts | 15
Selangerian Ltd. | 60
Selangerian Ltd. | 20
The Cannon Group | 50

The following is the Order By clause in SQL that corresponds to the OrderBy property in this example.

Copy Code
OrderBy Name,Quantity


Owner Property

Sets the Microsoft Dynamics NAV Server user who owns the object in the BLOB field of a table object.

Applies To

  • Fields of the BLOB Data Type.

Remarks

This property is available when the DataType field of the table field is set to BLOB Data Type.

See Also

Reference

Table Properties


PagePartID Property

Sets a link to another page.

Applies To

  • Part controls on pages

See Also

Reference

PartType Property
SystemPartID Property
ChartPartID Property


PageType Property

Sets the type of page that is created.

Applies To

Pages

Remarks

You typically set this property when you are create new pages, but you can change it at any time. The value for the PageType property specifies the Page layout in Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client.

See Also

Tasks

How to: Create a Page

Concepts

Pages
Properties


PaperSourceDefaultPage Property

Specifies the default paper source to use when printing the report.

Applies To

Reports

Remarks

In the Report - Properties window, in the PaperSourceDefaultPage field, choose the paper source. The list contains 13 standard trays and 16 printer-specific trays. It is based on information in the fin.stx file.

If the printer that is used for this report does not support the specified paper source, then the printer uses the default tray that is specified by the printer driver.

If you do not specify a value for the PaperSourceDefaultPage property, then the printer uses the default printer tray that is defined for the operating system.

If you do not specify a value for the PaperSourceFirstPage property or the PaperSourceLastPage property, then the printer uses the tray that is specified in the PaperSourceDefaultPage property.

The printer specific trays that are contained in the list are intended for use with printers that have other paper sources than the standard ones that are listed in the property.

The settings in the Print and Page Setup dialog boxes override the value that is specified for the PaperSourceDefaultPage property.

You can use the GetPaperTrayForReport function in codeunit 1, Application Management, to set the paper tray from C/AL code. This gives you runtime control over paper tray selection for first, last, and default pages in a report.

See Also

Tasks

How to: Add GetPaperTrayForReport Procedure in Codeunit 1

Reference

PaperSourceFirstPage Property
PaperSourceLastPage Property


PaperSourceFirstPage Property

Specifies which paper source to use when printing page one of the report.

Applies To

Reports

Remarks

In the Report - Properties window, in the PaperSourceFirstPage field, choose the paper source. The list contains 13 standard trays and 16 printer-specific trays. It is based on information in the fin.stx file.

If the printer that is used for this report does not support the specified paper source, then the printer uses the default tray that is specified by the printer driver.

If you do not specify a value for the PaperSourceFirstPage property, then the printer uses the tray that is specified in the PaperSourceDefaultPage Property.

If you do not specify a value for either the PaperSourceFirstPage property or the PaperSourceDefaultPage Property, then the printer uses the default printer tray that is defined for the operating system.

The printer specific trays that are contained in the list are intended for use with printers that have other paper sources than the standard ones that are listed in the property.

The settings in the Print and Page Setup dialog boxes override the value that is specified for the PaperSourceFirstPage property.

You can use the GetPaperTrayForReport function in codeunit 1, Application Management, to set the paper tray from C/AL code. This gives you runtime control over paper tray selection for first, last, and default pages in a report.

See Also

Tasks

How to: Add GetPaperTrayForReport Procedure in Codeunit 1

Reference

PaperSourceDefaultPage Property
PaperSourceLastPage Property


PaperSourceLastPage Property

Specifies which paper source to use when printing the last page of the report.

Applies To

Reports

Remarks

In the Report - Properties window, in the PaperSourceLastPage field, choose the paper source. The list contains 13 standard trays and 16 printer-specific trays. It is based on information in the fin.stx file.

If the printer that is used for this report does not support the specified paper source, then the printer uses the default tray that is specified by the printer driver.

If you do not specify a value for the PaperSourceLastPage property, then the printer uses the tray that is specified in the PaperSourceDefaultPage Property.

If you do not specify a value for either the PapersourceLastPage property or the PaperSourceDefaultPage property, then the printer uses the default printer tray that is defined for the operating system.

The printer specific trays that are contained in the list are intended for use with printers that have other paper sources than the ones listed in the property.

The settings in the Print and Page Setup dialog boxes override the value that is specified for the PaperSourceLastPage property.

You can use the GetPaperTrayForReport function in codeunit 1, Application Management, to set the paper tray from C/AL code. This gives you runtime control over paper tray selection for first, last, and default pages in a report.

See Also

Tasks

How to: Add GetPaperTrayForReport Procedure in Codeunit 1

Reference

PaperSourceDefaultPage Property
PaperSourceFirstPage Property


PartType Property

Sets the content type that can display in a part FactBox.

Applies To

  • Part controls on pages

Remarks

The following table describes the available SubType options.

Option | Description
Page | Select to display a page in the part. You specify the page in the set the PagePartID Property.
System | Select to display a system part that includes either Outlook, Notes, MyNotes, or RecordLinks. You specify the system part using the SystemPartID Property.
Chart | Select to display a chart in the part. You specify the system part using the ChartPartID Property.
Note
System and Chart options are not supported by the Microsoft Dynamics NAV Web client. If the page is displayed in the Microsoft Dynamics NAV Web client, then the property is ignored.

See Also

Reference

PagePartID Property
SystemPartID Property
ChartPartID Property


PasteIsValid Property

Sets whether inserting records into this table using the paste command is enabled.

Applies To

Tables

Property Value

Yes if you want to allow insert by pasting; otherwise, No. The default value is Yes.

Remarks

If records are usually inserted in the table through an external code unit function, set the PasteIsValid property equal to No.

The OnInsert Trigger of the table is executed when a record is inserted by pasting.

See Also

Reference

OnInsert Trigger


PDFFontEmbedding Property

Specifies whether fonts are embedded in PDF files that are generated for reports.

Applies To

  • Reports

    Note
    This property only applies when the report uses an RDLC report layout at runtime. This property is ignored when a Word report layout is used.

Property Value

Option | Description
Default | Uses the Report PDF Embedding setting of the Microsoft Dynamics NAV Server instance to determine whether fonts are embedded in PDF files. For more information, see Configuring Microsoft Dynamics NAV Server. This is the default setting.
No | Fonts are not embedded in PDF files.
Yes | Fonts are embedded in PDF files.

Remarks

This property applies when an RDLC report is saved as a PDF under the following circumstances:

  • On the Microsoft Dynamics NAV client when the user chooses to save a report as PDF from the report's request page or print preview.

    Note
    This property is ignored when a report is saved as PDF from the print preview in the Microsoft Dynamics NAV Web client. In this case, the Microsoft Dynamics NAV Server instance setting is always used.

  • On Microsoft Dynamics NAV Server by the SAVEAS Function or SAVEASPDF Function (Report).

Embedding fonts in a PDF of a report makes sure that the PDF will use the same fonts as the original file, regardless of where the PDF is opened and which fonts are installed on the computer. However, embedding fonts can significantly increase the size of the PDF files. By disabling font embedding, you can decrease the size of the report PDF files.

See Also

Concepts

Running Reports


Permissions Property

Sets whether an object has additional permission required to perform some operations on one or more tables. The operations can be to read, insert, modify, and delete data.

Applies To

  • Codeunits

  • Pages

  • Queries

  • Reports

  • Tables

  • XMLports

Remarks

The license file determines the permissions that users have within Microsoft Dynamics NAV. These permissions are further refined by the security permissions that you grant the different users.

Sometimes the license file only gives you indirect permission to perform operations on certain tables. Security permissions can also be used to give users only indirect permission to certain tables. If you only have indirect permission to, for example, insert data into a particular table, you cannot insert data into this table from the standard user interface. You must use a database object that has been given extra permission to insert data into the table in question.

Note
After you set the Permissions property of an object, only users with direct permission to perform all the extra operations that the object has been given can modify this object.

Do not use the Permissions property to give extra permissions to an object that you would like your users to be able to modify. These users might not have direct permission to perform these operations. This is why you should be careful when you use the Permissions property for tables and pages.

See Also

Concepts

Properties


PopulateAllFields Property

Sets whether fields are filled out automatically with a single filter value when a new record is inserted in a table.

Applies To

  • Pages

Property Value

Yes if you want the fields filled out automatically; otherwise, No. The default is No.

Remarks

Values are inserted in those fields where a currently active filter expression evaluates to exactly one value. Key fields are always populated.

See Also

Concepts

Properties


PreserveWhiteSpace Property

Determines whether white space should be preserved in documents that are imported through an XMLport.

By default, Microsoft Dynamics NAV supports the XML standard by normalizing white space in attribute names and values that are imported through an XMLport. It converts tabs, carriage returns, and spaces to single spaces. It also eliminates leading and trailing white space.

When this property is set to Yes, no normalizations are performed.

Applies To

XMLports

Property Value

No to normalize white space; otherwise, Yes to not normalize white space. The default is No.

See Also

Concepts

Properties


PreviewMode Property

Specifies how the report opens when you preview it.

Applies To

Reports

Property Value

Value | Description
Normal | Specifies that the report opens in the default view mode where you can navigate between entries and so on.
PrintLayout | Specifies that the report opens in the print layout mode that shows how the report will print on paper.

Remarks

In the Report - Properties window, in the PreviewMode field, specify how the report must open in preview mode. The default mode can be different to how the report prints on paper. If you want to make sure that users see the report as it will look on paper, choose PrintLayout.

Regardless of your choice, users can change the display mode in the Print Preview window. For example, if you choose the default mode, users can choose the Print Layout button. However, if the C/AL code for the report uses the PREVIEW function to disable printing from the preview, then users cannot change the display mode to print layout.

See Also

Print Preview

Reference

PREVIEW Function (Report)

Concepts

Report Design Overview
Designing Reports
Printing Reports


PrintOnlyIfDetail Property

Specifies whether to print data in a report for the parent data item when the child data item does not generate any output.

Applies To

Data items

Property Value

Yes if you want print only if the child data item generates output; otherwise, No. The default is No.

Remarks

This property has no effect on a data item that does not have any child data items. If this property is No and there is no record in the child data item that corresponds to the current record in the parent data item, then the report prints data from the current record in the parent data item, even though there is no data for the child data item. If this property is Yes and there is no record in the child data item that corresponds to the current record in the parent data item, then the report does not print data from the current record in the parent data item.

If there are more than two data items, then the report iterates through each parent-child relationship in the same way.

Another way to achieve the result of not printing blank lines is to add a filter on the table. For more information, see SETFILTER Function (Record).

In previous versions of Microsoft Dynamics NAV reports, you could control whether data items without data were printed with the use of body sections in Section Designer. After you upgrade reports in Microsoft Dynamics NAV 2016, verify whether you need to use filters or the PrintOnlyIfDetail property to achieve the same resulting report.

Example

In this example, you create a report to print data from the Sales Header and Sales Line tables. The parent data item is Sales Header. For each record in the Sales Header table, the report iterates through records in the Sales Line table.

The Sales Header table contains the following data.

Document Type | Sell-to Customer No. | No. | …
Order | 38128456 | 101009 | …
Order | 43687129 | 101011 | …
Order | 46897889 | 101013 | …
Order | 46897889 | 101015 | …
Order | 10000 | 101016 | …

The Sales Line table contains the following data.

Document Type | Document No. | Line No. | …
Order | 101009 | 10000 | …
Order | 101009 | 20000 | …
Order | 101013 | 10000 | …

In this example, you set the DataItemLink Property (Reports) to "Document Type=FIELD(Document Type),Document No.=FIELD(No.)". If you set PrintOnlyIfDetail to Yes, then the report outputs the following data.

Document Type | Customer No. | Document No. | Line No. | …
Order | 38128456 | 101009 | 10000 | …
Order | 38128456 | 101009 | 20000 | …
Order | 46897889 | 101013 | 10000 | …

If you set PrintOnlyIfDetail to No, then the report outputs the following data.

Document Type | Customer No. | Document No. | Line No. | …
Order | 38128456 | 101009 | 10000 | …
Order | 38128456 | 101009 | 20000 | …
Order | 43687129 | 101011 |  | …
Order | 46897889 | 101013 | 10000 | …
Order | 46897889 | 101015 |  | …
Order | 10000 | 101016 |  | …

See Also

Reference

PRINTONLYIFDETAIL Function (Report)


ProcessingOnly Property

Sets the value that indicates whether a report produces printed output or only processes data.

Applies To

  • Reports

  • Settings

Property Value

Yes if you want a report that will not produce output; otherwise, No. The default is No.

Remarks

If ProcessingOnly is Yes, then the Print and Preview options on the request page are replaced by an OK button.

See Also

Concepts

Properties


Promoted Property

Sets the value that indicates whether the selected action is promoted to the ribbon.

Applies To

  • Page Actions

Remarks

This feature allows you to make a copy of an action and place it on the ribbon so that it is easier to find.

Available options are Yes/No (Boolean).

On Microsoft Dynamics NAV Tablet client and Microsoft Dynamics NAV Phone client only promoted actions are displayed.

See Also

Tasks

How to: Promote Actions to the Ribbon on Pages

Reference

PromotedIsBig Property


PromotedActionCategoriesML Property

Sets the caption of the group that you are promoting the action to.

Applies To

  • Page actions

Remarks

Promoted actions appear in the ribbon on a page. You promote an action by setting the Promoted Property. Categories allow you to group similar actions under a common caption. You can choose between 10 categories: New, Process, Report, and Category4 through Category10. By default, the category names are used as the captions in the ribbon. For information about changing the captions, see How to: Define Promoted Action Categories Captions for the Ribbon.

See Also

Reference

Promoted Property


PromotedCategory Property

Sets a category for a promoted action.

Applies To

  • Page actions

Remarks

Promoted actions appear in the ribbon on a page. You promote an action by setting the Promoted Property. Categories allow you to group similar actions under a common caption. You can choose between 10 categories: New, Process, Report, and Category4 through Category10. By default, the category names are used as the captions in the ribbon. For information about changing the captions, see How to: Define Promoted Action Categories Captions for the Ribbon.

See Also

Tasks

How to: Promote Actions to the Ribbon on Pages

Concepts

Properties


PromotedIsBig Property

Sets a value that indicates whether the promoted action is displayed on the ribbon with a large icon.

Applies to

  • Page Actions

Remarks

Available options are Yes/No (Boolean).

See Also

Tasks

How to: Promote Actions to the Ribbon on Pages

Reference

Promoted Property


ProviderID Property

Sets the ProviderID for a FactBox.

Applies To

  • Part controls on pages

Remarks

This property enables you to create a link from a Repeater or any other type of control to a Factbox. It could also be used to link two FactBoxes. For example, the Sales Order page (42), uses this property to update the Sales Line FactBox by creating a ProviderID link to the SalesLines FastTab.

See Also

Concepts

Properties


QuickEntry Property

Specifies if the page control should have input focus. The default value of the property is true. To specify that a control can be skipped, change this value to false.

Note
Specifying an expression as the value of the property is not supported.

Applies To

Page fields

Remarks

Apply this property setting to page controls that can be skipped for a faster entry of data. The QuickEntry property is respected when you use the Enter key. Tabbing through a page will sequentially give input focus to all page controls.

On pages, you use the QuickEntry property for groups, parts, fields, and action controls. You can enable or disable them either statically by setting the property to true or false, or dynamically by using a Boolean variable or a Boolean field on the page. The Boolean field on the page can be either a true/false Boolean or a Boolean expression, such as “Credit Limit > Sales YTD”.

Example: Dynamic Property Change Using a Boolean Field

To skip over the Credit Limit (LCY) field on customer cards when the Allow Invoice Discount field is not selected, follow these steps:

  1. Open page 21, Customer Card, with Page Designer.

  2. View the properties of field 22, Credit Limit (LCY).

  3. For the QuickEntry property, enter “Allow Line Disc.” in the Value field.

  4. The Allow Line Disc. field is a Boolean field on page 21, Customer Card.

  5. Save the changes on page 21.

Now, when a user selects the Allow Invoice Disc. check box on a customer card, the Credit Limit (LCY) field receives focus when the user presses Enter to move focus to the field. Otherwise, focus skips over the field when the user presses Enter to move across the customer card.

See Also

Concepts

Properties


ReadState Property

Specifies which records are read and how they are locked when a query is executed.

Applies to

Queries

Property Value

The ReadState property has the following values.

Value Description

ReadUncommitted

Reads all data, regardless of whether it has been committed to the database. This means that the query can read data from table rows that have been modified by another running transaction, but have not yet been committed.

This mode is sometimes referred to as a dirty read. For those familiar with SQL, this translates to reading the data with ‘Read Uncommitted’.

No additional locks are placed on the read data. Because the query does not lock the rows it reads, other transactions can also read, modify, and delete the same data as the query.

Setting the property to ReadUncommitted can improve performance compared to ReadShared and ReadExclusive. However, the query can read data that potentially is rolled back or changed by another transaction when the query is running.

ReadShared

Reads only data that has been committed to the database.

Share locks are placed on all read data, which prevents it from being modified or deleted by other transactions. The locks are held until the current transaction is committed. It is possible for other transactions to read the data.

Note
The Transaction Type of the transaction within which the query is running is not affected.

If you are familiar with SQL, this mode translates to reading the data with Repeatable Read.

ReadExclusive

Reads only data that has been committed to the database.

Update locks are placed on all read data, which prevents it from being modified or deleted by other transactions. It is possible for other transactions to read the data depending on their transaction types.

Note
The Transaction Type of the transaction within which the query is running is not affected.

If you are familiar with SQL, this mode translates to reading the data with UpdLocks.

Remarks

Committed data is data that is saved to the database when a transaction is completed.

The ReadState property will overrule the current transaction type of the data as set by a CURRENTTRANSACTIONTYPE Function (Database) call in the C/AL code because queries ignore the CURRENTTRANSACTIONTYPE function call.

Each query will use the specified ReadState regardless of other queries that have already been executed. This means that you can read uncommitted data and committed data from the same tables in the same transaction. However, the strictest lock placed on a row will remain until the transaction is committed.


RecordSeparator Property

Sets the string that is to be used to separate records.

Applies To

  • XMLports

Property Value

Value | Description
<None> | There will no be RecordSeparator.
<NewLine> (default) | Any combination of CR and LF characters.
<CR/LF> | CR followed by LF.
<CR> | CR alone.
<LF> | LF alone.
<TAB> | Tabulator alone.
Other strings | The literal string entered.

Remarks

The strings in the preceding table must be entered literally, that is, the < and > characters must be entered. These special strings can be combined and can be mixed with other characters.

CR refers to the character with ASCII value 13.

LF refers to the character with ASCII value 10.

You can set the record separator in C/AL code so that the XMLport can import and export records with different separators. For example, if your XMLport must import from a file or stream where one record uses NewLine and another uses TAB, you can change the record separator at run time.

See Also

Concepts

Properties


ReqFilterFields Property

Sets which fields are automatically included on the tab of the request page that is related to this data item. The user can set filters on these fields.

Applies To

  • Data items on reports.

  • Table elements on XMLports.

Property Value

A comma-separated list of field names.

Remarks

You can select fields by choosing the AssistEdit button in the Value field of this property. A user can add other fields to the request page and set filters on these fields. We recommend that you use this property for common filter fields. If the source table of a report has many fields, then it is time-consuming for a user to add fields to the request page.

If you do not want users to add filters on fields, then use one of the following methods:

  • Do not specify any filters in the ReqFilterFields property and specify a key field on which to sort in the DataItemTableView Property.

  • Remove the request page by using the UseRequestPage Property of the report.

See Also

Concepts

Request Pages


ReqFilterHeading Property

Sets a caption for the request page tab that is related to this data item. The value is taken from the ReqFilterHeadingML Property if this property is set.

Applies To

  • Data items on reports.

  • Table elements XMLports.

Property Value

Any valid string. If ReqFilterHeadingML Property is set, then the value for the selected language is used. If ReqFilterHeadingML Property is not set, then the default is the name of the table that is the specified in the DataItemTable Property.

See Also

Concepts

Multilanguage Development


ReqFilterHeadingML Property

Sets the text used as a ReqFilterHeading Property for a request page tab.

Applies To

  • Data items on reports.

  • Table elements on XMLports.

Remarks

ReqFilterHeadingML is multilanguage enabled. This means that it can contain a list of text in different languages. The text that is used will be selected according to the current language setting of the user. The ReqFilterHeadingML property has the following format.

<Language ID>=<ReqFilterHeading>

<Language ID> is a Windows standard three-letter language ID and <ReqFilterHeading> is the caption text for this language. Semicolons separate entries.

You can enter values for the ReqFilterHeadingML property in the following ways:

  • If you enter a ReqFilterHeading, this value will be inserted in ReqFilterHeadingML as the value for the language that is currently selected. If the language is set to Danish when a value is entered in ReqFilterHeading, ReqFilterHeadingML will be updated with a DAN=<value

    > string. You have to use the abbreviated name (DAN for Danish, for example) of the languages.

  • When you choose the AssistEdit button in the ReqFilterHeadingML field, the Multilanguage Editor window opens. This window has two columns: Language and Value. The Language column is populated with all languages defined by Windows. For your convenience, the full names of the languages are displayed. The ReqFilterHeadingML value for a language is added by entering a value in the Value field for that language. To save the values that you set, you must close this window by choosing the OK button. If you close it by pressing the Esc key, then the ReqFilterHeadingML field is not updated.

See Also

Concepts

Multilanguage Development


ReverseSign Property

Changes negative values into positive values and positive values into negative values in a column of a resulting query dataset.

Applies to

Query columns

Note
The ReverseSign property applies only to columns that have a numeric data type. If you set the ReverseSign property on a column that does not have a numeric data type, you will get an error.

Property Value

Yes to reverse the sign of column values; otherwise, No. The default is No.

Remarks

Field values in a database table can be negative numbers, as well as positive. For example, credits are typically stored as negative values to deduct them from the overall balance due. However, for displaying purposes, such as in spreadsheets and charts, you might want these quantities to appear as a positive numbers.

See Also

Tasks

How to: Create Queries


RowSpan Property

Sets the number of rows that a field spans in a GridLayout control.

Applies to

Field controls that are in a GridLayout control on a page.

Property Values

An integer that specifies the number of rows to span the field.

Remarks

When you set a field to span several rows, then the field occupies the cells in the rows below it and existing fields in the occupied cells are moved to the right. For example, the following illustration shows a GridLayout control that consists of four fields arranged in two rows.

GridLayout of 4 fields in 2 rows and 2 columns

If you set Field 1 to span two rows, then the following layout is displayed:

GridLayout showing row span
Important
The RowSpan property is not supported by the Microsoft Dynamics NAV Web client. If the page displays in the Microsoft Dynamics NAV Web client, then the property is ignored and the field will not span any rows.

See Also

Tasks

How to: Arrange Fields in Rows and Columns Using the GridLayout Control


RunPageMode Property

Sets the mode in which the page is run. Choose between View, Edit, or Create.

See Also

Reference

RunObject Property


RunPageLink Property

Sets up a link to the page you are launching.

Applies To

  • Page Actions

Remarks

For example, if the current page is the customer card and you need to provide a way to see the outstanding sales orders for the current customer, you would select RunObject in the PushAction property and use the RunObject Property to run the customer sales orders page. In this property you would select the Customer No. field as the link between the two pages.

For an example of how to use RunPageLink to launch a page from an action in the RoleTailored client, see Walkthrough: Adding Actions to a Customer List Page.

See Also

Reference

RunPageView Property


RunPageOnRec Property

Sets the same record on the page you launch from this control as is already displayed on the current page.

Applies To

  • Page actions

Property Value

Yes if the current record on the page that you will launch from this control is displayed; otherwise, No. The default is No.

Remarks

For example, suppose the current page is the sales order and you are providing a way to see the sales statistics for the current customer. You would select RunObject in the PushAction property and use the RunObject Property to run the sales statistics page. In this property you could select Yes to display the same record on both pages.

See Also

Reference

RunPageView Property
RunPageLink Property


RunPageView Property

Sets a specific table view for the page that you launch from this control.

Applies To

  • Page Actions

Remarks

The table view is the view of the table that you present to the user. You determine what records the user can see by setting filters, determining the sorting order, and selecting the keys.

You can use this property to indicate how information should be sorted.

See Also

Reference

RunObject Property
RunPageLink Property


RunObject Property

Sets the object you want to run immediately when the action is activated.

Applies To

  • Page Actions

Remarks

To use this property, first select RunObject in the PushAction property. Then use this property to select the object you want to run.

Use the following properties to set parameters for the object you want to run:

  • RunPageView Property

  • RunPageLink Property

See Also

Reference

RunPageView Property
RunPageLink Property


RunOnClient Property

Sets whether a .NET object that is defined by a variable is run on the Microsoft Dynamics NAV Windows client or Microsoft Dynamics NAV Server.

Applies To

Variables of the DotNet data type.

Property Values

Yes if you want to run the .NET object on the Microsoft Dynamics NAV Windows client; otherwise, No. The default is No.

Note
The Microsoft Dynamics NAV Web client does not support running the .NET object on the client.

Remarks

The RunOnClient property is part of .NET interoperability in Microsoft Dynamics NAV 2016 that you can use to expand your solution using .NET assemblies. With .NET interoperability, you can call methods and properties in a class of a .NET assembly from C/AL code by defining a variable for the class. When you set the RunOnClient property to Yes, then the class instance that is defined by the variable is instantiated on the Microsoft Dynamics NAV Windows client.

Note
If you set the RunOnClient property to Yes, then the .NET assembly that is used by the variable must be installed on the machine that is running the Microsoft Dynamics NAV Windows client.

See Also

Tasks

How to: Call .NET Framework Types From C/AL Code

Concepts

Extending Microsoft Dynamics NAV Using Microsoft .NET Framework Interoperability


SaveValues Property

Sets whether user-specific control values are saved for this page.

Applies To

  • Pages

Property Value

Yes if user-defined control values are saved; otherwise, No. The default is No.

Remarks

This information is saved in the Page Data Personalization table.

See Also

Concepts

Properties


SecurityFiltering Property

Specifies how security filters are applied to the record.

Applies To

  • Record variables

  • Records on pages, reports, and XMLports

  • Query variables

Property Value

Value | Description
Disallowed | Security filters are not allowed on the record. If any security filters are set, then you receive an error when you run the object that uses this instance of the record.
Filtered | All security filters are applied to this instance of the record.
Ignored | All security filters are ignored for this instance of the record.
Validated | All security filters are applied to this instance of the record and if any code tries to access a record that is outside the range of the security filters, then an error occurs.

Remarks

To change the SecurityFiltering property on a record variable, either select the value in the Properties window of the variable, or specify the value in C/AL code. To change the SecurityFiltering property on an implicit record on a page, report, or XMLport, you must specify the value in C/AL code.

To specify the SecurityFiltering property in C/AL code, use the following syntax.

Copy Code
RecordVar.SecurityFiltering := SecurityFilter::<Disallowed|Filtered|Ignored|Validated>

The value of the SecurityFiltering property on a record takes effect immediately and remains in effect through the lifetime of the variable, or until you change the value.

See Also

Tasks

How to: Set Security Filters

Concepts

Record-Level Security
Security Filter Modes


ShortCutKey Property

Sets a shortcut key for selecting a menu item.

Applies To

  • Menu items

  • Pages

Remarks

Pressing the key you designate with this property provides the same result as clicking the item.

Note
Some shortcut keys have default assignments—for example, Shift+F12 opens the Object Designer. Do not reuse shortcut keys that are already assigned. For a complete list of shortcut keys, see Keyboard Shortcuts in the online Help for your Microsoft Dynamics NAV client.

See Also

Concepts

Properties


ShowAsTree Property

Sets the indentation of rows on a List Page to Tree View. If you enable this property, you can expand or collapse indented rows on a List Page.

Applies To

  • Group controls on pages

Property Value

Yes if a tree view is required; otherwise, No. The default is No.

See Also

Concepts

Properties


ShowCaption Property

Sets whether the text that is specified by the Caption Property is displayed for the control.

Applies To

Field controls on pages

Property Value

Yes if the caption is displayed; otherwise, No. The default is Yes.

See Also

Reference

Caption Property
CaptionML Property


ShowFilter Property

Sets whether the filter pane is shown on a page by default.

Applies To

Pages

Property Values

Yes to show the filter pane; otherwise, No. The default value is Yes.

Remarks

Using customization, a user can override the ShowFilter property setting to show or hide the filter except when the page is displayed in a part of another page, such as a FastTab or FactBox. When the page is displayed in a page part, the ShowFilter property permanently hides or shows the filter pane.


ShowMandatory Property

Sets a value that specifies whether users must enter a value in the selected field or text box. The field is marked on the page with a red asterisk and does not enforce any validation. Once the field is filled, the red asterisk disappears. The ShowMandatory property only controls the UI and overrides any asterisk marking of the NotBlank Property.

The ShowMandatory property can be specified as true, false, or as an expression.

For an example, see the Purchase Invoice page where the Vendor Invoice No field is controlled by the VendorInvoiceNoMandatory expression. VendorInvoiceNoMandatory is a variable that takes the value from the Ext. Doc. No. Mandatory field on the Purchase page and the Payables page.

Important
Using expressions has the limitation that number fields with default values, will be interpreted as having a value, and will not be marked with a red asterisk. For example, on the Customer page, on the Credit Limit (LCY) field, using an expression like Credit Limit (LCY) < 5000 will not result in a red asterisk, even if the value is below 5000, because the field already has a default value.

Also, be aware that while it is possible to use an expression for the ShowMandatory property, the property cannot validate a C/AL function.

Applies to

  • Page fields

Remarks

The ShowMandatory property controls marking the page field with a red asterisk independently of the NotBlank Property. The ShowMandatory property can be used to mark all page fields, but does not enforce any validation of the field. This means that the user will be able to close a page without entering data.

The NotBlank property can be used to mark the UI on primary key fields with a red asterisk and to enforce a validation error. For more information, see NotBlank Property.

See Also

Reference

NotBlank Property


ShowPrintStatus Property

Sets whether a window that shows the printing status of a report when it is run is displayed.

Applies To

Reports

Property Value

Yes if a status window is shown; otherwise, No. The default is Yes.

Remarks

Apart from showing the progress of the report, the window also contains a Cancel button that will cause the processing and printing of the report to terminate, when clicked. If you set ShowPrintStatus to No, the user will not be able to stop the report prematurely.

If the ProcessingOnly Property is Yes, there will be no status dialog box, even if ShowPrintStatus is Yes. If you need a status dialog box, you must create one yourself.

See Also

Reference

ProcessingOnly Property


SignDisplacement Property

Sets a value to shift negative values to the right for display purposes only. You can shift negative values in increments of 1/100 of a millimeter.

Applies To

Text boxes

Remarks

For example, if you enter 600 (6 millimeters) you would see a result similar to:

(+)999888777

(+)123456789

(-) 123456789

(-) 999888777

(+)987654321

See Also

Concepts

Properties


SingleInstance Property

Sets whether a single instance of the codeunit and codeunit variables are instantiated.

Applies To

Codeunits

Property Values

Yes if only one instance of a codeunit that makes it a single instance codeunit is set; otherwise, No. The default is No.

Remarks

When you set this property to Yes on a codeunit, all codeunit variables that use this codeunit use the same instance. That is, all codeunit variables of this codeunit use the same set of internal variables when the code is running on the same client. The codeunit remains instantiated until you close the company.

The following example shows how you can use the SingleInstance property.

Two pages can connect to the same codeunit.

On Page1:

Codeunit1.SetNumber(100);

On Page2:

Number := Codeunit1.GetNumber();

 MESSAGE(Format(Number));

The SingleInstance property in Codeunit1 is set to Yes. Page1 calls a function on Codeunit1 and sets the parameter to 100. Codeunit1 saves this parameter in a local variable. Page2 is now able to get the parameter value (=100) from Codeunit1. A message is displayed.

See Also

Concepts

Properties


SourceExpr Property

Sets the source expression for this control.

Applies To

  • Page Fields

Remarks

A source expression is a C/AL expression that defines where to find the value of a control. The source expression is evaluated when updates are performed. A source expression can be as simple as the name of a table field; it can also be a complex C/AL expression.

See Also

Reference

BitmapList Property


SourceField Property

Sets the field that you want to map XML data to.

Applies To

XMLports

Remarks

This property is only available if you have selected Field in the SourceType Property.

You need to select Table as the SourceType of the parent tag and specify the table in the SourceTable Property.

The SourceField property is related to the DataSource field in XMLport Designer.

When you choose the AssistButton in the Value field for the SourceField property, the window that opens lists all the tables that have been defined as part of this XMLport and you can select a field from one of these tables.

If you have given a table a variable name in the Properties window for that element, this name is displayed in the Field Lookup window.

When you select the variable name that you have given the current table, the selection is displayed in the DataSource field of XMLport Designer and in the Value field of the SourceField property in the following format:

Copy Code
tablevariablename::fieldname

See Also

Reference

SourceType Property
SourceTable Property


SourceTable Property

Sets the ID of the table from which this page will display records.

Applies To

  • Pages

Remarks

Use the up arrow to select the table you want.

See Also

Concepts

Properties


SourceTable Property (XMLports)

Sets the table to which you want to map XML data or the table that you want to export data from.

Applies To

XMLports

Remarks

This property is available if you selected Table in the SourceType Property.

The values of the VariableName Properties and the SourceTable properties correspond to the contents of the DataSource field in XMLport Designer. The values that you enter in these properties in the Properties window are shown in the DataSource field in XMLport Designer.

If you have defined a text variable, you can only see the name of the text variable in the DataSource field in the XMLport Designer. For example, if you have defined a table as an XML item, the DataSource field can display the following information.

Properties window SourceTable | Properties window VariableName | XMLport Designer
Customer | <Customer> default | <Customer>(Customer)
Customer | Cust. | Cust.<Customer>

See Also

Reference

SourceType Property
VariableName Properties


SourceTableTemporary Property

Sets whether the source table is a temporary table.

Applies To

  • Pages

Property Value

Yes if you want the source table to be a temporary table; otherwise, No. The default value is No.


SourceTableView Property

Sets the key, sort order, and filter you want to use to determine the view of the source table presented to the user.

Applies To

  • Pages

Remarks

Use the AssistEdit button to help you select the key, sort order, and filter. This property setting is checked when the page is opened.

See Also

Concepts

Properties


SourceTableView Property (XMLports)

Sets the key used to sort data in the source table for the XML item.

Applies To

XMLports

Remarks

The AssistButton in the Value field for this property opens the Table View window that allows you to specify sort order and the key that is used to sort the table data. You can also place a filter on the table.

See Also

Concepts

Properties


SourceType Property

Sets what a particular tag in the XMLport Designer corresponds to in the Microsoft Dynamics NAV database.

Applies To

XMLports

Property Value

Value Description

Text

The XML data in the object denoted by the NodeName Property cannot be mapped directly to the Microsoft Dynamics NAV database or when the database does not need the information. The name of the Text field in the XMLport Designer is put into a global text variable.

This variable functions just like a C/AL Global variable. However, it is not visible in C/AL Globals window but it is visible in the C/AL Symbol Menu.

Table

The object denoted by the NodeName Property corresponds to a Microsoft Dynamics NAV table. You should also select this value when a Microsoft Dynamics NAV table record needs to be initialized.

Field

Access is required to a field in the database. For this selection to be valid, you must first have declared a table as the parent of this object or attribute. Failure to do so will cause an error to occur when you try to compile the XMLport object.

Remarks

This property is directly related to the SourceType field in the XMLport Designer.

See Also

Reference

NodeName Property


SQL Data Type Property

Sets the data type that you want to allow in a code field.

Applies To

Code fields in Microsoft Dynamics NAV with Microsoft SQL Server.

Remarks

The values available are Varchar, Integer, BigInteger, and Variant. Leaving the value set at <Undefined>means that you accept the default setting, which is Varchar.

Note
The Variant option is represented by the SQL_VARIANT SQL data type that has been introduced in SQL Server 2000 and is not supported by SQL Server 7.0. This means that selecting Variant as the SQL Data Type property when creating or modifying a table on SQL Server 7.0 results in an error.

Varchar

If you set SQL Data Type to Varchar, all the values in the field are compared and sorted as character data, including numeric values.

Integer

If you set SQL Data Type to Integer, then the following are true:

  • All the values in the field are compared and sorted as integers. No alphanumeric values can be stored in the field.

  • If you enter negative values in the column outside Microsoft Dynamics NAV using external tools, they cannot be read into Microsoft Dynamics NAV.

  • The value "0" (zero) is used to represent an empty string in Microsoft Dynamics NAV.

  • Non-numeric code values or any numeric values beginning with "0" (zero) cannot be entered in the code field.

Variant

If you set SQL Data Type to Variant, then the following are true:

  • The values in the field are compared and sorted according to their base data type. Numeric values are sorted after alphanumeric values.

  • Data that is entered into the code field in Microsoft Dynamics NAV is stored as either the Varchar or Integer base data type, depending on the value that has been entered.

  • Any value beginning with "0" (zero) can be entered in the code field and is stored as an Integer base data type.

    Note
    You can change the SQL Data Type of a code field from Varchar or Integer to Variant and the data in the column is changed accordingly. You cannot change the SQL Data Type of a code field from Variant to Varchar or Integer, unless there are no rows in the table or unless the field contains only an empty string in every row.

See Also

Reference

Integer Data Type
BigInteger Data Type
Variant Data Type

Concepts

Properties


SQLIndex Property

Sets the actual fields that are used in the corresponding index on SQL Server.

Applies To

Keys

Remarks

This property allows you to define the fields that are used in the SQL index.

The fields in the SQL index can:

  • Differ in number from the fields defined in the key in Microsoft Dynamics NAV—there can be fewer fields or more fields.

  • Be arranged in a different order.

If you use this property to define an index on a key that is not the primary key, then the index that is created contains exactly the fields that you specify and will not be a unique index. A unique index will only be created if it contains all of the primary key fields.

If you use this property to define an index for the primary key, it must include all the fields defined in the primary key. You can add extra fields and you can rearrange the fields to suit your needs.

See Also

Tasks

How to: Define Primary and Secondary Keys


SQLJoinType Property

Sets the data item link type between data items in a query to determine the records that are included in the resulting dataset.

Applies To

  • Query data items

Property Value

The SQLJoinType property has the following values.

Value Description

Left Outer Join

The resulting dataset contains every record from the upper data item table, even if a record does not have a matching value in the lower data item for fields that are linked by the DataItemLink Property (Query).

Inner Join

The resulting dataset contains records from data item tables where a match is found between the fields that are linked by the DataItemLink property of the lower data item.

Right Outer Join

The resulting dataset set contains every record from the lower data item table, even if a record does not have a matching value in the upper data item for fields that are linked by the DataItemLink property.

Full Outer Join

The resulting dataset contains all the records from the upper data item table, and all records from the lower data item, including records that do not have a matching value for columns that are linked by the DataItemLink property.

Cross Join

The resulting dataset contains rows that combine each row from the upper data item table with each row from a lower data item table. Cross joins are also called Cartesian products.

Important
Cross Join does not require any comparisons between fields of data items, so the DataItemLink property must be left blank.

Remarks

When setting up a data item link between two data items, you always set up the SQLJoinType property on the lower data item in Query Designer. To access the SQL advanced options, you open the properties of a data item, and then set the DataItemLinkType property to SQL Advanced Options. The SQLJoinType property appears in the Properties window for the data item.

Except for Cross Join, the SQLJoinType property works together with the DataItemLinkType property to combine records from tables into a dataset. The DataItemLink property sets up "equal to" (=) comparison between two or more fields of the data item tables. When the query is run, the query compares each row of the two data items to find records that having matching values for the fields. Records that have matching field values are combined into a row in the resulting dataset. In some cases, there will be records that do not have matching values. You use the DataItemLinkType Property to include records that do not have matching field values.

For more information about data item links and SQL Advanced Option, see Understanding Data Item Links and SQL Advanced Options for Data Item Link Types.


SQL Timestamp Property

Specifies a field to be a timestamp field.

Applies To

Table Fields

Property Value

Yes if the field is the timestamp field; otherwise, No. The default value is No.

Remarks

Each table in Microsoft Dynamics NAV includes a hidden timestamp field. The timestamp field contains row version numbers for records as maintained in SQL Server. This property exposes the timestamp field in the table object, and enables you to write code against it.

For more information, see How to: Use a Timestamp Field.

See Also

Concepts

Tables


Standard Day/Time Unit Property

Sets the unit of measure that is used when you enter data into duration fields.

Applies To

Fields of the Duration data type.

Remarks

The units of measure that you can enter are: day, hour, minute, second, and millisecond.

The default value is hour.

Duration is always stored as milliseconds.

Note
Even if you change the value of this property, you must enter both the value and the units of measure in the duration field. For example, enter 3 minutes.

See Also

Concepts

Properties


Style Property

Sets a value that determines how text in a field on a page is formatted. For fields that are included in a CueGroup, this property sets the value of the color indicator on the cue.

Applies To

  • Page field controls that contain text.

  • Fields in a CueGroup control.

Property Value

The following table lists the values and their formatting for text and Cues.

Value | Text Formatting | Cue color indicator
Standard | Standard | Standard
StandardAccent | Blue | Not applicable.
Strong | Bold | Not applicable.
StrongAccent | Blue + Bold | Not applicable.
Attention | Red + Italic | Red
AttentionAccent | Blue + Italic | Not applicable.
Favorable | Bold + Green | Green
Unfavorable | Bold + Italic + Red | Red
Ambiguous | Yellow | Yellow
Subordinate | Grey | Grey

Remarks

Note
This information in this topic mainly pertains to formatting the text on page fields. For information about how to use the Style property for configuring Cues, see How to: Set Up Colored Indicators on Cues by Using the Style and StyleExpr Property.

The Style property works together with the StyleExpr Property value to determine whether the field is formatted. If the StyleExpr Property evaluates to true, then the value of the field is formatted as specified by the Style property.

By default, the Style property is not set.

This property is not supported if one of the following data types is used for the SourceExpr of the field:

  • Code

  • Boolean

  • Binary

  • BLOB

  • GUID

  • RecordID

On pages, you use the Style property for group, part, field, and action controls. You can change the formatting of a control either statically by setting the property to true or false, or dynamically by using a Boolean variable or a Boolean field on the page. The Boolean field on the page can be either a true/false Boolean or a Boolean expression, such as “Credit Limit > Sales YTD”.

Example: Dynamic Property Change Using a Boolean Field

To make the value in the Balance (LCY) field on customer cards bold green when line discounts are allowed, follow these steps:

  1. Open page 21, Customer Card, with Page Designer.

  2. View the properties of field 22, Balance (LCY).

  3. For the Style property, enter Favorable in the Value field.

  4. For the StyleExpr property, enter Allow Line Disc. in the Value field.

    The Allow Line Disc. field is a Boolean field on page 21, Customer Card.

  5. Save the changes on page 21.

Now, when a user selects the Allow Line Disc. check box on a customer card, the format of the Balance (LCY) field value changes to bold green. Otherwise, the field is not formatted.

See Also

Tasks

How to: Style Field Text on a Page

Concepts

Properties


StyleExpr Property

Sets whether the format that is specified in the Style Property is applied to text in a field. For fields in a CueGroup control, this property is used to configure the color of the color indicator on the cue.

Important
This note pertains to backward compatibility only. If the property is set to Boolean true or false, it sets whether the format specified in the Style property is applied to text in a field.

Applies To

  • Page field controls that are not of data type Boolean or BLOB.

  • Field controls in CueGroups of data type Boolean, Text, or Codeunit.

Remarks

Note
The information in this topic is mainly applicable to formatting the text of page fields. For information about how to use the StyleExpr property for configuring Cues, see How to: Set Up Colored Indicators on Cues by Using the Style and StyleExpr Property.

You can set StyleExpr to either the name of a variable; a text constant in apostrophes, for example, 'strong'; or, for backward compatibility, to true or false.

If the StyleExpr property evaluates to true, then the value of the field is formatted as specified by the Style Property. You can set the value to true or false, or you can use a variable that evaluates to true or false. The property's default value is false.

Important
You can use a conditional setting of styles by inserting the conditional code in, for example, the OnAfterGetRecord Trigger. Remember to cover all cases in else branches to avoid incorrect styles. For example: if (MyField = 'abc') then   MyStyleVar := 'Ambiguous' else   MyStyleVar := 'Favorable'

Note
To use a variable for the StyleExpr property, the IncludeInDataSet Property of the variable must be set to Yes.

See Also

Tasks

How to: Style Field Text on a Page


SubPageLink Property

Sets a link to a Factbox from a page.

Applies To

  • Pages

Remarks

The link is updated when the current record changes.

For an example of how to use SubPageLink to update the content of a FactBox in the RoleTailored client as different items are selected in a list page, see Walkthrough: Adding a FactBox to the Customer List Page.

See Also

Concepts

Properties


SubPageView Property

Sets the table view for a subpage.

Applies To

  • Pages

Remarks

The table view is the view of the table that you present to the user. You determine what records the user can see by setting filters, determining the sorting order, and selecting the keys.

You can use this property to sort the information in the table for display in this subpage. Use the AssistEdit button to help you set the table view for the subpage.


SubType Property (BLOB)

Sets additional information about what will be contained in the field.

Applies To

BLOB fields

Property Value

Value | Description
Bitmap | For storing bitmaps
Memo | For storing memos
User-Defined (default) | For user defined information

See Also

Concepts

Properties


SubType Property (Codeunit)

Sets the codeunit to function as a normal, test, test runner, or upgrade codeunit.

Applies To

Codeunits

Property Value

Value | Description
Normal | A normal codeunit. This is the default setting.
Test | A test codeunit includes C/AL functions that test the application. For more information, see How to: Create Test Codeunits and Test Functions.
TestRunner | A test runner codeunit manages the execution of one or more test codeunits. For more information, see How to: Create a Test Runner Codeunit.
Upgrade | An upgrade codeunit includes C/AL functions for synchronizing changes to a table definition in an application with the business data table in SQL Server and migrating existing data. For more information, see Upgrade Codeunits.

Remarks

You can create test codeunits and test runner codeunits to test your application.

You write test functions as C/AL code in the test codeunits. When a test codeunit runs, it executes the OnRun function and then executes each test function in the codeunit, records the outcome in a log, and displays the results in a message window. The continuation of the test function run is dependent on successful run of the OnRun function. The difference between a normal codeunit and a test codeunit is their execution at run time. When a normal codeunit is run, if one of its functions fails, then the codeunit is terminated. When a test codeunit is run, if a function fails, then the function is terminated, but the codeunit continues to run the remaining functions.

A test runner codeunit runs the test codeunits that are programmed to run from its OnRun trigger. When a test runner codeunit runs, it does the following:

  • Calls the OnBeforeTestRun Trigger before each test codeunit, and the OnRun function and test function is executed.

  • Calls the OnAfterTestRun Trigger after each test code unit, and the OnRun function and test function is executed.

  • Indicates that a test function has failed if it invokes the user interface.

For more information, see Testing the Application.

See Also

Tasks

How to: Create Test Codeunits and Test Functions
How to: Create Handler Functions
Walkthrough: Testing Purchase Invoice Discounts

Concepts

Testing the Application
Codeunits


SumIndexFields Property

Sets the SumIndexField Technology (SIFT) for the key, if applicable.

Applies To

Keys

Remarks

You can select up to 20 SumIndexFields for each key.

The fields must be of a numeric datatype (Decimal, Integer, BigInteger, or Duration).

Changing existing keys may affect the behavior of the application since other parts of your application may depend on the existence of certain keys.

See Also

Concepts

SumIndexField Technology (SIFT)


SuppressDispose Property

Specifies if a Microsoft .NET Framework object that is defined by a DotNet variable is disposed when it goes out of scope.

Applies to

Local variables of the DotNet data type.

Property

Yes if you do not want to dispose the .NET Framework object when it goes out of scope; otherwise, No. The default is No.

Remarks

When a local .NET Framework object is disposed, it cannot be assigned outside the scope of its local function. If you want to assign the local DotNet variable to a global C/AL or .NET Framework object, then you set the SuppressDispose property to Yes.

See Also

Tasks

How to: Call .NET Framework Types From C/AL Code

Concepts

Calling .NET Framework Members from C/AL


SystemPartID Property

Sets pre-defined system parts.

Applies To

  • Part control on a page

Remarks

The available options are: Outlook, Notes, MyNotes, RecordLinks, or None.

See Also

Reference

PartType Property
PagePartID Property
ChartPartID Property


TableIDExpr Property

Sets the ID of the table to which you want to apply a table filter.

Applies To

Fields

Remarks

The field must be of the TableFilter Data Type. The Table ID expression must be of the Integer Data Type and is typically the Object ID of the table. To understand how this property is applied, see the Permission table.

See Also

Reference

TableFilter Data Type


TableNo Property

Sets the source table number, if any, for this codeunit.

Applies To

Codeunits

Remarks

Use the lookup to select the appropriate table number. If the codeunit can apply to any table, then choose Undefined.

If you specify a table number for this property, then you can use the CurrRec global variable in the codeunit and use the Codeunit.RUN Function (Codeunit) to execute the code unit

See Also

Reference

Codeunit.RUN Function (Codeunit)


TableRelation Property

Sets relationships (links) to other tables. For example, if you want to provide a lookup into another table, enter the name of that table in this property.

Applies To

  • Table Fields

  • Page Fields

Remarks

The TableRelation property lets you establish lookups into other tables. For example, on the Item card you can select a vendor from who you usually purchase an item. This is done through a table relationship.

This property is also used to define where to look to validate entries.

In addition, when you choose the option to test the relationships between primary and secondary indexes, this property defines what to test. This option is one of the Database options on the File menu.

See Also

Reference

ValidateTableRelation Property
TestTableRelation Property


TableSeparator Property

Specifies the table separator for a table.

Applies To

  • XMLports

Property Value

Value | Description
<None> | There is no table separator.
<NewLine> | Any combination of CR and LF characters.
<CR/LF> | CR followed by LF.
<CR> | CR alone.
<LF> | LF alone.
<TAB> | Tabulator alone.
Other strings | The literal string entered.

Remarks

This property specifies how tables should be separated. The default value is a new line (<NewLine>). TableSeparator property is only used if the Format Property is set to Variable Text or Fixed Text. Otherwise, the setting is ignored.

You can set the table separator in C/AL code so that the XMLport can import and export tables with different separators. For example, if your XMLport must import from a file or stream where one table uses a single NewLine elements and another uses two NewLine elements, you can change the table separator at run time.

See Also

Concepts

Properties


Temporary Property

Sets whether a temporary table is created.

Applies To

Record variables

Remarks

Changes made to a temporary table are not stored to a database.

See Also

Concepts

Properties


Temporary Property (Reports)

Sets whether a temporary table is used to store the data set that is returned for columns of a data item.

Applies To

DataItems of reports

Property Value

Yes to use a temporary table; otherwise, No. The default value is No.

Remarks

A temporary table is used as a buffer or intermediate storage for data. A temporary table is not stored in the database, but is only held in memory until the report is closed. A temporary table is useful when the column data is not mapped directly to a field in the database but is instead the result of a process or operation, such as an aggregation of data from several columns. If a temporary table is not used, the data must be handled by C/AL code.

For an example of the use of the Temporary property, see report 1306 in the CRONUS International Ltd. demonstration database.

See Also

Concepts

Temporary Tables
Designing Reports


Temporary Property (XMLports)

Sets whether a temporary table is created to store the records imported using the XMLport.

Applies To

Record variables.

Remarks

If the data that you are importing has a different structure than the table in Microsoft Dynamics NAV that you want to insert it into, you could import the data into a temporary table. The temporary table holds the data in cache without writing it to the database. You can then modify the data before inserting it into the database.


TestIsolation Property

Specifies which changes to the database to roll back after the tests in the test runner codeunit execute.

Applies To

Test runner codeunits. A test runner codeunit has the SubType Property (Codeunit) set to TestRunner.

Property Value

Value | Description
Disabled | Do not roll back any changes to the database. Tests are not isolated from each other. This is the default value.
Codeunit | Roll back all changes to the database after each test codeunit executes.
Function | Roll back all changes to the database after each test function executes.

Remarks

We recommend that you design tests to be independent of each other. Tests might read from and write to the same database, which means that tests can interact with each other. If tests interact, then you may experience incorrect test results. To eliminate test interactions, use the TestIsolation property to roll back changes to the database after each test function or after each test codeunit.

Note
If you specify that you want to roll back database changes, then all database changes are rolled back, including changes that were explicitly committed to the database during the test by using the COMMIT function.

See Also

Tasks

How to: Create a Test Runner Codeunit

Concepts

Testing the Application


TestTableRelation Property

Sets whether to include this field when evaluating field relations between primary and secondary indexes.

Applies To

Fields

Property Value

Yes if you want to test the table relationship for this field; otherwise, No. The default is Yes.

Remarks

You may want to use this property to exclude certain fields from the table relation test. For example, if a table in your application has a field that is a foreign key, but records from the other table may have been deleted, then you would not want to test the relationship with this table. Only set this property to No if you are certain that testing this relationship would only cause errors that do not compromise the consistency of your application tables.

This test is available from the Database option on the File menu. You can use this property to limit the number of relationships that are tested.

If you set the ValidateTableRelation property to No, then you should also set the TestTableRelation property to No. Otherwise, a database test on the field relations in a database may fail.

See Also

Reference

TestTableRelation Property
ValidateTableRelation Property


TextEncoding Property (XMLports)

Specifies the text encoding format to use when you use an XMLport to export or import data as text.

Applies to

XMLports

Note
The TextEncoding property is only available when the Format Property (XMLports) of the XMLport is set to Fixed Text or Variable Text.

Values

  • MS-DOS (default)

  • UTF-8

  • UTF-16

  • Windows

For more information, see Text Encoding.

Remarks

Text encoding is the process of transforming bytes of data into readable characters for users of a system or program. There are several industry text encoding formats and different systems support different formats. Internally, Microsoft Dynamics NAV uses Unicode encoding. For exporting and importing data with an XMLport, Microsoft Dynamics NAV supports MS-DOS, UTF-8, UTF-16, and Windows encoding formats.

You should set the TextEncoding property to the encoding format that is compatible with the system or program that you will be exporting to or importing from. The following sections describe the available text encoding formats.

Tip
You can also set the TextEncoding property in C/AL code. For example, if your XMLport can import or export different formats based on certain conditions, you can change the encoding on the fly depending on the conditions. For example, you can write code such as the following:

currXMLport.TEXTENCODING := TEXTENCODING::Windows;

Example

The following code example illustrates how you can set the encoding during run time.

Copy Code
...
      CASE MyDefinitionTable."File Encoding" OF
        MyDefinitionTable."File Encoding"::"MS-DOS":
          currXMLport.TEXTENCODING(TEXTENCODING::MSDos);
        MyDefinitionTable."File Encoding"::"UTF-8":
          currXMLport.TEXTENCODING(TEXTENCODING::UTF8);
        MyDefinitionTable."File Encoding"::"UTF-16":
          currXMLport.TEXTENCODING(TEXTENCODING::UTF16);
        MyDefinitionTable."File Encoding"::WINDOWS:
          currXMLport.TEXTENCODING(TEXTENCODING::Windows);
...

The code example is based on XMLport 1220 in the CRONUS International Ltd. demonstration database. The table, MyDefinitionTable, has a field, File Encoding, that specifies the encoding for this part of an import.

See Also

Tasks

How to: Create XMLports
Walkthrough: Importing Data from Text Files to Tables

Reference

Format Property (XMLports)

Concepts

XMLports
Text Encoding


TextType Property

Sets the type of text this element or attribute contains.

Applies To

XMLports

Property Value

BigText if you want to display large text ; otherwise, Text. The default is Text.

See Also

Concepts

Properties


ToolTip Property

Sets whether tooltips are provided for the given object. The tooltip value is taken from the ToolTipML Property if this property is set.

Applies To

  • Actions in the ribbon

  • Fields on pages

  • Factboxes

  • Activity buttons

    Note
    Activity button tooltips are only shown on the Microsoft Dynamics NAV Web client.

  • ActionContainers

    Warning
    ActionContainers tooltips are only shown on the Microsoft Dynamics NAV Web client for the subtype HomeItems.

Remarks

The default is an empty string, which means there will be no tooltip.

See Also

Reference

ToolTipML Property

Concepts

Multilanguage Development


ToolTipML Property

Sets the text used for the tooltip of an action, a field, a factbox, or an activity button.

Applies To

  • Actions in the ribbon

  • Fields on pages

  • Factboxes

  • Activity buttons

    Note
    Activity button tooltips are only shown on the Microsoft Dynamics NAV Web client.

  • ActionContainers

    Warning
    ActionContainers tooltips are only shown on the Microsoft Dynamics NAV Web client for the subtype HomeItems.

Remarks

ToolTipML is multilanguage enabled. This means that it can contain a list of strings for use by different languages. The text that is used is selected according to the user's current language setting. For more information, see Multilanguage Development.

The ToolTipML property value has the following format.

Copy Code
<Language ID>=<tooltip>

<Language ID> is a Windows standard three-letter language ID and <caption> is the caption text for this language. Semicolons are used to separate entries.

In the following example, values are set for Danish (DAN) and English (ENG).

Copy Code
DAN=Dette felt indeholder kundens navn;ENG=This field contains the customer name

How to Enter ToolTipML Values

You can enter values for the ToolTipML property in two ways.

  • Enter a ToolTip Property value. This value is inserted in ToolTipML as the value for the language that is currently selected. If the language is set to Danish when a value is entered in ToolTip, ToolTipML is updated with a DAN=<value> string. You have to use the abbreviated language name (for example, DAN for Danish).

  • Choose the AssistEdit button in the ToolTipML Value field to open the Multilanguage editor. This is a page with two columns: Language and Value. The Language column is populated with all languages defined by Windows. Enter tooltip text in the Value field for the appropriate language and then choose the OK button to close the editor. If you press the Esc key to close the editor, the ToolTipML field is not updated.

See Also

Reference

ToolTip Property


TopNumberOfRows Property

Specifies the maximum number of rows to include in the resulting dataset of a query.

Applies to

Query objects

Property Value

An integer that specifies the maximum number of rows to include in the resulting dataset.

Note
A value of 0 is the same as leaving the property blank. If you set the value to 0, then there is no limit and all rows of the dataset are returned.

Remarks

You use the TopNumberOfRows property to limit the resulting dataset to the first set of rows that are generated for the query. For example, you can include only the first 10 or first 100 rows in the resulting dataset. The TOPNUMBEROFROWS property is useful for key performance indicators such as the top number of customers or sales.

You can also specify the number of rows to include in the dataset by calling the TOPNUMBEROFROWS Function from C/AL. The TOPNUMBEROFROWS function will overwrite the TopNumberOfRows property setting.

See Also

Concepts

Properties


TransactionModel Property

Specifies whether data is committed to the database during execution of a test function and whether transactions are rolled back at the end of a test function.

Applies To

C/AL test functions on test codeunits. A test codeunit is a codeunit that has the SubType Property (Codeunit) set to Test.

The TransactionModel property applies to both test functions that use TestPages and test functions that do not use TestPages.

Property Value

Value | Description
AutoCommit | A commit is issued at the end of the test function. If an error occurs during the test function, then the transaction is rolled back. If an error occurs and you catch it with an ASSERTERROR statement, then the transaction is rolled back. If the code that is being tested calls the COMMIT Function (Database) before an error occurs, then the transaction is rolled back only to the point at which the COMMIT was called. AutoCommit is the default value.
AutoRollback | The transaction is rolled back after test execution. Calls to the COMMIT function during a test that is set to AutoRollback fail with an error.
None | Used primarily with TestPages. The test function does not have an open write transaction; therefore, it cannot write to the database. Each interaction with the database occurs through TestPage triggers, which open their own write transactions. At the end of each trigger, if no errors occurred, then any changes are committed to the database. If an error occurred, then changes are rolled back at the end of the transaction.

Remarks

To create meaningful tests, you must first understand how transactions run. In a typical user scenario, a user who is logged on to a client enters data into one field of a page. Then the user enters some data in another field on the page. The user also checks the value of a third field. Finally, the user saves and closes the page. Every time a user enters data into a field, C/AL code may be triggered and a new transaction is automatically started. The trigger code runs within this new transaction. Field data is sent to the server where it is processed and often updated in the database. When the C/AL code in the trigger is finished, the transaction is automatically committed to the database and the page is refreshed with updated data.

When you create test functions that exercise pages that interact with the database, you have the following options for simulating user scenarios and then returning the database to its initial, well-known state:

  • Set the TransactionModel property on the test function to AutoRollback. This assumes that the code that you test does not include calls to the COMMIT function. Any calls to the COMMIT function give you an error. Most business logic does not call the COMMIT function, but relies on implicit commits at the end of the outermost C/AL trigger. The test proceeds as follows:

    1. The test function starts a transaction.

    2. The test function initializes data in the database. Database changes are made in the transaction that was started by the test function.

    3. Fields on the test page are set or updated. Database changes are made in the transaction that was started by the test function.

    4. The test function reads the values of fields on the test page or reads from the database to validate the test.

    5. After the test function is completed, the transaction is rolled back and the database is returned to its initial state.

  • If the code that you test includes calls to the COMMIT function, then set the TransactionModel property on the test function to AutoCommit. The test proceeds as follows:

    1. The test function starts a transaction.

    2. The test function initializes data in the database. Database changes are made in the transaction that was started by the test function.

    3. Fields on the test page are set or updated. Database changes are made in the transaction that was started by the test function.

    4. When the COMMIT function is called, changes are committed to the database.

    5. The test function reads the values of fields on the test page or reads from the database to validate the test.

    6. After the test function is completed, changes are committed to the database. To return the database to its initial state, either you must manually revert the changes by deleting, updating, or inserting records, or you must use the TestIsolation Property on the test runner codeunit to roll back changes.

  • Set the TransactionModel property on the test function to None to simulate the behavior of an actual user. The test function does not start a transaction and cannot write to the database. However, a new transaction is started every time that a field on the page is updated and C/AL code is triggered. At the end of each trigger, changes are automatically committed to the database. You can use this option if your test does not write to the database and you do not have to initialize data in the database before the test starts. For example, use this option for tests that validate calculation formulas or tests that read from the database. The test proceeds as follows:

    1. If a field on the test page is set or updated and C/AL code is triggered, then the test page starts a transaction. At the end of the trigger, changes are committed to the database.

    2. The test function validates the test.

    3. After the test is completed, no transactions are rolled back. To return the database to its initial state, either you must manually revert the changes by deleting, updating, or inserting records, or you must use the TestIsolation Property on the test runner codeunit to roll back changes.

With AutoCommit and AutoRollback, the test function starts a write transaction. Triggers that are invoked by the test code inherit this open transaction instead of running in their own separate transactions. By using the AutoCommit and AutoRollback settings, if several page interactions are invoked from test code, then they share the same transaction. By using the None setting, each page interaction runs in a separate transaction.

See Also

Tasks

How to: Create Test Codeunits and Test Functions

Reference

TestIsolation Property

Concepts

Testing the Application
Testing Pages
C/AL ASSERTERROR Statements


TransactionType Property

Sets the transaction type.

Applies To

  • Database transactions for all C/AL code

Remarks

There are four basic transaction types: Browse, Snapshot, UpdateNoLocks, and Update. Additionally, there is a Report type that maps to the Browse transaction type. Each transaction type defines the behavior of a transaction in Microsoft Dynamics NAV and takes effect from the start of a transaction. A transaction starts at the start of the outermost code or immediately after the COMMIT Function (Database) is called. A transaction ends at the end of the outermost code or when the COMMIT function is called. For example, if a function in a codeunit calls another codeunit, then a new transaction is not started at the start of the second codeunit.

The following table shows transaction behavior with SQL Server.

Transaction Type Behavior

Browse

This is a read-only transaction. Modifications cannot occur within the transaction. All read operations are performed with READ UNCOMMITTED locking. Therefore, no locks are added and locks that are added by other sessions are not honored. This means that the transaction may read uncommitted data.

For more information about READ UNCOMMITTED locking, see SET TRANSACTION ISOLATION LEVEL (Transact-SQL) in the MSDN Library.

Snapshot

This is a read-only transaction. Modifications cannot occur within the transaction. All read operations are performed with REPEATABLE READ locking. Therefore, shared locks are added on all data and are maintained until the end of the transaction. This prevents other transactions from modifying any rows that have been read by the current transaction.

For more information about REPEATABLE READ locking, see SET TRANSACTION ISOLATION LEVEL (Transact-SQL) in the MSDN Library.

UpdateNoLocks

This is an update transaction. Modifications can occur within the transaction. All read operations are performed with READ UNCOMMITTED locking until the table is either modified by a write operation or locked with the LOCKTABLE Function (Record). From this point until the end of the transaction, all read operations are performed with UPDLOCK locking.

For more information about UPDLOCK locking, see Table Hints (Transact-SQL) in the MSDN Library.

This transaction type improves concurrency for all tables that users access within the transaction by delaying locking as much as it can. However, the disadvantage is that you must know when to lock the tables for the required transaction behavior.

This is the default transaction type if you have not specified a type with the CURRENTTRANSACTIONTYPE Function (Database).

Update

This is an update transaction. Modifications can occur within the transaction. All read operations are performed with REPEATABLE READ locking until the table is either modified by any write operation or locked with the LOCKTABLE function. From this point forward, all read operations are performed with UPDLOCK locking.

This transaction type provides full transaction isolation from the start of the transaction, regardless of the lock status of tables that users access within the transaction.

Note
In earlier versions of Microsoft Dynamics NAV, the Snapshot and Update transaction types performed read operations with SERIALIZABLE locking until the table was either modified by a write operation or locked with the LOCKTABLE function. In Microsoft Dynamics NAV 2016, these transaction types perform read operations with REPEATABLE READ locking until the table is either modified by a write operation or locked with the LOCKTABLE function.

Phantom reads cannot occur with SERIALIZABLE locking because the filter range is locked instead of the records. Phantom reads can occur with REPEATABLE READ locking because only the records are locked. You should know this difference when you upgrade from an earlier version to Microsoft Dynamics NAV 2016. For more information about phantom reads, see Concurrency Effects in the MSDN Library.

Report and XMLport objects have a TransactionType property, which you can view and modify in the Properties window. The TransactionType property that is specified on a report or XMLport object is used only when you run the report or XMLport from Object Designer.

See Also

Reference

CURRENTTRANSACTIONTYPE Function (Database)

Other Resources

Isolation Levels in the Database Engine


TryFunction Property

Specifies the function to be try function, which can be used to catch and handle errors and exceptions that occur when code is run.

Applies to

C/AL functions.

Note
In test and upgrade codeunits, this property only applies to normal functions as specified by the FunctionType Property (Test Codeunits) or FunctionType Property (Upgrade Codeunits).

Remarks

Try functions in C/AL enable you to handle errors that occur in the application during code execution. For example, with try functions, you can provide more user-friendly error messages to the end user than those thrown by the system. You can use try functions to catch errors/exceptions that thrown by Microsoft Dynamics NAV or exceptions that are thrown during .NET Framework interoperability operations.

For more information, see Handling Errors by Using Try Functions.

See Also

Concepts

C/AL Function Statements


Unbound Property

Sets whether the element can be repeated an unknown number of times at runtime before the import or export moves on to the next element.

Applies To

  • XMLports.

Property Value

Yes if the element can be unbound; otherwise, No. The default value is No.

Remarks

If you design an XMLport that is used to import or export data in different formats where the number of columns can vary, you can use this property to handle the number of columns.

Warning
If this property is set to Yes, then your code for handling exports must specify when to break to the next element by using the BREAKUNBOUND function.

During an import, the XMLport will automatically move on to the next record when the code reaches a record separator.

For example, your XMLport can export data in two different file formats. One format contains 5 columns, and the other contains 10 columns. Instead of duplicating the maximum number of columns and writing code that skips any redundant columns, you can set up a single column, make it unbound, and then specify in code when to break to the next element.

See Also

Reference

BREAKUNBOUND Function (XMLport)


UpdatePropagation Property

Sets a value that specifies what happens when a main page with a subpage is updated. The UpdatePropagation property is available on part controls and has two options; Subpage and Both. If UpdatePropagation is set to Subpage, an update action will update the subpage only. If UpdatePropagation is set to Both, an update action will update both the main page and the subpage. This is useful if a value on the subpage changes, and you want a main page total to be refreshed automatically.

Applies to

  • Page fields

Remarks

Use the UpdatePropagation property to update a main page total, when the amount on the subpage lines is updated. Add a CurrPage.UPDATE(); call, for example, in the OnValidate trigger on the subpage to have the UpdatePropagation property take effect.


UseDefaultNamespace Property

Specifies whether the value in default namespace should be used for both output and input XML documents.

Applies To

  • XMLports

Property Value

true if the default namespace should be used; otherwise, false. The default is false.

See Also

Concepts

Properties


UseLax Property

Specifies whether an XMLport uses LAX (Lazy API for XML) to process an XML file.

Applies To

  • XMLports

Property Value

Yes if the XMLport uses LAX; otherwise No.

Remarks

Extra elements and attributes are often added to XML documents when they are processed in software systems. If this property is set to Yes, the XML document will be validated as long as the document meets the minimum schema definition. For example, if an XML document contains extra elements and attributes than the schema strictly defines, the document will validated against the schema.

See Also

Concepts

Properties


UseRequestPage Property

Sets whether a request page is presented to the user.

Applies To

  • Reports

  • XMLports

Property Value

Yes if you want to show a request page; otherwise, No. The default is Yes.

Remarks

If UseRequestPage is No, then a request page is not shown. The user cannot choose a sort order or set filters.

You can override the setting of the UseRequestPage property at runtime by setting the ReqWindow parameter of the REPORT.RUN Function, REPORT.RUNMODAL Function, or RUN Function (XMLport).


UseSystemPrinter Property

Sets which printer is suggested when the report is run.

Applies To

Reports

Property Value

Yes if you want the system default printer to be used; otherwise, No. The default is No.

Remarks

The user will be able to select another printer at runtime if the UseRequestPage Property is Yes.

If the UseSystemPrinter property is set to No, but there is no specific printer defined for the User/Report combination, the system default printer will be suggested.

See Also

Reference

UseRequestPage Property


ValidateTableRelation Property

Sets whether to validate a table relationship.

Applies To

  • Fields

Property Value

Yes if you want to validate the table relationship; otherwise, No. The default is Yes.

Remarks

For fields, use this property to determine whether to validate the user's entry based on the information already in the table set up through the TableRelation Property property.

If you want to let users enter any value without validating the entry, then choose No. For example, on the item card, you can specify the vendor that you typically purchase the item from. Set this property to No to allow users to select a vendor that may not already be in the Vendor table.

If you set the ValidateTableRelation property to No, then you should also set the TestTableRelation property to No. Otherwise, a database test on the field relations in a database may fail.

See Also

Reference

TestTableRelation Property


ValuesAllowed Property

Sets the values that are allowed in the field.

Applies To

  • Table Fields

  • Page Fields

Remarks

Separate the values with a semicolon. For example, if you only want the user to enter 1, 3, or 5 in this field, enter 1;3;5 for this property.

The property setting is checked during validation. Validation occurs only if the field or control value is updated through the UI, for example, if a value is updated on a page or if a field is updated in a table. If a field is updated through application code, then the ValuesAllowed property is not validated.

See Also

Concepts

Properties


VariableName Properties

Sets a variable name for the table that you have specified in the SourceTable Property. It is also used to specify a variable name for a text that you have specified in the SourceType Property.

Applies To

XMLports

Remarks

The text or table variables that you define here act the same way as variables that are defined in the C/AL Globals window. However, these variables are only visible in the C/AL Symbol Menu.

The values of the VariableName and SourceTable Property correspond to the contents of the DataSource field in XMLport Designer. The values that you enter in these properties in the Properties window are shown in the DataSource field in XMLport Designer.

If you have defined a text variable, you can only see the name of the text variable in the DataSource field in XMLport Designer.

If you have defined a table as an XML item, the DataSource field can display the following information.

Properties window SourceTable | Properties window VariableName |  | XMLport Designer DataSource field
Customer |  | <Customer> default | <Customer>(Customer)
Customer |  | Cust. | Cust.<Customer>

See Also

Reference

SourceTable Property
SourceType Property


Visible Property

Sets whether to display the page or control.

Applies To

  • Page fields

  • Group and part controls on pages

  • FactBoxes

Property Value

Yes (true on pages) if you want the page or control to be visible; otherwise, No (false on pages). The default is Yes (true on pages).

Remarks

Because this property also applies to containers, such as pages and subpages, if the Visible property for the container is set to No, then controls on the container are also not displayed, even if the Visible property is set to Yes.

On pages, you use the Visible property to show or hide group, part, field, and action controls. You can show or hide the control either statically by setting the property to true or false, or dynamically by using a Boolean variable or a Boolean field on the page. The Boolean field on the page can be either a true/false Boolean or a Boolean expression, such as “Credit Limit > Sales YTD”.

Note
The dynamic options are only possible for group and part controls.

Using a variable for field and action controls requires that the variable be resolved by the OnInit Trigger or OnOpenPage Trigger.

Example: Dynamic Property Change Using a Boolean Field

To hide all payment fields on a customer card when line discounts are allowed, follow these steps:

  1. Open page 21, Customer Card, with Page Designer.

  2. View the properties of the group named Payments, which represents the Payments FastTab.

  3. For the Visible property, enter NOT “Allow Line Disc.” in the Value field.

    The Allow Line Disc. field is a Boolean field on page 21, Customer Card.

  4. Save the changes on page 21.

Now, when a user selects the Allow Line Disc. check box on a customer card, the Payments FastTab is not visible. Otherwise, the FastTab is visible.

See Also

Concepts

Properties


Width Property

Sets the width of the control. Width is set as a number of characters and must be a fixed number when specified.

Applies To

  • Page Fields

  • Table Fields

Remarks

For controls, the width specifies the width of the column. Static controls in the heading inherit the width from the column control.

For example, use the Width property in the RoleTailored client to set decimals so that they do not take up too much space in a grid.

For controls on the RoleTailored client you always have the option of resizing column width in the UI, but when running the Microsoft Dynamics NAV Web client the Width property can be set to a fixed number to increase readability.


Width Property (XMLport)

Sets the width of a data item of an XMLport.

Applies To

Fields (in XMLports)

Remarks

This property is used only if the Format Property (XMLports) is Fixed Text.

The value is an integer that defines the number of characters in the field.

See Also

Concepts

XMLport Properties


WithEvents Property
Important
This property is not supported in Microsoft Dynamics NAV 2016. The property must be set to No, otherwise you will receive an error at runtime.

Applies To

Global variables of the Automation Data Type.

See Also

Reference

Automation Data Type


XMLVersionNo Property

Set which version of XML the XML document conforms to. Two options are available: 1.0 (the default) and 1.1.

Applies To

XMLports

Remarks

The XML version number is inserted into the XML document as the XML declaration, for example, <?xml version="1.0"?>.

See Also

Concepts

Properties


TableType Property

Specifies the table type.

Applies To

  • Tables

Property Value

Value | Description
Normal | Specifies the table as a normal table in the Microsoft Dynamics NAV database. This is the default value.
CRM | Specifies the table as an integration table for integrating Microsoft Dynamics NAV with Microsoft Dynamics CRM. The table is typically based on an entity in Microsoft Dynamics CRM, such as the Accounts entity.
ExternalSQL | Specifies the table as a table or view in SQL Server that is not in the Microsoft Dynamics NAV database.

Remarks

Tables that are marked as CRM or ExternalSQL are considered to external tables that are not managed by Microsoft Dynamics NAV. These tables use a different SQL Server connection than the normal tables in the Microsoft Dynamics NAV database. For more information, see External Tables.

Important
We advise against creating tables of type CRM manually. Instead, use the integration mapping functionality. For more information, see Integration Concepts and Terminology.

See Also

Reference

Table Designer

Concepts

External Tables
Properties


ExternalName Property

Specifies the name of the original table in the external database.

Specify this property if the original name is different from the name that you specify in the Name property. This means that you can use a different name for the table in Microsoft Dynamics NAV.

Applies To

  • Tables

Property Value

The name of the table in the external database.

Remarks

This property appears when you specify CRM or ExternalSQL in the TableType property. These tables use a different SQL Server connection than the normal tables in the Microsoft Dynamics NAV database.

See Also

Integrating Microsoft Dynamics CRM in Microsoft Dynamics NAV

Reference

TableType Property
ExternalSchema Property
Name Property
Table Designer

Concepts

Properties
External Tables


ExternalSchema Property

Specifies the name of the database schema of the external database.

Applies To

  • Tables

Property Value

The name of the schema of the external database.

Remarks

This property appears when you specify ExternalSQL in the TableType property. These tables use a different SQL Server connection than the normal tables in the Microsoft Dynamics NAV database.

See Also

Integrating Microsoft Dynamics CRM in Microsoft Dynamics NAV

Reference

TableType Property
ExternalSchema Property
Name Property
Table Designer

Concepts

Properties
External Tables


Triggers

Triggers are available for the different objects in Microsoft Dynamics NAV 2016 as described in the following sections:

  • Report and Data Item Triggers

  • Table and Field Triggers

  • XMLport Triggers

  • Page and Action Triggers

  • Codeunit Triggers

  • Query Triggers

See Also

Concepts

C/AL Functions
Properties
Triggers Overview


Report and Data Item Triggers

In reports, triggers are typically used to perform calculations and verification. Triggers let you control how data is selected and retrieved in a more complex and effective way than you can achieve by using properties.

Report Triggers

The following table lists triggers that apply to the report itself.

Trigger | Executed
OnInitReport Trigger | When the report is loaded.
OnPreReport Trigger | Before the report is run, but after the RequestPage has been run.
OnPostReport Trigger | After the report has run, but not if the report was stopped manually or by the QUIT Function (Report, XMLport).

Data Item Triggers

The following table lists triggers that apply to each data item on the report.

Trigger | Executed
OnPreDataItem Trigger | Before the data item is processed, but after the associated variable has been initialized.
OnAfterGetRecord (Data Items) Trigger | When a record has been retrieved from the table.
OnPostDataItem Trigger | When the data item has been iterated for the last time.

See Also

Concepts

Report Triggers
Triggers


OnAfterGetRecord (Data Items) Trigger

Executed each time a record is retrieved from the data item.

Applies To

Data items

Remarks

Use this trigger to perform any processing that is needed, based on the values in the fields of the individual records of a data item.

If the record contains FlowFields, you can put CALCFIELDS Function (Record) statements in this trigger to have them calculated. While it is normally easier to use the CalcFields Property to have it done automatically, there are situations where you have to use this trigger to perform the calculation explicitly. For example, if you apply FlowFilters based on the context of the report or the XMLport to the FlowFields inside this trigger, you need to recalculate the FlowFields after you have applied the FlowFilters.

Another example is when you need to retrieve information from a table that is external to the report or XMLport. This is the situation when the records of a data item contain fields that are foreign keys (that is, fields that are primary keys in other tables), and you want to extract further information from the related tables. For example, in a report, the records in a data item might contain a field with a Vendor code, while you want to print the full name and address of the vendor. You use this trigger to retrieve the information in order to print it in your report.

See Also

Concepts

Triggers
FlowFilter Overview


OnInitReport Trigger

Executed when the report is loaded.

Applies To

Reports

Remarks

This trigger is executed before the request page is run and before any table views or filters are set. This trigger performs any processing that is required before the report is run, such as initializing global variables. It can also stop the report.

See Also

Concepts

Triggers


OnPreReport Trigger

Executed before a report is run.

Applies To

Reports

Remarks

This trigger executes after the request page is run. The table views and filters for the report data items are set while this trigger is executed. As this trigger is executed after the request page is processed, you have access to any filters the user has set. If you want to print the settings of these filters in the report, you can retrieve them using the following text string.

Copy Code
ReportFilter := SomeRecord.GETFILTERS;

Use the ReportFilter text string as the source expression for a control in a section of the report.

See Also

Reference

GETFILTERS Function (Record)


OnPostReport Trigger

Executed after a report is run.

Applies To

Reports

Remarks

This trigger is executed after all data items are processed. The trigger is not run if the report was stopped manually or by using the QUIT function before processing had concluded.

Because this trigger is executed after the report is processed, you can use it to inform users about the result of the report run. For example, if some records could not be processed, you could inform the user of this using the following code in this trigger.

Copy Code
IF ProblemsInReport THEN
MESSAGE(Text000, NumberOfErrors);

Create the following text constant in the C/AL Globals window.

Text constant | ENU value
Text000 | '%1 records were not processed'

Because this trigger is executed before the End Write Transaction, you can also give the user the opportunity to roll back changes to the database by leaving the report with the QUIT Function (Report, XMLport).

See Also

Reference

QUIT Function (Report, XMLport)


OnPreDataItem Trigger

Executed before a data item is processed.

Applies To

Data items

Remarks

This trigger is executed before a data item is processed, but after the associated variable is initialized and table views and filters are set.

You can use this trigger to add additional filtering beyond what is established by the DataItemLink Property (Reports) or DataItemTableView Property. For example, use this trigger if you need to filter an indented data item based on the result of a calculation. Use the SETRANGE Function (Record) or SETFILTER Function (Record) function to add extra delimiters.

See Also

Reference

DataItemLink Property (Reports)
DataItemTableView Property
SETRANGE Function (Record)
SETFILTER Function (Record)


OnPostDataItem Trigger

Executed after a data item is processed.

Applies To

Data items

Remarks

This trigger executes after the last record in the data item is processed but before the OnPostReport Trigger or the OnPostXMLport Trigger is executed, if it is the last data item of the report or XMLport.

Use this trigger to perform any cleanup or post processing needed after a data item is processed. For example, if you create a non-printing report where records are updated, you can update all the records with the modification date like this.

Copy Code
MODIFYALL("Modification Date",TODAY);

See Also

Reference

OnPostReport Trigger


Table and Field Triggers

Microsoft Dynamics NAV recognizes certain actions that happen to a table when you use it, for example, that you insert or modify data. In response, you can set up Microsoft Dynamics NAV to execute C/AL code defined in a trigger. Triggers are predefined functions that are executed when certain actions happen. The bodies of these functions are initially empty and must be defined by the developer. Defining C/AL code in triggers allows you to change the default behavior of Microsoft Dynamics NAV.

The triggers in a table can be divided into two categories:

  • Table triggers

  • Field triggers

Tables have the following triggers.

Table trigger | Executes when
OnInsert Trigger | A new record is inserted into the table.
OnModify Trigger | A record in the table is modified.
OnDelete Trigger | A record in the table is deleted.
OnRename Trigger | A record is modified in a primary key field.

Fields have the following triggers.

Field trigger | Executes when
OnValidate (Fields) Trigger | Data is entered in a field or when the VALIDATE Function (Record) is executed.
OnLookup (Fields) Trigger | Lookup is activated.

See Also

Tasks

How to: Define or Modify Table or Field Triggers


OnDelete Trigger

Executed when a user tries to delete a record.

Applies To

Tables

Remarks

This trigger executes before the default delete behavior. The record is not deleted if an error occurs in the trigger code.

See Also

Concepts

Triggers


OnInsert Trigger

Executed when a user inserts a new record into the table.

Applies To

Tables

Remarks

This trigger is executed before default insert behavior occurs. The new record is not inserted if an error occurs in the trigger code.

In tables where records are entered in pages that have the DelayedInsert Property set to Yes, we recommend that you write any code that is in an OnInsert trigger so that it will always succeed. For example, this applies to journal lines.

See Also

Reference

PasteIsValid Property

Concepts

Triggers


OnModify Trigger

Executed when a user modifies an existing record in a table.

Applies To

Tables

Remarks

This trigger is executed before the default modify behavior is executed. If an error occurs in the trigger code, the record changes are canceled.

We recommend that you do not include code that can stop the user from recording a change in the OnModify trigger on a table. For example, do not include code for displaying error messages. If a user has previously changed the contents of some fields in a record, then these changes must always be accepted by the system.

See Also

Concepts

Triggers


OnRename Trigger

Executed when a user tries to rename a record.

Applies to

Tables

Remarks

When you rename a record in one location, it is updated in all other locations. The OnRename trigger executes before the rename occurs. The record is not renamed if an error occurs in the trigger code.

See Also

Concepts

Triggers


OnLookup (Fields) Trigger

Causes the system to display a lookup page.

Applies To

Fields

Remarks

There are three lookup options:

  1. Default Lookup - The lookup into the table is performed without applying filters or other special parameters.

  2. Field Lookup - You can use this trigger to define a field lookup that will be used in place of the default lookup.

  3. Text box Lookup - You can use the OnLookup (Page fields) Trigger to define a lookup based on the value of a text box. This value will be used in place of the default lookup or the field lookup.

When using this trigger, follow this approach:

  • Use the field value to determine what filters or other parameters to apply.

  • Run the lookup page as a modal page.

  • Transfer the value the user selects back to the field when the user chooses OK.

If an error occurs in the trigger code, the lookup page is closed.

See Also

Reference

OnLookup (Page fields) Trigger


OnValidate (Fields) Trigger

Executed when user input is validated.

Applies To

Fields

Remarks

This trigger is executed after the default validation behavior. An error message displays if an error occurs in the trigger code. In case of an error, the user entry is not written to the database.

See Also

Concepts

Triggers


XMLport Triggers

The following triggers apply to XMLports.

XMLport Triggers

XMLport trigger | Executed
OnAfterAssignField Trigger | Executed after a field has been assigned a value and before it is validated and imported. This trigger is only used to import data.
OnAfterAssignVariable Trigger | Executed after the value defined in the XML document is assigned to the text variable. This trigger is only used to import data.
OnAfterGetField Trigger | Executed after a field is passed to the XML document. This trigger is only used to export data.
OnAfterGetRecord (XMLports) Trigger | Executed after a record is retrieved from a table and before it is exported to the XML document. This trigger is only used to export data.
OnAfterInitRecord Trigger | Executed after a record is loaded. This trigger is only used to import data.
OnAfterInsertRecord Trigger | Executed after a record has been inserted into a database table. This trigger is only used to import data.
OnBeforeInsertRecord Trigger | Executed after a record has been loaded and before it is inserted into a database table. This trigger is only used to import data.
OnBeforePassField Trigger | Executed before a field is passed to the XML document. This trigger is only used to export data.
OnBeforePassVariable Trigger | Executed after the source expression has been formatted into a text variable and before the text variable is passed to the XML document. This trigger is only used to export data.
OnInitXMLport Trigger | Executes when the XMLport is loaded and before any table views and filters are set.
OnPreXMLport Trigger | Executed after the table views and filters are set and before the XMLport is run.
OnPostXMLport Trigger | Executes after the XMLport is run.
OnPreXMLItem Trigger | Executed after the table is initialized and before you start exporting data to an XML object. This trigger only applies to XMLport elements that have a source type of Table. This trigger is only used to export data.

See Also

Tasks

How to: Define or Modify Table or Field Triggers


OnAfterAssignField Trigger

Executed after a field has been assigned a value and before it is validated and imported.

Applies To

XMLports

Remarks

This trigger is only used to import data. It gives you access to the values in the imported record and is typically used to manipulate data that is being imported.

See Also

Concepts

Triggers


OnAfterAssignVariable Trigger

Executed after the value defined in the XML document is assigned to the text variable.

Applies to

XMLports

Remarks

This trigger is only used to import data and gives you access to the imported value in text format.

See Also

Concepts

Triggers


OnAfterGetField Trigger

Executed after a field is passed to the XML document.

Applies To

XMLports

Remarks

This trigger is only used to export data. This trigger gives you access to the field value in the record just before it is exported and is typically used to manipulate the field.

See Also

Concepts

Triggers


OnAfterGetRecord (XMLports) Trigger

Executed after a record is retrieved from a table and before it is exported to the XML document.

Applies To

XMLports

Remarks

This trigger is only used to export data. It is typically used to manipulate the fields that are being exported from the table and to calculate the variables that depend on the record.

See Also

Concepts

Triggers


OnAfterInitRecord Trigger

Executed after a record is loaded.

Applies To

XMLports

Remarks

This trigger is only used to import data. It is typically used to set up the preconditions for the record before it is inserted into the database table.

See Also

Concepts

Triggers


OnAfterInsertRecord Trigger

Executed after a record has been inserted into a database table.

Applies To

XMLports.

Remarks

This trigger is only used to import data and can be used to move data from temporary tables to real tables.

If the AutoSave Property is No, then although the record is not inserted automatically, the OnAfterInsertRecord trigger is still called after the insertion would have occurred.

See Also

Concepts

Triggers


OnAfterModifyRecord Trigger

Executed after a record has been modified.

Applies To

XMLports

Remarks

This trigger is used when you import data from an XMLport and then update an existing record in a table with the data from the XMLport.

If the AutoSave Property is No, then although the record is not modified automatically, the OnAfterModifyRecord trigger is still called after the modification would have occurred.

See Also

Reference

OnAfterInsertRecord Trigger
OnBeforeModifyRecord Trigger
OnBeforeInsertRecord Trigger
AutoReplace Property
AutoSave Property
AutoUpdate Property


OnBeforeInsertRecord Trigger

Executed after a record has been loaded and before it is inserted into a database table.

Applies To

XMLports

Remarks

This trigger is only used to import data. It is typically used for evaluation or calculations before the record is inserted into the database table.

If the AutoSave Property is No, then although the record is not inserted automatically, the OnBeforeInsertRecord trigger is still called before the insertion would have occurred.

See Also

Concepts

Triggers


OnBeforeModifyRecord Trigger

Executed after a record is read from the input stream and before the existing record in the database is modified.

Applies To

XMLports

Remarks

This trigger is used when you import data from an XMLport and then update an existing record in a table with the data from the XMLport.

If the AutoSave Property is No, then although the record is not modified automatically, the OnBeforeModifyRecord trigger is still called before the modification would have occurred.

See Also

Reference

OnAfterModifyRecord Trigger
OnAfterInsertRecord Trigger
OnBeforeInsertRecord Trigger
AutoReplace Property
AutoSave Property
AutoUpdate Property


OnBeforePassField Trigger

Executed before a field is passed to the XML document.

Applies To

XMLports

Remarks

This trigger is only used to export data. This trigger gives you access to the field value in the record just before it is exported and is typically used to manipulate the field.

See Also

Concepts

Triggers


OnBeforePassVariable Trigger

Executed after the source expression has been formatted into a text variable and before the text variable is passed to the XML document.

Applies To

XMLports

Remarks

This trigger is only used to export data and is typically used to manipulate the text variable.

See Also

Concepts

Triggers


OnInitXMLport Trigger

Executed when the XMLport is loaded and before any table views and filters are set.

Applies To

XMLports

See Also

Concepts

Triggers


OnPreXMLport Trigger

Executed after the table views and filters are set and before the XMLport is run.

Applies To

XMLports

See Also

Concepts

Triggers


OnPostXMLport Trigger

Executed after the XMLPort is run.

Applies To

XMLPorts

Remarks

This trigger is executed after all data items are processed.

See Also

Concepts

Triggers


OnPreXMLItem Trigger

Executed after the table is initialized and before you start exporting data to an XML object. This trigger only applies to XMLPort elements that have a source type of Table.

Applies To

XMLports

Remarks

This trigger is only used to export data. It is typically used to set filters on the data and to initialize variables before finding the first record.

See Also

Concepts

Triggers


Page and Action Triggers

Page triggers allow you to use C/AL code to control the behavior of the system as a result of an event on the page, such as a page opening or a field changing its value. You typically use page triggers for advanced validation and logic.

Page triggers can be divided into three categories:

  • General page triggers that apply to the entire page

  • Field page triggers that apply to a field control on a page

  • Action triggers that apply to an action on a page.

Important
If you define two functions that have the same name, one defined in a page and the other in a table that is referenced by the page, you cannot invoke the function defined in the page directly. By default, a call to the function invokes the function that is defined in the table. This behavior occurs when the function is called from a source expression or a trigger.

General Triggers

The following table lists triggers that apply to the entire page.

Page trigger name | Executed
OnInit Trigger | When the page is loaded, but before the controls are available.
OnOpenPage Trigger | When the page is initialized and the controls are available.
OnClosePage Trigger | When the page about to close and after OnQueryClosePage Trigger trigger.
OnFindRecord Trigger | When the page is opened and a record is retrieved from a table.
OnNextRecord Trigger | When the page changes from displaying one record to another record in a table. For example, on a Customer card page, this happens when a user selects Next (Ctrl+Page Down) or Previous (Ctrl+Page Up).
OnAfterGetCurrRecord Trigger | After the current record is retrieved from the table.
OnAfterGetRecord Trigger | When a record has been retrieved but not yet displayed.
OnNewRecord Trigger | When a new record has been initialized but not yet displayed.
OnInsertRecord Trigger | When a new record is about to be inserted in the table.
OnModifyRecord Trigger | When a record is about to be modified in the table.
OnDeleteRecord Trigger | When a record is about to be deleted from the table.
OnQueryClosePage Trigger | When the page is about to close, but before the OnClosePage Trigger.

Field Triggers

The following table describes the triggers that are available on field controls.

Control trigger | Executed
OnValidate (Page fields) Trigger | When the user changes the value in a field and then selects away from the field so that the field loses focus.
OnLookup (Page fields) Trigger | When the user requests a lookup by clicking a field's lookup button or pressing F4.
OnDrillDown Trigger | When the user requests a drill-down by choosing the field's drill-down button or pressing Shift+F8.
OnAssistEdit Trigger | When the user requests assist-edit by choosing an AssistEdit button or by pressing Shift+F4.
OnControlAddin Trigger | When a control add-in is initiated on a page.

Action Triggers

The following table lists triggers that apply to actions on a page.

Triggers | Executed
OnAction Trigger | When an action is initiated on a page.

See Also

Concepts

Triggers


OnAction Trigger

Executed when a user selects an action on a page.

OnAction()

Applies To

  • Page actions

Remarks

This is called after the action properties, such as the RunObject Property, are invoked.

You typically use the RunObject Property to run objects such as pages, reports, and codeunits from an action. You can use the OnAction trigger when you require more processing than the RunObject Property can support, such as filtering data before a page is displayed or writing to the database.

Note
The OnAction trigger is not used on Role Center pages. If you add C/AL code to the trigger, the Role Center page will compile, but the C/AL code will be ignored at runtime.

See Also

Concepts

Page and Action Triggers


OnAfterGetCurrRecord Trigger

Executed after the current record is retrieved from the table.

Applies To

Pages

Remarks

In a page with a repeater, the trigger is only called when the current record in the repeater is updated. OnAfterGetCurrRecord is called directly after all OnAfterGetRecord triggers are called for each row in a list.

If there is an error in the trigger code, then the page is closed.

See Also

Concepts

Triggers


OnAfterGetRecord Trigger

Executed after a record is retrieved from a table but before it is displayed to the user.

Applies To

Pages

Remarks

Use this trigger to calculate variables that depend on the current record.

If there is an error trigger code, then the page is closed.

See Also

Concepts

Triggers


OnAssistEdit Trigger

Executed in place of the AssistEdit Property features that are provided in Microsoft Dynamics NAV.

Applies To

Fields on pages

Note
The trigger is not invoked on a page that is in view mode in the Microsoft Dynamics NAV Web client.

Remarks

If there is an error in the trigger code, then the page is closed.

You can use this trigger to write to the database.

See Also

Concepts

Triggers


OnClosePage Trigger

Executed as a page closes after the OnQueryClosePage Trigger is executed.

OnClosePage()

Applies To

  • Pages

Important
The OnClosePage trigger is not fully supported by the Microsoft Dynamics NAV Web client. When the page displays in the Microsoft Dynamics NAV Web client, the trigger is only invoked when the page is hosted in a modal popup window (MPO).

Remarks

This trigger is initiated by a user action, such as when the user chooses the Close button, or by the CurrPage.CLOSE function being called.

You can write to the database from this trigger.


OnControlAddin Trigger

Executed when a control add-in on the Microsoft Dynamics NAV Windows client page sends event information to the server-side business logic. You add C/AL code to process the data that is sent with the event.

OnControlAddin(Index ; Data)

Parameters

Index

Type: Integer

An integer identifier that a control add-in sends with the event.

Data

Type: Text or BigText

A text string that a control add-in sends with an event.

Note
The data type is determined by the binding target that is specified in the SourceExpr Property of the page field control. If the binding target is of type BigText, then the Data parameter is BigText. Otherwise, the Data parameter is Text

Applies To

  • Page field controls

Remarks

An example of an event is when a user chooses a button in the control add-in user interface or when a user changes a value in a field. A control add-in can use events like these to invoke the OnControlAddin trigger and pass information as an integer in the Index parameter and as a text string in the Data parameter. To process the information, you add the C/AL code to the OnControlAddin trigger. For more information, see Exposing Events and Calling Respective C/AL Triggers from a Windows Client Control Add-in.

Example

The following is an example of C/AL code on a OnControlAddin trigger that takes a text string that is received from a control add-in event and then displays the text string in a message window. Because the information is a text string, the Data parameter is used. To see how to develop and use a sample control add-in that implements this event, see Walkthrough: Creating and Using a Windows Client Control Add-in.

Copy Code
Message(Data);

See Also

Tasks

How to: Set Up a Windows Client Control Add-in on a Page

Concepts

Windows Client Control Add-in Overview
Developing Windows Client Control Add-ins
Exposing Events and Calling Respective C/AL Triggers from a Windows Client Control Add-in


OnDeleteRecord Trigger

Executed before a record is deleted from the table.

[Ok]:= OnDeleteRecord

Return Value

Ok

(Boolean) If true, the record is deleted. If false, the record is not deleted. This value is checked after each function call.

Applies To

  • Pages

Remarks

The action is canceled but the page is not closed if an error occurs in the trigger code. You can use this trigger to write to the database.

See Also

Concepts

Triggers


OnDrillDown Trigger

Overrides the default drill-down behavior defined in the table definition for the FlowField.

Applies To

Fields on pages

Note
The OnDrillDown trigger is not invoked on fields in a Repeater control in the Microsoft Dynamics NAV Web client.

Remarks

If there is an error in the trigger code, the drilldown is canceled. You can use this trigger to write to the database.

This trigger overrides the DrillDownPageID Property setting of the FlowField.

See Also

Concepts

Triggers


OnFindRecord Trigger

Overrides the default page behavior and enables you to specify which record you want to display when the page opens.

[Ok]:= OnFindRecord(Which)

Parameters

Which

Text or code value with the following options:

Parameter Value | Result
- (a dash) | First record
+ (a plus sign) | Last record
=>< | Record defined in the Rec variable or the closest match

Return Value

Ok

(Boolean) Indicates whether the specified record was found.

Value | Result
TRUE | Found
FALSE | Not found (default)

Applies To

  • Pages

Remarks

By default, opened pages display the last record shown when the user exited the page. Use this trigger to override the default behavior and display the first record, last record, or a specific record as defined in the Rec variable.

See Also

Concepts

Triggers


OnInit Trigger

Initializes the user-defined variables on the page.

Applies To

Pages

Remarks

The C/AL code in this trigger is executed immediately after the variables are cleared and the page is loaded. This trigger cannot be used to access the controls on the page. You can change properties that are dynamic, including those properties that can only be changed when the page is opened.

After this trigger is executed, the OnOpenPage Trigger for pages is called. If an error occurs in the trigger code, then the page is closed.

Note
The OnInit trigger does not support calls to control add-in methods and properties because the trigger is invoked before the page is instantiated. For more information see, Exposing Methods and Properties in a Windows Client Control Add-in.

See Also

Concepts

Triggers


OnInsertRecord Trigger

Executed before a new record is inserted into the table.

[Ok]:= OnInsertRecord(BelowxRec)

Return Value

BelowxRec

(Boolean) This return value indicates whether the new record was inserted after the last record in the table (xRec) or not. If false, the record was inserted between an existing record and the last record. If true, the record was inserted below the last record in the table (xRec).

Ok

(Boolean) Indicates whether a new record should be inserted. The return value is checked after each function call. If true, the record is inserted. If false, the record is not inserted.

Applies To

  • Pages

Remarks

If an error occurs in the trigger code, the action is canceled, but the page is not closed. The user cannot enter any new data and an error is shown in the message bar.

See Also

Concepts

Triggers


OnLookup (Page fields) Trigger

Executed in place of the normal lookup features for the current page.

OnLookup(TextString)

Parameters

TextString

Text string entered into the text box and used as the lookup value.

Applies To

Fields on pages

Remarks

There are three lookup options:

  • Default Lookup - The lookup into the table is performed without applying filters or other special parameters.

  • Field Lookup - You can define a lookup trigger on a field that will be used in place of the default lookup. For more information, see OnLookup (Fields) Trigger.

  • Text box Lookup - You can use this trigger to define a lookup based on the value of a text box. This value will be used in place of the default lookup or the field lookup.

For example, for the Customer Code field, a lookup into the Customer table is provided. If you want a lookup into another table or if you want to place a filter on the table before displaying the lookup, use this trigger.

If an error occurs in the trigger code, the lookup is canceled.

You can use this trigger to write to the database.

Note
OnLookup is also a field trigger at the table level. The flow is different for this trigger. When a lookup is requested, the page field's OnLookup trigger is executed if it is defined in the field lookup or system default. If no control lookup trigger is defined, the OnLookup (Fields) Trigger (if defined) replaces the system default lookup function.

See Also

Concepts

Triggers


OnModifyRecord Trigger

Executed before a record is modified in the table.

[Ok]:= OnModifyRecord

Return Value

Ok

(Boolean) Indicates whether a record should be modified. The return value is checked after each function call. If true, the record is modified (default). If false, the record is not modified.

Applies To

  • Pages

Remarks

If an error occurs in the trigger code, the action is canceled, but the page is not closed.

You can write to the database using this trigger.

See Also

Concepts

Triggers


OnNewRecord Trigger

Executed after a new record is initialized, but before users can make entries.

OnNewRecord(BelowxRec)

Return Value

BelowxRec

(Boolean) This return value indicates whether the new record was inserted after the last record in the table (xRec). If false, the record was inserted between an existing record and the last record. If true, the record was inserted below the last record in the table (xRec).

Applies To

Pages

Remarks

Use this trigger to initialize a new record or other variables on the page.

If an error occurs in the trigger code a popup dialog shows an error message. When the dialog is closed, the user can enter new data.

Note
The OnNewRecord trigger does not support calls to control add-in methods and properties because the trigger is invoked before the page is instantiated. For more information see, Exposing Methods and Properties in a Windows Client Control Add-in.

See Also

Concepts

Triggers


OnNextRecord Trigger

Determines the next record to be displayed.

[ActualSteps]:=OnNextRecord(Steps)

Parameters

Steps

(Integer) The number of records stepped through before displaying another record. A negative value indicates steps backwards.

Return Value

ActualSteps

(Integer) This return value contains the actual number of steps or records cycled through. The default value is zero (0).

Applies To

  • Pages

Remarks

This trigger is executed in place of the default next record behavior.

If an error occurs in the trigger code, the page is closed.

See Also

Concepts

Triggers


OnOpenPage Trigger

Executed after a page is initialized and run.

OnOpenPage()

Applies To

  • Pages

Remarks

This trigger is executed after the OnInit Trigger.

You use the OnOpenPage trigger to change dynamic properties, including those which can only be changed when the page is opened, such as the Visible Property. You can also write to the database from the trigger.

The OnOpenPage trigger is the only trigger that can toggle the Visible Property and the property can only be toggled on columns. This is true for all of the Microsoft Dynamics NAV clients.

If an error occurs in the trigger execution, then the page closes.

Note
If you use the LOCKTABLE Function (Record) in the OnOpenPage trigger, then the table lock will be released when the trigger completes execution and not when the user closes the page.

Note
The OnOpenPage trigger does not support calls to control add-in methods and properties because the trigger is invoked before the page is instantiated. For more information see, Exposing Methods and Properties in a Windows Client Control Add-in.


OnQueryClosePage Trigger

Executed as a page closes and before the OnClosePage Trigger executes.

[Ok]:= OnQueryClosePage(CloseAction)

Parameters

CloseAction

(Action) The CloseAction chosen by the user; usually OK or Cancel.

Return Value

Ok

Type: Boolean

true to close the page; otherwise false. This value is checked after each function call.

Applies To

  • Pages

Important
The OnQueryClosePage trigger is not fully supported by the Microsoft Dynamics NAV Web client. When the page displays in the Microsoft Dynamics NAV Web client, the trigger is only invoked when the page is hosted in a modal popup window (MPO).

Remarks

If the page that is closing and all its child pages return true in the OnQueryClosePage trigger, then the OnClosePage Trigger is called for all child pages and then for the parent page.

If an error occurs in the OnQueryClosePage trigger or it returns false, then the page is not closed.

When the OnQueryClosePage trigger is called on a subpage, the CloseAction parameter is set to the same value as the parent page.

You can use this trigger to write to the database.


OnValidate (Page fields) Trigger

Executed when a field loses focus after its value has been changed.

OnValidate()

Applies To

  • Pages

Remarks

Use this trigger to validate user entries in a page field. If validation fails, then the field is marked with an error and its value is not saved.

The OnValidate trigger is also a field trigger at the table level. For more information, see OnValidate (Fields) Trigger. If both the table field and page field triggers are defined, then the OnValidate trigger on the table field is executed before the OnValidate trigger on the page field.

Note
You can use this trigger to write to the database. You cannot call the UPDATE function from this trigger.


Codeunit Triggers

The following triggers apply to codeunits.

Codeunit trigger name | Executed
OnBeforeTestRun Trigger | Before a test function of a test codeunit is run.
OnAfterTestRun Trigger | After a test function of a test codeunit is run.

See Also

Tasks

How to: Create Test Codeunits and Test Functions

Concepts

Testing the Application


OnAfterTestRun Trigger

Executed after a test function of a test codeunit has been run.

OnAfterTestRun(CodeunitID : Integer;CodeunitName : Text[30];FunctionName : Text[128];Success : Boolean)

Parameters

CodeunitID

Type: Integer

The ID of the codeunit that has run.

CodeunitName

Type: Text

The name of the test codeunit that has run.

FunctionName

Type: Text

The name of the test function that has run.

Note
This parameter is empty when the OnAfterTestRun trigger is called for the whole test codeunit.

Success

Type: Boolean

true indicates that the test function run succeeded; otherwise, false indicates that the test function run failed.

Applies To

Test runner codeunits. Test runner codeunits have the SubType Property (Codeunit) set to TestRunner.

Note
This trigger is optional and not available on a test runner codeunit by default. To implement this trigger, you must manually add it as a function.

Remarks

A test runner codeunit manages the execution of test codeunits that are run from its OnRun function. When a test codeunit runs, it executes each test function one at a time in the codeunit. When implemented, the OnAfterTestRun trigger is called after each test function has run and after all of the test codeunit has run.

The OnAfterTestRun trigger suppresses the automatic display of the results message after the test codeunit runs.

Note
To return the error message for a failed test function run, use the GETLASTERRORTEXT Function.

You can use the OnAfterTestRun trigger to perform post-processing, such as logging, or to automate tests by integrating the test runner codeunit with a test management framework.

The OnAfterTestRun trigger is run in its own database transaction.

For more information, see Testing the Application and How to: Create a Test Runner Codeunit.

Example

The following OnAfterTestRun trigger code logs test results to a test reporting system. This example requires that you create a record variable named log.

Copy Code
log.INIT;
log.UnitId := CodeunitId;
log.Unit := CodeunitName;
log.Func := FunctionName;
log.Before := Before;
log.After := CURRENTDATETIME;
If Success THEN
  log.Status := log.Status::Success
ELSE BEGIN
  log.Status := log.Status::Failure;
  IF FunctionName <> '' THEN
    log.Message := GETLASTERRORTEXT;
END
log.INSERT(true);

The GETLASTERRORTEXT function returns the text that was contained in the last error message.

See Also

Tasks

How to: Create a Test Runner Codeunit
How to: Create Test Codeunits and Test Functions
How to: Create Handler Functions
Walkthrough: Testing Purchase Invoice Discounts

Reference

OnBeforeTestRun Trigger

Concepts

Testing the Application


OnBeforeTestRun Trigger

Executed before a test function of a test codeunit is run.

OnBeforeTestRun(CodeunitID : Integer;CodeunitName : Text[30];FunctionName : Text[128]) Ok : Boolean

Parameters

CodeunitID

Type: Integer

The ID of the codeunit to be run.

CodeunitName

Type: Text

The name of the test codeunit to be run.

FunctionName

Type: Text

The name of the test function to be run.

Note
This parameter is empty when the OnBeforeTestRun trigger is called for the entire test codeunit.

Return Value

Ok

Type: Boolean

true to run the test function; otherwise, false. This value is checked after each function call.

Applies To

Test runner codeunits. Test runner codeunits have the SubType Property (Codeunit) set to TestRunner.

Note
This trigger is optional and not available on a test runner codeunit by default. To implement this trigger, you must manually add it as a function.

Remarks

A test runner codeunit manages the execution of test codeunits that are run from its OnRun function. When a test codeunit runs, it executes each test function in the codeunit, one at a time. The OnBeforeTestRun trigger is called before the test codeunit, the OnRun function, and each test function.

The OnBeforeTestRun trigger is run in its own database transaction.

You can use the OnBeforeTestRun triggers to perform preprocessing, such as general initialization and logging, or to automate tests by integrating the test runner codeunit with a test management framework.

For more information, see Testing the Application and How to: Create a Test Runner Codeunit.

Example

The following OnBeforeTestRun trigger code initializes a logging variable and returns true to indicate that the test function should execute. This example requires that you create the following global variable.

Name | DataType
Before | DateTime
Copy Code
Before := CURRENTDATETIME;
EXIT(true);

See Also

Tasks

How to: Create a Test Runner Codeunit
How to: Create Test Codeunits and Test Functions
How to: Create Handler Functions
Walkthrough: Testing Purchase Invoice Discounts

Reference

OnAfterTestRun Trigger

Concepts

Testing the Application


Query Triggers

This topic describes the C/AL triggers that are available for queries. Triggers are typically used to perform calculations and verification. Triggers let you control how data is selected and retrieved in a more complex and effective way than you can achieve by using properties.

Query Object Triggers

The following table lists the triggers that apply to the query object.

Trigger | Executes
OnBeforeOpen | Before the query object is run and the dataset is generated. For example, you can use the OnBeforeOpen trigger to apply filters using the SETFILTER function.

See Also

Reference

SETFILTER Function (Query)

Concepts

Queries


OnBeforeOpen Trigger

Executed before a query is run and the dataset is generated.

Visual Basic
OnBeforeOpen()

Remarks

The C/AL code of a query object includes the OnBeforeOpen trigger that you can use to change the data that will be included in the resulting dataset. For example, you can use the OnBeforeOpen trigger to apply filters to a column.

The OnBeforeOpen trigger only supports local variables; global variables are not supported.

Note
A query cannot be run from the OnBeforeOpen trigger. You cannot call functions from the triggers that run the query, such as OPEN, SAVEASXML, READ, or CLOSE functions.

Example

The following code applies a filter on the Quantity column of the query by calling the SETFILTER function on the OnBeforeOpen trigger of the query object.

Copy Code
currQuery.SETFILTER(Quantity, '>50');

See Also

Concepts

Queries
Working with Queries in C/AL
Queries


Integration Triggers

The following triggers have been added to support integration with Microsoft Dynamics CRM:

  • OnDatabaseCreate

  • OnDatabaseModify

  • OnDatabaseRename

  • OnDatabaseDelete

Applies To

Pages

Tables

Remarks

These triggers are called whenever a record changes through code or user interaction.

See Also

Record ID


Development Environment Commands

Microsoft Dynamics NAV includes the finsql.exe file that enables you to perform certain tasks from a command prompt. The finsql.exe is an executable file that runs the development environment. By default, finsql.exe is located at C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client\.

The finsql.exe has several commands that you can use to perform the tasks that are described in the following table:

Command | Task
BuildVirtualMetadata | Regenerates C# and metadata information for virtual tables in a specified database.
CreateDatabase | Create a new Microsoft Dynamics NAV database.
UpgradeDatabase | Upgrades the specified Microsoft Dynamics NAV database on the specified server.
CompileObjects | Compile Microsoft Dynamics NAV objects from a specified database.
DeleteObjects | Delete Microsoft Dynamics NAV objects from a specified database.
DesignObject | Open a specified Microsoft Dynamics NAV object for design in the development environment.
ExportObjects | Export Microsoft Dynamics NAV objects from a specified database.
ImportObjects | Import Microsoft Dynamics NAV objects from a file to a specified database.
CreateLanguage | Create language captions on Microsoft Dynamics NAV objects in a specified database.
ExportLangModule | Export a Microsoft Dynamics NAV language module from a specified database.
ImportLangModule | Import a Microsoft Dynamics NAV language module to a specified database.
ExportTranslate | Export text strings from a specified database to a file.
ImportTranslate | Import text strings from a file to a specified database.
GetBuildVersion | Gets the Microsoft Dynamics NAV product name and build version.
Note
To compile objects, design objects, or import and export objects as .txt files, you must have a developer license. For all other tasks, you can have either an end-user license or a developer license.

See Also

Concepts

Using the Development Environment from the Command Prompt


BuildVirtualMetadata

Regenerates C# and metadata information in Microsoft Dynamics NAV virtual tables for a specified language.

finsql.exe command=buildvirtualmetadata, langid=<langid>, [servername=<server>,] [database=<database>,] [logfile=<path and filename>,] [username=<user name>,] [password=<password>,] [ntauthentication=<yes|no|0|1>]

Parameters

langid

Specifies the standard Windows three-letter ID of the language for which you want to build the metadata, such as ENU or DAN.

servername

The name of the database server that hosts the Microsoft Dynamics NAV database and objects that you want to modify. The format of this parameter is <computername>\<database server instance>.

If you do not specify both the servername parameter and the database parameter, then the database server and database that are stored in the fin.zup file are used.

Note
When you first specify a database server and database to open, either from a command at a command prompt or from a client, the database server and database are stored in the fin.zup file. By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\.

If you do not specify the servername parameter but you do specify the database parameter, then the Open Database window opens so that you can specify the database server name.

Tip
To view the name of the server on which the current database is stored, on the File menu, choose Database, and then choose Information. Use the value of the Database Server field for the servername parameter.

database

The name of the Microsoft Dynamics NAV database that contains the objects that you want to modify.

Tip
To view the name of the current database, on the File menu, choose Database, and then choose Information. Use the value of the Database Name field for the database parameter.

logfile

The path and file name for the file that contains error messages that result from the command. If there are no errors, then a log file is not created.

By default, the file is named naverrorlog.txt and is located in the same location as finsql.exe.

The navcommandresult.txt file, which contains information about the success or failure of the command, is created in the folder that is specified by the logfile parameter.

When you run finsql.exe with a command, the previous log file and result file are deleted.

Note
If User Access Control (UAC) is turned on and you do not specify to run the Command Prompt window as Administrator, then the Command Prompt window runs as a standard user. In this case, if you do not specify the logfile parameter, then the command fails because the standard user cannot write to the default location of the log file.

username

The user name to use to authenticate to the database. The user name must exist in the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

Note
If User Access Control (UAC) is turned on and you do not specify to run the Command Prompt window as Administrator, then the Command Prompt window runs as a standard user. In this case, if you do not specify the username parameter and the current Windows user is an Administrator, then the command is run as the standard user.

If you specify the username parameter, then you must also specify the password parameter and the ntauthentication parameter must be no.

For more information about database users and permissions, see Setting Database Owner and Security Administration Permissions.

password

The password to use with the username parameter to authenticate to the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

ntauthentication

Specifies if you want to use NT authentication. The possible values are yes, no, 1, or 0. If you specify the username and password parameters, then you must specify ntauthentication=no or ntauthentication=0.

Example

This example builds metadata for virtual tables in the Demo Database NAV (9-0) database.

Copy Code
finsql.exe command=buildvirtualmetadata, servername=TestComputer01\NAVDEMO, database="Demo Database NAV (9-0)"

See Also

Reference

CreateDatabase
UpgradeDatabase
DeleteObjects
DesignObject
ExportObjects
ImportObjects
ExportLangModule
ImportLangModule
ExportTranslate
ImportTranslate

Concepts

Compiling Objects
Using the Development Environment from the Command Prompt


CreateDatabase

Creates a new database for Microsoft Dynamics NAV on an SQL server.

finsql.exe command=createdatabase, [servername=<server>,] [database=<database>,] [collationname=<collation>,] [logfile=<path and filename>,] [username=<user name>,] [password=<password>,] [ntauthentication=<yes|no|0|1>]

Parameters

servername

The name of the database server on which you want to run the command and create the database.

Tip
To view the name of the server on which the current database is stored, on the File menu, choose Database, and then choose Information. Use the value of the Database Server field for the servername parameter.

database

The name of the new database that you want to create.

Tip
To view the name of the current database, on the File menu, choose Database, and then choose Information. Use the value of the Database Name field for the database parameter.

collationname

The collation to use when you create a new database. The value must be one of the following:

  • A full language culture name. For example, da-DK for Danish or hu-HU for Hungarian. ·

  • A SQL Server collation name without case or accent. For example, Latin1_General_100. ·

  • A SQL Server collation name with case and accent. For example, Danish_Greenlandic_100_CS_AI.

logfile

The path and file name for the file that contains error messages that result from the command. If there are no errors, then a log file is not created.

By default, the file is named naverrorlog.txt and is located in the same location as finsql.exe.

The navcommandresult.txt file, which contains information about the success or failure of the command, is created in the folder that is specified by the logfile parameter.

When you run finsql.exe with a command, the previous log file and result file are deleted.

Note
If User Access Control (UAC) is turned on and you do not specify to run the Command Prompt window as Administrator, then the Command Prompt window runs as a standard user. In this case, if you do not specify the logfile parameter, then the command fails because the standard user cannot write to the default location of the log file.

username

The user name to use to authenticate to the database. The user name must exist in the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

Note
If User Access Control (UAC) is turned on and you do not specify to run the Command Prompt window as Administrator, then the Command Prompt window runs as a standard user. In this case, if you do not specify the username parameter and the current Windows user is an Administrator, then the command is run as the standard user.

If you specify the username parameter, then you must also specify the password parameter and the ntauthentication parameter must be no.

For more information about database users and permissions, see Setting Database Owner and Security Administration Permissions.

password

The password to use with the username parameter to authenticate to the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

ntauthentication

Specifies if you want to use NT authentication. The possible values are yes, no, 1, or 0. If you specify the username and password parameters, then you must specify ntauthentication=no or ntauthentication=0.

Remarks

You use the CreateDatabase command together with the finsql.exe executable. Finsql.exe is the executable file that runs the development environment. By default, finsql.exe is located at C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client\.

Example

This example creates a database on a SQL server that is named TestComputer01\NAVDEMO. The new database is given the name NAV Danish Database and uses the collation da-DK.

Copy Code
finsql.exe command=createdatabase, servername=TestComputer01\NAVDEMO, database="NAV Danish Database", collationname=da-dk

See Also

Reference

BuildVirtualMetadata
UpgradeDatabase
CreateLanguage
CreateLanguage
DesignObject
ExportObjects
ImportObjects
ExportLangModule
ImportLangModule
ExportTranslate
ImportTranslate

Concepts

Compiling Objects
Using the Development Environment from the Command Prompt


UpgradeDatabase

Upgrades an existing Microsoft Dynamics NAV database.

finsql.exe command=upgradedatabase, servername=<server>, database=<database>[, logfile=<path and filename>,] [username=<user name>,] [password=<password>,] [ntauthentication=<yes|no|0|1>]

Parameters

servername

The name of the database server and server instance on which you want to run the command and upgrade the database.

Tip
To view the name of the server on which the current database is stored, on the File menu, choose Database, and then choose Information. Use the value of the Database Server field for the servername parameter.

database

The name of the database that you want to upgrade.

Tip
To view the name of the current database, on the File menu, choose Database, and then choose Information. Use the value of the Database Name field for the database parameter.

logfile

The path and file name for the file that contains error messages that result from the command. If there are no errors, then a log file is not created.

By default, the file is named naverrorlog.txt and is located in the same location as finsql.exe.

The navcommandresult.txt file, which contains information about the success or failure of the command, is created in the folder that is specified by the logfile parameter.

When you run finsql.exe with a command, the previous log file and result file are deleted.

Note
If User Access Control (UAC) is turned on and you do not specify to run the Command Prompt window as Administrator, then the Command Prompt window runs as a standard user. In this case, if you do not specify the logfile parameter, then the command fails because the standard user cannot write to the default location of the log file.

username

The user name to use to authenticate to the database. The user name must exist in the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

Note
If User Access Control (UAC) is turned on and you do not specify to run the Command Prompt window as Administrator, then the Command Prompt window runs as a standard user. In this case, if you do not specify the username parameter and the current Windows user is an Administrator, then the command is run as the standard user.

If you specify the username parameter, then you must also specify the password parameter and the ntauthentication parameter must be no.

For more information about database users and permissions, see Setting Database Owner and Security Administration Permissions.

password

The password to use with the username parameter to authenticate to the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

ntauthentication

Specifies if you want to use NT authentication. The possible values are yes, no, 1, or 0. If you specify the username and password parameters, then you must specify ntauthentication=no or ntauthentication=0.

Remarks

You use the UpgradeDatabase command together with the finsql.exe executable when you want to convert a database from an earlier version of Microsoft Dynamics NAV to the new version. For example, if you are upgrading several databases, you can create scripts that help you repeat the steps. Finsql.exe is the executable file that runs the Microsoft Dynamics NAV Development Environment. By default, finsql.exe is located at C:\Program Files (x86)\Microsoft Dynamics NAV\90RoleTailored Client\.

Important
The upgrade is not completed when you have run this command. You must compile all objects, and you must connect to a Microsoft Dynamics NAV Server instance. For more information, see Converting a Database.

Example

This example upgrades the NAV Danish Database database on the TestComputer01\NAVDEMO SQL Server instance.

Copy Code
finsql.exe command=upgradedatabase, servername=TestComputer01\NAVDEMO, database="NAV Danish Database"

See Also

Reference

BuildVirtualMetadata
CreateDatabase
UpgradeDatabase
CreateLanguage
CreateLanguage
DesignObject
ExportObjects
ImportObjects
ExportLangModule
ImportLangModule
ExportTranslate
ImportTranslate

Concepts

Using the Development Environment from the Command Prompt
Converting a Database
Microsoft Dynamics NAV Windows PowerShell Cmdlets
Compiling Objects


CompileObjects

Compiles objects from the specified database.

finsql.exe command=compileobjects, [servername=<server>,] [database=<database>,] [filter=<filter>,] [logfile=<path and filename>,] [username=<user name>,] [password=<password>,] [ntauthentication=<yes|no|0|1>,] [synchronizeschemachanges=<yes|no|force>,] [navservername=<server name>,] [navserverinstance=<instance>,] [navservermanagementport=<port>,] [tenant=<tenant ID>]

Parameters

servername

The name of the database server on which you want to run the command.

If you do not specify both the servername parameter and the database parameter, then the database server and database that are stored in the fin.zup file are used.

Note
When you first specify a database server and database to open, either from a command at a command prompt or from a client, the database server and database are stored in the fin.zup file. By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\.

If you do not specify the servername parameter but you do specify the database parameter, then the Open Database window opens so that you can specify the database server name.

Tip
To view the name of the server on which the current database is stored, on the File menu, choose Database, and then choose Information. Use the value of the Database Server field for the servername parameter.

database

The database in which the objects that you want to compile are stored.

If you do not specify both the servername parameter and the database parameter, then the database server and database that are stored in the fin.zup file are used.

Note
When you first specify a database server and database to open, either from a command at a command prompt or from a client, the database server and database are stored in the fin.zup file. By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\.

If you do not specify the database parameter but you do specify the servername parameter, then the Open Database window opens so that you can specify the database name.

Tip
To view the name of the current database, on the File menu, choose Database, and then choose Information. Use the value of the Database Name field for the database parameter.

logfile

The path and file name for the file that contains error messages that result from the command. If there are no errors, then a log file is not created.

By default, the file is named naverrorlog.txt and is located in the same location as finsql.exe.

The navcommandresult.txt file, which contains information about the success or failure of the command, is created in the folder that is specified by the logfile parameter.

When you run finsql.exe with a command, the previous log file and result file are deleted.

Note
If User Access Control (UAC) is turned on and you do not specify to run the Command Prompt window as Administrator, then the Command Prompt window runs as a standard user. In this case, if you do not specify the logfile parameter, then the command fails because the standard user cannot write to the default location of the log file.

filter

A filter on the Object table. Use the filter parameter to specify which objects to compile. Use a semicolon to separate multiple filters. The only operator that you can use in the filter is '='. The following table shows the fields in the Object table on which you can filter.

Object table field | Values | Example
Type | Table, Codeunit, Page, Report, XMLport, Query, MenuSuite | Type=Table|Page
ID | Integer or range of integers | ID=50000..50500
Name | Any valid object name | "Name=Cost Entry"
Modified | yes, no, 1, 0 | Modified=yes
Compiled | yes, no, 1, 0 | Compiled=0
Date | Date, in the numeric format determined by your regional settings | Date=12/1/2012
Time | Time, in the numeric format determined by your regional settings | Time=12:00:00
Version List | Any valid version | Version List=NAVW19.00
Caption | Any valid caption | Caption=Company Information
Locked | Yes, no, 1, 0 | Locked=1
Locked By | Domain\username | "Locked By=CRONUS\viktor"

If you do not specify a filter, then all objects in the Object table are included.

username

The user name to use to authenticate to the database. The user name must exist in the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

Note
If User Access Control (UAC) is turned on and you do not specify to run the Command Prompt window as Administrator, then the Command Prompt window runs as a standard user. In this case, if you do not specify the username parameter and the current Windows user is an Administrator, then the command is run as the standard user.

If you specify the username parameter, then you must also specify the password parameter and the ntauthentication parameter must be no.

For more information about database users and permissions, see Setting Database Owner and Security Administration Permissions.

password

The password to use with the username parameter to authenticate to the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

ntauthentication

Specifies if you want to use NT authentication. The possible values are yes, no, 1, or 0. If you specify the username and password parameters, then you must specify ntauthentication=no or ntauthentication=0.

synchronizeschemachanges

Specifies how to synchronize table definition changes in the business (tenant) database in SQL Server. The following table describes the available options.

Option Description

yes

Before applying changes to the business data table, Microsoft Dynamics NAV Server validates the changed table definition to check for destructive changes to the table. This includes changes that require that data is deleted in the fields of the business data table which are affected by the changes before the changes can be applied.

  • If there are no destructive changes to the table, then the schema changes are applied to the business data table immediately.

  • If there are destructive changes, Microsoft Dynamics NAV Server checks that there are table synchronization instructions in an upgrade codeunit. If there are instructions, then the schema changes are applied to the business database table according to the instructions. If there are no instructions, then an error message appears. The table definition changes are not saved and the schema changes are not applied.

no

Table definition changes are saved and compiled in the application but the changes are not validated or applied to the business data table. You synchronize the table schema later by doing one of the following:

  • Save or compile the table from Object Designer in development environment and choose either the Now - with validation or Force synchronization option.

  • Use the Sync. Schema for All Tables option on the Tools menu.

  • Run the Sync-NAVTenant cmdlet from the Microsoft Dynamics NAV 2016 Administration Shell.

force

Table definition changes are applied to the business data table schema without validation. For destructive changes, data in columns of the business data table that are affected by changes will be deleted.

This option ignores any table synchronization instructions for the table in upgrade codeunits.

For more information about table schema synchronization, see Synchronizing Table Schemas.

navservername

Specifies the name of the server that hosts the Microsoft Dynamics NAV Server instance, such as MyServer.

navserverinstance

Specifies the Microsoft Dynamics NAV Server instance that is being used, such as DynamicsNAV90.

navservermanagementport

Specifies the port on the Microsoft Dynamics NAV Server server that the Microsoft Dynamics NAV Windows PowerShell cmdlets access, such as 7045.

tenant

Specifies the ID of the tenant that is accessed when you run objects from the development environment. If your solution is not set up to deploy in a multitenant deployment architecture, leave the parameter empty.

Remarks

You use the CompileObjects command together with the finsql.exe executable. Finsql.exe is the executable file that runs the development environment. By default, finsql.exe is located at C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client\.

To compile objects, you must have a developer license.

Example

This example shows how to run a command to compile all tables and codeunits that have an ID that is greater than or equal to 500 and less than or equal to 1000.

Copy Code
finsql.exe command=compileobjects, servername=TestComputer01\NAVDEMO, database="Demo Database NAV (9-0)", filter="Type=Table|Codeunit;ID=500..1000"

See Also

Reference

BuildVirtualMetadata
CreateDatabase
UpgradeDatabase
CreateLanguage
CreateLanguage
DesignObject
ExportObjects
ImportObjects
ExportLangModule
ImportLangModule
ExportTranslate
ImportTranslate

Concepts

Compiling Objects
Using the Development Environment from the Command Prompt


DesignObject

Opens the development environment and opens the specified object for design.

Finsql.exe [servername=<server>,] [database=<database>,] designobject=<object type> <object ID>, [username=<user name>,] [password=<password>,] [ntauthentication=<yes|no|0|1>]

Parameters

servername

The name of the database server on which you want to run the command.

If you do not specify both the servername and the database parameter, then the database server and database that are stored in the fin.zup file are used.

Note
When you first specify a database server and database to open, either from a command at a command prompt or from a client, the database server and database are stored in the fin.zup file. By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\.

If you do not specify the servername parameter but you do specify the database parameter, then the Open Database window opens so that you can specify the database server name.

Tip
To view the name of the server on which the current database is stored, in the development environment, on the File menu, choose Database, and then choose Information. Use the value of the Database Server field for the servername parameter.

database

The database in which the objects that you want to compile are stored.

If you do not specify both the servername and the database parameter, then the database server and database that are stored in the fin.zup file are used.

Note
When you first specify a database server and database to open, either from a command at a command prompt or from a client, the database server and database are stored in the fin.zup file. By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\.

If you do not specify the database parameter but you do specify the servername parameter, then the Open Database window opens so that you can specify the database name.

Tip
To view the name of the current database, in the development environment, on the File menu, choose Database, and then choose Information. Use the value of the Database Name field for the database parameter.

designobject

The type and ID of the object that you want to design. This parameter is required. The possible values of the object type are:

  • Table

  • Page

  • Report

  • Codeunit

  • Query

  • XMLport

The possible values of the object ID are 0 and any ID of an existing object. If you specify 0 for the object ID, then you open a new object to design.

username

The user name to use to authenticate to the database. The user name must exist in the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

Note
If User Access Control (UAC) is turned on and you do not specify to run the Command Prompt window as Administrator, then the Command Prompt window runs as a standard user. In this case, if you do not specify the username parameter and the current Windows user is an Administrator, then the command is run as the standard user.

If you specify the username parameter, then you must also specify the password parameter and the ntauthentication parameter must be no.

For more information about database users and permissions, see Setting Database Owner and Security Administration Permissions.

password

The password to use with the username parameter to authenticate to the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

ntauthentication

Specifies if you want to use NT authentication. The possible values are yes, no, 1, or 0. If you specify the username and password parameters, then you must specify ntauthentication=no or ntauthentication=0.

Remarks

You use the DesignObject parameter together with the finsql.exe executable. Finsql.exe is the executable file that runs the development environment. By default, finsql.exe is located at C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client\.

To design objects, you must have a developer license.

Example

This example shows how to run a command to open the development environment and open Page Designer to design page 21, Customer Card.

Copy Code
finsql.exe servername=TestComputer01\NAVDEMO, database="Demo Database NAV (9-0)", designobject=Page 21

See Also

Reference

BuildVirtualMetadata
CreateDatabase
UpgradeDatabase
CreateLanguage
CreateLanguage
DesignObject
ExportObjects
ImportObjects
ExportLangModule
ImportLangModule
ExportTranslate
ImportTranslate

Concepts

Objects
Compiling Objects
Using the Development Environment from the Command Prompt


ExportObjects

Exports objects from the specified database.

finsql.exe command=exportobjects, file=<exportfile>, [servername=<server>,] [database=<database>,] [logfile=<path and filename>,] [filter=<filter>,] [username=<username>,] [password=<password>,] [ntauthentication=<yes|no|1|0>]

Parameters

file

The path and file name to which you export objects. This parameter is required. You can export objects to one of the following file types:

  • .txt

  • .fob

You specify the file type by the file name extension in the file parameter.

servername

The name of the database server on which you want to run the command. The format of this parameter is <computername>\<database server instance>.

If you do not specify both the servername and the database parameter, then the database server and database that are stored in the fin.zup file are used.

Note
When you first specify a database server and database to open, either from a command at a command prompt or from a client, the database server and database are stored in the fin.zup file. By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\.

If you do not specify the servername parameter but you do specify the database parameter, then the Open Database window opens so that you can specify the database server name.

Tip
To view the name of the server on which the current database is stored, on the File menu, choose Database, and then choose Information. Use the value of the Database Server field for the servername parameter.

database

The database in which the objects that you want to export are stored.

If you do not specify both the servername and the database parameter, then the database server and database that are stored in the fin.zup file are used.

Note
When you first specify a database server and database to open, either from a command at a command prompt or from a client, the database server and database are stored in the fin.zup file. By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\.

If you do not specify the database parameter but you do specify the servername parameter, then the Open Database window opens so that you can specify the database name.

Tip
To view the name of the current database, on the File menu, choose Database, and then choose Information. Use the value of the Database Name field for the database parameter.

logfile

The path and file name for the file that contains error messages that result from the command. If there are no errors, then a log file is not created.

By default, the file is named naverrorlog.txt and is located in the same location as finsql.exe.

The navcommandresult.txt file, which contains information about the success or failure of the command, is created in the folder that is specified by the logfile parameter.

When you run finsql.exe with a command, the previous log file and result file are deleted.

Note
If User Access Control (UAC) is turned on and you do not specify to run the command prompt window as Administrator, then the command prompt window runs as a standard user. In this case, if you do not specify the logfile parameter, then the command fails because the standard user cannot write to the default location of the log file.

filter

A filter on the Object table. Use the filter parameter to specify which objects to compile. Use a semicolon to separate multiple filters. The only operator that you can use in the filter is '='. The following table shows the fields in the Object table on which you can filter.

Object table field | Values | Example
Type | Table, Codeunit, Page, Report, XMLport, Query | Type=Table|Page
ID | Integer or range of integers | ID=50000..50500
Name | Any valid object name | "Name=Cost Entry"
Modified | yes, no, 1, 0 | Modified=yes
Compiled | yes, no, 1, 0 | Compiled=0
Date | Date, in the numeric format determined by your regional settings | "Date=12/1/2012"
Time | Time, in the numeric format determined by your regional settings | "Time=12:00:00"
Version List | Any valid version | "Version List=NAVW17.00"
Caption | Any valid caption | "Caption=Company Information"
Locked | Yes, no, 1, 0 | Locked=1
Locked By | Domain\username | "Locked By=CRONUS\viktor"

If you do not specify a filter, then all objects in the Object table are included.

username

The user name to use to authenticate to the database. The user name must exist in the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

Note
If User Access Control (UAC) is turned on, and you do not specify to run the command prompt window as Administrator, then the command prompt window runs as a standard user. In this case, if you do not specify the username parameter, then even if the current Windows user is an Administrator, the command is run as the standard user.

If you specify the username parameter, then you must also specify the password parameter and the ntauthentication parameter must be no.

For more information about database users and permissions, see Setting Database Owner and Security Administration Permissions.

password

The password to use with the username parameter to authenticate to the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

ntauthentication

Specifies whether to use NT authentication. The possible values are yes, no, 1, or 0. If you specify the username and password parameters, then you must specify ntauthentication=no or ntauthentication=0.

Remarks

You use the ExportObjects command with the finsql.exe from a command prompt. Finsql.exe is the executable file that runs the development environment. By default, finsql.exe is located at C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client\.

To export objects to a .txt file, you must have a developer license. To export objects to a .fob file, you can have either an end-user license or a developer license.

You can specify parameters in any order.

Example

This example shows how to run a command to export all queries in a given ID range, using the specified user name and password.

Copy Code
finsql.exe command=exportobjects, file=C:\QueryExport.txt, servername=TestComputer01\NAVDEMO, database="Demo Database NAV (9-0)", filter="Type=Query;ID=50001..50010", username=dbadmin, password=P@ssword, ntauthentication=no, logfile=C:\QueryExportLog.txt

See Also

Tasks

How to: Export Objects

Reference

BuildVirtualMetadata
CreateDatabase
UpgradeDatabase
CreateLanguage
CreateLanguage
DesignObject
ExportObjects
ImportObjects
ExportLangModule
ImportLangModule
ExportTranslate
ImportTranslate

Concepts

Compiling Objects
Using the Development Environment from the Command Prompt


ImportObjects

Imports objects from a file to the specified database.

finsql.exe command=importobjects, file=<importfile>, [servername=<server>,] [database=<database>,] [logfile=<path and filename>,] [importaction=<default|overwrite|skip|0|1|2>,] [username=<username>,] [password=<password>,] [ntauthentication=<yes|no|1|0>,] [synchronizeschemachanges=<yes|no|force>,] [navservername=<server name>,] [navserverinstance=<instance>,] [navservermanagementport=<port>,] [tenant=<tenant ID>]

Parameters

file

The path and file name from which you import objects. This parameter is required. The file must have a .fob or .txt file name extension.

servername

The name of the database server on which you want to run the command. The format of this parameter is <computername>\<database server instance>.

If you do not specify both the servername and the database parameter, then the database server and database that are stored in the fin.zup file are used.

Note
When you first specify a database server and database to open, either from a command at a command prompt or from a client, the database server and database are stored in the fin.zup file. By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\.

If you do not specify the servername parameter but you do specify the database parameter, then the Open Database window opens so that you can specify the database server name.

Tip
To view the name of the server on which the current database is stored, on the File menu, choose Database, and then choose Information. Use the value of the Database Server field for the servername parameter.

database

The database in which the objects that you want to compile are stored.

If you do not specify both the servername and the database parameter, then the database server and database that are stored in the fin.zup file are used.

Note
When you first specify a database server and database to open, either from a command at a command prompt or from a client, the database server and database are stored in the fin.zup file. By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\.

If you do not specify the database parameter but you do specify the servername parameter, then the Open Database window opens so that you can specify the database name.

Tip
To view the name of the current database, on the File menu, choose Database, and then choose Information. Use the value of the Database Name field for the database parameter.

logfile

The path and file name for the file that contains error messages that result from the command. If there are no errors, then a log file is not created.

By default, the file is named naverrorlog.txt and is located in the same location as finsql.exe.

The navcommandresult.txt file, which contains information about the success or failure of the command, is created in the folder that is specified by the logfile parameter.

When you run finsql.exe with a command, the previous log file is deleted.

Note
If User Access Control (UAC) is turned on and you do not specify to run the Command Prompt window as Administrator, then the Command Prompt window runs as a standard user. In this case, if you do not specify the logfile parameter, then the command fails because the standard user cannot write to the default location of the log file.

importaction

Specifies how to handle conflicts with existing objects when you import from a .fob file. The possible values are:

  • default or 0 (default) - If there is a conflict, then an error is logged in the log file and no objects from the file are imported.

  • overwrite or 1 - If there is a conflict, then overwrite the existing object with the object in the import file.

  • skip or 2 - If there is a conflict, then skip the object. The existing object remains unchanged.

Warning
If you import from a .txt file and there is a conflict, then the objects in the import file overwrite the existing objects in the database.

Note
After you import an object from a .txt file, you must compile the object before you use it. If you import an object from a .fob file, then the object is compiled automatically after it is imported.

username

The user name to use to authenticate to the database. The user name must exist in the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

Note
If User Access Control (UAC) is turned on, and you do not specify to run the Command Prompt window as Administrator, then the Command Prompt window runs as a standard user. In this case, if you do not specify the username parameter, then even if the current Windows user is an Administrator, the command is run as the standard user.

If you specify the username parameter, then you must also specify the password parameter and the ntauthentication parameter must be no or 0.

For more information about database users and permissions, see Setting Database Owner and Security Administration Permissions.

password

The password to use with the username parameter to authenticate to the database. If you do not specify a username and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

ntauthentication

Specifies whether to use NT authentication. The possible values are yes, no, 1, or 0. If you specify the username and password parameters, then you must specify ntauthentication=no or ntauthentication=0.

synchronizeschemachanges

Specifies how to synchronize table definition changes in the business (tenant) database in SQL Server. The following table describes the available options.

Option Description

yes

Before applying changes to the business data table, Microsoft Dynamics NAV Server validates the changed table definition to check for destructive changes to the table. This includes changes that require that data is deleted in the fields of the business data table which are affected by the changes before the changes can be applied.

  • If there are no destructive changes to the table, then the schema changes are applied to the business data table immediately.

  • If there are destructive changes, Microsoft Dynamics NAV Server checks that there are table synchronization instructions in an upgrade codeunit. If there are instructions, then the schema changes are applied to the business database table according to the instructions. If there are no instructions, then an error message appears. The table definition changes are not saved and the schema changes are not applied.

no

Table definition changes are saved and compiled in the application but the changes are not validated or applied to the business data table. You synchronize the table schema later by doing one of the following:

  • Save or compile the table from Object Designer in development environment and choose either the Now - with validation or Force synchronization option.

  • Use the Sync. Schema for All Tables option on the Tools menu.

  • Run the Sync-NAVTenant cmdlet from the Microsoft Dynamics NAV 2016 Administration Shell.

force

Table definition changes are applied to the business data table schema without validation. For destructive changes, data in columns of the business data table that are affected by changes will be deleted.

This option ignores any table synchronization instructions for the table in upgrade codeunits.

For more information about table schema synchronization, see Synchronizing Table Schemas.

navservername

Specifies the name of the server that hosts the Microsoft Dynamics NAV Server instance, such as MyServer.

navserverinstance

Specifies the Microsoft Dynamics NAV Server instance that is being used, such as DynamicsNAV90.

navservermanagementport

Specifies the port on the Microsoft Dynamics NAV Server server that the Microsoft Dynamics NAV Windows PowerShell cmdlets access, such as 7045.

tenant

Specifies the ID of the tenant that is accessed when you run objects from the development environment. If your solution is not set up to deploy in a multitenant deployment architecture, leave the parameter empty.

Remarks

You use the ImportObjects command with the finsql.exe from a command prompt. Finsql.exe is the executable file that runs the development environment. By default, finsql.exe is located at C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client\.

To import objects from a .txt file, you must have a developer license. To import objects from a .fob file, you can have either an end-user license or a developer license.

You can specify parameters in any order.

Example

This example shows how to run a command to import the objects from a .fob file into Microsoft Dynamics NAV. If any of the objects to import already exist in the database, then overwrite them with the objects from the import file.

Copy Code
finsql.exe command=importobjects, file=C:\NewObjects.fob, servername=TestComputer01, database="Demo Database NAV (9-0)", ImportAction=overwrite

See Also

Tasks

How to: Import Objects

Reference

BuildVirtualMetadata
CreateDatabase
UpgradeDatabase
CreateLanguage
CompileObjects
DeleteObjects
DesignObject
ExportObjects
ImportObjects
ExportLangModule
ImportLangModule
ExportTranslate
ImportTranslate

Concepts

Using the Development Environment from the Command Prompt


DeleteObjects

Deletes objects from the specified Microsoft Dynamics NAV database.

finsql.exe command=deleteobjects, [servername=<server>,] [database=<database>,] [filter=<filter>,] [logfile=<path and filename>,] [username=<user name>,] [password=<password>,] [ntauthentication=<yes|no|0|1>,] [synchronizeschemachanges=<yes|no|force>,] [navservername=<server name>,] [navserverinstance=<instance>,] [navservermanagementport=<port>,] [tenant=<tenant ID>]

Parameters

servername

The name of the database server that hosts the Microsoft Dynamics NAV database that contains the objects that you want to delete. The format of this parameter is <computername>\<database server instance>.

If you do not specify both the servername parameter and the database parameter, then the database server and database that are stored in the fin.zup file are used.

Note
When you first specify a database server and database to open, either from a command at a command prompt or from a client, the database server and database are stored in the fin.zup file. By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\.

If you do not specify the servername parameter but you do specify the database parameter, then the Open Database window opens so that you can specify the database server name.

Tip
To view the name of the server on which the current database is stored, on the File menu, choose Database, and then choose Information. Use the value of the Database Server field for the servername parameter.

database

The name of the Microsoft Dynamics NAV database in which the objects that you want to delete are stored.

If you do not specify both the servername parameter and the database parameter, then the database server and database that are stored in the fin.zup file are used.

Note
When you first specify a database server and database to open, either from a command at a command prompt or from a client, the database server and database are stored in the fin.zup file. By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\.

If you do not specify the database parameter but you do specify the servername parameter, then the Open Database window opens so that you can specify the database name.

Tip
To view the name of the current database, on the File menu, choose Database, and then choose Information. Use the value of the Database Name field for the database parameter.

logfile

The path and file name for the file that contains error messages that result from the command. If there are no errors, then a log file is not created.

By default, the file is named naverrorlog.txt and is located in the same location as finsql.exe.

The navcommandresult.txt file, which contains information about the success or failure of the command, is created in the folder that is specified by the logfile parameter.

When you run finsql.exe with a command, the previous log file and result file are deleted.

Note
If User Access Control (UAC) is turned on and you do not specify to run the Command Prompt window as Administrator, then the Command Prompt window runs as a standard user. In this case, if you do not specify the logfile parameter, then the command fails because the standard user cannot write to the default location of the log file.

filter

A filter on the Object table. Use the filter parameter to specify which objects to delete. Use a semicolon to separate multiple filters. The only operator that you can use in the filter is '='. The following table shows the fields in the Object table on which you can filter.

Object table field | Values | Example
Type | Table, Codeunit, Page, Report, XMLport, Query | Type=Table|Page
ID | Integer or range of integers | ID=50000..50500
Name | Any valid object name | "Name=Cost Entry"
Modified | yes, no, 1, 0 | Modified=yes
Compiled | yes, no, 1, 0 | Compiled=0
Date | Date, in the numeric format determined by your regional settings | Date=12/1/2012
Time | Time, in the numeric format determined by your regional settings | Time=12:00:00
Version List | Any valid version | Version List=NAVW17.00
Caption | Any valid caption | Caption=Company Information
Locked | Yes, no, 1, 0 | Locked=1
Locked By | Domain\username | "Locked By=CRONUS\viktor"

If you do not specify a filter, then all objects in the Object table are deleted.

username

The user name to use to authenticate to the database. The user name must exist in the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

Note
If User Access Control (UAC) is turned on and you do not specify to run the Command Prompt window as Administrator, then the Command Prompt window runs as a standard user. In this case, if you do not specify the username parameter and the current Windows user is an Administrator, then the command is run as the standard user.

If you specify the username parameter, then you must also specify the password parameter and the ntauthentication parameter must be no.

For more information about database users and permissions, see Setting Database Owner and Security Administration Permissions.

password

The password to use with the username parameter to authenticate to the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

ntauthentication

Specifies if you want to use NT authentication. The possible values are yes, no, 1, or 0. If you specify the username and password parameters, then you must specify ntauthentication=no or ntauthentication=0.

synchronizeschemachanges

Specifies how to synchronize table definition changes in the business (tenant) database in SQL Server. The following table describes the available options.

Option Description

yes

Before applying changes to the business data table, Microsoft Dynamics NAV Server validates the changed table definition to check for destructive changes to the table. This includes changes that require that data is deleted in the fields of the business data table which are affected by the changes before the changes can be applied.

  • If there are no destructive changes to the table, then the schema changes are applied to the business data table immediately.

  • If there are destructive changes, Microsoft Dynamics NAV Server checks that there are table synchronization instructions in an upgrade codeunit. If there are instructions, then the schema changes are applied to the business database table according to the instructions. If there are no instructions, then an error message appears. The table definition changes are not saved and the schema changes are not applied.

no

Table definition changes are saved and compiled in the application but the changes are not validated or applied to the business data table. You synchronize the table schema later by doing one of the following:

  • Save or compile the table from Object Designer in development environment and choose either the Now - with validation or Force synchronization option.

  • Use the Sync. Schema for All Tables option on the Tools menu.

  • Run the Sync-NAVTenant cmdlet from the Microsoft Dynamics NAV 2016 Administration Shell.

force

Table definition changes are applied to the business data table schema without validation. For destructive changes, data in columns of the business data table that are affected by changes will be deleted.

This option ignores any table synchronization instructions for the table in upgrade codeunits.

For more information about table schema synchronization, see Synchronizing Table Schemas.

navservername

Specifies the name of the server that hosts the Microsoft Dynamics NAV Server instance, such as MyServer.

Use this parameter only when you are deleting table objects and the validatetablechanges is set to no.

navserverinstance

Specifies the Microsoft Dynamics NAV Server instance that is being used, such as DynamicsNAV90.

Use this parameter only when you are deleting table objects and the validatetablechanges is set to no.

navservermanagementport

Specifies the port on the Microsoft Dynamics NAV Server server that the Microsoft Dynamics NAV Windows PowerShell cmdlets access, such as 7045.

Use this parameter only when you are deleting table objects and the validatetablechanges is set to no.

tenant

Specifies the ID of the tenant that is accessed when you run objects from the development environment. If your solution is not set up to deploy in a multitenant deployment architecture, then leave the parameter empty.

Use this parameter only when you are deleting table objects and the validatetablechanges is set to no.

Remarks

When you run the command, objects are deleted without a warning or confirmation prompt.

Example

This example shows how to run the DeleteObjects command to delete all tables and codeunits that have an ID that is greater than or equal to 500 and less than or equal to 1000.

Copy Code
finsql.exe command=deleteobjects, servername=TestComputer01\NAVDEMO, database="Demo Database NAV (9-0)", filter="Type=Table|Codeunit;ID=500..1000"

See Also

Reference

BuildVirtualMetadata
CreateDatabase
UpgradeDatabase
CreateLanguage
CompileObjects
DesignObject
ExportObjects
ImportObjects
ExportLangModule
ImportLangModule
ExportTranslate
ImportTranslate

Concepts

Using the Development Environment from the Command Prompt


CreateLanguage

Creates captions on Microsoft Dynamics NAV objects for a specified language.

finsql.exe command=createlanguage, langid=<langid>, [servername=<server>,] [database=<database>,] [filter=<filter>,] [logfile=<path and filename>,] [username=<user name>,] [password=<password>,] [ntauthentication=<yes|no|0|1>]

Parameters

langid

Specifies the standard Windows three-letter ID of the language that you want to add captions for.

servername

The name of the database server that hosts the Microsoft Dynamics NAV database and objects that you want to modify. . The format of this parameter is <computername>\<database server instance>.

If you do not specify both the servername parameter and the database parameter, then the database server and database that are stored in the fin.zup file are used.

Note
When you first specify a database server and database to open, either from a command at a command prompt or from a client, the database server and database are stored in the fin.zup file. By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\.

If you do not specify the servername parameter but you do specify the database parameter, then the Open Database window opens so that you can specify the database server name.

Tip
To view the name of the server on which the current database is stored, on the File menu, choose Database, and then choose Information. Use the value of the Database Server field for the servername parameter.

database

The name of the Microsoft Dynamics NAV database that contains the objects that you want to modify.

Tip
To view the name of the current database, on the File menu, choose Database, and then choose Information. Use the value of the Database Name field for the database parameter.

filter

Specifies a filter on the Object table. Use the filter parameter to specify which objects to add captions on. For example, you can add captions on a specific set of pages or reports. Use a semicolon to separate multiple filters. The only operator that you can use in the filter is '='. The following table shows the fields in the Object table on which you can filter.

Object table field | Values | Example
Type | Table, Codeunit, Page, Report, XMLport, Query | Type=Table|Page
ID | Integer or range of integers | ID=50000..50500
Name | Any valid object name | "Name=Cost Entry"
Modified | yes, no, 1, 0 | Modified=yes
Compiled | yes, no, 1, 0 | Compiled=0
Date | Date, in the numeric format determined by your regional settings | "Date=12/1/2012"
Time | Time, in the numeric format determined by your regional settings | "Time=12:00:00"
Version List | Any valid version | "Version List=NAVW17.00"
Caption | Any valid caption | "Caption=Company Information"
Locked | Yes, no, 1, 0 | Locked=1
Locked By | Domain\username | "Locked By=CRONUS\viktor"

Note
If you do not specify a filter, then captions are added on all objects in the Object table.

logfile

The path and file name for the file that contains error messages that result from the command. If there are no errors, then a log file is not created.

By default, the file is named naverrorlog.txt and is located in the same location as finsql.exe.

The navcommandresult.txt file, which contains information about the success or failure of the command, is created in the folder that is specified by the logfile parameter.

When you run finsql.exe with a command, the previous log file and result file are deleted.

Note
If User Access Control (UAC) is turned on and you do not specify to run the Command Prompt window as Administrator, then the Command Prompt window runs as a standard user. In this case, if you do not specify the logfile parameter, then the command fails because the standard user cannot write to the default location of the log file.

username

The user name to use to authenticate to the database. The user name must exist in the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

Note
If User Access Control (UAC) is turned on and you do not specify to run the Command Prompt window as Administrator, then the Command Prompt window runs as a standard user. In this case, if you do not specify the username parameter and the current Windows user is an Administrator, then the command is run as the standard user.

If you specify the username parameter, then you must also specify the password parameter and the ntauthentication parameter must be no.

For more information about database users and permissions, see Setting Database Owner and Security Administration Permissions.

password

The password to use with the username parameter to authenticate to the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

ntauthentication

Specifies if you want to use NT authentication. The possible values are yes, no, 1, or 0. If you specify the username and password parameters, then you must specify ntauthentication=no or ntauthentication=0.

Remarks

The CreateLanguage command adds a language caption entry in the CaptionML Property of the controls in the objects that you specify. By default, the caption is the same value as the Name Property of the control.

Note
After you run the command, you must to compile the modified objects. For more information, see Compiling Objects.

Example

This example adds captions for Danish (DAN) on all table and page objects with IDs from 1 to 10000 in the NAV Danish Database.

Copy Code
finsql.exe command=createlanguage, langid=DAN, servername=TestComputer01\NAVDEMO, database="NAV Danish Database", filter="Table|Page;ID=1..10000"

See Also

Reference

BuildVirtualMetadata
CreateDatabase
UpgradeDatabase
DeleteObjects
DesignObject
ExportObjects
ImportObjects
ExportLangModule
ImportLangModule
ExportTranslate
ImportTranslate

Concepts

Compiling Objects
Using the Development Environment from the Command Prompt


ExportLangModule

Exports a language module from the specified database to a file.

finsql.exe command=exportlangmodule, file=<exportfile>, langid=<langid>, [servername=<server>,] [database=<database>,] [logfile=<path and filename>,] [username=<username>,] [password=<password>,] [ntauthentication=<yes|no|1|0>]

Parameters

file

Specifies the path and file name to which you want to export the language module. This parameter is required.

Give the file name the extension .flm, for example, C:\ENUlanguagemodule.flm.

langid

Specifies the standard Windows three-letter ID of the language that you want to export, such as ENU or DAN.

ENU is the default value. If you do not specify the langid parameter, then the language module for ENU is exported.

servername

The name of the database server that hosts the Microsoft Dynamics NAV database that contains the language module that you want to export. The format of this parameter is <computername>\<database server instance>.

If you do not specify both the servername and the database parameter, then the database server and database that are stored in the fin.zup file are used.

Note
When you first specify a database server and database to open, either from a command at a command prompt or from a client, the database server and database are stored in the fin.zup file. By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\.

If you do not specify the servername parameter but you do specify the database parameter, then the Open Database window opens so that you can specify the database server name.

Tip
To view the name of the server on which the current database is stored, on the File menu, choose Database, and then choose Information. Use the value of the Database Server field for the servername parameter.

database

The name of the database in which the language that you want export to is stored.

If you do not specify both the servername and the database parameter, then the database server and database that are stored in the fin.zup file are used.

Note
When you first specify a database server and database to open, either from a command at a command prompt or from a client, the database server and database are stored in the fin.zup file. By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\.

If you do not specify the database parameter but you do specify the servername parameter, then the Open Database window opens so that you can specify the database name.

Tip
To view the name of the current database, on the File menu, choose Database, and then choose Information. Use the value of the Database Name field for the database parameter.

logfile

The path and file name for the file that contains error messages that result from the command. If there are no errors, then a log file is not created.

By default, the file is named naverrorlog.txt and is located in the same location as finsql.exe.

The navcommandresult.txt file, which contains information about the success or failure of the command, is created in the folder that is specified by the logfile parameter.

When you run finsql.exe with a command, the previous log file and result file are deleted.

Note
If User Access Control (UAC) is turned on and you do not specify to run the command prompt window as Administrator, then the command prompt window runs as a standard user. In this case, if you do not specify the logfile parameter, then the command fails because the standard user cannot write to the default location of the log file.

username

The user name to use to authenticate to the database. The user name must exist in the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

Note
If User Access Control (UAC) is turned on, and you do not specify to run the command prompt window as Administrator, then the command prompt window runs as a standard user. In this case, if you do not specify the username parameter, then even if the current Windows user is an Administrator, the command is run as the standard user.

If you specify the username parameter, then you must also specify the password parameter and the ntauthentication parameter must be no.

For more information about database users and permissions, see Setting Database Owner and Security Administration Permissions.

password

The password to use with the username parameter to authenticate to the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

ntauthentication

Specifies whether to use NT authentication. The possible values are yes, no, 1, or 0. If you specify the username and password parameters, then you must specify ntauthentication=no or ntauthentication=0.

Remarks

The language is not deleted from the database.

Example

This example shows how to run the ExportLangmodule command to export a language module for Danish (DAN) from the Demo Database NAV (9-0) database.

Copy Code
finsql.exe command=exportlangmodule, langid=DAN, file=C:\DANlanguagemodule.flm, servername=TestComputer01\NAVDEMO, database="Demo Database NAV (9-0)", username=dbadmin, password=P@ssword, ntauthentication=no, logfile=C:\ExportDANlanguagemoduleLog.txt

See Also

Reference

BuildVirtualMetadata
CreateDatabase
UpgradeDatabase
CreateLanguage
CompileObjects
DeleteObjects
DesignObject
ExportObjects
ImportObjects
ImportLangModule
ExportTranslate
ImportTranslate

Concepts

Compiling Objects
Using the Development Environment from the Command Prompt


ImportLangModule

Imports a language module from a file to the specified Microsoft Dynamics NAV database.

finsql.exe command=importlangmodule, file=<importfile>, [servername=<server>,] [database=<database>,] [filter=<filter>,] [logfile=<path and filename>,] [username=<username>,] [password=<password>,] [ntauthentication=<yes|no|1|0>]

Parameters

file

Specifies the path and file name of the language module to import. This parameter is required.

The file name should have the extension .flm, for example, C:\ENUlanguagemodule.flm.

servername

The name of the database server that hosts the Microsoft Dynamics NAV database in which to import the language module. The format of this parameter is <computername>\<database server instance>.

If you do not specify both the servername and the database parameter, then the database server and database that are stored in the fin.zup file are used.

Note
When you first specify a database server and database to open, either from a command at a command prompt or from a client, the database server and database are stored in the fin.zup file. By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\.

If you do not specify the servername parameter but you do specify the database parameter, then the Open Database window opens so that you can specify the database server name.

Tip
To view the name of the server on which the current database is stored, on the File menu, choose Database, and then choose Information. Use the value of the Database Server field for the servername parameter.

database

The name of the Microsoft Dynamics NAV database in which to import the language module.

If you do not specify both the servername and the database parameter, then the database server and database that are stored in the fin.zup file are used.

Note
When you first specify a database server and database to open, either from a command at a command prompt or from a client, the database server and database are stored in the fin.zup file. By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\.

If you do not specify the database parameter but you do specify the servername parameter, then the Open Database window opens so that you can specify the database name.

Tip
To view the name of the current database, on the File menu, choose Database, and then choose Information. Use the value of the Database Name field for the database parameter.

filter

A filter on the Object table. Use the filter parameter to specify the objects to which you want to import the language module. Use a semicolon to separate multiple filters. The only operator that you can use in the filter is '='. The following table shows the fields in the Object table on which you can filter.

Object table field | Values | Example
Type | Table, Codeunit, Page, Report, XMLport, Query | Type=Table|Page
ID | Integer or range of integers | ID=50000..50500
Name | Any valid object name | "Name=Cost Entry"
Modified | yes, no, 1, 0 | Modified=yes
Compiled | yes, no, 1, 0 | Compiled=0
Date | Date, in the numeric format determined by your regional settings | Date=12/1/2012
Time | Time, in the numeric format determined by your regional settings | Time=12:00:00
Version List | Any valid version | Version List=NAVW17.00
Caption | Any valid caption | Caption=Company Information
Locked | Yes, no, 1, 0 | Locked=1
Locked By | Domain\username | "Locked By=CRONUS\viktor"

If you do not specify a filter, then all objects in the Object table are included.

logfile

The path and file name for the file that contains error messages that result from the command. If there are no errors, then a log file is not created.

By default, the file is named naverrorlog.txt and is located in the same location as finsql.exe.

The navcommandresult.txt file, which contains information about the success or failure of the command, is created in the folder that is specified by the logfile parameter.

When you run finsql.exe with a command, the previous log file and result file are deleted.

Note
If User Access Control (UAC) is turned on and you do not specify to run the command prompt window as Administrator, then the command prompt window runs as a standard user. In this case, if you do not specify the logfile parameter, then the command fails because the standard user cannot write to the default location of the log file.

username

The user name to use to authenticate to the database. The user name must exist in the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

Note
If User Access Control (UAC) is turned on, and you do not specify to run the command prompt window as Administrator, then the command prompt window runs as a standard user. In this case, if you do not specify the username parameter, then even if the current Windows user is an Administrator, the command is run as the standard user.

If you specify the username parameter, then you must also specify the password parameter and the ntauthentication parameter must be no.

For more information about database users and permissions, see Setting Database Owner and Security Administration Permissions.

password

The password to use with the username parameter to authenticate to the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

ntauthentication

Specifies whether to use NT authentication. The possible values are yes, no, 1, or 0. If you specify the username and password parameters, then you must specify ntauthentication=no or ntauthentication=0.

Remarks

You can specify parameters in any order.

Example

This example shows how to run the ImportLangModule command to import a language module for Danish (DAN) to the Demo Database NAV (9-0) database. The language module file path is C:\DANlanguagemodule.flm.

Copy Code
finsql.exe command=importlangmodule, file=C:\DANlanguagemodule.flm, servername=TestComputer01\NAVDEMO, database="Demo Database NAV (9-0)"

See Also

Reference

BuildVirtualMetadata
CreateDatabase
UpgradeDatabase
CreateLanguage
CompileObjects
DeleteObjects
DesignObject
ExportObjects
ImportObjects
ExportLangModule
ExportTranslate
ImportTranslate

Concepts

Compiling Objects
Using the Development Environment from the Command Prompt


ExportTranslate

Exports UI text strings of objects from a specified Microsoft Dynamics NAV database to a text file.

finsql.exe command=exporttranslate, file=<exportfile>, [servername=<server>,] [database=<database>,] [filter=<filter>,] [logfile=<path and filename>,] [username=<username>,] [password=<password>,] [ntauthentication=<yes|no|1|0>]

Parameters

file

Specifies the path and name of the text file in which to export the text strings, for example C:\translatestrings.txt. This parameter is required.

servername

The name of the database server that hosts the Microsoft Dynamics NAV database that contains the text strings to export. The format of this parameter is <computername>\<database server instance>.

If you do not specify both the servername and the database parameter, then the database server and database that are stored in the fin.zup file are used.

Note
When you first specify a database server and database to open, either from a command at a command prompt or from a client, the database server and database are stored in the fin.zup file. By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\.

If you do not specify the servername parameter but you do specify the database parameter, then the Open Database window opens so that you can specify the database server name.

Tip
To view the name of the server on which the current database is stored, on the File menu, choose Database, and then choose Information. Use the value of the Database Server field for the servername parameter.

database

The Microsoft Dynamics NAV database that contains the objects from which you want to export text strings.

If you do not specify both the servername and the database parameter, then the database server and database that are stored in the fin.zup file are used.

Note
When you first specify a database server and database to open, either from a command at a command prompt or from a client, the database server and database are stored in the fin.zup file. By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\.

If you do not specify the database parameter but you do specify the servername parameter, then the Open Database window opens so that you can specify the database name.

Tip
To view the name of the current database, on the File menu, choose Database, and then choose Information. Use the value of the Database Name field for the database parameter.

filter

Specifies a filter on the Object table. Use the filter parameter to specify which objects to export text strings for. For example, you can export text strings for a set of pages or reports. Use a semicolon to separate multiple filters. The only operator that you can use in the filter is '='. The following table shows the fields in the Object table on which you can filter.

Object table field | Values | Example
Type | Table, Codeunit, Page, Report, XMLport, Query | Type=Table|Page
ID | Integer or range of integers | ID=50000..50500
Name | Any valid object name | "Name=Cost Entry"
Modified | yes, no, 1, 0 | Modified=yes
Compiled | yes, no, 1, 0 | Compiled=0
Date | Date, in the numeric format determined by your regional settings | "Date=12/1/2012"
Time | Time, in the numeric format determined by your regional settings | "Time=12:00:00"
Version List | Any valid version | "Version List=NAVW17.00"
Caption | Any valid caption | "Caption=Company Information"
Locked | Yes, no, 1, 0 | Locked=1
Locked By | Domain\username | "Locked By=CRONUS\viktor"

If you do not specify a filter, then text strings from all objects in the Object table are exported.

logfile

The path and file name for the file that contains error messages that result from the command. If there are no errors, then a log file is not created.

By default, the file is named naverrorlog.txt and is located in the same location as finsql.exe.

The navcommandresult.txt file, which contains information about the success or failure of the command, is created in the folder that is specified by the logfile parameter.

When you run finsql.exe with a command, the previous log file and result file are deleted.

Note
If User Access Control (UAC) is turned on and you do not specify to run the command prompt window as Administrator, then the command prompt window runs as a standard user. In this case, if you do not specify the logfile parameter, then the command fails because the standard user cannot write to the default location of the log file.

username

The user name to use to authenticate to the database. The user name must exist in the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

Note
If User Access Control (UAC) is turned on, and you do not specify to run the command prompt window as Administrator, then the command prompt window runs as a standard user. In this case, if you do not specify the username parameter, then even if the current Windows user is an Administrator, the command is run as the standard user.

If you specify the username parameter, then you must also specify the password parameter and the ntauthentication parameter must be no.

For more information about database users and permissions, see Setting Database Owner and Security Administration Permissions.

password

The password to use with the username parameter to authenticate to the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

ntauthentication

Specifies whether to use NT authentication. The possible values are yes, no, 1, or 0. If you specify the username and password parameters, then you must specify ntauthentication=no or ntauthentication=0.

Remarks

You can use this command for translating text strings in multilanguage setup of Microsoft Dynamics NAV. This command exports all text strings that are associated with objects, which includes text strings that are defined by for properties of the objects in all languages. For more information, see How to: Add Translated Strings By Importing and Exporting Multilanguage Files and Multilanguage Development.

Example

This example shows how to run the ExportTranslate command to export text strings from the Demo Database NAV (9-0) database to a .txt type file that has the path and file name C:\navtextstrings.txt.

Copy Code
finsql.exe command=exporttranslate, file=C:\navtextstrings.txt, servername=TestComputer01\NAVDEMO, database="Demo Database NAV (9-0)"

See Also

Reference

BuildVirtualMetadata
CreateDatabase
UpgradeDatabase
CreateLanguage
CompileObjects
DeleteObjects
DesignObject
ExportObjects
ImportObjects
ExportLangModule
ImportLangModule
ExportTranslate
ImportTranslate

Concepts

Compiling Objects
Using the Development Environment from the Command Prompt


ImportTranslate

Imports UI text strings for objects from a text file to a specified Microsoft Dynamics NAV database.

finsql.exe command=importtranslate, file=<importfile>, [servername=<server>,] [database=<database>,] [filter=<filter>,] [logfile=<path and filename>,] [username=<username>,] [password=<password>,] [ntauthentication=<yes|no|1|0>]

Parameters

file

Specifies the path and name of the text file that contains the text strings to import, for example C:\translatestrings.txt. This parameter is required.

servername

The name of the database server that hosts the Microsoft Dynamics NAV database in which you want to import text strings. The format of this parameter is <computername>\<database server instance>.

If you do not specify both the servername and the database parameter, then the database server and database that are stored in the fin.zup file are used.

Note
When you first specify a database server and database to open, either from a command at a command prompt or from a client, the database server and database are stored in the fin.zup file. By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\.

If you do not specify the servername parameter but you do specify the database parameter, then the Open Database window opens so that you can specify the database server name.

Tip
To view the name of the server on which the current database is stored, on the File menu, choose Database, and then choose Information. Use the value of the Database Server field for the servername parameter.

database

The Microsoft Dynamics NAV database in which you want to import the text strings.

If you do not specify both the servername and the database parameter, then the database server and database that are stored in the fin.zup file are used.

Note
When you first specify a database server and database to open, either from a command at a command prompt or from a client, the database server and database are stored in the fin.zup file. By default, the fin.zup file is located at C:\users\<user name>\AppData\Roaming\.

If you do not specify the database parameter but you do specify the servername parameter, then the Open Database window opens so that you can specify the database name.

Tip
To view the name of the current database, on the File menu, choose Database, and then choose Information. Use the value of the Database Name field for the database parameter.

filter

A filter on the Object table. Use the filter parameter to specify the objects to which you want to import the text strings. Use a semicolon to separate multiple filters. The only operator that you can use in the filter is '='. The following table shows the fields in the Object table on which you can filter.

Object table field | Values | Example
Type | Table, Codeunit, Page, Report, XMLport, Query | Type=Table|Page
ID | Integer or range of integers | ID=50000..50500
Name | Any valid object name | "Name=Cost Entry"
Modified | yes, no, 1, 0 | Modified=yes
Compiled | yes, no, 1, 0 | Compiled=0
Date | Date, in the numeric format determined by your regional settings | Date=12/1/2012
Time | Time, in the numeric format determined by your regional settings | Time=12:00:00
Version List | Any valid version | Version List=NAVW17.00
Caption | Any valid caption | Caption=Company Information
Locked | Yes, no, 1, 0 | Locked=1
Locked By | Domain\username | "Locked By=CRONUS\viktor"

If you do not specify a filter, then all objects in the Object table are included.

logfile

The path and file name for the file that contains error messages that result from the command. If there are no errors, then a log file is not created.

By default, the file is named naverrorlog.txt and is located in the same location as finsql.exe.

The navcommandresult.txt file, which contains information about the success or failure of the command, is created in the folder that is specified by the logfile parameter.

When you run finsql.exe with a command, the previous log file and result file are deleted.

Note
If User Access Control (UAC) is turned on and you do not specify to run the command prompt window as Administrator, then the command prompt window runs as a standard user. In this case, if you do not specify the logfile parameter, then the command fails because the standard user cannot write to the default location of the log file.

username

The user name to use to authenticate to the database. The user name must exist in the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

Note
If User Access Control (UAC) is turned on, and you do not specify to run the command prompt window as Administrator, then the command prompt window runs as a standard user. In this case, if you do not specify the username parameter, then even if the current Windows user is an Administrator, the command is run as the standard user.

If you specify the username parameter, then you must also specify the password parameter and the ntauthentication parameter must be no.

For more information about database users and permissions, see Setting Database Owner and Security Administration Permissions.

password

The password to use with the username parameter to authenticate to the database. If you do not specify a user name and password, then the command uses the Windows user name and password of the current user to authenticate to the database.

ntauthentication

Specifies whether to use NT authentication. The possible values are yes, no, 1, or 0. If you specify the username and password parameters, then you must specify ntauthentication=no or ntauthentication=0.

Remarks

You can use this command for translating text strings in multilanguage setup of Microsoft Dynamics NAV. The contents of the text file must be compatible with Microsoft Dynamics NAV. Therefore, the text file will typically have originated from a text file that was previously exported from the database, and then modified. For more information, see How to: Add Translated Strings By Importing and Exporting Multilanguage Files and Multilanguage Development.

Example

This example shows how to run the ImportTranslate command to import text strings from a text file to the Demo Database NAV (9-0) database. The text file that has the path and file name C:\navtextstrings.txt.

Copy Code
finsql.exe command=importtranslate, file=C:\navtextstrings.txt, servername=TestComputer01\NAVDEMO, database="Demo Database NAV (9-0)"

See Also

Reference

BuildVirtualMetadata
CreateDatabase
UpgradeDatabase
CreateLanguage
CompileObjects
DeleteObjects
DesignObject
ExportObjects
ImportObjects
ExportLangModule
ImportLangModule
ExportTranslate
ImportTranslate

Concepts

Compiling Objects
Using the Development Environment from the Command Prompt


GetBuildVersion

Gets the Microsoft Dynamics NAV product name and build version number that is currently installed and saves the information to a .txt type file.

finsql.exe command=getbuildversion, file=<versionfile>[, logfile=<path and filename>]

Parameters

file

Specifies the folder path and file name of the text file, for example C:\navbuildversion.txt, in which to save the build information. This parameter is required.

logfile

The folder path and file name of a text file, for example C:\navbuildversionlog.txt, in which to save error messages that result from the command. If there are no errors when you run the command, then a log file is not created.

Remarks

When you run the command, a file that contains information about the success or failure of the command is automatically created. The file has the name navcommandresult.txt. If you specify the logfile parameter, then the navcommandresult.txt file is created in the folder that is specified by the logfile parameter. If you do not specify the logfile parameter, the file is created in the same location as finsql.exe file, which by default is C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client.

Note
If User Access Control (UAC) is turned on and you do not run the command prompt as an Administrator, then the command prompt window runs as a standard user. In this case, if you do not specify the logfile parameter, then the command fails because the standard user cannot write to the default location of the finsql.exe file.

Example

This example shows how to run the GetBuildVersions command to get the product name and version of Microsoft Dynamics NAV that is currently installed on the computer. The example saves the build version information to a .txt type file that has the path and file name C:\temp\navbuildversion.txt. The example also specifies a log file that has the path and file name C:\temp\navbuildversionlog.txt

Copy Code
finsql.exe command=getbuildversion.txt, file=C:\temp\navbuildversion.txt, logfile= C:\temp\navbuildversionlog.txt

The build version file, in this case navbuildversion.txt, includes information that is similar to the following:

Product Name: Microsoft Dynamics NAV 2016

Product Version: 8.0.38865.0

See Also

Concepts

Using the Development Environment from the Command Prompt
Development Environment Commands


Window Overviews

To see the window topics in this section, choose the subentries in the table of contents.


Navigation Pane Designer

Creates and customizes MenuSuite objects. Navigation Pane Designer contains menus that represent departments in a company. It also contains menu items for each department. You modify the menus and menu items in Navigation Pane Designer.

You can modify a basic MenuSuite object, or you can create new objects from the basic MenuSuite object. You select the MenuSuite object that you to want to modify in Object Designer and then make your changes in Navigation Pane Designer.

Note
You cannot run MenuSuite objects from Object Designer. Instead, you run them in the Microsoft Dynamics NAV Windows client.

To open this window, on the Tools menu, choose Object Designer. In Object Designer, choose MenuSuite, select the MenuSuite that you want to modify, and then choose the Design button.

To create a new MenuSuite, in Object Designer, choose MenuSuite, choose the New button, select a design level, and then choose the OK button.

See Also

Tasks

How to: Modify Menu Items in a MenuSuite

Concepts

Designing MenuSuites


Insert Items

Inserts a menu item into a department menu. You can insert a menu item that is already created in Navigation Pane Designer. When you insert a menu item, you select the menu item from a list of menu items that are located in other departments or group folders. The Insert Items window lists all menu items that you can insert. The menu items are listed by the department where they were created and then alphabetically by menu item name.

To open this window, open Navigation Pane Designer, and then choose a department. In the department menus, right-click a folder, and then choose Insert Item. For more information about how to open Navigation Pane Designer, see Navigation Pane Designer.

Fields

Field | Description
Insert | The menu item to insert.
Item | The name of the menu item to insert.

See Also

Reference

Navigation Pane Designer


Create Item

Creates menu items in a department. In the Microsoft Dynamics NAV Windows client, menus items link to specific objects that you select from this window.

To open this window, open Navigation Pane Designer, choose a department, right-click the area where you want to create the item, and then choose Create Item. For more information about how to open Navigation Pane Designer, see Navigation Pane Designer.

Properties

Property Description

Object Type

The type of object that you want to create. You can select the following object types:

  • Codeunit

  • Page

  • Report

  • Query

  • XMLport

Object ID

The ID of the specific object type that you want to create. You select the ID from the <Object Type> List window, which provides a list of specific object types that you selected in Object Type. For example, if you selected Report, a list of reports is displayed.

Caption

The caption of the menu item.

CaptionML

The string that is used to identify the menu item in the user interface. The CaptionML Property is multilanguage enabled. Therefore, it can contain a list of text strings in different languages. The string that is used is selected according to the language settings on your computer.

Department

The category in the department menu where you want the menu item to be displayed in the Microsoft Dynamics NAV Windows client. You can select from the following categories:

  • List

  • Tasks

  • Reports and Analysis

  • Documents

  • History

  • Administration

See Also

Tasks

How to: Modify Menu Items in a MenuSuite

Reference

Navigation Pane Designer


Object List

Lists the objects that can be selected. This list can contain any kind of object. For example, when you create an item in a MenuSuite, you can create the item from a list of available objects.

To open this window, in Navigation Pane Designer, right-click a folder, and then choose Create Item. In the Object Type field, select an object, and then choose the Up Arrow button in the Object ID field.

For more information about how to open Navigation Pane Designer, see Navigation Pane Designer.

The following table describes the <object> list windows.

<Object> List | Description
Table List | List the tables that are available.
Page List | List the pages that are available.
Report List | List the reports that are available.
Codeunit List | List the codeunits that are available.
Query List | List the queries that are available.
XMLport List | List the XMLports that are available.

See Also

Concepts

Window Overviews


Group Properties

Groups menu items in a department. A group is a folder that you use to group related menu items. You group menu items to make them easier to access in the Microsoft Dynamics NAV Windows client. A group folder is displayed on the Microsoft Dynamics NAV Windows client as a submenu in the department. You can create a group folder inside another group folder. The group folder that is inside another group folder is a submenu.

To open this window, open Navigation Pane Designer, choose a department, right-click the area where you want to group the items, and then choose Create Group. For more information about how to open Navigation Pane Designer, see Navigation Pane Designer.

Properties

The following table describes the properties that can be set in the Group Properties window.

Property | Description
Caption | The caption of the group folder that you want to create.
CaptionML | The string that is used to identify the menu in the user interface. The CaptionML Property is multilanguage enabled. Therefore, it can contain a list of text strings in different languages. The string that is used is selected according to the language settings on your computer.
Department Page | Indicates whether a group folder should be displayed on the department page in the Microsoft Dynamics NAV Windows client. If this property is set to true, the group folder is displayed on the department page. Otherwise, the group folder will be displayed in the department category where the menu items are located.

See Also

Tasks

How to: Modify Menu Items in a MenuSuite

Reference

Navigation Pane Designer


Create Menu

Creates a new menu for a department. This menu represents a department in a company.

To open this window, open Navigation Pane Designer, right-click the department area, and then choose Create Menu. For more information about how to open Navigation Pane Designer, see Navigation Pane Designer.

Properties

Property | Description
Caption | The caption of the menu you want to create.
CaptionML | The string that is used to identify the menu in the user interface. The CaptionML Property is multilanguage enabled. Therefore, it can contain a list of text strings in different languages. The string that is used is selected according to the language settings on your computer.
Bitmap | The bitmap that you want to display on the menu button for the department. The number you enter represents the bitmap. You can enter numbers from 0 to 15. For more information, see Bitmap Property.

See Also

Tasks

How to: Create a Menu for a Department in a MenuSuite
Walkthrough: Creating MenuSuites for the Microsoft Dynamics NAV Windows Client

Reference

Navigation Pane Designer
Create Menu
Bitmap Property


Show Menus

Shows a menu in Navigation Pane Designer and the Microsoft Dynamics NAV Windows client. In Navigation Pane Designer, you can hide a menu so that it does not appear in both Navigation Pane Designer and the Microsoft Dynamics NAV Windows client. To show a menu that has been hidden, you select it from the Show Menus window and then show it in the designer. Menus that are hidden are listed in this window.

To open this window, open Navigation Pane Designer, right-click the department area, and then choose Show in Designer. For more information about how to open Navigation Pane Designer, see Navigation Pane Designer.

See Also

Tasks

How to: Modify a Department Menu in a MenuSuite

Reference

Navigation Pane Designer


Menu Properties

Modifies a menu for a department. The menu represents a department in a company.

To open this window, open Navigation Pane Designer, right-click the department that you want to modify, and then choose Properties. For information about how to open Navigation Pane Designer, see Navigation Pane Designer.

Properties

Property | Description
Caption | The caption of the menu.
CaptionML | The string that is used to identify the menu in the user interface. The CaptionML Property is multilanguage enabled. Therefore, it can contain a list of text strings in different languages. The string that is used is selected according to the language settings on your computer.
Bitmap | The bitmap that is displayed on the menu button in Navigation Pane Designer. The valid bitmap values are from 0 to 15. The number represents the bitmap.

See Also

Tasks

How to: Modify a Department Menu in a MenuSuite

Reference

Navigation Pane Designer


License Information

Shows the contents of the current license file. The information includes the license number, the name of the license owner, which application granules are included, and when the license expires. Typically, your serial number and the name of your company appear in the window. If your license file is not is shown in the window, then you must upload your own file by choosing the Upload button.

You generally do not have to use the License Information window. However, if you want to make any modifications or if you have problems with your license file, then you may have to open it.

To open this window, on the Tools menu, choose License Information.

Note
All license files that are not CRONUS International Ltd. demonstration license files have the same name, which is fin.flf. After you have received your license file and imported it, you should store the disk that contains the file in a safe location until you need it again. The CRONUS demonstration license file is saved under a different name, which is cronus.flf, so that you cannot overwrite it with your own license file.

Buttons

The following table shows the buttons in the License Information window.

Button Description

Upload

Uploads your license file to the SQL Server that you want to access. The license information will be used by all client computers that connect to this server unless a database license file is being used.

Change

Allows for a temporary change to a license file. This function ensures that the change is not saved the next time that you start the development environment, and your old license file is used. Use this function if you want to use the cronus.flf CRONUS demonstration license file and not overwrite your own license file.

You will receive a warning message before your license expires. If you allow the license on the server to expire, then you cannot access the server. However, you can use the Change function to access the server by using an alternate license file.

See Also

Tasks

How to: Upload the License File

Concepts

Properties of the Demo License
Administration in the Development Environment


Permissions

Manages object permissions for the selected codeunit.

To open this window, on the Tools menu, choose Object Designer, choose an object such as a table, and then on the View menu, choose Properties. In the Properties window, locate the Permissions property, and then choose the AssistEdit button in the Value field.


Object List

Lists the available objects to which you can assign permissions.

To open this window, open the Permissions window, and then choose the Up Arrow button in the Object ID column. For more information about how to open the Permissions window, see Permissions.


Select Server

Selects the computer running SQL Server on which you want to create a new database.

To open this window, on the File menu, choose Database, and then choose New.

See Also

Tasks

How to: Create Databases


Available Microsoft SQL Servers

Shows a list of the SQL Server instances that are currently available in the domain. The Server Name field contains the names of the SQL Server instances that are currently available.

To open this window, open the Open Database window, and then on the General tab, choose the Up Arrow button in the Server Name field. For more information about how to open the Open Database window, see Open Database.

To choose a server that is on the list, either select it and then choose the OK button or double-click the server name.

See Also

Tasks

How to: Create Databases
How to: Open Databases


Open Database

Specifies the database that you want to open.

To open this window, on the File menu, choose Database, and then choose Open.

General Tab

Field | Description
Server Name | The name of the SQL Server instance. You can choose the up arrow to select the server from the Available Microsoft SQL Servers window, or you can enter the server name manually.
Database Name | The name of the database that you want to open. You can choose the up arrow to select the server from the Available Databases window, or you can enter the database name manually.
Authentication | The authentication type that you want to use to connect to the server. You can select Database Server Authentication or Windows Authentication.
User ID | If you have selected Database Server Authentication in the Authentication field, then you must enter a user ID.
Password | If you have selected Database Server Authentication in the Authentication field, then you must enter a password.

Advanced Tab

Field | Description
Net type | The network type to use to connect to SQL Server. You generally do not have to change the network type from the default setting. The Default network type setting enables Microsoft Dynamics NAV to connect to a server by using the default client network type that is assigned by SQL Server. If you have installed SQL Server Client Utilities, then you can change the network type with the Client Network Utility, which is part of the SQL Server Client Utilities.
Attach file | If you want to attach and open a detached database that consists of a single data file, excluding the transaction log file, then you must enter the complete path and file name of the database in the Attach File field. This file typically has the .mdf file name extension. You can give this single file database any name by entering it in the Database Name field on the General tab. If no transaction log file exists with the data file, it is automatically created when you attach the data file. The database file is attached when you open it.

See Also

Tasks

How to: Open Databases

Concepts

Configuring Microsoft SQL Server


New Database

Creates a database.

Before you can enter any information in this window, you must enter the correct information in the Select Server window.

To open this window, on the File menu, choose Database, choose New, and then in the Select Server window, choose the OK button.

The New Database window contains the same tabs as the Alter Database window. The window contains the following tabs:

  • Altering Databases - General Tab

  • Altering Databases - Database Files Tab

  • Altering Databases - Transaction Log Files Tab

  • Altering Databases - Collation Tab

  • Altering Databases - Options Tab

  • Altering Databases - Integration Tab

  • Altering Databases - Advanced Tab

See Also

Tasks

How to: Create Databases


Available Databases

Shows a list of the SQL Server databases that you can access from Microsoft Dynamics NAV and that are currently available on this SQL Server instance. This window displays the following information:

  • Name of the database.

  • Who created the database.

  • When the database was created.

  • Whether the database is being replicated on SQL Server.

  • The type of replication that is being used.

You cannot change the contents of this window.

To open this window, open the Open Database window, and then on the General tab, choose the Up Arrow button in the Database Name field. For information about how to open the Open Database window, see Open Database.

Note
You must select a SQL Server instance before you can select a database.

See Also

Tasks

How to: Create Databases
How to: Open Databases


Alter Database

Modifies a database.

To open this window, on the File menu, choose Database, and then choose Alter.

This window contains the following tabs:

  • Altering Databases - General Tab

  • Altering Databases - Database Files Tab

  • Altering Databases - Transaction Log Files Tab

  • Altering Databases - Collation Tab

  • Altering Databases - Options Tab

  • Altering Databases - Integration Tab

  • Altering Databases - Advanced Tab

See Also

Tasks

How to: Alter Databases


Altering Databases - General Tab

Shows the name of the currently opened database and the name of the SQL Server instance on which the currently opened database is stored. You cannot change the contents of this tab.

To open this window, on the File menu, choose Database, choose Alter, and then choose the General tab.

See Also

Tasks

How to: Alter Databases

Concepts

Altering Databases - Database Files Tab
Altering Databases - Transaction Log Files Tab
Altering Databases - Collation Tab
Altering Databases - Options Tab
Altering Databases - Integration Tab
Altering Databases - Advanced Tab


Altering Databases - Database Files Tab

Increases the size of the database by either increasing the size of one or more of the database files or adding new data files to the database.

If you use secondary data files, then you must increase the size of the primary data file only when the catalog that it contains has become too large. When the catalog has become too large, new SQL Server objects, such as tables, cannot be created until you increase the size of the primary data file.

When you use secondary data files, you cannot create more space for storing Microsoft Dynamics NAV data by just increasing the size of the primary data file. You can create more space for storing data by increasing the size of the secondary data files that contain Microsoft Dynamics NAV information. You can also add new secondary data files in order to store more data.

To open this window, on the File menu, choose Database, choose Alter, and then choose the Database Files tab.

Note
The first data file that is listed on the Database Files tab is the primary file.

See Also

Tasks

How to: Increase the Size of Database Files
How to: Add New Database Files
How to: Alter Databases

Concepts

Altering Databases - General Tab
Altering Databases - Transaction Log Files Tab
Altering Databases - Collation Tab
Altering Databases - Options Tab
Altering Databases - Integration Tab
Altering Databases - Advanced Tab


Altering Databases - Transaction Log Files Tab

Increases the size of the existing transaction log files or adds new files to enable more transactions to be performed in the database. The transaction log grows as new transactions are performed in the database. SQL Server truncates the log after it performs a successful database or transaction log backup.

To open this window, on the File menu, choose Database, choose Alter, and then choose the Transaction Log Files tab.

You can also delete existing transaction log files that are empty. The first transaction log file that is listed is the primary file. You cannot delete the primary transaction log file.

See Also

Tasks

How to: Increase the Size of Transaction Log Files
How to: Add New Transaction Log Files
How to: Alter Databases

Concepts

Altering Databases - General Tab
Altering Databases - Database Files Tab
Altering Databases - Collation Tab
Altering Databases - Options Tab
Altering Databases - Integration Tab
Altering Databases - Advanced Tab


Altering Databases - Collation Tab

Changes the collation that is used by the database.

To open this window, on the File menu, choose Database, choose Alter, and then choose the Collation tab.

Before you change the collation, you have to select the Single user option on the Options tab.

Changing the Collation of a Microsoft Dynamics NAV Database

If you change the database collation, then the collation of objects in the database is changed except for tables that have the LinkedObject property set to Yes. You must manually re-create these objects. For example, you can script them in SQL Server Management Studio.

If you change the collation from a case-sensitive to a case-insensitive collation or from an accent-sensitive to an accent-insensitive collation, then duplicates can occur in the primary keys of the tables. Duplicates can be caused by the values of the character data stored in the primary keys. If duplicates occur, then you receive an error message and the database collation change is stopped. We recommend that you do not change these attributes of a collation.

Note
Changing the collation can be a lengthy process that depends on the size of the database and the number of companies in the database. The system tables and all user table indexes that contain character data must be rebuilt.

The Language drop-down list displays the friendly name of the language, not the full Windows collation name. For some languages, there are multiple collations that sort characters differently. For example, the Windows collation languages include multiple Scandinavian languages, some of which sort Aa after Z, Æ, Ø, and some of which sort Aa after A and before B. If you upgrade from Microsoft Dynamics NAV 2009 to Microsoft Dynamics NAV 2016, you upgrade the database to the Windows collations. If you used SQL collation in earlier versions of Microsoft Dynamics NAV, then after you upgrade, verify that the Windows collation sorts characters in the way that you expect.

If you set the Validate Collation check box, then collation languages that run with a different non-Unicode code page from your system non-Unicode code page are filtered out of the Language drop-down list. An example scenario of when you might want to choose a collation language that has a different code page from your system code page is if you want to prepare a Japanese database on a Danish computer.

You cannot change the collation directly in the current database. To change the collation, you must create a new database that uses the correct collation, and then export the data from the old database and import it to the new database. For more information, see How to: Alter Databases

See Also

Tasks

How to: Alter Databases
How to: Alter Databases

Concepts

Altering Databases - General Tab
Altering Databases - Database Files Tab
Altering Databases - Transaction Log Files Tab
Altering Databases - Options Tab
Altering Databases - Integration Tab
Altering Databases - Advanced Tab


Altering Databases - Options Tab

Specifies database options that you set when you created the database. For example, you must select the Single User option before you perform any database tests. You must clear this option when the tests are completed.

To open this window, on the File menu, choose Database, choose Alter, and then choose the Options tab.

Access Section

Field Description

Single user

Specifies that only one user can access the database at a time. You can use this setting when you are performing administrative functions such as testing or restoring the database. By limiting access to the database to one user, you make sure that the database is not changed when you are testing it.

Important
Clear this check box when you are finished to give other users to access the database.

Settings Section

Field Description

Recovery Model

Determines the kind of information that is written to the transaction log and therefore the kind of recovery model that you want to use in this database.

Note
The Full and Bulk-logged recovery models are similar, and many users of the Full recovery model will use the Bulk-logged recovery model occasionally.

Option Description

Bulk-logged

The transaction log will contain only limited information about certain large-scale or bulk copy operations. The Bulk-logged recovery model provides protection against media failure combined with the best performance and the minimal use of log space for certain large-scale or bulk copy operations.

The backup strategy for bulk-logged recovery consists of:

  • Database backups.

  • Differential backups (optional).

Full

The details of every transaction are stored in the transaction log. This information can be used when you apply transaction log backups. The Full recovery model uses database backups and transaction log backups to provide complete protection against media failure. If one or more data files are damaged, media recovery can restore all the committed transactions. Incomplete transactions are rolled back.

Full recovery lets you recover the database to the point of failure or to a specific point in time. All operations are fully logged to guarantee that the database is recoverable. This includes bulk operations such as SELECT INTO, CREATE INDEX, and bulk loading data.

The backup strategy for full recovery consists of:

  • Database backups.

  • Differential backups (optional).

  • Transaction log backups.

Simple

The database can be recovered to the point at which the last backup was made. However, you cannot restore the database to the point of failure or to a specific point in time. To do that, select either the Full or Bulk-logged recovery model.

The backup strategy for simple recovery consists of:

  • Database backups.

  • Differential backups (optional).

ANSI NULL default

Specifies whether the database default NULL settings for column definitions and user-defined data types are to be applied. When you select this option, all user-defined data types or columns that have not been explicitly defined as NOT NULL are set to allow NULL entries. Columns that have been defined by using constraints follow the constraint rules, regardless of this setting.

Recursive triggers

Specifies recursive trigger settings. Triggers can have direct recursion or indirect recursion. Direct recursion occurs when a trigger occurs and performs an action that causes the same trigger to be fired again. Indirect recursion occurs when a trigger occurs and performs an action that causes a trigger on another table to occur. This second trigger updates the original table which causes the first trigger to occur again.

Torn page detection

Enables SQL Server to detect incomplete input/output operations that have been caused by power failures or other system outages.

Auto shrink

Specifies whether SQL Server can periodically shrink data files and transaction log files.

See Also

Tasks

How to: Alter Databases

Concepts

Altering Databases - General Tab
Altering Databases - Database Files Tab
Altering Databases - Transaction Log Files Tab
Altering Databases - Collation Tab
Altering Databases - Integration Tab
Altering Databases - Advanced Tab


Altering Databases - Integration Tab

Specifies database settings that determine how Microsoft Dynamics NAV integrates with SQL Server and external tools.

To open this window, on the File menu, choose Database, choose Alter, and then choose the Integration tab.

Objects Options

Field Description

Convert Identifiers

Defines characters that you want to map to the underscore character in the names of all SQL Server objects, such as tables, columns, and constraints. If these characters occur in tables or fields in Microsoft Dynamics NAV, then they are converted to underscores in the SQL Server names.

When the conversion is complete, you must close and reopen the database before you can use the new identifiers.

License Options

Field | Description
Save license in database | Specifies that the license file is uploaded and stored in the database instead of on the server. This is useful if you are hosting several databases with separate license files on the same server.

See Also

Tasks

How to: Alter Databases

Concepts

Altering Databases - General Tab
Altering Databases - Database Files Tab
Altering Databases - Transaction Log Files Tab
Altering Databases - Collation Tab
Altering Databases - Options Tab
Altering Databases - Advanced Tab


Altering Databases - Advanced Tab

Specifies how locking is handled in the database and specifies the start ID for elements on new objects.

To open this window, on the File menu, choose Database, choose Alter, and then choose the Advanced tab.

Locking Options

Field | Description
Lock timeout | Specifies whether a session waits to place a lock on a resource that has already been locked by another session. If you clear this field, then the session waits indefinitely.
Timeout duration (sec) | Specifies the maximum length of time that a session waits to place a lock on a resource that has already been locked by another session. The default value is 10 seconds.

Designer Options

Field | Description
Start ID (UidOffset) | Specifies the start ID for elements on new objects. When you create a new table, page, report, codeunit, query, or XMLport, the elements have IDs that are offset by the Start ID (UidOffset) value that you specify. Object elements include containers, groups, fields, parts, DataItems, columns, filters, variables, functions, or text constants. You must specify an Integer that is greater than or equal to 0. The default value is 1.

See Also

Tasks

How to: Alter Databases
How to: Specify the Start ID Offset of Elements on Objects

Concepts

Altering Databases - General Tab
Altering Databases - Database Files Tab
Altering Databases - Transaction Log Files Tab
Altering Databases - Collation Tab
Altering Databases - Options Tab
Altering Databases - Integration Tab


Database Information

Shows information about the database. The only field that you can change is the Server Instance field.

To open this window, on the File menu, choose Database and then choose Information.

General Tab

Field Description

Database Server

The full name of the SQL Server where the Microsoft Dynamics NAV database is stored.

You cannot change the contents of this field.

Database Name

The name of the Microsoft Dynamics NAV database that is currently open.

You cannot change the contents of this field.

SQL Edition

The edition of SQL Server that is running on the database server.

You cannot change the contents of this field.

Server Instance

The server instance name and server port of Microsoft Dynamics NAV Server. This is the server that is used to run objects in the current database. Choose the drop-down arrow to change the server instance. You can choose a server instance from the Available Server Instances window.

You can also change the server instance from the Options window.

For more information, see Managing Microsoft Dynamics NAV Server Instances and How to: Change the Microsoft Dynamics NAV Server Instance.

Sessions Tab

Field | Description
Licensed Sessions | The maximum number of sessions that can be connected to the database that has the current license. To view the current Microsoft Dynamics NAV sessions, in the Microsoft Dynamics NAV Windows client, in the Search box, enter Sessions, and then choose the related link.

See Also

Tasks

How to: Change the Microsoft Dynamics NAV Server Instance

Reference

Available Server Instances

Concepts

Managing Microsoft Dynamics NAV Server Instances


Available Server Instances

Shows the available Microsoft Dynamics NAV Server instances that can connect to the database. You select the instance that you want to use. For more information, see Managing Microsoft Dynamics NAV Server Instances.

To open this window, on the File menu, choose Database, and then choose Information to open the Database Information window. On the General tab, choose the Down Arrow button in the Server Instance field.

The available Microsoft Dynamics NAV Server instances are stored in table 2000000112, the Server Instance table. For more information, see Server Instance.

See Also

Tasks

How to: Change the Microsoft Dynamics NAV Server Instance

Reference

Database Information


Find

Searches for text. You can also replace text that you find with other text by choosing the Replace button.

To open this window, on the Edit menu, choose Find.

If you have set the Quick Find option in the Options window, then you can use the Find function by typing in a non-editable text or code field. To enable Quick Find, on the Tools menu, choose Options, and then enter Yes in the Quick Find field.

See Also

Reference

Replace


Replace

Replaces text that you find with other text. You can only replace information that can be changed. If you try to replace an entry that you cannot change, then you receive an error message.

To open this window, on the Edit menu, choose Replace. To open this window another way, on the Edit menu, choose Find, and then choose the Replace button in the Find window.

Important
If you have replaced the contents of a field, then you cannot undo the replacement by choosing Undo on the Edit menu.

See Also

Reference

Find


Toolbar

Specifies whether the toolbar is displayed in the development environment. If the toolbar is displayed, then you can specify options for how it is displayed.

To open this window, on the View menu, choose Toolbar.

Options

Option | Description
Toolbar | Specifies if the toolbar is displayed
Large Buttons | If the toolbar is displayed, then this option specifies if large or small buttons are displayed.
Show ToolTips | If the toolbar is displayed, then this option specifies if ToolTips are displayed when you move the pointer over a button.
With Shortcut Keys | If the toolbar is displayed and if ToolTips are displayed, then this option specifies if shortcut keys are included in the ToolTips.


Show Column

Specifies which columns in the active window to show or hide.

To open this window, on the View menu, choose Show Column.


Object Designer

Lists objects in the Microsoft Dynamics NAV application and gives you access to designers that you use to create and modify objects. The following objects and designers are available from Object Designer.

To open this window, on the Tools menu, choose Object Designer.

Objects

Object type | Designer
Table | Table Designer
Page | Page Designer
Report | Report Dataset Designer
Codeunit | C/AL Editor
Query | Query Designer
XMLport | XMLport Designer
MenuSuite | Navigation Pane Designer

See Also

Concepts

Designing Application Objects


C/AL Symbol Menu

Shows variables, functions, and objects that are defined in the C/AL Globals window and provides information about the syntax and description of the variables, functions, and objects.

To open this window, on the Tools menu, choose Object Designer. In Object Designer, choose Table, Page, Report, Codeunit, Query or XMLport, choose the Design button, and then on the View menu, choose C/AL Symbol Menu.

Elements

Elements | Description
Left column | List of objects and variables that are available.
Middle column | List of subcategories for the selected object or variable in the left column.
Right column | List of functions, properties, and objects that are associated with the subcategory that is selected in the middle column.
OK button | If selected, inserts the selected function, property, or object from the right column into the C/AL Editor. Closes the C/AL Symbol Menu window after the insertion.
Apply button | If selected, inserts the selected function, property, or object from the right column into the C/AL Editor. Does not close the C/AL Symbol Menu window after the insertion.
Paste Arguments check box | If selected, inserts arguments of functions into the C/AL Editor.
Syntax | Displays syntax, description, and field information when it is available.
Right arrow | If selected, displays the next three columns that are to the right of the current columns that are displayed.
Left arrow | If selected, displays the previous three columns that are to the left of the current columns that are displayed.

For example, if you select DATABASE in the left column, then the middle column displays Functions and Tables as subcategories. If you select Functions in the middle column, then all database functions are displayed. If you select Tables in the middle column, then all tables in the database are displayed.

See Also

Reference

C/AL Editor


C/AL Editor

Adds C/AL code in triggers and user-defined functions. The trigger or function signature is displayed on a gray line in the C/AL Editor. You enter code for the trigger or function under the signature.

To open this window, on the Tools menu, choose Object Designer. In Object Designer, choose Table, Page, Report, Codeunit, Query or XMLport, choose the Design button and then on the View menu, choose C/AL Code.

The first column in the C/AL Editor displays breakpoints that are set on lines of code.

The second column in the C/AL Editor lets you expand or collapse a trigger or function.

The first trigger in the C/AL Editor is the Documentation trigger. You use the Documentation trigger to add notes about the code or to document changes that you make. Anything in the Documentation trigger is treated as a comment by the compiler.

See Also

Concepts

Programming in C/AL
Viewing the Definition of a Function or Object by Using Go To Definition
Standard and User-Defined Functions
Triggers Overview


C/AL Editor

Adds C/AL code in triggers and user-defined functions.

To open this window, on the Tools menu, choose Object Designer. In Object Designer, choose Table, Page, Report, Codeunit, Query or XMLport, choose the Design button and then on the View menu, choose C/AL Code.

Tip
The C/AL editor was newly designed in Microsoft Dynamics NAV 2016. You can use the old version of the editor by running the Microsoft Dynamics NAV Development Environment from the command prompt. For more information, see Using the Development Environment from the Command Prompt.

Using the C/AL Editor

The trigger or function signature is displayed in bold text next to either a minus (-) or plus (+) sign that enables you to expand or collapse the code. You enter code for the trigger or function under the signature.

There are several features to assist you when you write code:

  • For a list of keyboard shortcuts, see C/AL Editor Keyboard Shortcuts.

  • As you type, a list of valid members that begin with the entered characters appears. You can choose a member from the list to insert it in the code or if you continue typing characters, the list is filtered to include only the members that begin with those characters.

  • Breakpoints in code are indicated by circles in the left margin.

  • The first trigger in the C/AL Editor is the Documentation trigger. You use the Documentation trigger to add notes about the code or to document changes that you make. Anything in the Documentation trigger is treated as a comment by the compiler.

See Also

Concepts

Programming in C/AL
Viewing the Definition of a Function or Object by Using Go To Definition
Standard and User-Defined Functions
Triggers Overview


C/AL Globals

Declares global variables, text constants, and functions in Microsoft Dynamics NAV. The scope of the global variables, text constants, and functions is limited to the object.

To open this window, on the Tools menu, choose Object Designer. In Object Designer, choose Table, Page, Report, Codeunit, Query or XMLport, choose the Design button, and then on the View menu, choose C/AL Globals.

Variables Tab

You can declare global user-defined variables or system-defined variables. For more information about variables, see C/AL Variables.

Field Description

Name

The name of the variable.

Tip
When you create a variable that has the DataType of Codeunit, Page, Testpage, Report, Query, or XMLport, you do not have to manually add a value to the Name field. If you just set the DataType and SubType fields, then the Name field will be automatically generated when you leave the line. The generated name is based on the name that is assigned to the associated Microsoft Dynamics NAV object. You can change the generated name as you like.

DataType

The data type that is applied to the variable. For more information, see C/AL Data Types.

SubType

The type of data that is stored in a variable. SubType contains additional information about a data type. For example, a Report data type might have the Customer table as a subtype.

Length

The length of the characters in the field. This applies to Code and Text. For example, a Text data type might have a length of 100.

Text Constants Tab

A text constant is a character string that is declared to enable translation of messages into other languages.

Field | Description
Name | The name of the text constant.
ConstValue | The value of the character string that is declared as a constant. You can open the Multilanguage Editor window by choosing the AssistEdit button in the ConstValue field.

Functions Tab

Field | Description
Name | The name of the function.
Locals button | Opens the C/AL Locals window. The window contains parameters, return values, variables, and text constants that are declared for local functions or triggers. For more information, see C/AL Locals.

See Also

Reference

C/AL Locals


C/AL Locals

Declares local variables and text constants in Microsoft Dynamics NAV. Local variables can only exist in the scope of triggers or functions. For more information about variables, see C/AL Variables.

To open this window, on the Tools menu, choose Object Designer, choose Codeunit, and then on the View menu, choose C/AL Locals.

You can also open the C/AL Globals window, choose the Functions tab, and then choose the Locals button. For more information about how to open the C/AL Globals windows, see C/AL Globals.

Parameters Tab

Field Description

Var

The parameter is either passed by value or by reference.

Name

The name of the parameter.

Tip
When you create a parameter that has the DataType of Codeunit, Page, Testpage, Report, Query, or XMLport, you do not have to manually add a value to the Name field. If you just set the DataType and SubType fields, then the Name field will be automatically generated when you leave the line. The generated name is based on the name that is assigned to the associated Microsoft Dynamics NAV object. You can change the generated name as you like.

DataType

The data type of the parameter.

SubType

Additional information about the parameter. For example, a Page data type may have a table as the subtype.

Length

The length of the parameter. For example, if the parameter is a Text DataType, then the text might have a length of 50.

Return Value Tab

Field | Description
Name | The name of the return value.
Return Type | The data type of the return value.
Length | The length of the return value. For example, if the return value is a Text DataType, the text might have a length of 50.

Variables Tab

You can declare local user-defined variables.

Field Description

Name

The name of the variable.

Tip
When you create a variable that has the DataType of Codeunit, Page, Testpage, Report, Query, or XMLport, you do not have to manually add a value to the Name field. If you just set the DataType and SubType fields, then the Name field will be automatically generated when you leave the line. The generated name is based on the name that is assigned to the associated Microsoft Dynamics NAV object. You can change the generated name as you like.

DataType

The data type of the variable. For more information, see C/AL Data Types.

SubType

The type of data that is stored in a variable. SubType contains additional information about a data type. For example, a Report data type might have the Customer table as a subtype.

Length

The length of the characters in the field. For example, a Text data type might have a length of 100. This applies to Code and Text data types.

Text Constants Tab

A text constant is a character string that is declared to enable translation of messages into other languages.

Field | Description
Name | The name of the text constant.
ConstValue | The value of the character string that is declared as a constant. You can open the Multilanguage Editor window by choosing the AssistEdit button in the ConstValue field.

See Also

Reference

C/AL Globals


Error List

Shows a list of errors and warnings, including obsolete constructs, that occur in your C/AL code.

To open this window, on the Tools menu, choose Error List.

Fields

Field | Description
Error No. | The number that identifies the error that occurred.
Object Type | The type of object that caused the error.
Object ID | The ID of the object that caused the error.
Object Name | The name of the object that caused the error.
Error Type | The type, either warning or error.
Function/Trigger | The function or trigger that the error occurred in.
Line No. | The line number in the code where the error is located.
Description | The description of the error.

See Also

Concepts

Error Handling


Options

Specifies the system setup options for the current database.

To open this window, in the Microsoft Dynamics NAV Development Environment, on the Tools menu, choose Options.

Fields

Field Description

Object Cache (KB)

Specifies the size of the object cache, in kilobytes. Objects such as code, descriptions, and windows that are used on the computer that is running the development environment are stored in the object cache.

Values: Any integer value

Default: 32000

TempFilePath

Specifies the path of the location to store temporary files that are created while Microsoft Dynamics NAV runs. These files are automatically deleted when the Microsoft Dynamics NAV is closed.

By default, these files are put in the Temp folder for the user, such as <C:\Users\<user name>\AppData\Local\Temp\>

Status Bar

Specifies whether the status bar is displayed in the development environment. The status bar displays the following:

  • Name and contents of the active field

  • Current user ID

  • Whether you are working in Insert (INS) or Overtype (OVR) mode

Values: Yes, No

Default: Yes

Close Forms on Esc

Specifies if the active window in the development environment closes when you press Esc.

Values: Yes, No

Default: Yes

Marquee Full Selection

Not relevant in Microsoft Dynamics NAV 2016.

Quick Find

Specifies whether quick find is enabled. If quick find is enabled, then you can search for an entry in any non-editable field in the development environment by typing a letter or number. You can also type the complete name of the element you are looking for. When you type a letter or number, the Find window opens automatically and the first row that matches what you typed becomes the active row.

If quick find is not enabled, then you can open the Find window by choosing the Edit menu, and then choosing Find.

Values: Yes, No

Default: Yes

Max. no. of XML records to send

Not relevant in Microsoft Dynamics NAV 2016. For more information about similar functionality, see the MaxNoOfXMLRecordsToSend setting in Configuring the Windows Client.

Auto-Lock on Design

Specifies if you want to automatically lock objects when you open them for design in the development environment.

Values: Yes, No

Default: No

Server Name

Specifies the server that hosts the Microsoft Dynamics NAV Server instance, such as MyServer.

Server Instance Name

Specifies the Microsoft Dynamics NAV Server instance that is being used, such as DynamicsNAV90.

Server Port

Specifies the port on the Microsoft Dynamics NAV Server server, such as 7046.

Management Port

Specifies the port on the server that runs the Microsoft Dynamics NAV Server instance that the Microsoft Dynamics NAV cmdlets access, such as 7045.

Tenant

Specifies the ID of the tenant that is accessed when you run objects from the development environment. If your solution is not set up to deploy in a multitenant deployment architecture, leave the field empty.

Company

Specifies the name of the company that is accessed when you run objects from the development environment. If the database only contains a single company, leave the field empty.

Use Report Builder

Specifies if you want to use SQL Server Report Builder to design the layout for reports. To continue to use Visual Studio Report Designer, do not change the value of this field.

SQL Server Report Builder is included when you install the development environment.

See Also

Tasks

How to: Change the Microsoft Dynamics NAV Server Instance

Reference

Find

Concepts

Managing Microsoft Dynamics NAV Server Instances
Locking and Unlocking Objects


Request Options Page Designer

Designs the Options FastTab of a request page. Request pages let users specify options and filters for a report before the report runs.

To open this window, on the Tools menu, choose Object Designer, choose Report, choose the Design button, and then on the View menu, choose Request Page.

This window behaves similarly to Page Designer. For more information, see Page Designer.

See Also

Concepts

Request Pages


Report Label Designer

Adds labels to reports. You add labels that are not related to a data item in this window.

To open this window, on the Tools menu, choose Object Designer, choose Report, choose the Design button, and then on the View menu, choose Labels.

Fields

Field | Description
Name | The name of the label. The name must be a Common Language Specification (CLS)-compliant name.
Caption | The caption of the label. The captions are available in the Parameters section in the Report Data pane in Visual Studio.

See Also

Tasks

How to: Create Labels for a Report


Report Dataset Designer

Designs the dataset of a report.

To open this window, on the Tools menu, choose Object Designer, choose Report, and then choose the Design button. You can choose the New button instead of the Design button to design a new report.

Fields

Field Description

Expanded

Expands and collapses all indented hierarchy. This includes child data items and columns.

Data Type

Specifies either DataItem or Column. A data item is a table. A column can be:

  • A field in a table.

  • A variable.

  • An expression.

  • A TextConstant that could represent a caption that is not related to a specific table.

Data Source

Specifies the source of the DataItem or Column. For example, specify the table for a DataItem, or specify a field, variable, expression, or text for a Column. On a DataItem row, either enter the table name or table number or use the up arrow to select a table from the Object List window. On a Column row, either enter a value or choose the AssistEdit button or use the Field Menu to select a field, variable, or text constant from the C/AL Symbol Menu.

Name

Specifies a name that complies with the Common Language Specification (CLS). For more information, see the "Naming" section in Common Language Specification in the MSDN Library.

Include Caption

Includes the caption of a field in the dataset when the check box of a Column data type is selected. For more information about how to include captions, see IncludeCaption Property.

See Also

Concepts

Reports


Table View

Specifies the sorting and filtering for the data item.

To open this window, on the Tools menu, choose Object Designer, choose Report, choose the Design button, choose a DataItem, and then on the View menu, choose Properties. Locate the DataItemTableView property, and then choose the AssistButton in the Value column.

Fields

Field | Description
Key | Specifies a table key on which you want to sort the data in the report or choose the Up Arrow button to select a key from the Key List window. If you specify a key, then this data item does not have a FastTab on the request page, and end users cannot select a key for sorting, sort order, or filters for the data item.
Order | Specifies the sort order by choosing either Ascending or Descending from the drop-down list. If you specify a sort order, then this sort order is used for the report regardless of the sort order that the end user selects on the request page.
Table Filter | Specifies a filter expression to use to filter the data in the report or choose the AssistEdit button to enter a filter in the Table Filter window. If you specify a filter, then this filter is not displayed on the request page, but it is used along with any filters that the end user specifies on the request page.

See Also

Reference

DataItemTableView Property


DataItem Link

Specifies the relationship between fields in the current data item and reference fields on a parent data item. The parent data item is specified in the DataItemLinkReference Property.

To open this window, on the Tools menu, choose Object Designer, choose Report, choose the Design button, choose a DataItem, and then on the View menu, choose Properties. Locate the DataItemLink property, and then choose the AssistButton in the Value column.

Fields

Field | Description
Field | Specify a field name from the current data item or choose the Up Arrow button to select a field from the Field List window. The Field List window displays fields from the table that is specified in the DataItemTable Property.
Reference Field | Specify a field name from the parent data item or choose the Up Arrow button to select a field from the Field List window. The Field List window displays fields from the table that is specified in the DataItemLinkReference Property.


About

Shows version, license, and copyright information about Microsoft Dynamics NAV.

To open this window, on the Help menu, choose About Microsoft Dynamics NAV Development Environment.

See Also

Reference

License Information


Field Filter

Sets a field filter.

To open this window, on the Tools menu, choose Object Designer, and then on the View menu, choose Field Filter.

See Also

How to: Set Filters


Table Filter

Sets a table filter.

To open this window, on the Tools menu, choose Object Designer, and then on the View menu, choose Table Filter.

See Also

How to: Define Table Filters


FlowFilter

Sets a FlowFilter.

To open this window, on the Tools menu, choose Object Designer, and then on the View menu, choose FlowFilter.

See Also

FlowFilters

Concepts

FlowFilter Overview


Sort

Specifies the key on which to sort the items in the window and the sort order.

To open this window, open Object Designer, and then on the View menu, choose Sort.

You can choose to sort object in Object Designer on one of the following keys:

  • Type, Company Name, ID

  • Type, Name

  • Locked, Locked By

You can choose from the following sort orders:

  • Ascending

  • Descending

After you choose the key and sort order, choose either the OK button or the Apply button to apply the sorting.

See Also

Concepts

Table Keys


Custom Controls

Lists all OCX controls that are registered on the client computer.

To open this window, on the Tools menu, choose Custom Controls.

For more information, see the COM Overview.


Table Designer

Provides functionality for designing tables.

Table Designer is part of Object Designer. You use Object Designer to access the Microsoft Dynamics NAV Development Environment. You use the development environment to modify the application or to create new application areas.

To open this window, on the Tools menu, choose Object Designer, choose Table, and then choose the Design button. You can choose the New button instead of the Design button to design a new table.

For more information, see Tables.

Fields

Field | Description
Enabled | Specifies whether a field is enabled.
Field No. | Specifies the field number.
Data Type | Specifies the data type of the field.
Length | Specifies the length of the field if the data type is Code or Text.
Description | Specifies the description of the field.

See Also

Reference

Object Designer


Keys

Shows all keys that have been defined in the table that you selected in the Table Designer.

To open this window, on the Tools menu, choose Object Designer, choose Table, and then on the View menu, choose Keys.

See Also

Concepts

Table Keys


Field List

Selects fields in the table.

To open this window, open Table Designer, and then on the View menu, choose Keys. In the Keys window, choose the AssistEdit button in the Key field.

In this window, choose the Up Arrow button to open the Field List window.

See Also

Concepts

Table Keys


Field List

Specifies all fields in the table that you selected.

To open this window, open Table Designer, and then on the View menu, choose Keys. In the Keys window, choose the Up Arrow button in the Key field.

See Also

Reference

Field List

Concepts

Table Keys


Field Groups

Defines the fields to display in a drop-down control.

To open this window, on the Tools menu, choose Object Designer, choose Table, and then on the View menu, choose Field Groups.

In the RoleTailored client, some fields are enabled with filter-as-you-type functionality. When you type text into these fields, a drop-down control that displays data from a source table opens. By default, only data from the primary key and description fields in the source table are shown if you do not define any field groups for the drop-down control. These two fields are indexed automatically.

Fields

Field | Description
ID | The ID of the drop-down control.
Name | The name of the control.
Group | The fields to display in the control.


Key List

Sets the key field or fields on which to sort the data. The window lists the fields in the selected table.

To open this window, open the Table View window. In the Table View window, choose the Up Arrow button in the Key field. For more information about how to open the Table View window, see Table View.


Table Filter

Sets a filter on a DataItem. The filter can be a constant expression or a filter expression. The filter that you set is not displayed on the request page, but it is used with filters that the end user specifies on the request page.

To open this window, open the Table View window. In the Table View window, choose the AssistEdit button in the Table Filter field. For more information about how to open the Table View window, see Table View.

Fields

Field | Description
Field | The field to filter on.
Type | The type of filter to set. This can be a constant expression or a filter expression.
Value | The value of the constant or filter expression.


Table Filter

Sets a filter on a field. The filter can be a constant expression, a filter, or a field.

For more information about how to open this window, see Table Filter.

Fields

Field | Description
Field | The field to filter on.
Type | The type of filter to set. This can be a constant expression, a filter, or a field.
Value | The value of the constant, filter, or field


Table Relation

Sets up a lookup into another table.

When you create table relations, you can define a simple or an advanced table relationship. A typical simple table relationship consists of a table name and an optional field name. An advanced table relationship can also contain conditions and filters.

To open this window, open Table Designer, and then select a field. On the View menu, choose Properties, locate the Table Relation property, and then in the Value field, choose the AssistEdit button.

Fields

Field | Description
Condition | The table relations condition to use for the lookup.
Table | The table to set up the lookup for.
Field | A field in the related table.
Table Filter | A constant expression or a filter expression.


XMLport Designer

Provides functionality for designing XMLports.

XMLport Designer contains the following column fields:

  • Node Name

  • Node Type

  • Source Type

  • Data Source

To open this window, on the Tools menu, choose Object Designer, choose XMLport, and then choose the Design button. You can choose the New button instead of the Design button to design a new XMLport.

Fields

Field Description

Node Name

Specifies the XML node name of the XML element or attribute. You must enter node names in the order in which they appear in the XML document. Parent elements must precede their child elements. You indent the node names of child elements under their parent elements by using one indentation per level. You list attributes under the elements that they define and you indent them to the child level.

Node Type

Specifies whether the name in the Node Name field represents data of the type element or attribute. The drop-down list in a Node Type field contains two options: Element and Attribute. The default setting is Element.

Source Type

Specifies the data structure that the node name corresponds to in the Microsoft Dynamics NAV database. The Source Type field contains a drop-down list that has the following options:

  • Text

    This is the default setting. Specifies that the XML data cannot be mapped to the database or when the database does not need the information. The value of the Text field will be put into a text variable with the name that you have specified in the VariableName property. By default, the node name is used if you do not specify a value. The text variable behaves like a typical global C/AL text variable. You can also turn the text source type into a big text variable by setting the TextType property to BigText.

  • Table

    Specifies that the node name is equivalent to a table or that a table record must be initialized. Like the Text option, you can specify a variable name for the table, which also behaves like a global record variable. By default, the variable name is the name of the table.

  • Field

    Specifies that the node name is equivalent to a field in the database. However, for this selection to be valid, you must first declare a table as the parent of the field. If you do not declare a table as the parent of the field, then an error occurs when you try to compile the XMLport object.

Data Source

A Data Source field has the following interactions with the Source Type field:

  • If Source Type is set to Table and you have defined a variable name for the table, the format of the value shown in the DataSource field will be tablevariablename(tablename). If you have not defined a variable name, then the format of the value will be shown as <tablename>(tablename).

  • If Source Type is set to Field, then select a field from a table that you have specified in the XMLport. The format of the value is shown as tablevariablename::fieldname.

Note
If an XMLport is designed to import or export XML documents, the Node Name for the first element in XMLport designer window must be set to Root, the Node Type must be set to Element and the Source Type must be set to Text. This represents the root of the XML document.

XMLport Properties, Functions, and Triggers

There are properties, functions, and triggers that you can use to work with an XMLport. There are properties, functions, and triggers for the object level and for the element level, which consists of Field, Table, and Text. The properties that are available at the element level depend on the selections you make in the Node Type and Source Type fields in XMLport Designer. For more information, see C/SIDE Reference Guide.

When you design XMLports, you must set the value of the Format Property (XMLports) and the Direction Property. The Format Property (XMLports) indicates the type of file that you want to import or export and the direction property value indicates whether the XMLport will be used for import or export.

See Also

Concepts

XMLports


Table List

Lists the tables that the XML item in the XMLport should link to. This list is only available for XML items that have a table as their data source.

To open this window, open XMLport Designer, select a table item, and then on the View menu, choose Properties. In the Properties window, locate the LinkTable property, and then choose the Up Arrow button in the Value field. For more information about how to open XMLport Designer, see XMLport Designer


Field Lookup

Creates a lookup for a field in an XMLport.

To open this window, open XMLport Designer, select a field attribute, and then choose the Up Arrow button in the Data source field. For more information about how to open XMLport Designer, see XMLport Designer.

Controls

Control | Description
Left List box | Lists the table which the field belongs to.
Right List box | Lists the fields that you can create a lookup to.


Query Designer

Retrieves records from one or more tables and combines the records into rows and columns in a single dataset. You create queries in the development environment with Query Designer.

To open this window, on the Tools menu, choose Object Designer, choose Query, and then choose the Design button. Choose the New button instead of the Design button to design a new query.

In Query Designer, tables are specified by data items. You combine tables by linking the data items in Query Designer. In most cases, the tables are combined based on a relationship between certain fields in the tables. Microsoft Dynamics NAV includes different types of data item links that you can use to limit the records that are included in the resulting dataset by how the fields in data item tables are related to each other.

Fields

Field Description

Expanded

Expands and collapses all indented hierarchy. This includes child data items and columns.

Type

Specifies the type of data to include in the dataset. You can choose one of the following types of data:

  • DataItem

  • Column

  • Filter

Data Source

Specifies the table to retrieve the dataset from.

Name

Specifies the name of the data item, column, or filter element.

Method Type

Specifies the date or totals type method on the query column. For more information, see MethodType Property.

Method

Specifies either a date method for retrieving the year, month, or day from a Date field or a totals method for performing calculations on field values. For more information, see Method Property.

Group By

Specifies that records are grouped by this column. You cannot change the contents of this field. It is automatically calculated from the defined columns. All columns where Method Type is not Totals are used for grouping.

See Also

Concepts

Queries
Understanding Query Totals and Grouping


Column Filter

Sets a filter on the Column row of a query.

To open this window, open Query Designer, and then select a column in the designer. On the View menu, choose Properties, locate the ColumnFilter property, and then choose the AssistEdit button in the Value field. For more information about how to open Query Designer, see Query Designer.

Note
The filter on a Column row is similar to a filter on a data item except that the filter of a Column row can be programmatically overwritten by calling the SETFILTER Function (Query) and SETRANGE Function (Query) from C/AL code.

Fields

Field | Description
Column | The column on which to set the filter.
Type | The type of filter that you want to set. Set this field to CONST if you want to filter on constant value. Set the field to FILTER if you want to set a filter that is based on an expression.
Value | The constant value or the filter expression you want to set for Type.


Order By

Sorts rows in a dataset from a query in ascending or descending order by a column or columns.

To open this window, open Query Designer, and then select an empty row in the designer. On the View menu, choose Properties, locate the OrderBy property, and then choose the AssistEdit button in the Value field. For more information about how to open Query Designer, see Query Designer.

Note
You cannot sort on the same column more than once.

Fields

Field | Description
Column | The name of the query column as specified by its Name Property.
Direction | The direction of the sort. You can choose Ascending or Descending.


Column List - Table

Selects the columns by which to sort the rows in a dataset in a query.

To open this window, open Query Designer, select an empty row in the designer, and then on the View menu, choose Properties. In the Properties window, locate the OrderBy property, and then choose the AssistEdit button in the Value field. In the OrderBy window, choose the Up Arrow button in the Column field. For more information about how to open Query Designer, see Query Designer.

By default, rows in a dataset of query are not sorted. You can sort the rows in the dataset in ascending or descending order by one or more selected columns in the query. For information about how to sort a dataset in a query, see How to: Sort a Query Dataset in Ascending or Descending Order.

Fields

Field | Description
Column Name | Specifies the name of the column.
Column Caption | Specifies the caption of the column.


Multilanguage Editor

Specifies text in multiple languages.

To open this window, open a designer such as Page Designer, and then on the View menu, choose Properties. Locate the CaptionML property, and then choose the AssistEdit button in the Value field.

Fields

Field | Description
Language | Specifies the language to support.
Value | Specifies the text string to display in the selected language.


Windows Language List

Lists all Windows languages. You can add string translations for UI elements in a standard country/region-specific version of Microsoft Dynamics NAV 2016. To enable multilanguage support, you install a language module so that end users can view UI elements in a different language.

Note
If you have customized objects in the application, then you must also add translations for those objects.

To open this window, in the Multilanguage Editor window, choose the Up Arrow button in the Language field. For more information about how to open the Multilanguage Editor window, see Multilanguage Editor.


Application Languages

Lists the languages that are included in your license and installed on your computer.

To open this window, on the Tools menu, choose Language.

The languages are used for captions in windows, on command buttons, and in other user interface (UI) elements. You can change the language from both the Microsoft Dynamics NAV Development Environment and the Microsoft Dynamics NAV Windows client. For more information about how to change a language, see How to: Change the Language in the User Interface.


Action Designer

Adds actions to the menu bar of a page.

To open this window, open Page Designer, and then on the View menu, choose Page Actions. For more information about how to open Page Designer, see Page Designer.

In the RoleTailored client for Microsoft Dynamics NAV, menu items are called actions.

Note
Actions can only be linked to a page or to a group control that has a subtype of CueGroup. Actions cannot be linked to fields, containers, or parts on a page. For more information about adding actions to a CueGroup control, see Adding an Action to the Cue.

Fields and Controls

Field Description

Name

The name of the action.

Caption

The caption of the action.

Type

The type of the action you want to create. You can select one of the following action types.

  • ActionContainer

  • Separator

  • ActionGroup

  • Action

For example, to create a container for your actions, select ActionContainer. For more information, see Actions Overview.

Subtype

The subtype of the action you want to create. You can select one of the following subtypes:

  • NewDocumentItems

  • ActionItems

  • RelatedInformation

  • Reports

  • HomeItems

  • ActivityButtons

    For example, to put your action in the Actions tab, select ActionItems.For more information, see Actions Overview.

Control | Description
Separator button | Inserts a separator between actions.


Page Designer

Provides functionality for designing pages.

Page Designer is part of Object Designer. Object Designer gives you access to the Microsoft Dynamics NAV Development Environment. You use the development environment to modify the application or to create new application areas.

To open this window, on the Tools menu, choose Object Designer, choose Page, and then choose the Design button. Choose the New button instead of the Design button to design a new page.

Columns

Column Description

Expanded

Expands or collapses the element and child elements in Page Designer.

Type

Specifies the type of the control to display on the page. You can choose from the following control types:

  • Container

  • Group

  • Field

  • Part

SubType

Specifies the subtype of the control to display on the page.

For Container, you can choose from the following subtypes:

  • ContentArea

  • FactBoxArea

  • RoleCenterArea

For Group, you can choose from the following subtypes:

  • Group

  • Repeater

  • CueGroup

  • FixedLayout

  • GridLayout

For Part, you can choose from the following subtypes:

  • Page

  • System

  • Chart

SourceExpr

Specifies an expression that defines where to find the value of the control.

Name

Specifies the name of the control or field to display on the page. The name cannot contain spaces.

Caption

Specifies the caption of the control or field.

See Also

Tasks

How to: Create a Page


Image List

Shows images that you can associate with an action. You can only choose from the images that are available in this window.

To open this window, open Action Designer, and then select an action. On the View menu, choose Properties and then locate the Image property. In the Value field, choose the Up Arrow button. For more information about how to open Action Designer, see Action Designer.


Indent Controls

Specifies whether a column or columns (controls) are indented in a Repeater subtype control on a page.

To open this window, open Page Designer, select a control, and then on the View menu, choose Properties. Locate the IndentationControls property, and then choose the AssistEdit button in the Value field. For more information about how to open Page Designer, see Page Designer.

Fields

Field | Description
Indentation | Specifies whether a field should be indented. When this field is selected then that field is indented.
Name | Specifies the name of the field to indent.
Caption | Specifies the caption of the field to indent.


Control Number

Selects columns that should remain in view on a page when you scroll to the right.

Columns can extend beyond a control’s boundaries. This may require you to scroll to the right to see all columns. In this window, you can select columns that always remain in view even when you scroll through the remaining columns. The column that you select and all columns before it remain in view on the page. You can access this window with the FreezeColumnID Property.

To open this window, open Page Designer, and then select a control in the designer. On the View menu, choose Property. In the Properties window, locate the FreezeColumnID property, and then in the Value field, choose the Up Arrow button. For more information about how to open Page Designer, see Page Designer.


Control Add-ins

Contains control add-ins that have been registered.

To register an add-in, you include it on the Control Add-ins page in Microsoft Dynamics NAV. A control add-in is a Microsoft .NET Framework assembly that enables you to add custom functionality to the Microsoft Dynamics NAV clients. After you have registered a control add-in, you can use it on Microsoft Dynamics NAV pages. You select the control add-in from this window and add it to a field control on the page.

See Also

Concepts

Extending Any Microsoft Dynamics NAV Client Using Control Add-ins
Extending the Windows Client Using Control Add-ins


Chart List

Contains a list of charts that can be added to a page. The name and ID of the chart is listed in this window. When you select a chart, a link is created to the selected chart.

To open this window, open Page Designer, select a Part control, and then on the View menu, choose Properties. In the Properties window, locate the ChartPartID property, and then choose the Up Arrow button in the Value field. For more information about how to open Page Designer, see Page Designer.


New Page

Creates a new page. Pages are objects for viewing and editing data in the Microsoft Dynamics NAV Windows client and Microsoft Dynamics NAV Web client.

To open this window, on the Tools menu, choose Object Designer, choose Page, and then choose the New button.

There are ten page types from which you can choose, including:

  • Role Center pages, which are home pages for a specific user role.

  • List pages, which display multiple records on a page.

  • Card pages, which are used to edit individual customer or item records.

The page type determines which controls, parts, and properties are valid for the page. You can choose to create a blank page and build it from scratch, or you can use the page wizard to create a specific type of page

Fields

Field | Description
Table | Specifies the table to use to create the page.
Create blank page | Specifies whether to create a blank page.
Create a page using wizard | Specifies whether to create the page with a wizard.
List box | Lists the type of pages that be created.

See Also

Working with Role Centers

Concepts

Page Designer Walkthroughs


Page Designer Wizard, Available Fields

Creates a List page and adds fields with the page wizard. List pages display multiple records on a page.

To open this window, on the Tools menu, choose Object Designer, choose Page, and then choose the New button. In the New Page window, select a table from the list, select Create a Page using a wizard, select List, and then choose the OK button.

List Page Wizard Window

The following table describes the contents of the first page of the List Page Wizard.

Field | Description
Available Fields list box | Contains a list of the fields from the table you want to display on the page.
Field Order list box | Contains the fields that you have selected to include on the page and the order they will appear.

Controls | Description
> button | Adds a field from the Available Fields list box.
>> button | Adds all the fields from the Available Fields list box.
< button | Removes the selected field from the Field Order list box.
<< button | Removes all the fields from the Field Order list box.
Back button | Not enabled.
Next button | Moves to the next page.
Preview button | Not enabled.
Finish button | Opens Page Designer.

See Also

Tasks

Walkthrough: Creating a Wizard Page


Page Designer Wizard, FactBox

Adds a FactBox to a List page or Card page. A FactBox is an area on the page that allows you to display another page that displays targeted, related information about a selection on the main page. A FactBox can include only CardPart and ListPart page types.

To open this window, open the List Page Wizard window, select the fields that you want on the page, and then choose the Next button. For more information about how to open List Page Designer, see Page Designer Wizard, Available Fields.

List Page Wizard, FactBoxes

Field | Description
Page tab | Lists page FactBox parts that are available for Card and List pages.
System tab | Lists system FactBox parts that are available for Card and List pages.
Chart tab | Lists chart parts that are available for Card and List pages.
Part Order | Lists parts that have been added to the page and the order the parts were added.

Controls | Description
> button | Adds a FactBox from the available parts list.
>> button | Adds all the FactBoxes from the available parts list.
< button | Removes a FactBox from the Part Order list box.
<< button | Removes all the FactBoxes from the Part Order list box.
Back button | Moves to the previous page.
Next button | Not enabled.
Preview button | Not enabled.
Finish button | Opens Page Designer.


Page Designer Wizard, FastTab

Creates a FastTab control on a Card page.

You can use FastTab controls to add data in groups on Card or Task pages. If a group is expanded, then you see all fields in a group. If it is collapsed, then you only see the summary line. When you organize data with FastTabs, you help users find key information quickly, and you give them an overview of areas that would otherwise remain hidden.

To open this window, on the Tools menu, choose Object Designer, choose Page, and then choose the New button. On the New Page window, select a table from the list, select Create a page using a wizard, select Card, and then choose the OK button.

Page Designer Wizard Window, FastTab

Controls | Description
FastTab Name list box | Specifies the FastTab control to create.
Next button | Moves to the next page. From the next page, you select the fields that you want on the FastTab.
Finish button | Opens Page Designer.

See Also

Tasks

How to: Add FastTabs to a Customer Card Page

Reference

Page Designer Wizard, Available Fields


Page Preview

Previews a page directly from Page Designer to see how the page will look in the Microsoft Dynamics NAV Windows client. Unlike running a page from Object Designer, previewing a page does not start the Microsoft Dynamics NAV Windows client, which means that you can keep working in the development environment. For more information, see How to: Preview Pages and Identify Page and Action Controls.

To open this window, open Page Designer, and then choose the Preview button.

See Also

Concepts

Pages


Language Module Export

Exports a language module. Microsoft Dynamics NAV 2016 is multilanguage enabled, which means that you can display the user interface (UI) in different languages. To view Microsoft Dynamics NAV content in multiple languages, you must install the module for the languages. You can uninstall a language if it is no longer supported. For more information, see How to: Uninstall Language Modules.

To open this window, on the Tools menu, choose Language Module, and then choose Export.

Fields

Field | Description
File Name | Specifies the path and file name of the file that will contain the exported language module.
Language | Specifies the language that you want to export.
Delete Language | Specifies whether the language should be uninstalled.

See Also

Reference

Microsoft Dynamics NAV Windows Client Component


Name

Contains the names of the available languages that are included in your license and that are installed on your computer. This field is located in the Application Languages window.

For more information about how to open the Application Languages window, see Application Languages.

Example

English (United States)


Access By Permission

Specifies an object to which users must have certain permissions before the related UI element is accessible to the user.

The AccessByPermission property sets a value for a table field or UI element that determines the permission mask for an object that a user must have to see and access the related page fields or UI element in the client. The UI element will be removed at runtime if the user does not have permissions to a certain object as specified in the Access By Permission window. For more information, see How to: Remove UI Elements Using the AccessByPermission Property.

To use the AccessByPermission property, the UI Elements Removal field in the Microsoft Dynamics NAV Server Administration tool must be set to LicenseFile or LicenseFileAndUserPermissions. For more information, see How to: Specify When UI Elements Are Removed.

Note
To use the LicenseFileAndUserPermissions option in the UI Elements Removal field, you must assign the special FOUNDATION permission set to the user along with the relevant application permission sets that define which application objects the user will access. Unlike the BASIC permission set, the FOUNDATION permission set only grants access to application setup and system tables and requires that other assigned permission sets define which specific application objects can be accessed. For more information, see Special Permission Sets.

Not all of the 167 default permission sets that are provided with Microsoft Dynamics NAV are ready to support the FOUNDATION permission set to remove UI elements according to user permissions. You must therefore edit the relevant permission sets as explained in the following procedures.

To experience how UI elements are removed for a user performing the task to create and edit a new customer, you can create a sample user interface based on default permission sets provided with Microsoft Dynamics NAV. For more information, see How to: Try Out the UI Elements Removal Feature Based on Demonstration Permission Sets.

See Also

Tasks

How to: Remove UI Elements Using the AccessByPermission Property
How to: Specify When UI Elements Are Removed
How to: Try Out the UI Elements Removal Feature Based on Demonstration Permission Sets
How to: Define Permissions for Users

Reference

AccessByPermission Property
Access By Permission

Concepts

Removing Elements from the User Interface According to Permissions

Other Resources

Managing Permissions and Permission Sets


Save

Saves changes that have been made to a Microsoft Dynamics NAV object.

The following table describes the options on the Save window.

Option Description

Compile

Specifies whether to compile the object.

Compiling the table object will check for syntax errors and obsolete construct errors in C/AL code. For more information, see Compiling Objects.

Synchronize Schema

Specifies how to apply the table definition changes to the business data table in SQL Server. This option is only available when you compile a table.

Use the text on the Save window to help you select the desired option, or for more information, see Synchronizing Table Schemas.

See Also

Concepts

Compiling Objects


Save As

Creates a new Microsoft Dynamics NAV object by copying the selected object.

The following table describes the options on the Save As window.

Option Description

ID

Specifies the ID to assign the object. This sets the object's ID Property.

Name

Specifies the name to assign the object. This sets the object's Name Property.

Compile

Specifies whether to compile the object.

Compiling the table object will check for syntax errors and obsolete construct errors in C/AL code.

Synchronize Schema

Specifies how to apply the table definition changes to the business data table in SQL Server. This option is only available when you compile a table.

Use the text on the Save AS window to help you select the desired option, or for more information, see Synchronizing Table Schemas.

See Also

Concepts

Compiling Objects


Compile

Compiles the Microsoft Dynamics NAV table object.

Compiling the table object will check for syntax errors and obsolete construct errors in C/AL code.

To compile that table, you must set the Synchronize Schema field to specify how to apply the table definition changes to the business data table in SQL Server. Use the text on the Compile window to help you select the desired option, or for more information, see Synchronizing Table Schemas.

See Also

Concepts

Compiling Tables
Compiling Objects


Delete

Deletes the Microsoft Dynamics NAV object from the database.

If you are deleting a table, then you will have to set the Synchronize Schema field to specify how to synchronize the table definition changes with the business data table in SQL Server. Use the text on the Delete window to help you select the desired option, or for more information, see Synchronizing Table Schemas.


Start Data Upgrade

Specifies how to run the data upgrade.

To open this window, on the Tools menu, choose Data Upgrade, and then choose the Start.

The following table describes the options in the Start Data Upgrade window.

Option Description

Execution mode

Specifies how to run the Upgrade functions in upgrade codeunits.

  • Parallel runs the Upgrade functions at the same time. This is the default setting.

  • Serial runs the Upgrade functions one after the other (sequentially).

For more information, see Parallel and Serial Function Execution Modes.

Continue on Error

Specifies whether the Microsoft Dynamics NAV Server instance continues to execute other Upgrade functions in the Upgrade codeunits when an error occurs while executing an upgrade function.

If you clear this check box, when an error occurs, the Microsoft Dynamics NAV Server instance will suspend the data upgrade process. It will cancel the execution of upgrade functions currently in progress and roll back any changes that were applied. Completed functions will not be rolled back. This is the default setting.

Show Progress

Specifies whether to display the progress window during the data update process. The progress windows provides the state of the database, details about the current operation, such as errors, and a

You can always view the progress from the Tools menu by selecting Data Upgrade, and then Show Progress.

See Also

Concepts

Upgrading Data
Upgrade Codeunits


Resume Data Upgrade

Specifies which Upgrade functions to rerun when you resume a data upgrade process that has been suspended.

To open this window, on the Tools menu, choose Data Upgrade, and then choose the Resume.

The following table describes the options in the Resume Data Upgrade window.

Option Description

Resume All

Specifies to run all Upgrade functions that failed or where cancelled during the data upgrade.

Resume

Specifies to run a specific Upgrade function in an upgrade codeunit.

Tip
To get a list of invoked functions, use the Get-NAVDataUpgrade cmdlet from the Microsoft Dynamics NAV 2016 Administration Shell.

Codeunit

Specifies the ID of the upgrade codeunit to run.

Codeunit Method

Specifies the name of the Upgrade function in the upgrade codeunit to run.

Company

Specifies the name of the Microsoft Dynamics NAV company for which to run the Upgrade function.

Note
You can only rerun failed or canceled Upgrade functions.

See Also

Concepts

Upgrading Data
Upgrade Codeunits


Namespaces

Specifies namespaces for the XMLport that imports or exports data as XML.

To open this window, open an XMLport in XMLport Designer, and then on the View menu, choose Properties. Locate the Namespaces property, and then choose the AssistEdit button in the Value field.

Fields

Field | Description
Prefix | Specifies the namespace prefix. You apply namespaces to XMLport elements by setting the NamespacePrefix Property of the element.
Namespace | Specifies the namespace, which is typically in the form of a URL string.

To specify the default namespace, leave the Prefix field blank.

Note
You can only define one default namespace. You can also define a space by specifying the namespace in the DefaultNamespace Property and setting the UseDefaultNamespace Property to Yes. If you want to specify the default namespace in this window, then you must set the UseDefaultNamespace Property to No.

For more information about namespaces with XMLports, see Using Namespaces with XMLports.

See Also

Tasks

How to: Create XMLports

Concepts

Designing XMLports


Event Subscriptions (window)

Open the [image] Event Subscriptions window.

Specifies the current subscriptions to published events.

A subscription is defined by an event subscriber function and an event publisher function that event subscriber function subscribes to. When a published event is raised in the application, the event subscriber function is called.

The following table describes the fields that are available for a subscription:

Field Description

Subscriber Codeunit ID

Specifies the ID of codeunit that contains the event subscriber function.

Subscriber function

Specifies the event subscriber function in the subscriber codeunit that subscribes to the event.

Event type

Specifies the event type, which can be Business, Integration, or Trigger. For more information about the types, see Event Types.

Publisher Object Type

The type of object that contains the event publisher function that publishes the event.

Publisher Object ID

Specifies the ID of the object that contains the event publisher function that publishes the event.

Published Function

Specifies the name of the event publisher function in the publisher object that the event subscriber function subscribes to.

Active

Specifies whether the event subscription is active or inactive. When the check box is cleared, the event subscription is inactive. This occurs if the event publisher object or function cannot be found.

Number of calls

Specifies how many times the event subscriber function has been called. The event subscriber function is called when the published event is raised in the application.

This field specifies the total number of calls since the last time the Microsoft Dynamics NAV Server instance was started or since the last event subscription error was fixed. The field will reset to zero when the Microsoft Dynamics NAV Server instance is restarted or when an event subscription error occurs.

Error Information

Specifies the error message when an error occurs and the event subscription fails.

For more information about the error messages, see Event Errors.

See Also

Concepts

Events in Microsoft Dynamics NAV
Publishing Events
Subscribing to Events


Code Coverage (window)

Open the [image] Code Coverage window.

Specifies the extent to which the application code is covered by tests. You use the Code Coverage window to track code coverage after you have run one or more test suites in the CAL Test Tool window. You can run both pages from the development environment, or from the Microsoft Dynamics NAV Windows client or the Microsoft Dynamics NAV Web client.

In the Code Coverage window, you can start, refresh, and stop the code coverage recorder.

Important
Code coverage is recorded globally for all sessions, so make sure that you run the tool in a controlled environment so you do not have any activity from unaccounted sessions.

Monitoring Code Coverage

Code coverage is the means of being able to track which part of the application code has been exercised during test activity. In Microsoft Dynamics NAV, code coverage is recorded by C/AL code line and specifies if a code line was exercised by test and the number of times the line of code was recorded.

To start monitoring code coverage, choose Start. This starts the code coverage engine, and code coverage is captured. However, you will not be able to see any updated information until you choose Refresh or Stop. The information contains coverage of objects, triggers and functions, and individual lines of code or empty lines as determined by the column Line Type. Only lines of type Code can have coverage. Lines of type Trigger/Function show the average coverage of all code lines in the trigger or function. Lines of type Object show the average coverage of all code lines inside the object. The following table illustrates the result of a code coverage run:

Code | Coverage % | Line Type
Table Currency (4) | 20,00 | Object
OnModify() | 0,00 | Trigger/Function
OnDelete() | 0,00 | Trigger/Function
OnRename() | 0,00 | Trigger/Function
InitRoundingPrecision() | 81,82 | Trigger/Function

In this example, the activity exercised 20% of the Currency table, including 81,82% of the InitRoundingPrecision function.You can then expand the section for InitRoundingPrecision to investigate the code coverage for each line of code in this function.

Only objects that are touched by the activity are recorded. This means that if an object is not shown in this window, the coverage of the object is implied to be zero. If you want to force the code coverage recorder to include specific objects even if they are not covered, choose the Load objects action, and then specify the relevant objects. This forces the code coverage engine to load these objects and provide information on even when no lines are covered.

See Also

Reference

Code Coverage Virtual Table

Concepts

Application Test Automation


Upgrading to Microsoft Dynamics NAV 2016

This section describes how to upgrade from Microsoft Dynamics NAV 2013 or Microsoft Dynamics NAV 2013 R2 to Microsoft Dynamics NAV 2015. If you have an earlier version, such as Microsoft Dynamics NAV 5.0 or Microsoft Dynamics NAV 4.0, you must first upgrade that version to Microsoft Dynamics NAV 2013. For more information, see Upgrading to Microsoft Dynamics NAV 2013 in the MSDN Library. You can upgrade from Microsoft Dynamics NAV 2009 SP1 or Microsoft Dynamics NAV 2009 R2 to Microsoft Dynamics NAV 2015 Cumulative Update 1 and later. For more information, see the Dynamics NAV Team Blog.

To upgrade to Microsoft Dynamics NAV 2015, you must complete the following main steps:

  • Convert the database.

  • Upgrade the code.

  • Upgrade the data.

In This Section

  • Converting a Database

  • Upgrading the Application Code

  • Upgrading the Data

  • Automating the Upgrade Process using Sample Windows PowerShell Scripts

Important
If you upgrade from Microsoft Dynamics NAV 2009 R2 or earlier, the link between interaction records and logged email messages is lost. To resolve this issue, the administrator has to log all mails again to restore the links. For more information, see Troubleshooting: Email Logging.

Related Sections

Product and Architecture Overview

Migrating to Multitenancy

Deployment

See Also

Other Resources

Transforming Forms to Pages


Upgrade Considerations

Depending on which version you are upgrading from, and the degree to which your solution differs from the standard version of Microsoft Dynamics NAV, you may want to prepare your solution for the upgrade. This topic provides tips for things to consider when you prepare to upgrade to Microsoft Dynamics NAV 2016.

Names of Variables

Microsoft Dynamics NAV 2016 introduces new functions and statements. If your solution includes variables where the name is now used by a standard C/AL function or statement such as REGISTERTABLECONNECTION or FOREACH, you must change the variables before you upgrade to Microsoft Dynamics NAV 2016. Alternatively, you can enclose the variable names in quotation marks. If you do not, and you import an object that has this code in text format, you cannot compile the object. For more information, see Changes in C/AL Behavior and Support from Earlier Versions of Microsoft Dynamics NAV.

Deprecated or Redesigned Functionality

If you are upgrading a solution that depends on functionality that is deprecated or changed in the default version of Microsoft Dynamics NAV 2016, you must verify that the upgrade codeunits migrate data correctly. For more information about deprecated or changed functionality, see What’s New: Application Changes for Microsoft Dynamics NAV.

Upgrade Codeunits

When you introduce changes to the database schema in Microsoft Dynamics NAV 2016, Microsoft Dynamics NAV will check if these changes are destructive or not. If the database check indicates that the change may lead to data deletion, such as if you are dropping a table column so that the contents of that column will be deleted, this is considered a destructive change. You will be prompted to handle the situation using upgrade codeunits. For more information, see Upgrade Codeunits.

Company Names

If a company name includes a special character, an error may display during the upgrade. In this context, special characters include the following:
[ ~ @ # $ % & * ( ) . ! % - + / = ? ]

If you are going to upgrade a database where one or more company name includes a special character, we recommend that you rename the company before you start the upgrade process. After the upgrade is successfully finished, you can rename the company again.

System Tables with Non-English Names

In the oldest versions of Microsoft Dynamics NAV, you could translate the columns in system tables to a language other than English. Starting with version 3.0, we advised heavily against this, and versions later than Microsoft Dynamics NAV 2013 R2 require that all columns in all system tables are in English. As a result, if you try to open a database with non-English system tables in Microsoft Dynamics NAV 2013 R2 or later, an error displays, saying that one or more columns do not exist.

Make sure that all objects where compiled in a development environment with the right .ETX and .STX files. You can verify that you are running in the correct environment with English (US) as the base language by opening the ndo$dbproperty table in SQL Server Management Studio. In the Identifiers column, the word Object must be written exactly as shown here.

See Also

What’s New: Application Changes for Microsoft Dynamics NAV

Tasks

What's New: Developer and IT Pro Changes for Microsoft Dynamics NAV

Concepts

Upgrading the Application Code
Upgrading the Data
Changes in C/AL Behavior and Support from Earlier Versions of Microsoft Dynamics NAV

Other Resources

Upgrading to Microsoft Dynamics NAV 2016


Converting a Database

If your current solution is based on Microsoft Dynamics NAV 2013 or Microsoft Dynamics NAV 2013 R2, you must convert the database to the Microsoft Dynamics NAV 2016 technical requirements as part of the data upgrade process to Microsoft Dynamics NAV 2016 and then upgrade the application and data later. In this topic, the Microsoft Dynamics NAV 2013 or Microsoft Dynamics NAV 2013 R2 databases are sometimes referred to as the old database.

Similarly, when you upgrade from one Microsoft Dynamics NAV 2016 cumulative update to the next cumulative update, you can be required to convert the database as described in task 2. This occurs when the cumulative update introduces changes to system tables. This type of database conversion is less complicated than the conversion from Microsoft Dynamics NAV 2013 or Microsoft Dynamics NAV 2013 R2 to Microsoft Dynamics NAV 2016.

Warning
You can choose to convert the old database and not upgrade your application. However, we recommend that you upgrade the application objects as well so that your solution includes important application fixes and new functionality that is introduced in Microsoft Dynamics NAV 2016. Upgrading the application will also reduce the amount of merging required to upgrade to the next major version of Microsoft Dynamics NAV, bringing you to the latest version of the product faster.

Important
Before you start, make sure that you have applied the changes that are described in KB 2804640 Code corrections for some Microsoft Dynamics NAV 2013 reports to prevent compilation errors with Report Viewer 2012 when upgrading to later versions of Microsoft Dynamics NAV.

To convert the old database to a Microsoft Dynamics NAV 2016 database, complete tasks 1 and 2. To convert the database from one cumulative update of Microsoft Dynamics NAV 2016 to the next cumulative update, complete task 2.

Task 1: Preparing the Old Database

The first task is to back up the old database and then prepare to convert it.

To prepare the old database

  1. Make a copy of the old database or create full database backup.

    For more information, see Create a Full Database Backup (SQL Server).

  2. Open the development environment that matches the Microsoft Dynamics NAV version of the old database, and then connect to the old database.

    For more information, see How to: Open Databases.

  3. In Object Designer, verify that no objects are locked.

    If one or more objects are locked, the conversion process cannot update the database version number. As a result, the conversion does not complete.

  4. On the Tools menu, choose Build Server Application Objects, and then choose the Yes button.

    Note
    This step does not compile objects in the old database that have not compiled.

  5. If any errors occur, they are shown in the Error List window. Make sure that you address all compilation errors before you continue.

  6. Upload the Microsoft Dynamics NAV 2016 Partner license to the database

    For more information, see Uploading a License File for a Specific Database.

    Important
    The license that you upload must be a developer license. During the conversion, the development environment will convert the report objects that are stored in the old database to the RDL 2012 format.

  7. If you are converting a Microsoft Dynamics NAV 2013 R2 database, then run the Sync-NavTenant cmdlet from the Microsoft Dynamics NAV 2013 R2 Administration Shell to synchronize the database schema changes.

    For more information, see How to: Run the Sync-NAVTenant Cmdlet to Synchronize the Tenant Database with the Application Database.

Task 2: Converting the Old Database

Next, you will convert the old database so that it can be used in Microsoft Dynamics NAV 2016.

Before you start the following procedure, you can choose to uninstall Microsoft Dynamics NAV 2013 or Microsoft Dynamics NAV 2013 R2. When you uninstall Microsoft Dynamics NAV 2013 or Microsoft Dynamics NAV 2013 R2, the database is still attached to the instance of SQL Server, which you can verify using SQL Server Management Studio.

Tip
If you want to write a script that helps you convert databases, you can use the Invoke-NAVDatabaseConversion function in the Microsoft Dynamics NAV 2016 Development Shell.

To convert the database

  1. Install Microsoft Dynamics NAV 2016.

    Run the Microsoft Dynamics NAV 2016 Setup, and choose to install the Developer option.

  2. Open the Microsoft Dynamics NAV 2016 development environment, and then connect to the database that you prepared in the previous task.

    For more information, see How to: Open Databases.

  3. In the dialog box that appears, read the instructions carefully because this action cannot be reversed. When you are ready, choose the OK button, and then choose the OK button to confirm that you want to convert the database.

    Microsoft Dynamics NAV will now convert the database. This includes an upgrade of system tables, and an upgrade of all reports to support Report Viewer 2012.

  4. When you are notified that the conversion was successful, choose the OK button.

  5. Connect a Microsoft Dynamics NAV 2016 Server instance to the converted database.

    You use the Microsoft Dynamics NAV Server Administration tool to connect a Microsoft Dynamics NAV Server instance to the converted database.

    In addition, you must add the service account that is used by the Microsoft Dynamics NAV Server instance as a member of the db_owner role in the Microsoft Dynamics NAV database on SQL Server.

    For more information, see How to: Connect a Microsoft Dynamics NAV Server Instance to a Database and Giving the account necessary database privileges in SQL Server.

  6. Run the development environment as an administrator, and then set the development environment to use the Microsoft Dynamics NAV Server instance that connects to the database.

    For more information, see How to: Change the Microsoft Dynamics NAV Server Instance or Database Information.

  7. Run the schema synchronization to complete the database conversion.

    You can run the schema synchronization from the Microsoft Dynamics NAV Development Environment or Microsoft Dynamics NAV 2016 Administration Shell.

    From the development environment:

    Open development environment as an administrator. On the Tools menu, choose Sync. Schema For All Tables, and then choose With Validation and follow the schema synchronization instructions.

    From the Microsoft Dynamics NAV 2016 Administration Shell:

    Open the Microsoft Dynamics NAV 2016 Administration Shell as an administrator, and then run Sync-NavTenant cmdlet as follows:

    Copy Code
    Sync-NavTenant -ServerInstance <ServerInstanceName>

    Replace <ServerInstanceName> with the name of the Microsoft Dynamics NAV Server instance that is connected to the database. For more information, see How to: Run the Sync-NAVTenant Cmdlet to Synchronize the Tenant Database with the Application Database.

  8. If the database references any assemblies (such as client control add-ins) that are not included on the Microsoft Dynamics NAV 2016 installation media (DVD), then add the assemblies to the Add-ins folder on Microsoft Dynamics NAV Server or Microsoft Dynamics NAV Windows client computers.

    For the Microsoft Dynamics NAV Windows client, the default path is C:\Program Files (x86)\Microsoft Dynamics NAV\90\RoleTailored Client\Add-ins folder.

    For Microsoft Dynamics NAV Server, the default path is the C:\Program Files\Microsoft Dynamics NAV\90\Service\Add-ins folder

  9. In the development environment, on the Tools menu, choose Build Server Application Objects, and then, in the dialog box, choose the Yes button.

  10. Fix compilation errors.

    If any errors occur, they are shown in the Error List window. For information about compilation errors when you are converting a Microsoft Dynamics NAV 2013 database, see Compilation Errors When Converting a Microsoft Dynamics NAV 2013 Database.

    You can find all objects which did not compile in the Object Designer window, by setting a field filter on the Compiled field.

  11. Upload the customer license to the converted database.

    For more information, see Uploading a License File for a Specific Database.

You have now completed the conversion of the Microsoft Dynamics NAV 2013 or Microsoft Dynamics NAV 2013 R2 database to be accessed from Microsoft Dynamics NAV 2016. To test the converted database, you can connect it to the Microsoft Dynamics NAV 2016 Server instance that by Microsoft Dynamics NAV clients, and then open a client.

Next, upgrade the application code to Microsoft Dynamics NAV 2016.

See Also

Concepts

Upgrading the Application Code
Upgrading the Data
Automating the Upgrade Process using Sample Windows PowerShell Scripts

Other Resources

Upgrading to Microsoft Dynamics NAV 2016


Compilation Errors When Converting a Microsoft Dynamics NAV 2013 Database

If you converted a Microsoft Dynamics NAV 2013 database, then after the database conversion has completed, you will receive compilation errors in several standard Microsoft Dynamics NAV objects. The following table provides guidance to help you resolve these errors.

Object Type | Object ID | Object Name | Compilation Status | Solution
Table | 5540 | Timeline Event | Error | Update the Subtype property of the variables that reference the DataVisualization add-in with references to the new version of the add-in.
Table | 5541 | Timeline Event Change | Error | Update the Subtype property of the variables that reference the DataVisualization add-in with references to the new version of the add-in.
Codeunit | 9180 | Generic Chart Mgt. | Error | Remove the code line that refers to the Company field. This field is obsolete.
Codeunit | 9500 | Debugger Management | Error | Remove the code lines that refer to the User SID field. This field is obsolete.
Page | 692 | Import Style Sheet | Error | Rename the ObjectType global variable to ObjType. In Microsoft Dynamics NAV 2016, ObjectType is a reserved word in C/AL.
Page | 693 | Program Selection | Error | Rename the ObjectType global variable to ObjType. In Microsoft Dynamics NAV 2016, ObjectType is a reserved word in C/AL.
Page | 5540 | Item Availability by Timeline | Error | Update the Subtype property of the variables that refer to the DataVisualization add-in with references to the new version of the add-in.
Page | 9170 | Profile Card | Error | Remove the Owner ID column from the page. This field is obsolete.
Page | 9171 | Profile List | Error | Remove the Owner ID column from the page. This field is obsolete.
Page | 9182 | Generic Charts | Error | Remove the code line that refers to the Company field. Remove the Company column from the page. This field is obsolete.
Page | 9183 | Generic Chart Setup | Error | Remove the Company column from the page. This field is obsolete.
Page | 9500 | Debugger | Error | Remove the code lines that refer to the User SID field. This field is obsolete.
Page | 9503 | Debugger Watch Value FactBox | Error | Remove the code lines that refer to the User SID field. This field is obsolete.
Page | 9504 | Debugger Code Viewer | Error | Remove the code lines that refer to the User SID field. This field is obsolete. Rename the ObjectType global variable to ObjType. In Microsoft Dynamics NAV 2016, ObjectType is a reserved word in C/AL.
Page | 9505 | Debugger Breakpoint List | Error | Remove the User SID field from the expression in the SourceTableView property. Remove the code lines that refer to the User SID field. This field is obsolete.
Table | 79 | Company Information | Warning | Several warnings. See the solution in the following section.
Codeunit | 40 | LogInManagement | Warning | See the solution in the following section.
Codeunit | 43 | LanguageManagement | Warning | See the solution in the following section.

The following 3 sections provide before and after code that will help you resolve the warnings you receive when you compile the objects.

Before and After Code for Warnings in Table 79

The following table describes the before and after code that will help you resolve the warnings that you receive when you compile table 79 Company Information.

Before

Copy Code
LOCAL PROCEDURE GetDatabaseIndicatorText@9(IncludeCompany@1003 : Boolean) : Text[250];
VAR
  Session@1000 : Record 2000000009;
  Text@1002 : Text[1024];
BEGIN
  Session.SETRANGE("My Session",TRUE);
  Session.FINDFIRST;
  Text := Session."Database Name" + ' - ' + Session."Host Name";
  IF IncludeCompany THEN
    Text := COMPANYNAME + ' - ' + Text;
  IF STRLEN(Text) > 250 THEN
    EXIT(COPYSTR(Text,1,247) + '...');
  EXIT(Text)
END;

After

Copy Code
LOCAL PROCEDURE GetDatabaseIndicatorText@9(IncludeCompany@1003 : Boolean) : Text[250];
VAR
  ActiveSession@1000 : Record 2000000110;
  Text@1002 : Text[1024];
BEGIN
  ActiveSession.SETRANGE("Server Instance ID",SERVICEINSTANCEID);
  ActiveSession.SETRANGE("Session ID",SESSIONID);
  ActiveSession.FINDFIRST;
  Text := ActiveSession."Database Name" + ' - ' + ActiveSession."Server Computer Name";
  IF IncludeCompany THEN
    Text := COMPANYNAME + ' - ' + Text;
  IF STRLEN(Text) > 250 THEN
    EXIT(COPYSTR(Text,1,247) + '...');
  EXIT(Text)
END;

Before and After Code for Codeunit 40

The following tables describe the before and after code that will help you resolve the warnings that you receive when you compile codeunit 40 LogInManagement.

Before

Copy Code
User@1003 : Record 2000000120;

After

Copy Code
User@1003 : Record 2000000120 SECURITYFILTERING(Filtered);

Before

Copy Code
Language.SETRANGE("STX File Exist",TRUE);

After

Copy Code
Language.SETRANGE("Localization Exist",TRUE);

Before and After Code for Codeunit 43

The following table describes the before and after code that will help you resolve the warnings that you receive when you compile codeunit 43 LanguageManagement.

Before

Copy Code
Language.SETRANGE("STX File Exist",TRUE);

After

Copy Code
Language.SETRANGE("Localization Exist",TRUE);

See Also

Concepts

Converting a Database


Upgrading the Application Code

Typically, customers want all the customizations that have been implemented in their existing Microsoft Dynamics NAV databases to be migrated to their new Microsoft Dynamics NAV 2016 databases. Depending on the version of Microsoft Dynamics NAV that a database is being upgraded from, the amount of code changes between the two versions is large or small. To upgrade the application code, you must merge code from different versions of the application. This merge process is known as a code upgrade or application upgrade. You must upgrade the application before you upgrade the data.

Application Upgrade Overview

During an upgrade, you have to identify which changes you have to make, you have to upgrade the application objects and the application code, and you might have to upgrade data so that it fits the new database schema. You can use any tool or set of tools to help you compare and merge code. For example, Microsoft Dynamics NAV includes Windows PowerShell cmdlets and sample scripts that can help you upgrade your application. For more information, see Comparing and Merging Application Object Source Files.

You must analyze and process code changes by comparing and evaluating three separate versions of the Microsoft Dynamics NAV database:

Version | Description
Original version | This is the baseline version of the solution that you want to upgrade, such as the original release of Microsoft Dynamics NAV 2013.
Modified version | This is the version that you want to upgrade, such as a customer's database with customizations and add-on solutions.
Target version | This is the target of the merge process that you want to upgrade your application to, such as the standard version of the Microsoft Dynamics NAV 2016 database.

When you merge the application objects from these three versions, you can import the result into a new Microsoft Dynamics NAV 2016 database that then contains the upgraded application. At the end of the process, you export the merged Microsoft Dynamics NAV 2016 objects from this database to a .fob file that you will use during the data upgrade.

The following list describes the main steps of upgrading the application code:

  1. Prepare the application object text files.

  2. Merge versions.

  3. Resolve conflicts

  4. Import and compile the merged application objects.

  5. Export all objects.

When you upgrade to Microsoft Dynamics NAV 2016, we recommend that you use the Windows PowerShell cmdlets and sample scripts that are included on the product media. During the code upgrade, Windows PowerShell cmdlets can make it faster to merge most changes. For example, you can combine several steps in a command that uses a cmdlet such Merge-NAVApplicationObject. The following section describes how you can use the Merge-NAVApplicationObject cmdlet and other Windows PowerShell cmdlets. For information about other ways of upgrading your code, see Upgrading the Application Code for Microsoft Dynamics NAV 2013 R2 in the MSDN Library.

To begin, create four folders on the computer and name them as follows:

  • ORIGINAL

    This folder must contain the application objects from the baseline version, such as the original release of Microsoft Dynamics NAV 2013.

  • MODIFIED

    This folder must contain the application objects from the modified version, such as the customer's database.

  • TARGET

    This folder must contain the application objects from Microsoft Dynamics NAV 2016.

  • RESULT

    This folder will contain the application objects that are the result of the application merge. It will also contain zero or more .CONFLICT files that describe conflicting code.

Preparing the Text Files

The Microsoft Dynamics NAV cmdlets take text files as input. You must prepare three sets of text files that contain application objects as describes in the list above. You can export application objects to text files from the development environment, or by running the ExportObjects command. The following list describes the main steps of preparing the text files that you must provide as input for the application merge process.

  1. First, export all application objects from the original version, such as the original Microsoft Dynamics NAV 2013 database. Do not export system tables. Name the file OldBaseVersion.txt, and then save the file in the ORIGINAL folder that you created earlier.

    For example, the Microsoft.Dynamics.Nav.Model.Tools.psd1 module includes a function, Export-NAVApplicationObject, that runs the ExportObjects command. This means that you can run a command such as the following:

    Copy Code
    Export-NAVApplicationObject -DatabaseServer MyServer -DatabaseName "Demo Database NAV (7-0)" -Path C:\Upgrade\ORIGINAL\OldBaseVersion.txt
  2. Next, export all relevant application objects from the modified version, such as the customized Microsoft Dynamics NAV 2013 database. Do not export system tables. Name the file OldCustomVersion.txt, and then save the file in the MODIFIED folder that you created earlier.

    Tip
    In some cases, existing customizations might be irrelevant after the upgrade because they correspond to new functionality in Microsoft Dynamics NAV 2016. For a description of new application functionality in Microsoft Dynamics NAV 2016, see What’s New: Application Changes for Microsoft Dynamics NAV.

  3. Finally, export all application objects from the new base version, such as the original Microsoft Dynamics NAV 2016 database. Do not export system tables. Name the file NewBaseVersion.txt, and then save the file in the TARGET folder that you created earlier.

Optionally, you can use the Split-NAVApplicationObjectFile cmdlet to split each text file into separate text files for each application object. This can make it easier to keep track of the process. The end result at this stage is three folders with one or more text files that contain the three sets of application objects that you want to merge.

In certain scenarios, you can choose to use the Compare-NAVApplicationObject cmdlet to identify the changes between the existing customized application and the new application. You can then choose to use the Update-NAVApplicationObject cmdlet to apply all or some of the changes to the new version. For more information, see How to: Compare and Update Application Object Source Files. However, we recommend that you use the Merge-NAVApplicationObject cmdlet in most cases. For more information, see How to: Merge Application Changes.

Merging Versions

You must now merge the three sets of application objects to create the application for the new database.

The sample scripts on the Microsoft Dynamics NAV product media provide examples of how you can use the Merge-NAVApplicationObject cmdlet to merge the three sets of application objects. The following example illustrates the type of command that you can run.

Copy Code
Merge-NAVApplicationObject -OriginalPath .\ORIGINAL -TargetPath .\TARGET -ModifiedPath .\MODIFIED -ResultPath .\RESULT

Depending on the number of objects that you are merging and the number of differences found, this can take a few seconds, a few minutes, or longer. The RESULT folder will contain a text file for each application object. The result of the merge is shown when the cmdlet completes, including a description of any application objects with conflicting code. These conflicts are stored in .CONFLICT files in the RESULT folder. You can import all objects in the RESULT folder into the new Microsoft Dynamics NAV 2016 database, or you can analyze the conflicts before you import the objects.

Handling Conflicts

Depending on the application that you are upgrading, you can choose to analyze the conflicting code before you import the merged objects into the development environment. The conflicts are shown in the merged text files but are also identified in .CONFLICT files in the RESULT folder. Subfolders then contain copies of the source files from the versions that have conflicting code. You can analyze the conflicts in any tool, make the relevant changes, and then run the merge operation again. Alternatively, you can import the merged files into the development environment, and resolve the conflicts there. For more information, see Handling Merge Conflicts.

Importing and Compiling Merged Objects

After you have completed the merge, import the new custom version into the new Microsoft Dynamics NAV 2016 database, and then compile all objects. You must resolve any compilation errors before you can continue. The text files with the merged application objects include successfully merged code, and code that is partially merged. You can import the partially merged objects into the Microsoft Dynamics NAV 2016 development environment and resolve the conflicts there.

For example, the Microsoft.Dynamics.Nav.Model.Tools.psd1 module includes a function, Import-NAVApplicationObject, that runs the ImportObjects command. This means that you can run a command such as the following:

Copy Code
Join-NAVApplicationObject -Source C:\Upgrade\RESULT\*.txt -Destination C:\Upgrade\all-merged.txt

Import-NAVApplicationObject -DatabaseServer MyServer -DatabaseName "My Upgraded App" -Path C:\Upgrade\all-merged.txt

In this example, you first join the many text files into a single file, which you then import into an existing, empty database. When you compile the objects, an error is thrown for each code conflict, and you can use the tools that are available in the development environment to resolve the conflicts.

You now have a new database with a fully upgraded application.

Exporting All Objects

Now, you must export all objects to an objects.fob file so that you can import them when performing the data upgrade. The export must include customized objects, upgraded reports, and all other Microsoft Dynamics NAV 2016 objects.

This completes the upgrade of the application code. Next, you must upgrade the data in the database. For more information, see Upgrading the Data.

See Also

Concepts

Upgrading the Data

Other Resources

Upgrading to Microsoft Dynamics NAV 2016


Upgrading the Data

This topic describes the tasks required for upgrading a Microsoft Dynamics NAV 2013, Microsoft Dynamics NAV 2013 R2, or Microsoft Dynamics NAV 2015 database to Microsoft Dynamics NAV 2016.

You use data conversion tools provided with Microsoft Dynamics NAV 2016 to convert the old data with the old version’s table and field structure, so that it functions together with the new version’s table and field structure.

  • Prerequisites

  • Task 1: Create a full SQL backup of the old database on SQL Server

  • Task 2: Upload the Microsoft Dynamics NAV 2016 license to the old database

  • Task 3: Delete all objects

  • Task 4: Uninstall the old product and install the new

  • Task 5: Convert the old database to a Microsoft Dynamics NAV 2016 format

  • Task 6: Connect a Microsoft Dynamics NAV 2016 Server instance to the converted database

  • Task 7: Run the schema synchronization to complete the database conversion

  • Task 8: Import the application objects to the converted database

  • Task 9: Run the schema synchronization to synchronize the new tables

  • Task 10: Run the data upgrade process

  • Task 11: Delete the upgrade objects

  • Task 12: Import upgraded permission sets and permissions by using the Roles and Permissions XMLports

  • Task 13: Set the language of the customer database

  • Task 14: Add new control add-ins

  • Task 15: Import Payment Services and Data Encryption Key (Optional)

Important
During the data upgrade, you must make sure that your computer uses the same codepage as the data. When you use conflicting codepages, some characters will not display in captions, and you might not be able to access the upgraded database.

Optionally, you can export the captions before the upgrade. For more information, see How to: Add Translated Strings for Conflicting Text Encoding Formats.

If you upgrade a database using a different codepage, Microsoft Dynamics NAV must remove incorrect metadata characters to complete the data upgrade. Then, you must open the database in the development environment on a computer with the relevant codepage and compile all objects. This adds the missing characters again.

Prerequisites

  • A FOB file that contains the upgraded application code and upgrade toolkit. The upgrade toolkit can also be in a separate FOB file.

    For more information, see Upgrading the Application Code.

  • All application objects in the old database have been built.

    For more information, see How to: Build Server Application Objects.

  • All application objects are unlocked.

    For more information, see How to: Unlock an Object.

  • The database schema has been synchronized in the old application.

    For more information, see How to: Run the Sync-NAVTenant Cmdlet to Synchronize the Tenant Database with the Application Database.

  • Updated permission sets permissions XML files.

  • (Optional) If the old Microsoft Dynamics NAV application uses Payment Services for Microsoft Dynamics ERP, download the encryption key file that is used on the service connection.

    You can download the encryption from the Microsoft Dynamics ERP Payment Services Connection Setup window in the Microsoft Dynamics NAV client. For more information, see Microsoft Dynamics ERP Payment Services Connection Setup

  • (Optional) If the old Microsoft Dynamics NAV application uses data encryption, export the encryption key file that it used for the data encryption.

    For more information, see How to: Export and Import Encryption Keys.

Task 1: Create a full SQL backup of the old database on SQL Server

You must create a full backup of the old database in the SQL Server. Alternatively, you can make a copy of the old database and perform the upgrade tasks on the copy.

For more information, see Create a Full Database Backup (SQL Server).

Task 2: Upload the Microsoft Dynamics NAV 2016 license to the old database

In the development environment, upload the Microsoft Dynamics NAV 2016 license to the database. For more information, see Uploading a License File for a Specific Database.

Task 3: Delete all objects

Open the old database in the Microsoft Dynamics NAV 2013, Microsoft Dynamics NAV 2013 R2, or Microsoft Dynamics NAV 2015 Development Environment, open Object Designer, and then delete all objects.

Task 4: Uninstall the old product and install the new

Uninstall Microsoft Dynamics NAV 2013, Microsoft Dynamics NAV 2013 R2, or Microsoft Dynamics NAV 2015, and then install Microsoft Dynamics NAV 2016.

During installation of Microsoft Dynamics NAV 2016, you can either choose the Install Demo option, for which you will discard the Demo database afterwards, or choose the Custom option, where you then select to install the Client (with the Development Environment), Server, and Administration Tool components.

Task 5: Convert the old database to a Microsoft Dynamics NAV 2016 format

To convert the old database to a Microsoft Dynamics NAV 2016 format, open the old database in the development environment, and follow the conversion instructions.

Task 6: Connect a Microsoft Dynamics NAV 2016 Server instance to the converted database

You use the Microsoft Dynamics NAV Server Administration tool to connect a Microsoft Dynamics NAV Server instance to the converted database.

In addition, you must add the service account that is used by the Microsoft Dynamics NAV Server instance as a member of the db_owner role in the Microsoft Dynamics NAV database on SQL Server.

Important
When upgrading a large database, you should increase the SQL Command Timeout setting for the Microsoft Dynamics NAV Server instance, to avoid timeouts during schema synchronization. The default setting is 30 minutes.

For more information, see How to: Connect a Microsoft Dynamics NAV Server Instance to a Database and Giving the account necessary database privileges in SQL Server.

Task 7: Run the schema synchronization to complete the database conversion

You can run the schema synchronization from the Microsoft Dynamics NAV Development Environment or Microsoft Dynamics NAV 2016 Administration Shell.

From the development environment:

Open development environment as an administrator. On the Tools menu, choose Sync. Schema For All Tables, and then choose With Validation and follow the schema synchronization instructions.

From the Microsoft Dynamics NAV 2016 Administration Shell:

Open the Microsoft Dynamics NAV 2016 Administration Shell as an administrator, and then run Sync-NavTenant cmdlet as follows:

Copy Code
Sync-NavTenant -ServerInstance <ServerInstanceName>

Replace <ServerInstanceName> with the name of the Microsoft Dynamics NAV Server instance that is connected to the database. For more information, see How to: Run the Sync-NAVTenant Cmdlet to Synchronize the Tenant Database with the Application Database.

Task 8: Import the application objects to the converted database

In the development environment, import all the application objects that you want in the Microsoft Dynamics NAV 2016 database. This includes the FOB file that contains all the Microsoft Dynamics NAV 2016 objects from the application code upgrade and upgrade toolkit objects.

When you import the FOB file, if you experience metadata conflicts, use the Import Worksheet to handle these conflicts.

Finally, on the dialog box for selecting the schema synchronization, set the Synchronize Schema option to Later.

If the upgrade toolkit objects are stored in a separate FOB file, then import the upgrade toolkit FOB file after the application objects are imported.

Task 9: Run the schema synchronization to synchronize the new tables

Similar to task 7, to publish the data schema changes of the newly imported tables to the SQL tables, run the Sync. Schema For All Tables - With Validation option from the development environment or run the Sync-NavTenant cmdlet from the Microsoft Dynamics NAV 2016 Administration Shell.

Task 10: Run the data upgrade process

A data upgrade runs the upgrade toolkit objects, such as upgrade codeunits and upgrade tables, to migrate business data from the old table structure to the new table structure. You can start the data upgrade from the Microsoft Dynamics NAV Development Environment or Microsoft Dynamics NAV 2016 Administration Shell.

Note
In the last phase of data upgrade, all companies will be initialized by running codeunit 2 Company Initialization. This is done automatically. If you want to skip company initialization, then use the Start- NavDataUpgrade cmdlet and set the SkipCompanyIntitialization parameter.

From the development environment:

Open development environment as an administrator. On the Tools menu, choose Data Upgrade, and then choose Start and follow the instructions.

To view the progress of the data upgrade, on the Tools menu, choose Data Upgrade, and then choose Show Progress.

From the Microsoft Dynamics NAV 2016 Administration Shell:

Open the Microsoft Dynamics NAV 2016 Administration Shell as an administrator, and then run Start-NavDataUpgrade cmdlet as follows:

Copy Code
Start-NavDataUpgrade -ServerInstance <ServerInstanceName> -Force

Replace <ServerInstanceName> with the name of the Microsoft Dynamics NAV Server instance that is connected to the database.

To view the progress of the data upgrade, you can run Get-NavDataUpgrade cmdlet with the -Progress switch.

The data upgrade process runs CheckPreconditions and Upgrade functions in the upgrade codeunits. If any of the preconditions are not met or an upgrade function fails, you must correct the error and resume the data upgrade process. If CheckPreconditions and Upgrade functions are executed successfully, codeunit 2 is automatically run to initialize all companies in the database unless you set the SkipCompanyIntitialization parameter.

Task 11: Delete the upgrade objects

At this point, you have upgraded the database to Microsoft Dynamics NAV 2016. Now, you can delete the upgrade codeunits and upgrade table objects that you imported in task 8.

When you delete tables, on the Delete dialog box, set the Synchronize Schema option to Force.

Task 12: Import upgraded permission sets and permissions by using the Roles and Permissions XMLports

You import the permission sets and permissions XML files according to the following procedure.

To import the permission sets and permissions

  1. Delete all permission sets in the database except the SUPER permission set.

    In Object Designer, run page 9802 Permission Sets, and then delete the permission sets.

  2. Run XMLport 9171 Import/Export Permission Sets to import the permission sets XML file,

    In the request page for the XMLport, in the Direction field, choose Import, choose the OK button, and then specify the permission sets XML file.

  3. Run XMLport 9172 Import/Export Permissions to import the permission XML file.

    In the request page for the XMLport, in the Direction field, choose Import, choose the OK button, and then specify the permissions XML file.

Task 13: Set the language of the customer database

In the development environment, choose Tools, choose Language, and then select the language of the original customer database.

Task 14: Add new control add-ins

The database is now fully upgraded and is ready for use. However, you may want to add the new client control add-ins that are included in Microsoft Dynamics NAV 2016. These are not added by the upgrade process. The following client control add-ins are available from the Microsoft Dynamics NAV product media:

  • Microsoft.Dynamics.Nav.Client.BusinessChart

  • Microsoft.Dynamics.Nav.Client.PageReady

  • Microsoft.Dynamics.Nav.Client.PingPong

  • Microsoft.Dynamics.Nav.Client.VideoPlayer

  • Microsoft.Dynamics.Nav.Client.SocialListening

You can add control add-ins in the Control Add-ins window in the Microsoft Dynamics NAV Windows client. For more information, see How to: Register a Windows Client Control Add-in.

Task 15: Import Payment Services and Data Encryption Key (Optional)

  • If you want to set up Payment Services for Microsoft Dynamics ERP as before, you must upload the payment service encryption key file that was downloaded previously.

    You upload the encryption key from the Microsoft Dynamics ERP Payment Services Connection Setup window in the Microsoft Dynamics NAV client. For more information, see Microsoft Dynamics ERP Payment Services Connection Setup.

  • If you want to use data encryption as before, you must import the data encryption key file that was exported previously.

    For more information, see How to: Export and Import Encryption Keys.

See Also

Concepts

Upgrading the Application Code
Automating the Upgrade Process using Sample Windows PowerShell Scripts
Synchronizing Table Schemas

Other Resources

Upgrading to Microsoft Dynamics NAV 2016


How to: Run the Sync-NAVTenant Cmdlet to Synchronize the Tenant Database with the Application Database

This topic describes how to run the Sync-NAVTenant cmdlet to synchronize the business data (tenant) database schema with the application database.

To run the Sync-NAVTenant cmdlet

  1. On the computer that is running the Microsoft Dynamics NAV Server, run Microsoft Dynamics NAV Administration Shell as an Administrator.

    1. Choose Start, in the Search box, type Microsoft Dynamics NAV Administration Shell.

    2. Right-click the related link, and then choose Run as Administrator.

  2. At the command prompt, type the following command:

    Copy Code
    Sync-NAVTenant -ServerInstance <ServerInstanceName> -Tenant <TenantId>

    Change the following parameter values.

    Parameter Description

    <NAVServerInstance>

    Specifies the Microsoft Dynamics NAV Server instance.

    <TenantId>

    Specifies the name of the tenant database.

  3. Press Enter to run the cmdlet.

See Also

Tasks

How to: Add a Microsoft Dynamics NAV Web Server Instance
How to: Add a Microsoft Dynamics NAV Database
How to: Add a Microsoft Dynamics NAV Server Instance

Concepts

Scaling the Microsoft Dynamics NAV Network Topology
Multitenant Deployment Architecture
Migrating to Multitenancy
Deploying and Managing Microsoft Dynamics NAV on Microsoft Azure


How to: Connect a Microsoft Dynamics NAV Server Instance to a Database

This procedure describes how to use the Microsoft Dynamics NAV Server Administration tool to change the Microsoft Dynamics NAV database to which a Microsoft Dynamics NAV Server instance connects.

To connect a database to a Microsoft Dynamics NAV Server instance

  1. Start the Microsoft Dynamics NAV Server Administration tool.

    For more information, see Microsoft Dynamics NAV Server Administration Tool.

  2. Navigate to the Microsoft Dynamics NAV 2016 server instance that you want to connect to the converted database, and then choose the Edit button.

  3. On the General FastTab, change the following fields to point at the converted database:

    • Database Instance

    • Database Name

    • Database Server

    Important
    With a large database, increase the SQL Command Timeout setting to avoid timeouts during schema synchronization. The default setting is 30 minutes.

  4. Choose the Save button, and then, in the dialog box that appears, choose the OK button.

  5. In the left pane, choose the Microsoft Dynamics NAV Server computer where the service instance that you modified in the previous step runs.

    Unless you are administering a remote computer, this is Microsoft Dynamics NAV (local).

  6. In the central pane, right-click the service instance that you modified, and then choose Restart.

    This stops and restarts the service instance, and the service instance now connects to the converted database.

  7. To verify that the Microsoft Dynamics NAV Server instance accesses the converted database, open the Microsoft Dynamics NAV Windows client and connect to the modified Microsoft Dynamics NAV Server instance.

See Also

Upgrading the Data


Automating the Upgrade Process using Sample Windows PowerShell Scripts

You can use Windows PowerShell scripts to help you upgrade to the latest version of Microsoft Dynamics NAV. You can use automation to upgrade a single Microsoft Dynamics NAV database as well as multiple Microsoft Dynamics NAV databases that use the same application. Microsoft Dynamics NAV 2016 provides sample scripts that you can adapt for your deployment architecture.

Automating the Upgrade Process

When you upgrade to Microsoft Dynamics NAV 2016, you must first upgrade the application code, and then you upgrade the data. By using Windows PowerShell, you can automate both parts of the upgrade process. Also, you can use the same scripts to test each step in your upgrade process before you upgrade production databases.

Also, if you maintain multiple Microsoft Dynamics NAV databases, for example if you support multiple customers with the same Microsoft Dynamics NAV application, you can reduce the time that you spend upgrading each database by using Windows PowerShell scripts. In that case, you can upgrade the application locally, and then use scripts to roll out the upgrade of each database with reduced unavailability for each database. You can combine this automated upgrade with a migration to multitenancy if this makes maintenance easier for you.

The Sample Scripts for Code Upgrade

Microsoft Dynamics NAV includes sample scripts that illustrate how you can use Windows PowerShell cmdlets to upgrade your application to the latest version of Microsoft Dynamics NAV. The sample scripts are located in the ApplicationMergeUtilities folder under the WindowsPowerShellScripts folder on the Microsoft Dynamics NAV product media. The sample scripts illustrate how you can create scripts that you run in the Microsoft Dynamics NAV 2016 Development Shell or the Windows PowerShell Integrated Scripting Environment (ISE).

The sample scripts show different ways of merging application objects that can help you find the best approach to upgrade your application code. The ApplicationMergeUtilities folder contains four subfolders that can help you start working with the scripts. The demonstration data in the ORIGINAL, MODIFIED, and TARGET folders illustrate the text files that are the input to the cmdlets. The __Run-Application-Merge-Utilities.ps1 script runs the sample scripts based on simplified demonstration data. For more information, see Merging Application Objects using the Example Scripts.

The Sample Scripts for Data Upgrade

Microsoft Dynamics NAV includes sample scripts that illustrate how you can automate the upgrade of data to the latest version of Microsoft Dynamics NAV. The sample scripts are located in the Upgrade folder under the WindowsPowerShellScripts folder on the Microsoft Dynamics NAV product media. The sample scripts include a HowTo script that illustrates how you can use the Microsoft Dynamics NAV cmdlets and sample scripts.

The HowTo-UpgradeNAVDatabase.ps1 script illustrates how you can create a script that upgrades a database from an earlier version of Microsoft Dynamics NAV to a new version through a set of upgrade tasks. You can run the sample script using a partner license or a customer license.

The Upgrade folder also contains the Set-PartnerSettings.ps1 where you can specify values for the input parameters that the HowTo-UpgradeNAVDatabase.ps1 script requires, such as the database that you want to upgrade. You must also specify the folder where the license is stored. Finally, you must specify the location of the .fob file with the upgraded application objects. Optionally, the upgrade toolkit objects can be part of that .fob file, or they can be stored in a separate .fob file and import them later.

The Example.ps1 script reads the upgrade parameters from the Set-PartnerSettings.ps1 script, calls the HowTo script, passing the upgrade parameters, and then shows the detailed information about each upgrade task. To run the sample script for the data upgrade of a Microsoft Dynamics NAV database, you must have a Microsoft Dynamics NAV 2013, Microsoft Dynamics NAV 2013 R2, or Microsoft Dynamics NAV 2015 database that is available on a SQL Server instance and is ready to be upgraded. The Example.ps1 script runs the following main steps:

  1. Loads the settings from the Set-PartnerSettings.ps1 file, and prepares the Windows PowerShell session by importing the required modules.

  2. Saves the current license from the Microsoft Dynamics NAV 2013, Microsoft Dynamics NAV 2013 R2, or Microsoft Dynamics NAV 2015 database.

  3. Creates a backup of the Microsoft Dynamics NAV 2013, Microsoft Dynamics NAV 2013 R2, or Microsoft Dynamics NAV 2015 database, and then converts the database to Microsoft Dynamics NAV 2016.

  4. Connects the Microsoft Dynamics NAV 2016 Server instance to the converted database, imports the Microsoft Dynamics NAV 2016 license file, and then synchronizes the table schema.

  5. Imports the application objects and upgrade toolkit objects from the specified .fob file, and then synchronizes the table schema again. This updates the SQL Server database based on the new table schema that is defined by the imported application objects. Data that must be mapped to another table is saved in upgrade tables.

  6. Calls the Start-NAVDataUpgrade cmdlet to verify the data upgrade preconditions and transfer data from the upgrade tables to the destination tables.

  7. Deletes all obsolete tables and the upgrade toolkit objects.

  8. Initializes all companies in the upgraded database. If you specified a RapidStart package in the Set-PartnerSettings.ps1 file, the package is applied to all companies.

The sample script is intended to be run in the context of a Microsoft Dynamics NAV 2016 deployment, including the Microsoft Dynamics NAV Server instance. The Microsoft Dynamics NAV Server instance cannot be multitenant. When the sample script runs successfully, the result is a Microsoft Dynamics NAV 2016 database that is connected to a Microsoft Dynamics NAV 2016 Server instance, and which uses a Microsoft Dynamics NAV 2016 license. The sample script also returns a list of statistics about the upgrade tasks, including information about whether the task ran or not. If a task failed, it is marked, and the information includes the error message and stack trace to help you identify the problem. You can resolve errors in the Microsoft Dynamics NAV Development Environment, save changes, and then run the sample script again, using the database backup that you created earlier.

See Also

Concepts

Microsoft Dynamics NAV Windows PowerShell Cmdlets
Sample Windows PowerShell Scripts for Microsoft Dynamics NAV
Merging Application Objects using the Example Scripts
Upgrading the Application Code

Other Resources

Upgrading to Microsoft Dynamics NAV 2016