MICROSOFT DYNAMICS ® NAV 2009
C-SIDE INTRODUCTION
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Last Revision: December 2008 The information contained in this document represents the current view of Microsoft Corporation on the issues discussed as of the date of publication. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information presented after the date of publication. This document is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS DOCUMENT. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation. 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, copyrights, or other intellectual property.
© 2008 Microsoft Corporation. All rights reserved. Microsoft Dynamics®, Microsoft® PowerPoint® Microsoft® SQL Server® and Microsoft Dynamics® NAV MorphX® are trademarks or registered trademarks of Microsoft Corporation. The names of actual companies and products mentioned herein may be the trademarks of their respective owners. This course content is designed for Microsoft Dynamics® NAV 2009.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Table of Contents Introduction
0-1
Welcome ............................................................................................................ 0-1 Microsoft Dynamics Courseware Contents ........................................................ 0-2 Documentation Conventions .............................................................................. 0-3 Student Objectives ............................................................................................. 0-4
Chapter 1: Client/Server Integrated Development Environment (C/SIDE)
1-1
Objectives ........................................................................................................... 1-1 Introduction ......................................................................................................... 1-1 Basic Objects in Microsoft Dynamics NAV ......................................................... 1-2 C/SIDE Fundamentals ........................................................................................ 1-3 The Physical and the Logical Database ............................................................. 1-8 Integration Tools ............................................................................................... 1-10 Summary .......................................................................................................... 1-12 Quick Interaction: Lessons Learned ................................................................. 1-13
Chapter 2: Tables
2-1
Objectives ........................................................................................................... 2-1 Introduction ......................................................................................................... 2-1 Table Fundamentals ........................................................................................... 2-2 Primary and Secondary Keys ........................................................................... 2-10 Demonstration: Create a Simple Table ............................................................ 2-12 Table Relationships .......................................................................................... 2-17 Demonstration: Table Relations ....................................................................... 2-21 Special Table Fields ......................................................................................... 2-29 Demonstration: Special Table Fields ................................................................ 2-31 Table Types and Characteristics ...................................................................... 2-41 Lab 2.1 - Create a Table .................................................................................. 2-53 Summary .......................................................................................................... 2-57 Test Your Knowledge ....................................................................................... 2-58 Quick Interaction: Lessons Learned ................................................................. 2-59
Chapter 3: Forms
3-1
Objectives ........................................................................................................... 3-1 Introduction ......................................................................................................... 3-1 Form Fundamentals ........................................................................................... 3-2 Demonstration: Create a Simple Form ............................................................... 3-8 Form Types and Characteristics....................................................................... 3-24 Demonstration: Create a Card Form ................................................................ 3-34 Demonstration: Create a List Form .................................................................. 3-39 Demonstration: Link the Card Form and the List Form .................................... 3-41 Demonstration: Form and Subform .................................................................. 3-45 Lab 3.1 - Create a Card and a List Form .......................................................... 3-48 Standard Navigation ......................................................................................... 3-51 Summary .......................................................................................................... 3-53 Test Your Knowledge ....................................................................................... 3-54 Quick Interaction: Lessons Learned ................................................................. 3-55
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
i
C/SIDE Introduction in Microsoft Dynamics® NAV 20099 Chapter 4: Pages
4-1
Objectives ........................................................................................................... 4-1 Introduction ......................................................................................................... 4-1 Page Fundamentals ........................................................................................... 4-2 Page Designer .................................................................................................... 4-8 Demonstration: Create a Simple Page ............................................................. 4-13 Page Types and Characteristics....................................................................... 4-25 Design Pages: Best Practices .......................................................................... 4-34 Demonstration: Create a Card Page ................................................................ 4-35 Demonstration: Create a List Page .................................................................. 4-38 Demonstration: Page and Part Page ................................................................ 4-39 Lab 4.1 - Create a Card, a List and a ListPart Page......................................... 4-42 Summary .......................................................................................................... 4-45 Quick Interaction: Lessons Learned ................................................................. 4-46
Chapter 5: Introduction to C/AL Programming
5-1
Objectives ........................................................................................................... 5-1 Introduction ......................................................................................................... 5-1 C/AL Programming ............................................................................................. 5-2 Intrinsic Data Types ............................................................................................ 5-5 Identifiers, Variables and Syntax ...................................................................... 5-13 The Syntax of Identifiers ................................................................................... 5-14 Variable Scope ................................................................................................. 5-14 Variable Initialization ........................................................................................ 5-15 Demonstration: Data Types and Variables Initialization ................................... 5-15 Lab 5.1 - Investigate Data Types...................................................................... 5-20 Summary .......................................................................................................... 5-22 Test Your Knowledge ....................................................................................... 5-23 Quick Interaction: Lessons Learned ................................................................. 5-24
Chapter 6: Assignment Statements and Expressions
6-1
Objectives ........................................................................................................... 6-1 Introduction ......................................................................................................... 6-1 Assignment Statements ..................................................................................... 6-2 The Syntax of Statements .................................................................................. 6-2 Automatic Type Conversions.............................................................................. 6-4 Demonstration: Use Assignment Statements and the Symbol Menu ................. 6-5 Expressions, Terms, and Operators ................................................................... 6-9 The Syntax of an Expression ........................................................................... 6-11 The String Operator .......................................................................................... 6-11 Demonstration: Use the String Operator .......................................................... 6-12 Function Calls in Expressions .......................................................................... 6-13 Demonstration: Use the MAXSTRLEN and the COPYSTR Function............... 6-14 Numeric Expressions ....................................................................................... 6-16 Arithmetic Operators ........................................................................................ 6-16 Demonstration: Use the Arithmetic Operators .................................................. 6-21 Relational and Logical Expressions.................................................................. 6-24 Relational Expressions for Comparison ........................................................... 6-25 Relational Expressions for Set Inclusion .......................................................... 6-27 Logical Expressions ......................................................................................... 6-28 ii
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Table of Contents Demonstration: Use Logical and Relational Expressions in a Page................. 6-30 Summary .......................................................................................................... 6-33 Test Your Knowledge ....................................................................................... 6-34 Quick Interaction: Lessons Learned ................................................................. 6-35
Chapter 7: C/AL Statements
7-1
Objectives ........................................................................................................... 7-1 Introduction ......................................................................................................... 7-1 Conditional Statements and Boolean Expressions............................................. 7-2 The IF Statement ................................................................................................ 7-2 The EXIT Statement ........................................................................................... 7-4 The CASE Statement ......................................................................................... 7-5 Compound Statements and Comments ............................................................. 7-6 The Syntax of Compound Statements ............................................................... 7-6 Compound Statement by Using Nested IF Statements ...................................... 7-8 The Syntax of Comments ................................................................................. 7-10 Demonstration: Use the IF, EXIT, CASE and Compound Statements in a Page7-11 Test Your Knowledge ....................................................................................... 7-20 Lab 7.1 - Use Conditional and Compound Statements .................................... 7-21 Arrays ............................................................................................................... 7-25 The Syntax of Arrays ........................................................................................ 7-26 The Power of Arrays ......................................................................................... 7-28 Strings as Arrays of Characters........................................................................ 7-29 Repetitive Statements ...................................................................................... 7-30 Demonstration: Use Arrays and Repetitive Statements ................................... 7-35 The WITH Statement ........................................................................................ 7-45 Summary .......................................................................................................... 7-47 Test Your Knowledge ....................................................................................... 7-48 Quick Interaction: Lessons Learned ................................................................. 7-49
Chapter 8: C/AL Functions
8-1
Objectives ........................................................................................................... 8-1 Introduction ......................................................................................................... 8-1 Functions and Parameters ................................................................................. 8-2 Review Built-in Functions ................................................................................... 8-3 Demonstration: Use the DATE2DMY Function .................................................. 8-8 Test Your Knowledge ......................................................................................... 8-9 Essential C/AL Functions ................................................................................. 8-10 User Communication Functions ....................................................................... 8-19 String Functions ............................................................................................... 8-22 System Functions ............................................................................................. 8-25 Date Functions ................................................................................................. 8-28 Number Functions ............................................................................................ 8-31 Array Functions ................................................................................................ 8-32 Other Functions ................................................................................................ 8-34 Create Custom Functions ................................................................................. 8-38 Formal and Actual Parameters ......................................................................... 8-39 Local Functions, Variables and the EXIT Statement ........................................ 8-40 Demonstration: Create Custom Functions ....................................................... 8-41 Summary .......................................................................................................... 8-45
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
iii
C/SIDE Introduction in Microsoft Dynamics® NAV 20099 Test Your Knowledge ....................................................................................... 8-46 Quick Interaction: Lessons Learned ................................................................. 8-47
Chapter 9: Reports
9-1
Objectives ........................................................................................................... 9-1 Introduction ......................................................................................................... 9-1 Reports Fundamentals ....................................................................................... 9-2 Types of Printing Reports ................................................................................... 9-7 Report Design Process ...................................................................................... 9-9 Design the Data Model ..................................................................................... 9-11 Demonstration: Create a Data Model ............................................................... 9-12 Design the Visual Element ............................................................................... 9-15 Demonstration: Design the Report Section ...................................................... 9-17 Demonstration: Modify Report Properties ........................................................ 9-27 Demonstration: Design the Report Layout ....................................................... 9-31 The Request Options Designer ........................................................................ 9-40 Demonstration: Design the Request Options Form .......................................... 9-41 Demonstration: Design the Request Options Page .......................................... 9-44 Grouping Within a Classic Report .................................................................... 9-47 Demonstration: Create Grouping For The Classic Report................................ 9-48 Totaling in a Report .......................................................................................... 9-51 Demonstration: Create Totals For The Classic Report..................................... 9-52 Demonstration: Create Grouping and Totals For The RoleTailored Report ..... 9-54 Demonstration: Add Some Advanced Features ............................................... 9-59 Lab 9.1 - Create a Basic Report ....................................................................... 9-67 Summary .......................................................................................................... 9-70 Test Your Knowledge ....................................................................................... 9-71 Quick Interaction: Lessons Learned ................................................................. 9-72
Chapter 10: Dataports and XMLports
10-1
Objectives ......................................................................................................... 10-1 Introduction ....................................................................................................... 10-1 Dataport Fundamentals .................................................................................... 10-2 Design Dataports .............................................................................................. 10-4 Demonstration: Create Dataports For Export ................................................... 10-8 Demonstration: Create Dataports For Import ................................................. 10-14 XMLPort Fundamentals .................................................................................. 10-17 Design XMLports ............................................................................................ 10-21 Demonstration: Create XMLports For Use In The Classic Client ................... 10-26 Demonstration: Create XMLports For Use In The RoleTailored Client .......... 10-33 Lab 10.1 - Create XMLports ........................................................................... 10-36 Summary ........................................................................................................ 10-40 Test Your Knowledge ..................................................................................... 10-41 Quick Interaction: Lessons Learned ............................................................... 10-42
Chapter 11: Codeunits
11-1
Objectives ......................................................................................................... 11-1 Introduction ....................................................................................................... 11-1 Codeunit Fundamentals ................................................................................... 11-2 Design Codeunits ............................................................................................. 11-3
iv
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Table of Contents Use Codeunits .................................................................................................. 11-4 Demonstration: Define Variables, Text Constants and Functions in a Codeunit11-6 SMTP ............................................................................................................... 11-7 Summary .......................................................................................................... 11-9 Test Your Knowledge ..................................................................................... 11-10 Quick Interaction: Lessons Learned ............................................................... 11-11
Chapter 12: MenuSuites
12-1
Objectives ......................................................................................................... 12-1 Introduction ....................................................................................................... 12-1 MenuSuite Fundamentals................................................................................. 12-2 Create and Design MenuSuites........................................................................ 12-2 Upgrade MenuSuite ......................................................................................... 12-6 Demonstration: Create a MenuSuite For The Classic Client ............................ 12-7 Demonstration: Create A MenuSuite For The RoleTailored Client................... 12-9 Lab 12.1 - Create MenuSuites ....................................................................... 12-12 Summary ........................................................................................................ 12-14 Test Your Knowledge ..................................................................................... 12-15 Quick Interaction: Lessons Learned ............................................................... 12-16
Chapter 13: Integration Options
13-1
Objectives ......................................................................................................... 13-1 Introduction ....................................................................................................... 13-1 Web Services ................................................................................................... 13-2 Demonstration: Create, Expose and Consume Web Services ......................... 13-6 ODBC ............................................................................................................. 13-18 Demonstration: Use Microsoft Dynamics NAV ODBC.................................... 13-22 C/FRONT ....................................................................................................... 13-25 OCX ................................................................................................................ 13-27 Demonstration: Use OCX Controls................................................................. 13-29 Automation Server .......................................................................................... 13-32 Demonstration: Create a Report with Automation .......................................... 13-35 Summary ........................................................................................................ 13-40 Test Your Knowledge ..................................................................................... 13-41 Quick Interaction: Lessons Learned ............................................................... 13-42
Appendix A: Solutions to Exercises
A-1
Test Your Knowledge Answers (CH2) ............................................................... A-1 Test Your Knowledge Answers (CH3) ............................................................... A-3 Test Your Knowledge Answers (CH5) ............................................................... A-4 Test Your Knowledge Answers (CH6) ............................................................... A-6 Test Your Knowledge Answers (CH7 Part 1) .................................................... A-8 Test Your Knowledge Answers (CH7 Part 2) .................................................... A-9 Test Your Knowledge Answers (CH7 Part 2) .................................................... A-9 Test Your Knowledge Answers (CH8 Part 1) .................................................. A-11 Test Your Knowledge Answers (CH8 Part 2) .................................................. A-13 Test Your Knowledge Answers (CH9) ............................................................. A-14 Test Your Knowledge Answers (CH10) ........................................................... A-16 Test Your Knowledge Answers (CH11) ........................................................... A-18 Test Your Knowledge Answers (CH12) ........................................................... A-19
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
v
C/SIDE Introduction in Microsoft Dynamics® NAV 20099 Test Your Knowledge Answers (CH13) ........................................................... A-20
vi
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Introduction
INTRODUCTION Welcome We know training is a vital component of retaining the value of your Microsoft Dynamics® NAV 2009 investment. Our quality training from industry experts keeps you up-to-date on your solution and helps you develop the skills necessary for fully maximizing the value of your solution. Whether you choose Online Training, Classroom Training, or Training Materials; there is a type of training to meet everyone's needs. Choose the training type that best suits you so you can stay ahead of the competition.
Online Training Online Training delivers convenient, in-depth training to you in the comfort of your own home or office. Online training provides immediate access to training 24 hours-a-day. It is perfect for the customer who does not have the time or budget to travel. Our newest online training option, eCourses, combine the efficiency of online training with the in-depth product coverage of classroom training, with at least two weeks to complete each course.
Classroom Training Classroom Training provides serious, in-depth learning through hands-on interaction. From demonstrations to presentations to classroom activities, you receive hands-on experience with instruction from our certified staff of experts. Regularly scheduled throughout North America, you can be sure you will find a class convenient for you.
Training Materials Training Materials enable you to learn at your own pace, on your own time with information-packed training manuals. Our wide variety of training manuals feature an abundance of tips, tricks, and insights you can refer to again and again:
Microsoft Dynamics Courseware The Microsoft Dynamics Courseware consists of detailed training manuals, designed from a training perspective. These manuals include advanced topics as well as training objectives, exercises, interactions and quizzes. Look for a complete list of manuals available for purchase on the Microsoft Dynamics website: www.microsoft.com/Dynamics.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
0-1
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Microsoft Dynamics Courseware Contents Test Your Skills Within the Microsoft Dynamics Training Materials you find a variety of different exercises. These exercises are offered in three levels to accommodate the variety of knowledge and expertise of each student. We suggest you try the level three exercises first, if you need help completing the task look to the information in the level two exercises. If you need further assistance each step of the task is outlined in the level one exercise.
Challenge Yourself! Level 3 exercises are the most challenging. These exercises are designed for the experienced student who requires little instruction to complete the required task.
Need a Little Help? Level 2 exercises are designed to challenge students, while providing some assistance. These exercises do not provide step by step instructions, however, do provide you with helpful hints and more information to complete the exercise.
Step by Step Level 1 exercises are geared towards new users who require detailed instructions and explanations to complete the exercise. Level 1 exercises guide you through the task, step by step, including navigation.
Quick Interaction: Lessons Learned At the end of each chapter within the Microsoft Dynamics Training Material, you find a Quick Interaction: Lessons Learned page. This interaction is designed to provide the student with a moment to reflect on the material they have learned. By outlining three key points from the chapter, the student is maximizing knowledge retention, and providing themselves with an excellent resource for reviewing key points after class.
0-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Introduction
Documentation Conventions The following conventions and icons are used throughout this documentation to help you quickly and effectively navigate through the information. CAUTION: Cautions are found throughout the training manual and are preceded by the word CAUTION in bold. Cautions are used to remind you of a specific result of a specific action which may be undesirable. HINT: Hints are found throughout the training manual and are preceded by the word HINT in bold. Hints are used to suggest time-saving features or alternative methods for accomplishing a specific task. NOTE: Notes are found throughout the training manual and are preceded by the word NOTE in bold. Notes are used to provide information which, while not critical, may be valuable to an end user. BEYOND THE BASICS: Advanced information found throughout the training manual is preceded by the words BEYOND THE BASICS in bold. Beyond the Basics provides additional detail, outside of standard functionality, that may help you to more optimally use the application. EXAMPLE: Examples are found throughout the training manual and are preceded by the word EXAMPLE in bold. Examples bring to light business scenarios that may better explain how an application can be used to address a business problem.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
0-3
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Student Objectives What do you hope to learn by participating in this course? List three main objectives below. 1.
2.
3.
0-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 1: Client/Server Integrated Development Environment (C/SIDE)
CHAPTER 1: CLIENT/SERVER INTEGRATED DEVELOPMENT ENVIRONMENT (C/SIDE) Objectives The objectives are: •
Discuss Basic Objects in Microsoft Dynamics® NAV 2009.
•
Describe fundamental aspects of C/SIDE development, including the UI, application objects, C/SIDE concepts, and the types of databases.
•
Discuss the database structure.
•
Describes some integration tools and advanced development concepts.
Introduction The starting point to learn developing solutions in Microsoft Dynamics NAV 2009 is to understand the basic objects available in Microsoft Dynamics NAV, understand the Client / Server Integrated Development Environment (C/SIDE, which is the development environment for Microsoft Dynamics NAV) fundamentals and understand the concepts of the database structure.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
1-1
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Basic Objects in Microsoft Dynamics NAV There are eight basic objects available in Microsoft Dynamics NAV 2009, they are as follows: Object
Description
Tables
Used to describe how data is stored in the database and how it is retrieved. Understanding tables is the key to using all of the other objects in C/SIDE.
Forms
Used to display data to users in the Microsoft Dynamics NAV Classic client. Forms allow users to add records to a table, and to view and modify records.
Pages
Used to display data to users in the Microsoft Dynamics NAV RoleTailored client. Pages allow users to add records to a table, and to view and modify records.
Reports
Used to summarize and print detailed information by using filters and sorting, which are selected by the users.
Dataports
Used to export or import table data in text format. Not supported in the RoleTailored client.
XMLports
Used to export or import table data in XML format. In the RoleTailored client, XMLports replace Dataports as a means to export and import data, even in text format.
Codeunits
Used to organize and group code which is written by the developers.
MenuSuites
Used to contain menus that are displayed in the Navigation Pane in the Classic client and the Departments page in the RoleTailored client.
Is Microsoft Dynamics NAV Object Oriented? Microsoft Dynamics NAV is not object-oriented but object-based. This is an important distinction. In an object-oriented language or environment, developers can create new types of objects based on the ones that are already in the system. In C/SIDE, developers have eight types of application objects and that is all. Developers can create and use Tables, Forms, Pages, Reports, Dataports, XMLports, Codeunits, and MenuSuites, but nothing else. Limiting developers to use these eight objects makes their work faster and more efficient. The biggest benefit from this limitation is stability. It is fairly difficult to create a severe bug in C/SIDE.
1-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 1: Client/Server Integrated Development Environment (C/SIDE)
C/SIDE Fundamentals A C/SIDE application is composed of the eight types of application objects, which are described in the previous lesson. Each application object is created using a specific designer. For example, tables are created with the Table Designer, pages are created with the Page Designer, and so on.
FIGURE 1.1 THE CLASSIC CLIENT WITH TABLE DESIGNER OPENED
The application objects which are created by using designers are all based on several general concepts. A fundamental knowledge of these concepts speeds up the C/SIDE application development process.
C/SIDE User Interface C/SIDE is accessed from the Classic client. The C/SIDE user interface is composed of the following: •
Object Designer, which contains designers for each of the eight object types.
•
Navigation Pane Designer, which is used to arrange MenuSuites on the Navigation Pane.
•
Various Tools and Editors, including a Toolbox for adding controls to forms, a C/AL Editor for editing code, a Properties window, a Debugger, and other tools and editors.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
1-3
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The user interface gives access to a number of tools and functions. Some parts of the user interface also provide information about the current state of the system. To...
Use the...
Get information about the name and path of the current database
Title Bar
Access functions on drop-down menus
Menu Bar
Access the frequently used functions
Toolbar
Work with the application design tools
Work Area
View basic status information about the system (such as the current date and user ID)
Status Bar
Depending on the task the users are working on, the system automatically changes the menus and icons in the Menu Bar and the Toolbar.
Design Application Objects Any application designed in C/SIDE is based on the eight different types of application objects available through the Object Designer. Tables are the fundamental objects that store the actual data. Other application objects are needed to insert, modify, delete, or view data from tables. A form or a page is typically used to enter or retrieve data from the database and a report is used to print data. NOTE: All application objects are identified by an ID number. There are, however, restrictions about which numbers can be used when creating application objects. In the Object Designer, select the type of application object to work on. The following can be done from the Object Designer: •
1-4
Run an application object (except for page, XMLport and MenuSuite objects.)
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 1: Client/Server Integrated Development Environment (C/SIDE) •
Open the application object designer to modify an existing object.
•
Create a new application object.
FIGURE 1.2 THE OBJECT DESIGNER
The following table lists the tools that are accessed from the Object Designer and when to use them. Use the…
When working on…
Table Designer
Tables
Form Designer
Forms
Page Designer
Pages
Report Designer
Reports
Dataport Designer
Dataports
XMLport Designer
XMLports
C/AL Editor
Codeunits
Navigation Pane Designer
MenuSuites
There is a specific designer for each type of application object. When creating or modifying an application, developers can work on any number of application objects at the same time, and each application object is shown in its own designer. For example, if a developer works on three pages at the same time, each page is displayed in its own Page Designer. The Navigation Pane Designer is the only designer that cannot have more than one instance running at a time.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
1-5
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 General C/SIDE Concepts The eight application object types are based on some general concepts. Some of these concepts are restricted to one type of application object whereas others apply to several types. The following table summarizes how the application objects are related to these general concepts and explains for what each type of application object is used.
1-6
Application Object Type
Uses
Concepts
Table
A table is used for storing the actual data. Typically a business application has a Customer table that stores information such as name, address, phone number, and contact person for each customer.
Properties, Fields, Field Groups, Keys, C/AL, Triggers
Form
A form is used to access the information contained in tables in the Classic client. Forms are used when users enter new information and when they view existing information.
Properties, C/AL, Controls, Triggers
Page
A page is used to access the information contained in tables in the RoleTailored client. Pages are used when users enter new information and when they view existing information.
Properties, C/AL, Controls, Triggers
Report
A report is used to present data that contains summary information. For example, use a report to print a list of customers.
Properties, C/AL, DataItems, Sections, Controls, Triggers, RequestForm, RequestPage, Client Report Definition ( RDLC) report layout
Dataport
A dataport is used to import and export information to and from other programs in a text format (for example, a commaseparated text file). Dataports are used only in the Classic client.
Properties, C/AL, DataItems, RequestForm, Triggers
XMLport
An XMLport is used to import and export information to and from other programs in an XML format. XMLports simplify and streamline the process of exchanging data in XML documents. In the RoleTailored client, XMLports are also used to import and export
Properties, C/AL, NodeNames, NodeTypes, XMLport Events, RequestPage
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 1: Client/Server Integrated Development Environment (C/SIDE) information in a text format. Codeunit
A codeunit contains user-defined functions written in C/AL code. These functions can be used from the other objects in the application. This minimizes the size of the application because the same code can be reused.
C/AL, Triggers
MenuSuite
A MenuSuite contains the menus displayed in the Navigation Pane and in the Departments Page.
Menu Node, Menu Group, Menu Item
Terminologies The following shows descriptions of several terms in the third column: Properties: Properties control the appearance and behavior of application objects and all sub-objects. Properties are used to control the appearance of data, specify default values, specify colors, and define relationships. C/AL: C/AL is the language used for writing functions in C/SIDE. In the previous table, C/AL refers to functions written in this language. Triggers: When specific things happen to the application objects, the system automatically activates a trigger. Inside a trigger, developers can add C/AL code if they want to modify the default behavior of the application object or extend its functionality. Fields: A field is the smallest unit of information in the database. A field typically stores information such as a name or a number. Keys: A key defines the order in which data is stored in the tables. Speed up searches in tables by defining several keys to sort information in different ways. Controls: Controls are objects on a form or report that display data, perform actions or decorate the form. Typical examples are command buttons and text labels. Request Form: A request form is a form used in a report or a dataport. Before a report or a dataport is run, a request form appears to let the user specify filters and options for the report or the dataport. Request Page: A request page is the request form equivalent in the RoleTailored client.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
1-7
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Data Items: A data item is a building block used for defining a model of data when creating a report or a dataport. By using a hierarchy of data items, developers define which data to include in the report. A data item represents a table and when a report is run, the system cycles through the records in the associated table. In a report, a data item can have one or more sections. Sections: A section is a substructure of a data item. A section is where controls are placed to display information. Generally, sections are used to define the body, header, and footer in the report. NodeName: NodeNames are used to specify the name of a node in an XML document. The name specified is inserted in the NodeName field of the XMLport Designer of the element or attribute in question. NodeTypes: This property is used to specify whether an XML object is an element or an attribute. Menu Node: A Menu Node can be either a Menu Group or a Menu Item. Menu Group: A Menu Group is a collection of Menu Nodes. Menu Item: A Menu Item is the lowest level of the menu tree. It is associated with a specific application object.
The Physical and the Logical Database Typical database users are not concerned with where each piece of data is stored on the hard disk or what its size is; they just want to be sure that when they refer to a name, the correct value is returned. This is why the C/SIDE database system provides a conceptual representation of data that does not include too many details about how the data is stored. An abstract data model is used for this conceptual representation. This data model uses logical concepts (such as objects, their properties, and their relations) that are easier to understand. Therefore, it is helpful to distinguish between the logical and the physical database. When speaking about the logical database, only be concerned with the structure of the data and the relationships between different bits of information. That is, users do not deal with how these structures and relations are implemented. The physical database deals with how the structures in the logical database and the search paths between them are implemented. When the term database is used, it generally refers to the logical database unless otherwise noted.
1-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 1: Client/Server Integrated Development Environment (C/SIDE) What is visible to the user as a coherent set of information in the C/SIDE database system can be stored in several physical disk files, but this is transparent to the user. The following figure illustrates how one logical database can be physically stored on three hard disks but still comprise a single (logical) database.
FIGURE 1.3 ILLUSTRATION OF LOGICAL VERSUS PHYSICAL DATABASE
Access to the data is made possible by a well-defined logical organization composed of: •
Fields
•
Records
•
Tables
•
Companies
Fields A field is the smallest logical structure used in the C/SIDE database. A field is used to hold a single bit of information, such as a name or an amount. Any particular field can hold information of only one specific type. Fields are assembled into a structure called a record. On its own, a field is not useful as it can hold only a limited amount of information. Having these small bits of information assembled into records results in a much more flexible "information-holder" that is also better organized because it groups fields that belong together.
Records A record is a logical structure assembled from an arbitrary number of fields; it is used to store a single entry in the database. The fields in a record are used to store information about important properties of the entry. Records are organized in tables.
Tables A table can be thought of as an N times M matrix. Each of the N rows describes a record and each of the M columns describes a field in the record. Tables are organized in companies.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
1-9
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Companies A company is the largest logical structure used in a C/SIDE database. A company may be considered as a sub-database; its primary use is to separate and group large portions of data in a database. A company can contain private tables and tables that are shared with other companies.
FIGURE 1.4 RELATIONSHIP OF LOGICAL DATABASE STRUCTURE
Integration Tools Microsoft Dynamics NAV 2009 provides several integration tools that can be used inside or outside of Microsoft Dynamics NAV to integrate to other applications.
Web Services Web services are a standardized way for independent software systems to communicate with one another over standard Internet protocols. Web services architecture is designed for dynamic program-to-program interaction. Microsoft Dynamics NAV 2009 supports Web services, which makes it easy to integrate Microsoft Dynamics NAV with other systems. This is possible with the introduction of Microsoft Dynamics NAV Server. There are several types of Web service in Microsoft Dynamics NAV 2009:
1-10
•
The simplest Web service type is developed by using the page object. By using the page object, Microsoft Dynamics NAV constructs a default Web service that has a fixed set of methods. Generally, it corresponds to general data access, such as get and set individual values or retrieves and updates lists of values.
•
Another Web service type involves including codeunits and the functions from those codeunits in the Web service.
•
The last type of Web service includes the ability to pass complex data types by using an XMLport object as a parameter in a codeunit function.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 1: Client/Server Integrated Development Environment (C/SIDE) ODBC Open DataBase Connectivity, or ODBC, is a standard database access method developed by Microsoft. The goal of ODBC is to make it possible to access any data from any application regardless of which database management system (DBMS) is handling the data. ODBC manages the access of data by inserting a middle layer called a database driver between an application and the DBMS. The purpose of the middle layer is to translate the application's data queries into commands that the DBMS understands. For this to work, both the application and the DBMS must be ODBC-compliant; that is, the application must be capable of issuing ODBC commands and the DBMS must be capable of responding to them.
C/FRONT C/FRONT is an application programming interface that can be used to access a Microsoft Dynamics NAV database. C/FRONT facilitates high-level interaction with the Microsoft Dynamics NAV database and enables developers to manipulate any Microsoft Dynamics NAV database. The central component of C/FRONT is a library of C functions. These functions provide access to every aspect of data storage and maintenance, and enable the integration of both standard and custom applications with a Microsoft Dynamics NAV database. C/FRONT comes as a DLL for direct linkage with a program and also as an OCX that a program can use.
OCX OLE Custom control, or OCX, is an independent program module that can be accessed by other programs in a Microsoft® Windows® environment. OCX controls end with an .ocx extension. OCX controls represent Microsoft's second generation of control architecture, the first being VBX controls written in Visual Basic. Both VBX and OCX controls have now been superseded by Microsoft ActiveX® controls. However, ActiveX is backward compatible with OCX controls which means that ActiveX containers such as Microsoft Internet Explorer can execute OCX components. There is a vast array of commercially available OCXs that perform a variety of tasks and developers can produce their own. They can use tools such as Microsoft Visual C++ or Visual Basic to create OCXs that can be called by Microsoft Dynamics NAV.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
1-11
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Automation OLE Automation is the name for the ability of one program to expose any or all of its capability for another program to use. The program that provides the functionality being called is the Automation server and the program that uses the functionality of the Automation server is the Automation controller (or client). C/SIDE supports Automation servers by acting as an Automation controller and by using OCXs (custom controls). However, Microsoft Dynamics NAV is not an Automation server. The most common use of Automation within Microsoft Dynamics NAV is to control applications such as Microsoft® Word®, Microsoft® Excel®, and Microsoft® Outlook®. Both OCX and Automation are part of Microsoft COM technologies. Developers who plan to use existing COM objects from C/SIDE, such as controls or Automation servers, do not need a complete understanding of COM. Although, understanding how to use objects and how to access the COM object may be necessary. Using the functionality provided by a COM object is no different than using any C/AL function.
Summary A thorough understanding of C/SIDE enables developers to streamline their development processes by learning how to develop customizations and integrations for the Microsoft Dynamics NAV system. This training material explains how to navigate within the development environment, how to create and use the basic objects, and how to implement best practices for ensuring smooth software upgrades in the future. Additional resources (Microsoft Dynamics NAV 2009 Developer and IT Pro Documentation) can be found in the following locations:
1-12
Location
Address
Download Center
http://go.microsoft.com/fwlink/?LinkID=126282
MSDN
http://go.microsoft.com/fwlink/?LinkID=126283
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 1: Client/Server Integrated Development Environment (C/SIDE)
Quick Interaction: Lessons Learned Take a moment and write down three Key Points you have learned from this chapter 1.
2.
3.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
1-13
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
1-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables
CHAPTER 2: TABLES Objectives The objectives are: •
Understand the concepts of tables and table components.
•
Examine the concept behind primary and secondary keys, and how to set them.
•
Create a simple table with primary and secondary keys and add data to the table.
•
Understand the concept of table relation.
•
Set table relations with a filter and condition.
•
Describe the special table fields.
•
Use special table fields to improve table features.
•
Provide an overview of different table types and their characteristics.
Introduction Tables are the most fundamental objects in Microsoft Dynamics® NAV objects. They store records that are collected through forms and pages, for example customers, sales, and inventories. These records are then presented to users through forms, pages and reports.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-1
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Table Fundamentals Records in Microsoft Dynamics NAV databases are stored in tables. A table can be visualized as a two-dimensional matrix, comprising of columns and rows. Each row is a single record, and each column is a field in that record. A table consists of table data and the table description. The table data contains the actual records and their fields. The table description specifies the layout and properties of the table and the fields. The table description is not directly visible to the user. When a developer creates a table, he/she assigns the table name, ID number and fields. This establishes the table description. Field characteristics, such as field name, ID number, data type, and initial value, together with the primary and secondary keys (used to sequence data), are also part of the table description. The table description contains properties, triggers, fields, and keys. The following shows components of the table description and how they are related:
FIGURE 2.1 TABLE COMPONENTS AND THEIR RELATION
Properties The table description contains some properties that are related to the table and properties which are related to the fields or the keys in the table. When a table is created, C/SIDE automatically defines several default values for table properties. Depending on the purpose of the table and how it is related to other application objects, these default values may have to be changed.
2-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables Some standard table properties such as ID, Name and Caption, differentiate one table from another. Permissions property establishes specific permission for users. Other examples of table properties include LookupFormID and DrillDownFormID which specify which form and page ID are used to look up and drill-down information in the table. Table properties can be viewed and modified from the Properties window which is accessed from the Table Designer. The following steps show how to open the Properties window for the Customer table and examine several table properties. In Microsoft Dynamics NAV Classic client: 1. On the Tools menu, click Object Designer. 2. Click the Table button to open the Table list. 3. Select table 18, Customer, and then click the Design button to design the Customer table.
FIGURE 2.2 THE CUSTOMER TABLE IN TABLE DESIGNER
4. Scroll down and put the cursor on an empty line at the bottom of the Table Designer.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-3
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 5. Click View, Properties, or click the Properties button on the Toolbar. The Table - Properties window opens and shows the properties for the table. Here developers can view and modify properties for the Customer table.
FIGURE 2.3 THE CUSTOMER TABLE AND ITS PROPERTIES
6. Locate the DataPerCompany property. The value of this property is
. The <> sign shows that Yes is a default value assigned to this property when the table is created and it has not been changed. NOTE: To modify the value of a property, select or type a new value in the Value column, and update the property by either pressing ENTER or moving the cursor away from the field. 7. Locate the LookupFormID property. The value of this property is Customer List. This property specifies that the Customer List form and the Customer List page are used to look up values in the Customer table. 8. Click the DrillDownFormID property, and press F1. The C/SIDE Reference Guide opens and shows a Help topic for the DrillDownFormID property.
Triggers Triggers are predefined functions that are executed when certain events occur. The bodies of these functions are first empty and must be defined by the developer. Defining C/AL code in triggers lets developers change the default behavior of the system. Triggers in a table can be divided into two categories: •
Table triggers
•
Field triggers
Examples of table triggers include OnInsert which contains statements that are executed when a new record is inserted into the table, and OnModify which contains statements that are executed when a record in the table is modified.
2-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables Triggers in a table are edited in the C/AL Editor which is accessed from the Table Designer.
Fields At the very least, a table must have one field. Fields define the actual information kept in a table. Each field has its own properties and triggers. Each field has an appropriate data type. Each data type is designed to hold a specific kind of information, such as text, numbers, dates and so on. The following list shows several data types available in the Microsoft Dynamics NAV database system. Data Type
Description
BigInteger
This data type is a 64-bit integer. It is used to store large whole numbers.
Binary
This data type contains binary data. The binary data is stored in the record. The corresponding SQL data type is VARBINARY. The Binary data type is removed from Microsoft Dynamics NAV 2009.
BLOB
A Binary Large Object (BLOB) is used to store bitmaps and memos. The BLOB is not stored in the record, but in the BLOB area of the table. The corresponding SQL data type is IMAGE.
Boolean
This data type indicates the values TRUE or FALSE. When formatted, a boolean field is displayed as Yes or No. The corresponding SQL data type is TINYINT.
Code
This data type denotes a special type of alphanumeric string which is right-justified if the contents are numbers only. If letters or blanks occur among the numbers, the contents are left-justified. All letters are converted to uppercase upon entry. The field must be defined to be between 1 and 250 characters. In the SQL Server Option for Microsoft Dynamics NAV, code fields work in a different way. The SQL Data Type property can be used to indicate whether code fields can contain integers or text strings. The corresponding SQL data type is VARCHAR.
Date
This data type indicates a date value in the range from January 3, 1 to December 31, 9999. An undefined date is expressed as 0D. 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 corresponding SQL data type is DATETIME.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-5
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
2-6
Data Type
Description
DateFormula
This data type is used to contain a date formula that has the same capabilities as an ordinary input string for the CALCDATE Function (DATE). The following shows examples of DateFormula: • 30D (30 days) •
CM+1M (current month plus one month)
•
D15 (the 15th of each month)
DateTime
This 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 the client computer. DateTimes must always be entered as local time. When a DateTime is entered as local time, it is converted to UTC by using the current settings for the time zone and daylight saving time. The DateTime data type does not support closing dates.
Decimal
This data type denotes a decimal number from 999,999,999,999,999.99 to +999,999,999,999,999.99. In Microsoft Dynamics NAV 2009, the Decimal data type is mapped to the Microsoft .NET 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.
Duration
This data type represents the difference between two points in time, in milliseconds. This value can be negative.
GUID
A Globally unique identifier (GUID) is used for the global identification of objects, programs, records, and so on.
Integer
This data type indicates a whole number between 2,147,483,647 and 2,147,483,647. The corresponding SQL data type is INTEGER.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables
Data Type
Description
Option
This data type indicates an option value which is an integer in the range -2,147,483,647 and 2,147,483,647. An option field is defined by using an option string. This is a commaseparated 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.
RecordID
This data type contains the table number and the primary key of a table.
TableFilter
This data type is used to apply a filter to another table. This can only be used to apply security filters from the Permission table.
Text
This data type denotes an alphanumeric string. The string must be defined to be between 1 and 1024 characters. An empty text string has the length of zero. The corresponding SQL data type is VARCHAR.
Time
This data type indicates any time in the range 00:00:00 to 23:59:59.999. An undefined time is expressed as 0T. The corresponding SQL data type is DATETIME.
Field Properties Some field properties are used to identify the field among other fields, such as ID, Name and Caption. Other field properties are used to establish data type and set the fields behavior, such as DataType, Enabled, and NotBlank property. The following steps show how to open the Properties window for one of the fields (the No. field) in the Customer table. 1. Design table 18, Customer, from the Object Designer. 2. Click the No. field, and then click View, Properties, or click the Properties button on the Toolbar.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-7
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 3. The No. – Properties window opens and shows the properties for the field. Here developers can view and modify properties for the No. field.
FIGURE 2.4 THE NO. FIELD PROPERTIES
4. Locate the NotBlank property. The value of this property is . This property prevents leaving this field blank. It is used on most primary key fields.
Field Triggers Each field has the following triggers: Fields Trigger Name
When it is executed
OnValidate
Data is entered in a field or when .VALIDATE is executed in C/AL code.
OnLookup
Lookup (or F6) is activated.
Table and field triggers can be viewed and modified from the C/AL Editor which is accessed from the Table Designer. The following steps show how to view and modify the fields and table triggers of the Customer table. 1. Design table 18, Customer, from the Object Designer.
2-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables 2. Click View, C/AL Code, or click the C/AL Code button on the Toolbar. The C/AL Editor opens and shows all the triggers available to the Customer table and its fields. From the top, the table triggers are shown, followed by the field triggers and the function triggers at the bottom.
FIGURE 2.5 THE CUSTOMER TABLE TRIGGERS
Keys The 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. Keys are used to define the sorting method of records in a table, although this is not the only use of keys. The following steps show how to view the Customer table keys. 1. Design table 18, Customer, from the Object Designer. 2. Click View, Keys. The Keys window opens. It shows the keys defined for the Customer table.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-9
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The keys associated with a table, also have properties that describe their behavior. The following steps show how to open the Properties window for the Customer table key. 1. In the Keys window, click any of the keys. 2. Click View, Properties, or click the Properties button on the Toolbar.
FIGURE 2.6 THE CUSTOMER TABLE KEY AND ITS PROPERTIES
Primary and Secondary Keys There are two kinds of keys, primary key and secondary key. Up to 40 keys can be associated to a table and the first on the list is the primary key. All other keys are secondary keys, and are optional.
Primary Keys The database keeps track of each record by using the record's primary key. Consider the primary key of a record as the name of the record. The name of each record in a particular table for a particular company must be unique. This name is how the database management system (DBMS) retrieves and updates records. The primary key is composed of up to 20 fields in a record. The combination of values in fields in the primary key makes it possible for the DBMS to perform a unique identification of each record. The primary key determines the logical order in which records are stored, regardless of their physical placement on a disk.
2-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables Logically, the records are stored sequentially in ascending order, sorted according to the primary key. Before adding a new record to a table, the DBMS checks that the information in primary key fields in the record is unique and only then inserts the record into its correct logical position. Because the records are sorted as they are entered, the database is always structurally correct. This enables fast data manipulation and retrieval. The primary key is always active. The DBMS 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. It is not the value in each field in the primary key that must be unique, but the combination of values in all the fields consisting of the primary key. The Microsoft Dynamics NAV database system does not support unkeyed tables.
Secondary Keys Secondary keys are used to view records in an order different from the one in which they are sorted according to the primary key fields. The number of fields in the primary key together with all the fields in each secondary key must not exceed 20. Each secondary key can contain up to 20 unique fields. However, these 20 unique fields must also include all the fields from the primary key. The primary key fields that are not mentioned specifically in the secondary key are added to the end of the key by the DBMS. This means that if the primary key includes four distinct fields, then a secondary key can include these four fields and at most 16 other fields. Correspondingly, if the primary key consists of 20 distinct fields, then any secondary key must consist only of combinations of these fields. When a secondary key is defined and selected as active, the system automatically maintains an index reflecting the sorting order defined by the key. Several secondary keys may be active at the same time. A secondary key can be changed into an inactive key. This means that the DBMS does not use time during updates to maintain its index. Moreover, an inactive key does not occupy database space. Inactive keys can be reactivated. This process may consume some time, depending on the size of the table because the DBMS has to scan the table to rebuild the index. The fields consisting of the secondary keys are not guaranteed to contain unique data. The DBMS does not reject records with duplicate data in secondary key fields. If two or more records contain identical information in the secondary key, the DBMS uses the primary key for the table to solve this conflict.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-11
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Demonstration: Create a Simple Table The following demonstration shows how to create a simple table, set the primary key, create secondary keys and add data to the table. The purpose of the table is to record information of Vehicles. This includes the model, serial number, transmission type and date of manufacturing.
Create a New Table The following steps show how to create a new table. 1. In the Object Designer's Table list, click the New button. The Table Designer opens. 2. Type the following in the Table Designer: Field No.
Field Name
Data Type
Length
10
Model
Code
20
20
Serial No.
Integer
30
Description
Text
40
Transmission
Option
50
List Price
Decimal
60
Date of Manufacturing
Date
FIGURE 2.7 THE NEW TABLE
2-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
50
Chapter 2: Tables 3. Open the Properties window for the Transmission field, and set the following property: o OptionString: Automatic,4-Speed,5-Speed
FIGURE 2.8 THE TRANSMISSION FIELD PROPERTIES
NOTE: The options set here are displayed in a drop-down list in the table. If a space is added between the options, or any symbols, such as the greater-than and less-than symbols are added in the option string, those symbols are displayed in the drop-down list. 4. Close the Properties window. 5. Compile and save the table by clicking File, Save As. The Save As dialog box opens. 6. Type 90000 in the ID and Vehicle in the Name, ensure that the Compiled check box is selected, and then click OK. This compiles and saves the table.
FIGURE 2.9 THE SAVE AS WINDOW
7. Close the table by closing the Table Designer.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-13
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Set the Primary Key The Microsoft Dynamics NAV database system does not allow for unkeyed tables. When a new table is created and saved without a key, the first field is defaulted as the first key. Therefore, it defaults and becomes the primary key. With this configuration, there cannot be any two records with the same Model. This is not a good choice for the primary key. The following steps show how to set a correct primary key. 1. Design table 90000, Vehicle, from the Object Designer. 2. Click View, Keys, to open the Keys window. Notice that Model is defaulted as the primary key. NOTE: With the current configuration, there can be only one unique model of vehicle in the Vehicle table. 3. Replace the current primary key with the following: o Key: Model,Serial No.
FIGURE 2.10 THE VEHICLE TABLE WITH THE PRIMARY KEY
NOTE: Instead of typing the value directly to the Key field, click the Assist-Edit button on the Key field to open the Field List window. Add the fields to be created as a key in the Field List window and then click OK. 4. Close the Keys window. 5. Compile, save and close the table.
NOTE: This enables multiple models of the vehicle in the Vehicle table, as long as they have different serial numbers.
2-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables Add Data to the Table Generally, data is added to a table through forms or pages. The following steps show how to add data manually directly to the table. 1. In the Object Designer's Table list, select table 90000, Vehicle, and then click the Run button. The Vehicle table opens in a tabular form. This form is auto-created by the Microsoft Dynamics NAV Classic client. Notice that the table is currently empty. 2. Type the following in the Vehicle table: Model
Serial No.
Description
Transmission
List Price
Date of Mfg
FORD
5000
Red, Mustang
Automatic
18,000
01/15/10
FORD
2000
Blue, F150
5-Speed
26,000
01/15/10
TOYOTA
1000
Gold, Camry
Automatic
23,000
02/01/11
FORD
3000
Black, Explorer
Automatic
30,000
01/15/10
TOYOTA
3000
Black, Tacoma
5-Speed
20,000
12/15/09
TOYOTA
2000
Gray, Camry
Automatic
22,000
01/15/10
NOTE: Every new record is sorted in the order of the primary key fields: alphabetically by Model, and then numerically by Serial No.
FIGURE 2.11 THE VEHICLE TABLE WITH DATA
3. Close the table.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-15
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Create a Secondary Key For some users, the date of manufacturing and the transmission are more important than the model and serial number. Those users may want to change the order of the records on the form to be sorted by Date of Manufacturing and Transmission. To do this, a secondary key must be created. The following steps show how to create a secondary key. 1. Design table 90000, Vehicle, from the Object Designer. 2. Click View, Keys. The Vehicle - Keys window opens. 3. Click the Assist-Edit button on the Key field of the first blank line (second line.) The Field List window opens. 4. Type the following in the Field List window: Field Date of Manufacturing Transmission NOTE: Instead of typing the field name in the Field List window, use the Lookup button to select the fields from the Vehicle table. The order of these fields is important. In the order described, the records are sorted by date of manufacturing first, and then by transmission, if the dates are the same. 5. Click OK to close the Field List window. The secondary key of Date of Manufacturing,Transmission is created in the Vehicle - Keys window.
FIGURE 2.12 THE VEHICLE TABLE WITH A SECONDARY KEY
6. Close the Vehicle - Keys window. 7. Compile, save and close the table.
2-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables Use the Secondary Key The following steps show how to use the secondary key. 1. Run table 90000, Vehicle, from the Object Designer. The Vehicle table opens. It contains the data previously entered. The records are sorted in the primary key order. 2. Click the Sort button on the Toolbar. The Sort window opens. 3. Select the Date of Manufacturing,Transmission key, and then click OK. The records immediately re-sort themselves by their Date of Manufacturing and Transmission.
FIGURE 2.13 THE VEHICLE TABLE SORTED BY THE SECONDARY KEY
Table Relationships There are three kinds 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 a database contains tables with related data, developers can define a relationship between them. Developers relate tables by specifying one or more fields that contain the same value in related records. These matching fields frequently have the same name in each table. The fields can use relationships to do the following: •
Validate data entries.
•
Perform Lookup in other tables.
•
Automatically propagate changes from one table to other tables.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-17
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Table Relation Property Table relations are defined by using the TableRelation property. This property lets developers define both simple and advanced table relations. A simple table relation consists of only a table ID and an optional field ID, whereas advanced table relations are typically prefixed with a conditional statement and include filters. When developers create a table relation, they specify which field to look up in another table. If the optional field ID is left blank, the first field in the primary key is set to relate to. To make a relation to the second or third field in a primary key, the field ID must be specified. NOTE: The field ID specified in the TableRelation property must be in the primary key of the table specified by the table ID in the property. If the field specified is not the first field in the primary key, the other fields that are listed before it in the key must be filtered to one value. This is not a true requirement of the system, but makes sense in a real application to avoid user confusion. An example of a table relation is shown in the Sales Header table. The Sales Header table has a Salesperson Code field that relates to the Salesperson/Purchaser table. When the users look up the Salesperson Code field, the Lookup form of the Salesperson/Purchaser table opens.
FIGURE 2.14 TABLE RELATION IN SALES ORDER'S SALESPERSON CODE
2-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables Filter Table Relation Advanced table relations may involve filtering within the table relation. An example of filtering in a table relation is shown in the Sales Line table. The Sales Line table has a Location Code field that relates to the Location table.
FIGURE 2.15 FILTERED TABLE RELATION IN SALES ORDER LINE'S LOCATION CODE
The Location table holds all the records for location. This includes those used as In-Transit locations. When users select a location in the Sales Line, for example in the Sales Order, they must not be able to select a location that is used as InTransit locations. Therefore, the table relation must be filtered to show only those locations that are not used as In-Transit locations.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-19
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Conditional Table Relation Advanced table relations may also involve a conditional statement within the table relation. An example of a conditional table relation is also shown in the Sales Line table. The table Sales Line has a No. field that relates to six different tables, depending on the condition of the Type field in the Sales Line.
FIGURE 2.16 CONDITIONAL TABLE RELATION IN SALES ORDER LINE'S NO.
If the users select Item as the Type in the Sales Line, for example in the Sales Order, then the No. field relates to the Item table. When the users look up the No. field, the Lookup form of the Item table opens. Whereas if the users select Resource as the Type, the No. field relates to the Resource table, and when the users look up the No. field, the Lookup form of the Resource table opens.
2-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables
Demonstration: Table Relations The following demonstration shows how to create a table to record sales transactions and create fields that have a table relation to other tables.
Create a Table with Table Relations The following steps show how to create a table with table relations. 1. In the Object Designer's Table list, click the New button. The Table Designer opens. 2. Type the following in the Table Designer: Field No.
Field Name
Data Type
10
Line No.
Integer
20
Salesperson Code
Code
30
Type
Option
40
No.
Code
50
Amount
Decimal
Length
10 20
Now, the table looks as follows:
FIGURE 2.17 THE TABLE DESIGNER
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-21
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 3. Open the Properties window for the Type field, and set the following property: o OptionString: G/L Account,Item,Resource
FIGURE 2.18 THE TYPE - PROPERTIES WINDOW
4. Close the Properties window. 5. Compile and save the table with the ID 90001 and the name Sales Transactions.
Set a Table Relation with a Filter The Sales Transactions table must record the salesperson of a particular transaction. The Salesperson/Purchaser table holds the record of all salespersons and purchasers in CRONUS International Ltd. The following steps show how to set a table relation for the Salesperson Code field in the Sales Transactions table to relate to the Salesperson/Purchaser table. 1. Open the Properties window for the Salesperson Code field. 2. Click the Assist-Edit button on the TableRelation property. The Table Relation window opens. 3. Click the Lookup button on the Table column. The Table List window opens.
2-22
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables 4. Select Salesperson/Purchaser from the Table List window and then click OK.
FIGURE 2.19 THE TABLE LIST WINDOW
NOTE: Instead of selecting the table, typing the table ID or the table name directly in the Table column also achieves the same result. 5. Click the Assist-Edit button on the Table Filter column. The Table Filter window opens. In this window, specify filters on as many fields in the related table as needed. A filter can be added to the list in three ways: o By a constant value. o By using a filter expression. o By a field in the current table. In this case, use a filter expression. 6. Type the following in the Table Filter window: Field
Type
Value
Commission %
Filter
>0
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-23
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Now, the Table Filter window looks as follows:
FIGURE 2.20 THE TABLE FILTER WINDOW
NOTE: Selecting Filter in the Type column enables to filter instances where Commission % is greater than zero. For this scenario, only the Filter option can be used. Const and Field options locate exact matches only, by using the equal to operator. 7. Click OK to close the Table Filter window. Notice that the Table Filter column in the Table Relation window is set to Commission %=FILTER(>0).
FIGURE 2.21 THE TABLE RELATION WINDOW
2-24
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables 8. Click OK to close the Table Relation window. Notice that the TableRelation property is set to Salesperson/Purchaser WHERE (Commission %=FILTER(>0)).
FIGURE 2.22 THE SALESPERSON CODE - PROPERTIES WINDOW
9. Close the Salesperson Code - Properties window. 10. Compile and save the table.
Set a Conditional Table Relation The Sales Transactions table must be able to record sales transactions of Items, Resources or G/L Accounts. The Type field is used to differentiate this. Depending on the Type selected, the No. field must relate to different tables, the Item table, the Resource table, or the G/L Account table. The following steps show how to set a conditional table relation on the No. field. 1. Open the Properties window for the No. field. 2. Click the Assist-Edit button on the TableRelation property. The TableRelation window opens. 3. Type the following in the Table Relation window: Condition
Table
Type=CONST(G/L Account)
G/L Account
Type=CONST(Item)
Item
Type=CONST(Resource)
Resource
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-25
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Now, the Table Relation window looks as follows:
FIGURE 2.23 THE TABLE RELATION WINDOW
NOTE: In the Table Relation window, instead of typing the value, use the AssistEdit button on the Condition column to fill up each condition and use the Lookup button on the Table column to open the table list and select each table. Scroll quickly through the table list by pressing the first letter of the table name until the intended table is located. 4. Click OK to close the Table Relation window. Notice that the TableRelation property is set to IF (Type=CONST(G/L Account)) "G/L Account" ELSE IF (Type=CONST(Item)) Item ELSE IF (Type=CONST(Resource)) Resource.
FIGURE 2.24 THE NO. - PROPERTIES WINDOW
5. Close the No. - Properties window. 6. Compile, save and close the table.
2-26
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables Test the Table Relation The following steps demonstrate how powerful table relations are. Be aware that the lookup buttons on a field that has a table relation open the default lookup form for the related table. Without a form for the table, the lookup button does not work. In this example, there already is a lookup form defined for the Salesperson/Purchaser table. The following steps show how to test a table relation. 1. Run table 13, Salesperson/Purchaser, from the Object Designer. 2. Go to a blank line and type the following: Code
Name
Commission %
XX
New Salesperson
5
3. Close table 13. 4. Run table 90001, Sales Transactions. 5. Type the following in the Sales Transactions table: Line No. Salesperson Code Type No.
Amount
10000
XX
Item 70000
123.56
20000
JR
Item 70000
234.97
30000
XX
Item 70010
90.99
6. Close table 90001. 7. Run table 13, Salesperson/Purchaser. 8. Click the line added earlier, and then replace the XX in the Code field with YY. Click Yes when a message prompts asking for confirmation. Changing the primary key values of a record in a table changes the name of the record. This is known as renaming a record. Observe the results of renaming a record that has other records related to it by means of a table relation. 9. Close table 13. 10. Run table 90001, Sales Transactions. Notice that all records with Salesperson Code XX automatically changed to YY. 11. Close table 90001.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-27
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Test a Filter and a Conditional Table Relation The following steps show how to test a filter table relation. 1. Run table 90001, Sales Transactions, from the Object Designer. 2. Delete all the current records in the table. The easiest way to delete all records is to click the upper-left gray box of the form which selects all the records, and then press F4. 3. Type 10000 in the Line No. field of the first blank line. 4. Click the Lookup button on the Salesperson Code field to retrieve a value from the Salesperson/Purchaser table. Notice that not all records from the Salesperson/Purchaser table are shown. Only those records that have the Commission % field set to greater than zero are shown. 5. Select JR, John Roberts, and then click OK. NOTE: The value JR is added to the Salesperson Code field. Because the table relation is only set up to the table, and not to any particular field, the lookup returns the value from the first primary key field of the table. The Salesperson/Purchaser table only has one field in the primary key. Therefore, there is no need to specify a field in the table relation. Only primary key fields can be selected in a table relation. The following steps show how to test a conditional table relation. 6. Select Item in the Type field. 7. Click the Lookup button on the No. field. The lookup form of the Item table (the Item List form) opens. 8. Close the Item List window. 9. Select Resource in the Type field. 10. Click the Lookup button on the No. field. Notice that this time, the lookup form of the Resource table (the Resource List) opens. 11. Close the Resource List window, and close the table.
2-28
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables
Special Table Fields In addition to the conventional data fields which hold values, three kinds of specialized fields are available for data retrieval: •
SumIndexFields
•
FlowFields
•
FlowFilter Fields
FlowFields A FlowField is a virtual field that extends the table data. It is not a permanent part of the table data. A Flowfield is a powerful feature of the Microsoft Dynamics NAV database system. It is used to calculate values from another table. The information in the FlowFields exists only at run time. The values in FlowFields are automatically initialized to zero (0). To update a FlowField, developers use the CALCFIELDS function that has the following syntax: .CALCFIELDS
If a FlowField is a direct source expression of a control on a form, the FlowField is automatically calculated when the form is displayed. There are seven kinds of FlowFields: FlowField
Data Type
Description
Sum
Decimal
The sum of a specified set in a column in a table.
Average
Decimal
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.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-29
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Calculation Formulas and the CalcFormula Property A FlowField is always associated with a calculation formula that determines how the value in the FlowField is calculated. The following example shows a possible value for the CalcFormula property: Sum("Cust. Ledger Entry".Amount WHERE (Customer No.=FIELD(No.), Global Dimension 1 Code=FIELD(Department Filter), Global Dimension 2 Code=FIELD(Project Filter), Posting Date=FIELD(Date Filter), Currency Code=FIELD(Currency Filter)))
FlowFilter Users may want to limit calculations so that they include only those values in a column that have some specific properties. For example, the user may want to sum up only the amounts of customer entries that are entered in April. This is possible if the application is designed by using FlowFilter fields for the FlowFields.
SumIndexFields A SumIndexField is a decimal field that can be attached to a key definition. This is the fundamental feature of the Microsoft Dynamics NAV database that constructs the basis for FlowFields. SumIndexFields enable fast calculation of numeric columns in tables, even in tables with thousands of records. This is because SumIndexFields are maintained when the database record is updated. SumIndexFields enable the fast calculation such as sums of columns to be displayed by using FlowFields. For example, in a conventional database system, if a user wants the sum of all the values in the Amount field, the DBMS is forced to access every record and add each value in the Amount field. This is a timeconsuming operation in a database that has thousands of records. With Microsoft Dynamics NAV, as few as two accesses (if the best key is used) are used to sum the amount for these records. This special index structure, a SumIndexField, is associated with a key. Each key can have at most 20 SumIndexFields. During database design, a decimal field can be associated with a key as a SumIndexField. This tells the DBMS to create and maintain a structure that contains the accumulated sum of values in a column. When a new current key is selected, any SumIndexField associated with it becomes available.
2-30
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables Special Table Fields Example The usage of special table fields can be found almost everywhere in the application. For example, in the Customer table. There are several special table fields implemented in the Customer table. One of them is the Balance (LCY) field, which is a FlowField of type Sum. It is not a physical field in the table instead it is derived by calculating the Amount field from the Detailed Cust. Ledger Entry table, filtered by the Customer No., Dimensions Filter and Currency Filter fields. The Dimensions Filter (made of the Global Dimension 1 Filter and the Global Dimension 2 Filter) and the Currency Filter fields are FlowFilter fields in the Customer table, used to filter the calculation of the Balance (LCY) FlowField. However, the SumIndexField Amount is located in the keys of the Detailed Cust. Ledger Entry table. This finishes the implementation of special table fields.
Demonstration: Special Table Fields The following demonstration shows how to create special table fields in the Salesperson/Purchaser table for the Sales Transactions table that is created in the previous demonstration, to ease calculations of sales by salespersons.
Add Records The following steps show how to add records to the Sales Transactions table. 1. Run table 90001, Sales Transactions, from the Object Designer. 2. Delete all the current records in the table. 3. Type the following in the Sales Transactions table: Line No.
Salesperson Code
Type
No.
Amount
10000
JR
Item
70000
300.00
20000
MD
G/L Account
1120
150.00
30000
JR
G/L Account
1140
200.00
40000
MD
Item
70000
100.00
50000
PS
Item
70000
110.00
60000
JR
Item
70010
50.00
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-31
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Line No.
Salesperson Code
Type
No.
Amount
70000
JR
Resource
LIFT
500.00
80000
MD
Resource
LIFT
550.00
90000
PS
Item
70010
75.00
FIGURE 2.25 THE SALES TRANSACTIONS TABLE
4. Close the table.
Create a FlowField The following steps show how to create a FlowField in the Salesperson/Purchaser table. 1. Design table 13, Salesperson/Purchaser, from the Object Designer. 2. Add a new field to the table by typing the following:
2-32
Field No.
Field Name
Data Type
50000
Sales
Decimal
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables Now, the table looks as follows:
FIGURE 2.26 THE SALESPERSON/PURCHASER TABLE
NOTE: The field number must be between 50,000 and 99,999 because the Salesperson/Purchaser table is a base application table (table ID is less than 50,000). Customizations to the base application must be made in this range. The data type must be a decimal because a Sum FlowField calculates a decimal value.
3. Open the Properties window for the Sales field, and set the following property: o FieldClass: FlowField. The CalcFormula property is now available.
FIGURE 2.27 THE SALES - PROPERTIES WINDOW
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-33
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 4. Click the Assist-Edit button on the CalcFormula property. The Calculation Formula window opens. This is the place to set how the FlowField calculates its value. 5. Type the following in the Calculation Formula window: Method
Table
Field
Sum
Sales Transactions
Amount
6. Click the Assist-Edit button on the Table Filter field. The Table Filter window opens. 7. Type the following in the Table Filter window: Field
Type
Value
Salesperson Code
Field
Code
Now, the Table Filter window looks as follows:
FIGURE 2.28 THE TABLE FILTER WINDOW
NOTE: The previous step ensures that the Sales FlowField only sums the Amount from the Sales Transactions table that has the same Salesperson Code as the current Code, in the Salesperson/Purchaser table. 8. Click OK to close the Table Filter window. Notice that the Table Filter field in the Calculation Formula window is set to Salesperson Code=FIELD(Code).
FIGURE 2.29 THE CALCULATION FORMULA WINDOW
2-34
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables 9. Click OK to close the Calculation Formula window. NOTE: Just closing the window does not save the changes. 10. Close the Properties window. 11. Compile, save and close the table.
Create a SumIndexField The Sales FlowField is not yet usable. For the system to calculate the Sales FlowField, a SumIndexField must be created in the Sales Transactions table with a correct key. The Sales FlowField must sum the Amount fields from Sales Transactions table. Therefore, the Amount SumIndexField must be created in the Sales Transaction table. Because the calculation of the Sales FlowField is by Salesperson Code, the Salesperson Code must be a field in the key that the Amount SumIndexField is created in. The order of the fields in the key is not important for this FlowField. The following steps show how to create a secondary key with SumIndexField in the Sales Transaction table. 1. Design table 90001, Sales Transactions, from the Object Designer. 2. Click View, Keys. The Keys window opens. 3. In the Keys window, create a secondary key by typing the following: Enabled
Key
SumIndexFields
Selected
Salesperson Code
Amount
FIGURE 2.30 THE KEYS WINDOW
4. Close the Keys window. 5. Compile, save and close the table.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-35
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Test the FlowField The following steps show how to test the FlowField. 1. Run table 13, Salesperson/Purchaser, from the Object Designer. 2. Go to the last column of the table. Notice the Sales field calculates the value from the Amount field of the Sales Transactions table, by Salesperson Code.
FIGURE 2.31 THE SALESPERSON/PURCHASER TABLE
NOTE: The Drill-down button on the Sales FlowField is not working. This is because there is no drill-down form defined for the Sales Transactions table. 3. Close the table.
Create a FlowFilter A FlowFilter lets users dynamically change the Table Filter part of the FlowField. By creating a FlowFilter, the functionality of the current FlowField can be extended to allow users to change the sum based on the Type field in the Sales Transactions table. This lets users use the FlowField for four sums:
2-36
•
Total for G/L Accounts sold
•
Total for items sold
•
Total for resources sold
•
Total of all sales
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables Because the calculation will be based not only by Salesperson Code, but also Type, the key where the SumIndexField is created must be changed to include Type. The following steps show how to modify the key of interest in the Sales Transactions table. 1. Design table 90001, Sales Transactions, from the Object Designer. 2. Click View, Keys. The Keys window opens. 3. In the Keys window, modify the secondary key to the following: Enabled
Key
SumIndexFields
Selected
Salesperson Code, Type
Amount
FIGURE 2.32 THE KEYS WINDOW
4. Close the Keys window. 5. Compile, save and close the table. Next, create the FlowFilter in the Salesperson/Purchaser table. 1. Design table 13, Salesperson/Purchaser, from the Object Designer. 2. Add a new field to the table by typing the following: Field No.
Field Name
Data Type
50001
Type Filter
Option
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-37
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Now, the table looks as follows:
FIGURE 2.33 THE SALESPERSON/PURCHASER TABLE
3. Open the Properties window for the Type Filter field, and set the following property: o FieldClass: FlowFilter o OptionString: G/L Account,Item,Resource
FIGURE 2.34 THE TYPE FILTER - PROPERTIES WINDOW
4. Close the Properties window. 5. Open the Properties window for the Sales field. 6. Click the Assist-Edit button on the CalcFormula property. The Calculation Formula window opens.
2-38
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables 7. Click the Assist-Edit button on the Table Filter field. The Table Filter window opens. 8. Type the following in the Table Filter window: Field
Type
Value
Type
Field
Type Filter
Now, the Table Filter window looks as follows:
FIGURE 2.35 THE TABLE FILTER WINDOW
NOTE: The previous step ensures that the Sales FlowField not only sums the Amount from the Sales Transactions table that has the same Salesperson Code as the current Code, in the Salesperson/Purchaser table, but also has the same Type as the Type Filter field. 9. Click OK to close the Table Filter window. Notice that the Table Filter field in the Calculation Formula window is set to Sum ("Sales Transactions".Amount WHERE (Salesperson Code=FIELD(Code),Type=FIELD(Type Filter))).
FIGURE 2.36 THE CALCULATION FORMULA WINDOW
10. Click OK to close the Calculation Formula window. 11. Close the Properties window. 12. Compile, save and close the table.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-39
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Test the FlowFilter The following steps show how to test the FlowFilter. 1. Run table 13, Salesperson/Purchaser, from the Object Designer. 2. Go the last column of the table. Notice the Sales field calculates the value from the Amount field of the Sales Transactions table, by Salesperson Code. 3. Click the FlowFilter button on the toolbar. The FlowFilter window opens. This is where to change the value of a FlowFilter. Remember that changing the value of the FlowFilter may change the value of the FlowField. 4. In the Filter column for the Type Filter field, select Item and then click OK.
FIGURE 2.37 THE FLOWFILTER WINDOW
5. Notice the Sales field calculates the value from the Amount field of the Sales Transactions table, by Salesperson Code, by Type Item.
FIGURE 2.38 THE SALESPERSON/PURCHASER TABLE
6. Close the table.
2-40
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables
Table Types and Characteristics There are many types of standard tables in Microsoft Dynamics NAV. Understanding standards tables in Microsoft Dynamics NAV enables developers to understand areas of the application by just a superficial look at the objects. The following list shows the most common table types and some examples of each. Type
Brief Description
Examples
Master
Contains information about the primary focus subject of its functional area.
Customer, Vendor, Item
Supplemental
Contains information about a supplemental subject used in one or more functional areas.
Language, Currency
Setup
Contains one record that holds general information about its functional area.
General Ledger Setup, Sales &Receivables Setup
Register
A kind of table of contents for its corresponding Ledger table or tables.
G/L Register, Item Register
Subsidiary
Contains information which is subsidiary to either a Master table or a Supplemental table or both.
Item Vendor, FA Depreciation Book
Ledger
Contains the transactional information that is the primary focus of its functional area.
Cust. Ledger Entry, Item Ledger Entry
Journal
The primary transactional table that enable entries for a functional area.
Purchase Journal, Item Journal
Document
The secondary transactional tables that enable entries for one or multiple functional areas at the same time. This is actually implemented as a pair table.
Sales Header / Sales Line, Finance Charge Memo Header / Finance Charge Memo Line, Reminder Header / Reminder Line
Document History
Contains the transaction history for documents that have been posted.
Sales Invoice Header / Sales Invoice Line, Issued Fin. Charge Memo Header / Issued Fin. Charge Memo Line, Issued Reminder Header / Issued Reminder Line
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-41
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Master Tables A Master table contains information about the primary focus subject of its functional area. For example, the Customer table is a Master table. This is the primary focus of the Sales & Receivables functional area. Generally, many other tables are related to a Master table and the Master table itself is related to many other (usually Supplemental) tables. There is usually a Ledger table that is related to a Master table. Master tables also contain many FlowFilters and FlowFields, most of which relate to its corresponding Ledger table. Most functional areas have only one Master table, although some functional areas occasionally have two. Naming Master Tables The name of the Master table is the name of one of the records in the table. For example, the Customer table is named Customer because each record within it contains information about one customer. Primary Key and Other Standard Fields The primary key of a Master table is a Code field of length 20 named No. or occasionally Code. The description field of this table is a Text field of length 30 named Name or Description. These two fields are included in the DataCaptionFields property of the table so that these fields are displayed in the title bar of this table's forms and pages. Associated Forms and Pages There are three or more forms and pages that are used with a Master table. •
Card form and page
•
List form and page
•
Statistics form and page
The Associated Card Form and Page The Card form and page are used to edit the records in the Master table. The name of the form and page is the name of the table followed by the word Card. Therefore, the Card form and page for the Customer table are named Customer Card.
2-42
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables The associated Card form has at least one additional menu button (in addition to the usual OK, Cancel, and Help). This is labeled the same as the name of the table. The menu button provides links to other forms giving related or subsidiary information. These links can be to the following: •
To the List form that can be triggered by pressing F5 on the keyboard.
•
To the form that displays the related Ledger table that can be triggered by pressing CTRL + F5 on the keyboard.
•
To the related Statistics form that can be triggered by pressing F9 on the keyboard.
The Associated List Form and Page The List form and page are used to view the records in the Master table. Unlike the Card form and page, they cannot be used to edit the Master table. The name of the form and page is the name of the table followed by the word List. Therefore the List form and page for the Customer table are named Customer List. These form and page are set as the LookupFormID property and the DrillDownFormID property of the table, because they are used not only for viewing but also for lookups and drill-downs into this table. The associated List form has at least one additional menu button (in addition to the usual OK, Cancel, and Help). This is labeled the same as the name of the table. It provides links to other forms giving related or subsidiary information. These links can be to the following: •
To the Card form that can be triggered by pressing SHIFT + F5 on the keyboard.
•
To the form that displays the related Ledger table that can be triggered by pressing CTRL + F5 on the keyboard.
•
To the related Statistics form that can be triggered by pressing F9 on the keyboard.
The associated List page has its CardFormID property set to the page ID of the associated Card page. The Associated Statistics Form and Page The Statistics form and page are used to view calculated information about the record in the Master table. This information is separated from the Card form / page for performance reasons because this information is calculated. The name of this form and page is the name of the table followed by the word Statistics. Therefore the Statistics form and page for the Customer table are named Customer Statistics.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-43
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Supplemental Tables A Supplemental table contains information about a supplemental subject used in one or more functional areas. For example, the Currency table is a Supplemental table. It contains information about the currency. This is not the primary focus of any functional area but it is important to most of them. Generally, Supplemental tables are not related to other tables although many other tables of all types are related to Supplemental tables. Naming Supplemental Tables The name of the Supplemental table is the name of one of the records within the table. For example, the Currency table is named Currency because each record within it contains information about one currency. Primary Key and Other Standard Fields The primary key of a Supplemental table is a Code field of length 10 named Code. The description field of this table is a Text field of length 30 or 50 named Description. Some Supplemental tables do not contain a description field and some contain a description field named Name. Associated Forms and Pages The form used for a Supplemental table is a Tabular form. The associated form generally has no buttons except for the standard OK, Cancel, and Help. The page used for a Supplemental table is a List page. The name of the form and page is the plural of the name of the Supplemental table. Therefore, the form and page that are used to edit the Currency table is named Currencies. These form and page are set as the LookupFormID property of the table because they are used not only for editing but also for lookups into this table.
Subsidiary Tables A Subsidiary table contains information that is subsidiary to either a Master table or a Supplemental table or both. For example, the Item Vendor table is a Subsidiary table. It contains subsidiary information (vendor numbers) for the Item table in the Inventory functional area. Naming Subsidiary Tables The name of this table is generally made up of the names of the table or tables to which it is subsidiary or something close to that. For example, the table that is subsidiary to both the Vendor table and the Item table is named Item Vendor. Usually, it is a singular name that describes one record contained within the table.
2-44
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables Primary Key and Other Standard Fields The primary key for the Subsidiary table contains a field for each table to which it is subsidiary, each of which is related to that table. For example, the primary key fields for the Item Vendor table include an Item No. field (related to the Item Master table) and a Vendor No. field (related to the Vendor Master table). The primary key can also contain an Integer as the last field (named Line No.) to differentiate multiple records with the same subsidiary relationship. For example, the Employee Qualification table has an Integer field in the primary key to differentiate two records for the same employee. Subsidiary tables are generally not related to other tables except for the primary key fields mentioned before. Other tables are generally not related to a Subsidiary table because each Subsidiary table has multiple fields in the primary key. Subsidiary tables usually do not have description fields. Associated Forms and Pages A Subsidiary table uses one form and one page for editing and viewing purposes and this form or page are usually called from the Master or Supplemental form or page to which it is subsidiary. The name of the form and page are usually the plural of the name of the table, such as Employee Qualifications or something related to the information in the Subsidiary table, such as Item Vendor Catalog. The form used for a Subsidiary table is either a Worksheet form or a Tabular form. •
If the primary key for the Subsidiary table contains an Integer, the form is a Worksheet form and it does not contain any of the primary key fields. The primary key fields (except for the Integer field) are filtered so that they are set automatically.
•
If the primary key for the Subsidiary table does not contain an Integer, the form is a Tabular form and it does not contain the primary key field of the Master table. The primary key fields are filtered so that they are set automatically.
In both cases, the form is linked back to the form that called it up so that if the record there is changed, the filters on this form are also changed. This ensures that the correct related records are always in view. The page used for a Subsidiary table is a List page.
Ledger Tables A Ledger table contains the transactional information that is the primary focus of its functional area. For example, the Cust. Ledger Entry table is a Ledger table. It contains all Sales and Receivables transaction information that is the primary focus of the Sales and Receivables functional area.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-45
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 This table is much like a Subsidiary table because it is related to the corresponding Master table. However, it has different characteristics. It is related to many other tables, mostly Supplemental tables. Register tables are related to Ledger tables but rarely is another table related to a Ledger table. There is usually one Ledger table per functional area, although occasionally there are two.
Naming Ledger Tables The name of the Ledger table is usually the name of the Master table to which it is related, plus the words Ledger Entry describing one of the records in it (an entry). Because this is sometimes lengthy, the name is sometimes abbreviated. For example, the customer ledger entry table is actually named Cust. Ledger Entry. Sometimes, when there is more than one Master table, the name is the functional area followed by the words Ledger Entry. Ledger tables cannot be modified by users except for some highly controlled exceptions. These exceptions exclude the ability to add or delete a record.
Primary Key and Other Standard Fields The primary key of a Ledger table is an Integer field named Entry No. This primary key is always generated automatically by the posting routine that controls this Ledger table. There is always a field in the Ledger table that has a table relation to the Master table associated with this ledger table. The description field of this table is a Text field of length 50 named Description. In addition to the primary key, Ledger tables generally have many secondary keys, many of which have SumIndexFields attached to them. These are used together with the FlowFields on the Master table to calculate information for the user. Because of this, at least one of the secondary keys has a field that is related to the Master table as the first field in the key.
Associated Forms and Pages The List form and page are used to view the records in the Ledger table. The name of the form and page is the plural of the name of the Ledger table. Therefore, the form and page that are used to display records from the Cust. Ledger Entry table are named Customer Ledger Entries. These form and page are set as the LookupFormID property and the DrillDownFormID property of the table because they are used not only for viewing but also for lookups and drill-downs into this table. The List form can be displayed from the Master table forms by pressing the CTRL + F5 keys on the keyboard.
2-46
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables Register Tables A Register Table is a table of contents for its corresponding Ledger table or tables. There is one record per posting process and the Register table corresponds more closely to the posting routine instead of the functional area. For example, the table that contains the list of entries made to the Cust. Ledger Entry table is the G/L Register table. This is because the customer ledger entries are posted from the General Journal table by using the General Journal posting procedures. The Register table is related to its corresponding Ledger table or tables.
Naming Register Tables Register tables are named according to the posting function followed by the word Register. Therefore, the Register table updated by the General Ledger posting function is named G/L Register. The user can never modify the Register table.
Primary Key and Other Standard Fields The primary key of a Register table is an Integer field named No. The primary key is always generated automatically by the posting routine that controls this Register. Other standard fields for the Register table include two fields, both Integer fields related to the corresponding Ledger table, known as From Entry No. and To Entry No. Register tables usually do not have description fields.
Associated Forms and Pages The List form and page are used to view the records in the Register table. The name of the form and page is the plural of the name of the Register table. Therefore, the form and page that are used to display records from the G/L Register table are named G/L Registers. The List form contains a menu button named Register that contains links to other List forms displaying the corresponding Ledger table or tables.
Journal Tables A Journal table is the primary transactional table that enables entry for a functional area. All transactions, whether entered by the user directly or generated from another posting routine, pass through this table to eventually be posted to a Ledger table.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-47
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Journal tables are related to many other tables including the Master table, Supplemental tables, Subsidiary tables and even the corresponding Ledger table (for application purposes). Because of their use for transaction entries, Journal tables have more trigger code than most other table types.
Naming Journal Tables The name of the Journal table is the name of the transaction being posted, followed by the words Journal Line. For example, the table in which the user enters transactions to the Resource functional area is named Resource Journal Line. Each record in the Journal table contains one line from the journal. The Journal table is usually related to two corresponding Supplemental tables: the Journal Template table and the Journal Batch table. These tables let users split up data entry in various ways and let them set optional information that applies to the whole Journal. The names of these two tables are the same as the name of the Journal table, except followed by Journal Batch or Journal Template instead of Journal Line. Therefore, the two corresponding tables for the Resource Journal Line are named Resource Journal Template and Resource Journal Batch.
Primary Key and Other Standard Fields The primary key for the Journal table is made up of three fields, the field which is related to the Journal Template table, the field which is related to the Journal Batch table, and an Integer field named Line No. The description field of this table is a Text field of length 50 named Description.
Associated Forms and Pages The Worksheet form and page are used to make entries to the Journal table. The name of the form and page is the same as the Journal table, except without the word Line. Therefore the Worksheet form and page for the Resource Journal Line table are named Resource Journal. Sometimes, the form and page are named for the type of data being input. For example, one of the (many) Worksheet form and page used with the Gen. Journal Line table are named Sales Journal. None of the primary key fields are included on the form and page. When the Worksheet form is called, it is filtered by the Template and Batch fields, and the AutoSplitKey property of the Worksheet automatically sets the Line No. field. The Worksheet form always includes a menu button that has the same name as the related Master table. It includes a way to call up the Card form for the Master table that can be triggered by pressing Shift + F5 on the keyboard. It also has a way to call up the Ledger for that current Master record which can be triggered by pressing CTRL + f5.
2-48
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables The Worksheet form also always includes a menu button that is named Posting. This lets the user print the test report, post, or post and print a register and sometimes includes a choice to reconcile. The Worksheet form also usually includes other buttons that lets the user perform various processing functions.
Document Tables Document tables are secondary transactional tables that enable entries for one or multiple functional areas at the same time. They are secondary only in that their information is posted to ledgers through Journal tables, and not directly. For most users, Document tables are the primary means of entering a transaction. Because they are used for transaction entries, Document tables have more trigger code than most other table types. There are two kinds of Document tables: •
Document Header table
•
Document Line table
Document Header Table The Document Header table holds the main transaction information. For example, for a sales transaction, the Sales Header table contains information about the order or the invoice as a whole.
Document Line Table The Document Line table holds the detailed information for the transaction. For example, for a sales transaction, the Sales Line table contains information about each line of the order or invoice. The Document Line table is a Subsidiary table to the Document Header table. Like Journal tables, Document tables are related to many other tables. This includes Master, Supplemental, and Subsidiary tables, but rarely another table is related to a Document table.
Naming Document Tables The name of the Document Header table is the name of the transaction or document, plus the word Header. For example, the Document Header table that contains Sales transactions is named Sales Header. Each record contains one sale (order or invoice). The Document Header table that contains Finance Charge Memo transactions is named Finance Charge Memo Header. Each record contains one Finance Charge Memo.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-49
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The name of the Document Line table is the name of the transaction or document, plus the word Line. For example, the Document Line table that contains Sales transactions is named Sales Line. Each record contains one line from a sale (order or invoice), and, the Document Line table that contains Finance Charge Memo transactions is named Finance Charge Memo Line. Each record contains one line from a Finance Charge Memo.
Primary Key and Other Standard Fields For most Document Header tables, the primary key is a Code field of length 20 named No. that contains the document number. Some Document Header tables contain multiple kinds of documents each referring to the same transaction. For example, the Sales Header table contains Invoice documents, Credit Memo documents, Sales Order documents, and other document types. In these cases, the primary key has two fields - an Option field named Document Type and a Code field of length 20 named No. For most Document Line tables, the primary key has two fields - a Code field of length 20 that contains the document number and an Integer field named Line No. The Code field is table related to the Document Header table, and so is named according to that table's name (without Header) followed by that table's primary key field. For example, the Code field in the primary key of the Finance Charge Memo Line table is named Finance Charge Memo No. In the case in which the Document Header has a document type, the primary key of the Document Line table has three fields - an Option field named Document Type, a Code field of length 20 named Document No., and an Integer field named Line No. Again, the Code field is table related to the Document Header table.
Associated Forms and Pages A Document Header table uses a special kind of Card form or a Document page to display one header record at a time for the user to view and edit information. The name of the form and page is the name of the document that it displays. This is true even if the table can contain multiple kinds of documents because, in this case, the form is set up to only view information from one type. The form contains tabs and the page contains FastTabs to split the fields into logical groups to make it easier for the user to edit the information. The Document Header form always includes a menu button that is named Posting. This lets the user print the test reports, post, post and print the Document, or post a batch of these documents. The form also includes other buttons that let the user perform various processing functions. The thing that makes a Document Header form different from a Card form is that it contains a subform control. This in turn contains a Document Lines form.
2-50
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables A Document Line table uses a special kind of Worksheet form or a ListPart page to display multiple line records at a time for the user to view, and lets the user edit one at a time. The name of the form and page is the name of the document followed by either Lines or Subform. Because this name never shows, it is not that important. What is important is that the size of this form is identical to the size of the subform control in which it is displayed. None of the primary key fields are included on this form as the form and page are filtered (by using a link) for all the primary key fields except the Integer field. This is handled automatically by the AutoSplitKey property of the form and page. The Document Header table also uses a List form and page to let the user view multiple documents at the same time. The name of this form and page is the name of the table (without the word Header) followed by the word List. The List form can be invoked from the Header form by pressing the F5 key on the keyboard.
Document History Tables Document History tables are to Document tables what Ledger tables are to Journal tables. When a Document is posted, part of that posting process is copying the Document Tables to their corresponding Document History tables. To aid with that copying process, the Document History table generally has fields with the same field numbers, names, and properties as the original Document tables. Because the Document History tables record posted transactions, generally they cannot be edited by the user, although they can be deleted if the user has that permission. Other than that, the Document History tables, forms and pages are the same as the corresponding Document tables. Naturally, the subform is a List form instead of a Worksheet form because modifications are not allowed, and the names include either the word Posted or Issued to indicate that it is a history table instead of a transaction entry table.
Setup Tables A Setup table is a table that is designed to hold only one record. This record contains various fields that are used to select options for Microsoft Dynamics NAV or to hold data that applies to the company as a whole. Generally, no tables are related to a Setup table, although Setup tables can be related to other tables, usually Supplemental tables.
Naming Setup Tables The name of the setup table is usually the name of the functional area it is meant to set up, followed by the word Setup. For example, the table that contains the setup information for the General Ledger functional area is named General Ledger Setup. One exception to this rule is the Company Information table.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-51
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Primary Key and Other Standard Fields The primary key for this table is a Code field of length 10 named Primary Key. It is always left blank as only one record per table is allowed. The Setup tables do not have a description field.
Associated Setup Form and Page There is only one form and one page used for Setup tables. The form and page have the same name as the table. The primary key field is not included in this form and page. NOTE: There are some tables that contain the word Setup in their name which have more than one record. These tables generally follow the rules of the Subsidiary tables described previously, not the rules outlined here.
2-52
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables
Lab 2.1 - Create a Table The following lab tests the basic knowledge on how to create a table, set some basic field properties, and create primary and secondary keys for the table. Scenario Simon is a developer working for CRONUS International Ltd. CRONUS International has decided to start selling Microsoft Dynamics NAV training courses as its business. Simon must create a table to record course information and set several keys so that his users have the option for a different sorting sequence for the records in the table.
Challenge Yourself 1. Create a table to keep the course information. This includes the course code, course name, course description, course duration in days, course type (instructor led, e-learning or remote training), course prices, and whether it is an active course or not. 2. Add the following records to the new table. Code
Name
Description
Type
Duration
Price
Active
Difficulty
Passing Rate
80040
Installation & Configuration
Basic knowledge on installation and configuration
Remote Training
2
1,000
Yes
5
75
80041
Finance
Basic knowledge on finance
InstructorLed
3
1,500
Yes
7
80
80042
C/SIDE Introduction
Introduction to programming
InstructorLed
5
2,500
Yes
8
80
80043
Introduction
Introduction to Microsoft Dynamics NAV
Remote Training
2
1,000
Yes
4
60
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-53
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Code
Name
Description
Type
Duration
Price
Active
Difficulty
Passing Rate
80049
Application Setup
Basic knowledge on application setup
eLearning
2
1,000
Yes
5
65
80050
Business Intelligence
Basic knowledge on Business Intelligence
eLearning
1
500
Yes
5
65
80055
C/SIDE Solution Development
Advanced topics in programming
InstructorLed
5
2,500
Yes
10
75
Need a Little Help? Create a table to keep the course information. 1. Create a new table with the following fields: Code, Name, Description, Type, Duration, Price, Active, Difficulty and Passing Rate with their respective data types. 2. Set the OptionString property for the Type field. 3. Compile, save and close the table.
Add records to the new table. 1. Run the new table from the Object Designer. 2. Type the records into the table. 3. Close the table.
Step by Step Create a table to keep the course information. 1. In the Object Designer's Table list, click the New button. The Table Designer opens. 2. Type the following in the Table Designer:
2-54
Field No.
Field Name
Data Type
Length
10
Code
Code
10
20
Name
Text
30
30
Description
Text
50
40
Type
Option
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables
Field No.
Field Name
Data Type
50
Duration
Decimal
60
Price
Decimal
70
Active
Boolean
80
Difficulty
Integer
90
Passing Rate
Integer
Length
3. Open the Properties window for the Type field, and set the following property: o OptionString: Instructor Led,e-Learning,Remote Training 4. Close the Properties window. 5. Compile and save the table by clicking File, Save As. The Save As dialog box opens. 6. Type 90010 in the ID and Course in the Name, ensure that the Compiled check box is selected, and then click OK. 7. Close the table by closing the Table Designer.
Add records to the new table. 1. Run table 90010, Course, from the Object Designer. 2. Type the following: Code
Name
Description
Type
Duration
Price
Active
Difficulty
Passing Rate
80040
Installation & Configuration
Basic knowledge on installation and configuration
Remote Training
2
1,000
Yes
5
75
80041
Finance
Basic knowledge on finance
InstructorLed
3
1,500
Yes
7
80
80042
C/SIDE Introduction
Introduction to programming
InstructorLed
5
2,500
Yes
8
80
80043
Introduction
Introduction to Microsoft Dynamics NAV
Remote Training
2
1,000
Yes
4
60
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-55
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Code
Name
Description
Type
Duration
Price
Active
Difficulty
Passing Rate
80049
Application Setup
Basic knowledge on application setup
eLearning
2
1,000
Yes
5
65
80050
Business Intelligence
Basic knowledge on Business Intelligence
eLearning
1
500
Yes
5
65
80055
C/SIDE Solution Development
Advanced topics in programming
InstructorLed
5
2,500
Yes
10
75
3. Close the table.
2-56
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables
Summary Tables are the most fundamental objects in Microsoft Dynamics NAV. They are used to store information in the Microsoft Dynamics NAV database. C/SIDE provides the possibility for developers to create new tables, modify existing tables, properties and triggers, sort table data, and set relations between tables to look up data from other table fields. Microsoft Dynamics NAV also provides a powerful feature to perform fast calculations for huge records by means of special table fields. There are many standard tables available in Microsoft Dynamics NAV and C/SIDE provides a mean for developers to extend the application to suit their users' requirement, by creating custom tables or modifying existing tables. Developers are encouraged to work in Microsoft Dynamics NAV, become familiar with the various table types found in the application, and practice creating new tables. This helps developers understand the users' needs, and become adept at providing tables that meet those needs and integrate smoothly into the application.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-57
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Test Your Knowledge 1. What is the option string for the Reserve field in the Customer table? 2. What is the value of the TableRelation property of the Global Dimension 1 Code field in the Customer table? 3. What type of field is the Date Filter field in the G/L Account table? 4. What two major items can be defined within a table description? 5. What table property defines the default lookup form for the table? 6. What field property is used to force the user to enter a value into a Primary key field? 7. What number range can be used for new fields that are added to the customer table? 8. To view customers in order by the city that they live in, what needs to be changed in the table description? 9. What change needs to be made to the Salesperson Code field in the Customer table so that the user is only able to look up Salespeople that have a Commission % larger than zero? 10. What type of table is the Customer table? 11. What type of table is the Item Vendor table? 12. What type of table is the Department table? 13. What type of table is the Item Ledger Entry table?
2-58
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 2: Tables
Quick Interaction: Lessons Learned Take a moment and write down three key points you have learned from this chapter 1.
2.
3.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
2-59
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
2-60
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms
CHAPTER 3: FORMS Objectives The objectives are: •
Understand the concepts of forms and form components.
•
Create a simple form and add basic controls to the form.
•
Provide an overview of different form types and their characteristics.
•
Create a Card form.
•
Create a List form.
•
Link a Card form and a List form.
•
Create a main form and a subform.
•
Understand the concept of standard navigation between forms.
Introduction Forms are used for entering information into database tables and for retrieving and displaying information from database tables. Compared to programs written in traditional programming languages, C/SIDE applications do not execute sequentially. They are event-driven. A major part of the logic of the applications rests with the forms. It is through forms that users generate events that determine the flow of the application. Forms are used in the Microsoft Dynamics® NAV Classic client.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-1
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Form Fundamentals Forms can be used to access one table at a time, or they can combine information from several tables. A form can also display information that is calculated as the form is displayed, and it can also contain information that is not related to any table, such as labels or bitmap pictures. These are purely decorative. The following figure shows components of a form and how they are related:
FIGURE 3.1 FORM COMPONENTS AND THEIR RELATION
Properties Form properties are used to define the behavior of the forms. For example, form properties such as InsertAllowed, ModifyAllowed and DeleteAllowed, specify whether a form must be used only for displaying information or whether it is possible to insert new records, update or delete existing records through the form. Form properties are defined on the Properties window that can be edited when the form is opened in the Form Designer. The following steps show how to open the Properties window for the Customer Card form. In Microsoft Dynamics NAV Classic client: 1. On the Tools menu, click Object Designer. The Object Designer opens. 2. Click the Form button to open the Form list. 3. Select form 21, Customer Card, and then click the Design button to design the Customer Card form. The Form Designer opens. 4. Click anywhere outside the form, or click somewhere at the empty area inside the form, but not in any of the controls, and then click View, Properties, or click the Properties button on the Toolbar. NOTE: Alternatively, right-click anywhere outside the form, or somewhere at the empty area inside the form but not in any of the controls, and then click Properties.
3-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms 5. The Form - Properties window opens and shows the properties for the form. Here developers can view and modify properties for the Customer Card form.
FIGURE 3.2 THE CUSTOMER CARD FORM AND ITS PROPERTIES
Triggers Certain predefined events that occur to a form or a control cause the system to execute a user-definable C/AL function. The event and the function together are called a trigger. Triggers in a form can be divided into two categories: •
Form triggers
•
Control triggers
Examples of form triggers include OnOpenForm which contains statements that are executed when the form is opened, and OnModifyRecord which contains statements that are executed before the system accepts changes the user makes to a record. Triggers in a form are edited in the C/AL Editor which is accessed from the Form Designer.
Controls All information on a form is presented by using controls. Controls display data from the following: •
A database table field.
•
The value of a C/AL expression.
•
Bitmap pictures.
•
Static information such as a descriptive text.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-3
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 There are several kinds of controls that can be added to a form. The following list groups controls into several broad categories.
3-4
Control Type
Description
Static Controls
Static controls contain and display descriptive text or graphical information. The contents of static controls cannot be changed at run time. Example: Label, Image, Shape.
Data Controls
Data controls display the value of a C/AL expression. The simplest expression is the name of a table field or a variable. Example: Check Box, Option Button, Text Box, Picture Box, Indicator.
Containers
Container controls group other controls together. Some properties of the container overrule the same property in the contained controls. If the container cannot be edited, then none of the contained controls can be edited, even if they have their Editable property set to Yes. Example: Frame, Tab Control.
Data Containers
Data Containers are special kinds of containers that hold repeated data controls and are used to create columnar tables. Each data control that is contained by the data container makes up one column for which a static control is used as a heading. The rows are created by vertically repeating each data control. If the data container displays records from a table, each row displays one record. Example: Table Box.
Command Button
A command button is not related to data. It performs an action when it is clicked, or when ENTER or the spacebar is pressed while the button has the focus.
Menu Button
A menu button can be clicked exactly like a command button. However, it does not perform an action. When it is clicked, a menu opens showing several menu items.
Menu Item
The lines in a menu that are opened from a menu button are known as menu items. Each menu item can be clicked and resembles a command button because it performs an action when it is clicked.
Subform
Subforms display another form in a control on the main form. This lets the main form show data from two tables. For example, the main form is a card form and shows information about a customer from the customer table, whereas the subform is a tabular form and shows details of purchases made by the customer.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms Control Properties Control properties describe how a control is positioned on the form, what field that it is related to, and other behavior of the control. Different kinds of controls have different sets of properties. For example, a text box, a control type that is typically used to display the contents of a database field, has more properties than a picture box, a control that is used to display bitmap pictures. The following steps show how to open the Properties window for one of the controls (the Customer menu button) in the Customer Card form. 1. Design form 21, Customer Card, from the Object Designer. 2. Click the Customer menu button and then click View, Properties, or click the Properties button on the Toolbar. NOTE: Alternatively, right-click the Customer menu button and then click Properties. 3. The MenuButton - Properties window opens and shows the properties for the control. Here developers can view and modify properties for the Customer menu button.
FIGURE 3.3 THE CUSTOMER MENU BUTTON PROPERTIES
Control Triggers Control triggers describe what happens when certain events occur with regard to the control. For example, when a command button is clicked or when information is entered into a text box. The following steps show how to view the triggers for the Contact menu item on the Customer menu button, in the Customer Card form. 1. Design form 21, Customer Card, from the Object Designer. 2. Click the Customer menu button and then click View, Menu Items. The Menu Designer for the Customer menu button opens.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-5
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 NOTE: Alternatively, right-click the Customer menu button and then click Menu Items. 3. Click the Contact menu item and then click View, C/AL Code, or click the C/AL Code button on the Toolbar. The C/AL Editor opens and shows the triggers for the Contact menu item. Here developers can write C/AL statements to program certain activities when any particular trigger is executed, for example, when the Contact menu item is clicked. NOTE: The triggers for the Customer Card form are also shown together with the triggers for the Contact menu item.
FIGURE 3.4 THE CONTACT MENU ITEM TRIGGERS AND THE CUSTOMER CARD FORM TRIGGERS
Bound and Unbound Forms and Controls Typically, a form is related to a database table and is used to enter information into and display information from that table. The form is said to be bound to the table. An unbound form is not related to any table. An example of an unbound form is a form that is used as a menu, from which the user can select other forms or reports to run. NOTE: Menu forms are no longer part of the base product but can still be developed in Microsoft Dynamics NAV. The controls on a form that are bound to a table are usually bound to fields in the same table. There need not be a control for every field in the table, nor do all controls on the form need to be bound to table fields. Controls that are not bound to fields are called unbound controls. An example of an unbound control is a command button.
3-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms The Customer Card Form The Customer Card form is a bound form. As the name suggests, it is bound to the Customer table.
FIGURE 3.5 THE CUSTOMER CARD FORM
The Customer Card form has a tab control, grouping several other controls to six different tabs (General, Communication, Invoicing, Payments, Shipping and Foreign Trade). There are several labels and text boxes in the General tab and several check boxes in the Invoicing, Payments and Shipping tabs. The Customer Card form has three menu buttons (Customer, Sales and Functions), each containing menu items, and a command button (Help).
The Customer List Form The Customer List form is also a bound form that is bound to the Customer table.
FIGURE 3.6 THE CUSTOMER LIST FORM
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-7
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The Customer List form has a table box that contains several text boxes which are repeated for each row, and labels, one for each column. It has two menu buttons (Customer and Sales) and three command buttons (OK, Cancel and Help).
Demonstration: Create a Simple Form The following demonstration shows how to add basic controls from the Toolbox to a form, and how they are used together with several of their properties.
Create a Blank Form The following steps show how to create a blank form. 1. In the Object Designer's Form list, click the New button. The New Form window opens. 2. Select Create a Blank Form and then click OK. The Form Designer opens. NOTE: When a blank form is created, the size of the designer is small. This can be enlarged if it is necessary. 3. Compile and save the form by clicking File, Save As. The Save As dialog box opens. 4. Type 90000 in the ID and Blank Form in the Name, ensure that the Compiled check box is selected, and then click OK. This compiles and saves the form. 5. Close the form by closing the Form Designer. 6. In the Object Designer's Form list, select form 90000, Blank Form, and then click the Run button to run the newly created Blank Form.
FIGURE 3.7 THE BLANK FORM
7. Close the form.
3-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms Attach a Source Table A blank form is unbound when it is created. It is not associated with any table. The following steps show how to associate a blank form with a table. 1. Design form 90000, Blank Form, from the Object Designer. 2. Open the Properties window for the form, and set the following property: o SourceTable: Customer
FIGURE 3.8 THE FORM PROPERTIES
NOTE: SourceTable property accepts either the ID or the name of the table. 3. Close the Properties window. 4. Compile, save and close the form. 5. Run form 90000, Blank Form. Notice the value that is shown in the title bar of the form. 6. Click the Next button on the Toolbar. Notice the value that is shown in the title bar now. 7. Close the form. The Blank Form is now attached to the Customer table. When the Next button is clicked, the Blank Form shows the next customer record in the Customer table, although in this case, there are no controls available in the form to show any information from the customer record.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-9
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Add a Text Box The Blank Form is useless without any controls in it. The following steps show how to add a text box to the blank form. 1. Design form 90000, Blank Form, from the Object Designer. 2. Click View, Toolbox or click the Toolbox button on the Toolbar. The Toolbox opens.
FIGURE 3.9 THE TOOLBOX
3. Rest the mouse on each button on the Toolbox for several seconds to view the Tool Tip for each button and to become familiar with what each button represents. 4. Click the Text Box button on the Toolbox. 5. Move the cursor over the form, and then click somewhere in the middle of the form. Notice that the cursor changes to cross hairs and a box when it is moved over the form. The upper-left corner of the text box is where the form was clicked.
FIGURE 3.10 THE BLANK FORM WITH A TEXT BOX
3-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms Bind the Text Box The text box must be bound to a field or another data element. This can be anything that returns a valid value: variables, functions, or other expressions. 1. Open the Properties window for the text box, and set the following property: o SourceExpr: "No." 2. Close the Properties window. 3. Compile, save and close the form. 4. Run the form, and test the new text box by moving to the next, previous, first, or last record.
FIGURE 3.11 THE BLANK FORM WITH A TEXT BOX
Add a Label At this point, it is not clear what information the text box provides. To help the users, add a label that describes the field on the form. The following steps show how to add a label to the form. 1. Design form 90000, Blank Form, from the Object Designer. 2. Open the Toolbox and then click the Label button. 3. Move the cursor over the form, and then click somewhere to the left of the text box. Re-position the text box and the label if it is necessary. 4. Change the Caption property of the label to No. 5. Compile, save and close the form.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-11
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 6. Run the form, and test the new text box by moving to the next, previous, first, or last record.
FIGURE 3.12 THE BLANK FORM WITH A TEXT BOX AND A LABEL
The label indicates that the text box is looking at the No. (number) field from the Customer table.
Add a Check Box The following steps show how to add a check box to the form. 1. Design form 90000, Blank Form, from the Object Designer. 2. Open the Toolbox and then click the Check Box button. 3. Move the cursor over the form, and then click somewhere in the middle of the form under the text box. NOTE: For a check box to work correctly, the expression or field that it is bound to must return a Boolean value (true or false). A check mark in the check box represents true, and an empty check box represents false. 4. Adjust the width of the check box to the right side. 5. Open the Properties window for the check box, and set the following properties: o SourceExpr: "Print Statements" o ShowCaption: Yes
NOTE: A check box has a built-in label. Therefore, there is no need to add one separately. By default, the built-in label for a check box is displayed on the right side of the check box.
3-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms 6. Close the Properties window. 7. Compile, save and close the form. 8. Run the form, and test the new check box by moving to the next, previous, first, or last record.
FIGURE 3.13 THE BLANK FORM WITH A CHECK BOX
Use the Add Label and the Lock Option There are two useful options on the bottom of the Toolbox that help in designing forms. The first is the Add Label that enables developers to attach a label automatically when placing another type of control, such as a text box, onto the form. The second is the Lock. This enables developers to quickly add more than one control at a time. The following steps show how to use the Add Label and the Lock. 1. Design form 90000, Blank Form, from the Object Designer. 2. Open the Toolbox and then click the Add Label button. 3. Click the Text Box button.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-13
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 4. Move the cursor over the form, and then click somewhere in the middle of the form under the other controls. Notice that a label is automatically added alongside the text box. Also notice that the Text Box button is automatically un-clicked.
FIGURE 3.14 TEXT BOX ADDED BY USING THE ADD LABEL
NOTE: Labels added by using the Add Label, have their ParentControl property set to the ID of the parent control. 5. Click the Text Box button and also click the Lock button. 6. Move the cursor over the form, and then click somewhere in the middle of the form under the other controls. Notice that not only a label is added alongside the text box, but also the Text Box button and the Lock button remain clicked.
3-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms 7. Move the cursor over the form, under the previous control and click the form several times to add more text boxes. The Add Label and Lock option enables developers to efficiently add multiple controls to the form.
FIGURE 3.15 TEXT BOXES ADDED BY USING THE ADD LABEL AND THE LOCK
8. Close the form without saving it.
Add a Tab Control Container controls allow for the grouping of other controls and organize how information is presented in a form. The following steps show how to add a tab control and then to add new tabs into the tab control. 1. Create a new form, and attach the Item table as the source table. Compile and save it as form 90001, Custom Form. NOTE: When creating a new form, typing Item in the Table field in the New Form window sets the source table of the new form to Item table automatically. 2. Open the Toolbox and then click the Tab Control button. 3. Move the cursor over the form, and then click somewhere in the top left area of the form.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-15
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 NOTE: The form has only one tab. The name of the first tab is General. This name is a standard for forms that have tabs.
FIGURE 3.16 THE CUSTOM FORM WITH A TAB CONTROL
4. Open the Properties window for the tab control, and locate the PageNames property. NOTE: The current value of the PageNames property is (the name of the first tab). The PageNames property is a comma-separated list of tab names. To add a tab, add to this list. Press the F2 key to reach the end of a selected field. 5. Set the following property: o PageNames: General,Test,Frame,Table Box,Picture
NOTE: There are no spaces after the commas in the PageNames property. If spaces exist after the comma, they will become part of the tab names. 6. Close the Properties window.
Add Controls to a Tab 1. Click the Test tab of the tab control. 2. On the Toolbox, click the Label button.
3-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms 3. Move the cursor over the form, and then click somewhere in the middle of the form inside the Test tab.
FIGURE 3.17 THE CUSTOM FORM WITH A LABEL
4. Compile, save and close the form. 5. Run the form, toggle between the General and Test tab and view the changes.
Add a Frame A frame is similar to the page of a tab control, it holds other controls. When the frame is moved, the controls inside the frame stay with it. The following steps show how to add a frame. 1. Click the Frame tab of the tab control. 2. On the Toolbox, click the Frame button. 3. Add a frame to the Frame tab. Re-size the frame so that it fits inside the tab control. 4. Change the Caption property of the frame to Test Frame.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-17
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 5. Add several labels to the frame. Remember to drop the controls inside the frame.
FIGURE 3.18 THE CUSTOM FORM WITH A FRAME
Add a Table Box A table box is a container control that contains bound controls. It enables the form to display more than one record at a time. The following steps show how to add a table box to show multiple item records. 1. Click the Table Box tab of the tab control. 2. On the Toolbox, click the Table Box button. 3. Add a table box to the Table Box tab. Move it to the upper-left corner and resize it to fit the tab control. NOTE: The table box is currently empty. It is a container control, and other controls must be added to it. The most common control in a table box is a text box. 4. On the Toolbox, click the Text Box button. 5. Move the cursor over the form, and then click somewhere inside the table box. The text box becomes a column and a label is added to the top for a column heading.
3-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms 6. Change the SourceExpr property of the text box (the column) to "No."
FIGURE 3.19 THE CUSTOM FORM WITH A TABLE BOX
7. Compile, save and close the form. 8. Run the form, and view the table box inside the Table Box tab. The table box displays several rows of records from the item table. There is a triangle in the gray box next to the current row. The title bar of the form changes according to the row selected in the table box. When the form is maximized or adjusted, the controls all stay the same size and in the same location.
Autosizing Controls The tab control must grow together with the form, when the form is adjusted. This must also be the case with the table box. The HorzGlue and VertGlue properties of the controls determine this behavior. The following steps show how to set up the HorzGlue and VertGlue properties. 1. Design form 90001, Custom Form, from the Object Designer. 2. Open the Properties window of the tab control, and set the following properties: o HorzGlue: Both o VertGlue: Both NOTE: If the Frame and Table Box tabs disappear when this property is modified, complete the next step, and then compile, save and close the form. When the form is reopened in the Form Designer, the tabs will be there, and the properties will be set. 3. Close the Properties window.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-19
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 4. Open the Properties window of the table box, and set the following properties: o HorzGlue: Both o VertGlue: Both 5. Compile, save and close the form. 6. Run the form, and adjust the form width and height, or maximize the form. The tab control and the table box grow with the form.
Display an Option Field Option fields can be displayed to the user in two ways, by using a text box or option buttons. The following steps show how to display an option field by using both ways. 1. Design form 90001, Custom Form, from the Object Designer. 2. Click the General tab of the tab control. 3. Open the Toolbox, click the Add Label button and then click the Text Box button. 4. Add a text box with an attached label to the General tab. 5. Change the SourceExpr property of the text box to "Costing Method". NOTE: The Costing Method field is an option field in the Item table.
6. On the Toolbox, click the Lock button and the Option Button button. 7. Add three option buttons underneath the text box, without attached labels. NOTE: There are five option values for the Costing Method field. The option values are indexed starting from 0. In this demonstration, only three option buttons are created, therefore, the users will only be able to access three of the values. 8. Set the following properties for each option button: o For the first option button: – SourceExpr: "Costing Method" – OptionValue: FIFO – Caption: FIFO
3-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms o
For the second option button: – SourceExpr: "Costing Method" – OptionValue: LIFO – Caption: LIFO
o
For the first option button: – SourceExpr: "Costing Method" – OptionValue: Standard – Caption: Standard
NOTE: To effectively change properties for multiple controls, keep the Properties window open, and then click one control at a time. The Properties window automatically shows the property for the control that is clicked.
FIGURE 3.20 THE CUSTOM FORM THAT DISPLAYS AN OPTION FIELD BY USING TEXT BOX AND OPTION BUTTONS
9. Compile, save and close the form. 10. Run the form, and view several items with different costing methods. The text box displays a drop-down list, listing all the options available for the option field. If an item with Standard costing method is displayed, the Standard option button is selected. This is also the case for items with the FIFO and LIFO costing method. Only one of the option buttons can be selected at any point of time. If an Item with Average costing method is displayed (for example, item 80100, Printing Paper), none of the option buttons are selected, because there is no option button created for Average costing method.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-21
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Display a Progress Indicator An indicator creates a way for the user to easily view the percentage of a value in a graphical manner. The following steps show how to display the profit of an item by using an indicator. 1. Design form 90001, Custom Form, from the Object Designer. 2. Open the Toolbox, click the Indicator button. 3. Add an indicator to the General tab. NOTE: By default, an indicator starts from the left side and increases to the right side. 4. Set the following properties for the indicator: o Orientation: Bottom o MinValue: 0 o MaxValue: 100 o SourceExpr: "Profit %" 5. Increase the height of the indicator by dragging the top edge and decrease the width by dragging the left edge. 6. Compile, save and close the form. 7. Run the form.
FIGURE 3.21 THE CUSTOM FORM WITH AN INDICATOR
Display a BLOB Field (Picture) Binary Large Object (BLOB) fields are primarily used to store pictures. Some items in the Item table have pictures. The following steps show how to display a BLOB field to display a picture of an item by using a picture box. 1. Design form 90001, Custom Form, from the Object Designer. 2. Click the Picture tab of the tab control.
3-22
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms 3. Open the Toolbox, click the Picture Box button. 4. Add a picture box to the Picture tab. Move the picture box to fit inside the tab control. 5. Change the SourceExpr property of the picture box to Picture. 6. Compile, save and close the form. 7. Run the form. 8. Use the Next button to examine different records. List some items that have pictures. HINT: Start to look from item 1896-S, ATHENS Desk.
FIGURE 3.22 THE CUSTOM FORM WITH A PICTURE BOX
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-23
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Form Types and Characteristics There are five basic kinds of forms in C/SIDE, the development environment for Microsoft Dynamics NAV: •
Dialog boxes
•
Request forms
•
Unbound forms
•
One-record forms
•
Multi-record forms
Dialog boxes Dialog boxes are simple windows that display information such as error or message text. The only user interaction is to click a button, such as OK, Cancel, Yes, or No. These buttons are generated by C/AL functions such as ERROR, MESSAGE, TESTFIELD, and CONFIRM, or are created by using a variable of type Dialog. They are not associated with Form objects. Request Form Request forms are found only within Report objects and are not associated with Form objects. Unbound Forms Unbound forms are Form objects that are not associated with any table. They are mostly used for menu purposes or intermediate means to collect information from users for additional processing. One-Record Forms One-Record forms are Form objects that are associated with a table. They enable the user to view and possibly edit only one record from one table at a time. An example of this is a Card form. Multi-Record Forms Multi-record forms are Form objects that are associated with a table. They enable the user to view multiple records from one table at the same time and possibly edit them. Examples of these include Tabular forms, Trendscape forms, and Matrix forms. While C/SIDE enables developers to create forms of many kinds with different looks and methods of operation, the Microsoft Dynamics NAV application only uses several of the possibilities. This is to provide a consistent appearance to the application.
3-24
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms Developers may want to follow this policy when modifying forms or applications that interface with Microsoft Dynamics NAV. This makes the application more user-friendly and consistent. All the following descriptions assume full use of the Microsoft Dynamics NAV standards. Form Types and Examples There are several types of standard forms in Microsoft Dynamics NAV. The following list shows the most common form types and some examples of each. Type
One Record/MultiRecord
Examples
Card Form
One Record
Customer Card, Vendor Card, Item Card
Statistics Form
One Record
Customer Statistics, Vendor Statistics, Employee Statistics
Tabular Form
Multi-Record
Currencies, Payment Terms
List Form
Multi-Record
Customer List, Item List, Item Ledger Entries
Worksheet Form
Multi-Record
General Journal, Cash Receipts Journal, Item Transfer Journal
Header/Line Form
Both (actually two forms)
Sales Invoice, Posted Purchase Credit Memo, Finance Charge Memo
Setup Form
One Record
General Ledger Setup, Company Information, Sales & Receivables Setup
Understanding standards forms in Microsoft Dynamics NAV enables developers to understand areas of the application by just a superficial look at the objects.
Card Forms A card form enables users to view and edit one record at a time. It is used when there are too many fields to view them all conveniently on only one line. Card forms always have tabs, just as index tabs, across the top edge with which the user can select different groups of fields to display. Even if there are few fields, there is at least one General tab, which is always first. Tables that use card forms only have one field in their primary key and this field is always displayed as the first field in the General tab.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-25
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Naming Card Forms Card forms are named with the name of the associated table, followed by the word Card. For example, the card form associated with the Customer table is named Customer Card. Card forms also have at least one menu button at the bottom of the form and this button has the same name as the table that the card form is based on. This button provides ways of accessing information related to that table from the card form.
FIGURE 3.23 THE CUSTOMER CARD FORM
Statistics Forms A Statistics form is a one-record form that enables users to view, but not edit information. It usually uses FlowFields that let users drill-down for more information. It also contains calculated or derived information that is contained in variables that cannot be drilled-down. Statistics forms may also contain tabs to help organize the information. The primary key of the associated table is displayed in the form's title bar.
3-26
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms Naming Statistics Forms Statistics forms are named with the name of the associated table, followed by the word Statistics. For example, the Statistics form associated with the Customer table is named Customer Statistics.
FIGURE 3.24 THE CUSTOMER STATISTICS FORM
Entry Statistics forms are a special version of the statistics form. They are named after the name of the associated table, followed by the words Entry Statistics. For example, the Entry Statistics form associated with the Customer table is named Customer Entry Statistics.
Tabular Forms A Tabular form is a multi-record form that enables users to view multiple records from a table and edit them. Each record is displayed as a single row and each field is displayed as a column forming a spreadsheet-like table within the form itself. The primary key of the associated table is displayed in the left-most column. If there are multiple fields in the primary key, they are displayed in order of their significance in the columns, starting from the left.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-27
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Naming Tabular Forms Tabular forms are named with the plural of the name of the associated table. For example, the Tabular form associated with the Currency table is named Currencies.
FIGURE 3.25 THE CURRENCIES FORM
For associated tables that have multiple fields in their primary key, the name can be different. For example, the Tabular form associated with the General Posting Setup table is named General Posting Setup.
FIGURE 3.26 THE GENERAL POSTING SETUP FORM
3-28
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms Worksheet Forms A Worksheet form is a specialized version of the Tabular form. It is also a multirecord form that enables users to view multiple records from a table and edit them. Worksheet forms differ from ordinary Tabular forms, in that when the user inserts a new record, the record does not jump to another position within the form, but instead, the record stays in the same order in which the user inserted it. This order is done by using the AutoSplitKey property of the form, combined with an integer as the last field in the table's primary key. The primary key fields of the associated table are not displayed on the Worksheet form.
Naming Worksheet Forms Worksheet forms are named according to the purpose of the associated table. For example, for Journal tables, the name of the Worksheet form ends with the word Journal.
FIGURE 3.27 THE GENERAL JOURNAL FORM
List Forms A List form is a multi-record form that enables users to view multiple records from a table at the same time, but does not let the user edit them. It uses the same rows and columns look as the Tabular form. The primary key fields of the associated table are displayed in the left-most columns.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-29
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Naming List Forms List forms are named with the name of the associated table, followed by the word List. For example, the List form associated with the Customer table is named Customer List.
FIGURE 3.28 THE CUSTOMER LIST FORM
Ledger Form A Ledger form is a specialized version of the List form. Ledger forms are used only for Ledger Entry tables. They differ from ordinary List forms, in that, even though users cannot insert or delete records, they can sometimes edit a few fields. The primary key of the Ledger Entry tables, an integer named Entry No., is displayed in the right-most column instead of the left-most column.
Naming Ledger Forms Ledger forms are named with the plural of the name of the associated table. For example, the Ledger form associated with the Customer Ledger Entry table is named Customer Ledger Entries.
FIGURE 3.29 THE CUSTOMER LEDGER ENTRIES FORM
3-30
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms Header/Line Forms (Document Forms) Many forms within Microsoft Dynamics NAV have characteristics of both a Card form and a Tabular form, for example the Sales Invoice form. The fields that are common to the whole invoice are located on a card-like form with tabs that show one invoice at a time. However, the invoice lines are displayed in a table-like section of the form, where multiple invoice lines, from the same invoice, can be viewed at the same time and edited. These are known as Header/Line forms. Header/Line forms are, in fact, two separate forms associated with two tables. The main form is a card-like form associated with a table. The main form has a subform that displays a worksheet-like form that is associated with a different table, a table which is subsidiary to the first. The subform handles the linkage between the two forms.
Naming Header/Line Forms In many cases, a Header/Line form represents a document. In the previous example, the Sales Invoice form, the name of the form is the name of the document that it represents. In other cases, the name of the form is whatever the name of the main form may be without the subform.
FIGURE 3.30 THE SALES INVOICE FORM
Setup Forms A Setup form is a one-record form that enables users to view and edit the one and only one record in a setup table. The user is not able to insert or delete the single record by using this form. Because there are many fields, these forms contain tabs, just as index tabs, across the top edge to organize the information.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-31
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Because there is only one record, the primary key is not displayed anywhere on this form.
Naming Setup Forms Setup forms are named with the name of the associated table. For example, the setup form associated with the General Ledger Setup table is named General Ledger Setup.
FIGURE 3.31 THE GENERAL LEDGER SETUP FORM
Menu Forms A Menu form is an unbound form that enables users to access many of the other forms that are related to a functional area. The Menu form generally consists of command buttons or menu buttons. Menu form is no longer part of standard Microsoft Dynamics NAV, although it can still be developed in C/SIDE.
Naming Menu Forms Menu forms are named with the associated functional area, followed by the word Menu. For example, the Menu form associated with the General Ledger functional area is named General Ledger Menu.
Other Multi-record Forms There are other forms that enable users to view and edit multiple records at the same time. These include Trendscape forms and Matrix forms. These forms provide great functionality within Microsoft Dynamics NAV, but do not affect the main architecture of the system.
3-32
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms An example of a Trendscape form is the Contract Trendscape window.
FIGURE 3.32 THE CONTRACT TRENDSCAPE FORM
An example of a Matrix form is the Budget window.
FIGURE 3.33 THE BUDGET FORM
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-33
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Demonstration: Create a Card Form The following demonstration shows how to create a card form by using the CardType Form Wizard and add several fields to the card form by using the Field Menu and also add several buttons to the form.
Use the Card-Type Form Wizard Many of the form-related tasks presented to this point can be done more easily by using the form wizard. The form wizard can create two types of forms: Card and Tabular. 1. In the Object Designer's Form list, click the New button. The New Form window opens. 2. Type Customer in the Table field. 3. Select Create a form using a wizard, leave the Card-Type Form selected and then click OK. The Card-Type Form Wizard opens.
FIGURE 3.34 THE NEW FORM WINDOW
The Card-Type Form Wizard consists of two questions, and each question represents a step in the wizard. When creating the form in the wizard, click the Preview button to preview the form to be created.
3-34
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms Step 1 - Should the Form contain tabs? 1. Leave Yes selected. By default the first tab is named General. 2. Click the empty line under General and type Others.
FIGURE 3.35 CARD-TYPE FORM WIZARD STEP 1
3. Click Next.
Step 2 - Which fields from the Customer table do you want on the tabs? 1. Notice that the form has both of the tabs that are created in Step 1 of the Wizard. 2. Click the General tab. 3. Double-click the following fields: No., Name, Address, and City. These fields are moved to the General tab; alternatively, use the left arrow button to move the fields from the Available Fields list to the Field Order list. 4. Click the Others tab. Notice the Field Order list is empty.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-35
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 5. Double-click the following fields: Global Dimension 1 Code, Territory Code, and Global Dimension 2 Code.
FIGURE 3.36 CARD-TYPE FORM WIZARD STEP 2
6. Click Finish to end the wizard and open the newly created form in the Form Designer. The form is not yet saved. 7. Compile and save the form with the ID 90002, and the name My Customer Card, and close the form. 8. Run the form, and test the tabs and fields.
FIGURE 3.37 MY CUSTOMER CARD FORM
Use the Field Menu 1. Design form 90002, My Customer Card, from the Object Designer. 2. Click View, Field Menu or click the Field Menu button on the Toolbar. The Field Menu window opens. 3. Select the Balance field.
3-36
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms NOTE: Hold the CTRL key while selecting the fields in the Field Menu window to select multiple fields. 4. Move the cursor over the form, to where the field is to be added, and then click to create a new text box for the field. NOTE: The SourceExpr property of the text box is automatically set to the field selected in the Field Menu and a label is created attached to the text box.
FIGURE 3.38 BALANCE FIELD ADDED BY USING THE FIELD MENU
5. Compile, save and close the form. 6. Run the form, and test the field.
Add a Command Button The following steps show how to add a command button that closes the form. 1. Design form 90002, My Customer Card, from the Object Designer. 2. Open the Toolbox, and then click the Command Button button. 3. Move the cursor over the form, to the lower right of the form, to the left of the Help button, and then click to create the command button.
NOTE: On standard forms, buttons are positioned in the lower right corner of the forms.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-37
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 4. Set the following properties for the command button: o PushAction: OK o HorzGlue: Right o VertGlue: Bottom NOTE: The default PushAction <0> causes the button to do nothing except raise its OnPush trigger when it is clicked. Setting the PushAction property to OK sets the button as an OK button. OK buttons close the form when they are clicked. Setting the HorzGlue and VertGlue properties to right and bottom respectively ensures the command button is always proportionally aligned to the lower right corner of the form. 5. Compile, save and close the form. 6. Run the form, and test the command button.
FIGURE 3.39 MY CUSTOMER CARD FORM WITH A COMMAND BUTTON
3-38
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms
Demonstration: Create a List Form The following demonstration shows how to create a list form using the TabularType Form Wizard and add several fields by using the Field Menu, and then make a column invisible.
Use the Tabular-Type Form Wizard A list form displays many records at a time to the user. It usually has a table box. 1. In the Object Designer's Form list, click the New button. The New Form window opens. 2. Type Customer in the Table field. 3. Select Create a form using a wizard, select the Tabular-Type Form and then click OK. The Tabular-Type Form Wizard opens. The Tabular-Type Form Wizard consists of only one question. Therefore there is only one step in the wizard. When creating the form in the wizard, click the Preview button to preview the form to be created.
Step 1 - Which fields from the Customer table do you want on your form? 1. Double-click the following fields: No., Name, Address and City. 2. Click Finish to end the wizard and open the newly created form in the Form Designer. The form is not yet saved. 3. Change the Editable property of the form to No. 4. Compile and save the form with the ID 90003 and the name My Customer List, and close the form.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-39
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 5. Run the form, and test the fields.
FIGURE 3.40 MY CUSTOMER LIST FORM
Use the Field Menu 1. Design form 90003, My Customer List, from the Object Designer. 2. Click View, Field Menu or click the Field Menu button on the Toolbar. The Field Menu window opens. 3. Select the Balance field. 4. Move the cursor over the form, inside the table box, where the column is to be added, and then click to create a new column for the field. NOTE: The SourceExpr property of the text box is automatically set to the field selected in the Field Menu and a label is created as the column header.
FIGURE 3.41 BALANCE FIELD ADDED BY USING THE FIELD MENU
5. Compile, save and close the form. 6. Run the form.
3-40
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms Make Columns Invisible Most users may not have to view the customer's balance. By default the column must be made invisible on the My Customer List form. However, every user must be able to make it visible, upon request. 1. 2. 3. 4.
Design form 90003, My Customer List, from the Object Designer. Change the Visible property of the Balance column to No. Compile, save and close the form. Run the form.
The Balance column is now hidden. Every user can make this column visible by clicking View, Show Column and selecting the Balance field.
Demonstration: Link the Card Form and the List Form The following demonstration shows how to create a link from a list form to a card form by using the menu button, menu item and setting several properties. Then, create a link from the card form to the list form by using the Lookup form of the source table.
Create a Menu Button The following steps show how to create a link to the card form, from a list form. 1. Design form 90003, My Customer List, from the Object Designer. 2. Move the OK and Cancel buttons to the left, to make room for a new button. 3. On the Toolbox, click the Menu Button button. 4. Add a menu button to the form, between the Cancel and Help button.
FIGURE 3.42 MY CUSTOMER LIST FORM WITH A MENU BUTTON
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-41
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 5. Set the following properties for the menu button: o Caption: Customer o HorzGlue: Right o VertGlue: Bottom
NOTE: Most card and list forms contain a menu button with the name of the table.
Create a Menu Item The menu button has no menu item yet. The following steps show how to add menu items to the menu button. 1. Right-click the Customer menu button, and then click Menu Items. 2. Click the first empty line, and type the following: Caption
ShortCutKey
Action
RunObject
Card
Shift+F5
RunObject
Form My Customer Card
3. Open the Properties window for the menu item, and set the following properties: o RunFormLink: No.=FIELD(No.) o RunFormLinkType: OnUpdate
FIGURE 3.43 MENU DESIGNER AND MENU ITEM PROPERTIES
NOTE: The RunFormLink property on the menu item links the My Customer Card form and the My Customer List form. Changing the RunFormLinkType property to OnUpdate keeps the two forms synchronized whenever the calling form is updated. 4. Close the Properties window and close the Menu Designer. 5. Compile, save, and close the form. 6. Run the form, and test the menu button, the menu item and the shortcut key.
3-42
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms When the menu item is clicked, the My Customer Card opens and shows the current customer in the My Customer List. If another customer is selected in the My Customer List, the My Customer Card also reflects that customer. This is achieved by setting the RunFormLink and RunFormLinkType property of the menu item.
Create a Button to Look Up Information in a Table The following steps show how to create a button to look up information in a table. 1. 2. 3. 4. 5.
Design form 90002, My Customer Card, from the Object Designer. Move the OK button to the left, to make room for a new button. On the Toolbox, click the Menu Button button. Add a menu button to the form, between the OK and Help button. Set the following properties for the menu button: o Caption: Customer o HorzGlue: Right o VertGlue: Bottom
6. Right-click the Customer menu button, and then click Menu Items. 7. Click the first empty line, and type the following: Caption
ShortCutKey
Action
List
F5
LookupTable
NOTE: The PushAction LookupTable brings up the default Lookup form of the form's source table.
FIGURE 3.44 MENU DESIGNER
8. Close the Menu Designer. 9. Compile, save and close the form.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-43
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Change the Default Lookup Form The current Lookup form of the Customer table is form 22, Customer List. The following steps show how to change the default Lookup form of the Customer table. 1. Design table 18, Customer, from the Object Designer 2. Set the LookupFormID property of the table to My Customer List.
FIGURE 3.45 CUSTOMER TABLE PROPERTIES
3. Compile, save and close the table. 4. Run form 90002, My Customer Card, and test the menu button, the menu item and the shortcut key.
3-44
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms
Demonstration: Form and Subform Forms can also display information from a table other than that form's source table. One way to do this is to display another form within the first form. This is known as a subform. The following demonstration shows how to build two forms that are combined to show the customer records and the customer comments on one form.
Create the Main Form 1. Design form 90002, My Customer Card, from the Object Designer. 2. Adjust the form and the tab control vertically to make room for the subform. This also involves moving the buttons to the bottom of the form. 3. Open the Toolbox, and then click the Subform button. 4. Add a subform to the General tab. Adjust the subform proportioned to the height and width of the tab control. 5. Open the Properties window for the subform and note the value of the Height and Width properties. Height ____________________ Width _____________________
FIGURE 3.46 MY CUSTOMER CARD FORM WITH A SUBFORM
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-45
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 6. Set the following properties for the subform: o HorzGlue: Both o VertGlue: Both 7. Close the Properties window. 8. Compile, save and close the form.
Create the Subform Next is to create the form that displays the comment lines for the customer. It is a worksheet form that fits into the subform on the My Customer Card form. 1. In the Object Designer's Form list, click the New button. The New Form window opens. 2. Create a tabular form by using the wizard that contains the Date and Comment fields from the Comment Line table. 3. Delete the OK, Cancel, and Help buttons. 4. Set the following properties for the table box: o Height: Height of the subform created earlier. o Width: Width of the subform created earlier. 5. Move the table box into the upper-left corner of the form and make the form size the same as the table box. 6. Set the following properties of the form: o BorderStyle: None o AutoSplitKey: Yes NOTE: Setting BorderStyle property to None shows the subform without a border. The AutoSplitKey is a characteristic of a Worksheet form that enables entering information to the associated table in a spreadsheet like manner. 7. Compile and save the form with the ID 90004 and the name My Customer Subform, and close the form.
FIGURE 3.47 MY CUSTOMER SUBFORM FORM
3-46
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms Add the Subform to the Main Form The following steps show how to add the subform to the main form by setting up the subform in the main form. 1. Design form 90002, My Customer Card, from the Object Designer. 2. Open the Properties window for the subform, and set the following properties: o SubFormID: My Customer Subform o SubFormLink: Table Name=CONST(Customer),No.=FIELD(No.) NOTE: Use the Assist-Edit button on the SubFormLink property to assist setting this property. The SubFormID property tells the main form what form to be shown in the subform. The SubFormLink property links the main form and the subform by using certain fields. 3. Close the Properties window. 4. Compile, save and close the form. 5. Run the form, and test the subform.
FIGURE 3.48 MAIN FORM AND SUBFORM WITH SOME RECORDS IN THE SUBFORM
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-47
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Lab 3.1 - Create a Card and a List Form The following lab tests the basic knowledge on how to create a card form, and a list form and how to link both forms together. Scenario Simon is a developer working for CRONUS International Ltd. CRONUS International has decided to start selling Microsoft Dynamics NAV training courses as its business. Simon has already created a Course table to record the courses information. Now, Simon must create forms to interface the Course table so that his users can insert, edit and delete course records as needed, by using Microsoft Dynamics NAV Classic client.
Challenge Yourself! 1. 2. 3. 4.
Create a Card form for the Course table. Create a List form for the Course table. Create a link from the List form to the Card form. Create a link from the Card form to the List form.
Need a Little Help? Create the Card form for the Course table. 1. Create a new Card form with the source table Course. 2. Include the following fields: Code, Name, Description, Duration, Price, Type and Active. 3. Compile, save and close the form.
Create the List form for the Course table. 1. Create a new List form with the source table Course. 2. Include the following fields: Code, Name, Description, Duration, Price, Type and Active. 3. Change the Editable property of the form to No. 4. Compile, save and close the form.
Create a link from the List form to the Card form. 1. 2. 3. 4.
3-48
Design the List form. Add a menu button to the form, and set its properties. Add a menu item on the menu button, and set its properties. Compile, save, and close the form.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms Create a link from the Card form to the List form. 1. 2. 3. 4. 5. 6.
Design the Card form. Add a menu button to the form, and set its properties. Add a menu item on the menu button, and set its properties. Compile, save and close the form. Design the Course table, and set its properties. Compile, save and close the table.
Step by Step Create the Card form for the Course table. 1. In the Object Designer's Form list, click the New button. 2. Type Course in the Table field. 3. Select Create a form using a wizard, leave the Card-Type Form selected and then click OK. The Card-Type Form Wizard opens. 4. Leave Yes selected. 5. Click Next. 6. Double-click the following fields: Code, Name, Description, Duration, Price, Type and Active. 7. Click Finish to end the wizard. 8. Compile and save the form with the ID 90010, and the name Course Card, and close the form.
Create the List form for the Course table. 1. In the Object Designer's Form list, click the New button. 2. Type Course in the Table field. 3. Select Create a form using a wizard, select the Tabular-Type Form and then click OK. The Tabular-Type Form Wizard opens. 4. Double-click the following fields: Code, Name, Description, Duration, Price, Type and Active. 5. Click Finish to end the wizard. 6. Change the Editable property of the form to No. 7. Compile and save the form with the ID 90011 and the name Course List, and close the form.
Create a link from the List form to the Card form. 1. Design form 90011, Course List, from the Object Designer. 2. Move the OK and Cancel buttons to the left, to make room for a new button. 3. On the Toolbox, click the Menu Button button. 4. Add a menu button between the Cancel and Help buttons.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-49
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 5. Set the following properties for the menu button: o Caption: Course o HorzGlue: Right o VertGlue: Bottom 6. Right-click the Course menu button, and then click Menu Items. 7. Click the first empty line, and type the following: Caption ShortCutKey Action Card
Shift+F5
RunObject
RunObject Form Course Card
8. Open the Properties window for the menu item, and set the following properties: o RunFormLink: Code=FIELD(Code) o RunFormLinkType: OnUpdate 9. Close the Properties window and close the Menu Designer. 10. Compile, save, and close the form.
Create a link from the Card form to the List form. 1. 2. 3. 4.
Design form 90010, Course Card, from the Object Designer. On the Toolbox, click the Menu Button button. Add a menu button to the left of the Help button. Set the following properties for the menu button: o Caption: Course o HorzGlue: Right o VertGlue: Bottom
5. Right-click the Course menu button, and then click Menu Items. 6. Click the first empty line, and type the following:
Caption ShortCutKey Action List 7. 8. 9. 10. 11.
3-50
F5
LookupTable
Close the Menu Designer. Compile, save and close the form. Design table 90010, Course, from the Object Designer Set the LookupFormID property of the table to Course List. Compile, save and close the table.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms
Standard Navigation The standard navigation between forms helps establish consistency throughout the application. Although it is optional, it is recommended that all customizations follow these standard navigations.
Card and List Forms Most master tables have both a Card and a List form. Because both forms access the same table, there are many standards about what each form must do: •
The user must be able to view and edit one record at a time on the Card form.
•
The user must be able to view, but not edit, all records on the List form. Making this a form that cannot be edited enables the user to start a search by typing in a particular column.
•
The user must be able to open the List form from the Card form in the following ways: o o o
•
Press F5. Click the List menu item on the menu button that has the same name as the table. Click the List button on the Toolbar. In this case, the user can select a new master record and then click OK to exit the List form and change the original Card form to the selected master record.
The user must be able to open a new card from the List form that displays the master record selected on the List form. Users can open this new card by pressing SHIFT + F5 or clicking the Card menu item on the menu button that has the same name as the table.
Master Statistics Forms Many master tables also have a Statistics form. The user must be able to open this form from either the Card or the List forms in the same way. The standard way of opening the Statistics form is with the shortcut key F9 or the Statistics menu item, on the menu button that has the same name as the table.
Master and Ledger Forms Every master table has at least one ledger table. The user must be able to open the Ledger form from the master record's Card, List and Statistics form. There are three ways to open the Ledger Form: •
Click the Drill-down button on a FlowField.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-51
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 •
Press CTRL + F5.
•
Click the Ledger Entries menu item on the menu button that has the same name as the table.
If a Drill-down button is clicked, only the records that are used to create the calculated value are displayed. This is the built-in drill-down functionality. If the shortcut key or the menu item is used, all ledger records for this particular master record are shown. This requires a RunFormLink property on the menu item that links the two tables. And to keep the two forms synchronized when the master form is updated, the RunFormLinkType property must be change to OnUpdate. NOTE: For performance reasons, always set the RunFormView property if the RunFormLink property is set. In fact, the sort selected in the RunFormView property must contain the fields listed in the RunFormLink property or performance will be decreased.
Journal Forms Every journal form has similar buttons at the bottom of the form. These buttons enable the user to either open another form or perform a task. Generally, the buttons on a journal form are as follows: •
A menu button named after the master table for the functional area. This menu button must contain menu items that enable the user to open the card form for the master table or open the Ledger form for the ledger entries. In both cases, the form opened must be linked to the master table record that the journal line is associated with.
•
A menu button named Posting. This menu button contains the following menu items related to posting the journal lines: o o o
3-52
Post Post and Print Test Report
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms
Summary Forms allow users to interact directly with Microsoft Dynamics NAV. They are effective means for users to view, organize, and add information to the Microsoft Dynamics NAV database. There are many standard forms available in Microsoft Dynamics NAV and C/SIDE provides a means for developers to customize the application to suit their users' requirements, by creating custom forms or by modifying existing forms. Developers are encouraged to work in Microsoft Dynamics NAV, become familiar with the various form types found in the application, and practice creating sample forms. This helps developers understand the users' needs, and become adept at providing forms that both meet those needs and integrate smoothly into the application.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-53
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Test Your Knowledge 1. True or False. All forms are bound. 2. True or False. The Form Wizard is not useful. 3. Which property must be set on the Command button for the RunObject property to work? 4. Which control enables a form to display more than one record at a time? 5. Which control enables one form to display another form? 6. Which property of a Text box binds it to a field in a table? 7. What form property binds a form to a table? 8. How is a menu item turned into a submenu on a menu button? 9. How is a label attached to another control so that the label follows the other control if it is moved? 10. What are the steps to create a List form for a table?
3-54
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 3: Forms
Quick Interaction: Lessons Learned Take a moment and write down three key points you have learned from this chapter 1.
2.
3.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3-55
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
3-56
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages
CHAPTER 4: PAGES Objectives The objectives are: •
Understand the concepts of pages and page components.
•
Describe Page Designer and Action Designer.
•
Create a simple page and add basic controls to the page.
•
Provide an overview of different page types and their characteristics.
•
Discuss best practices in designing pages.
•
Create a Card page, add a container, FastTabs and fields.
•
Create a List page and link it to the Card page.
•
Create a main page, a Part page and link the two pages.
Introduction In Microsoft Dynamics® NAV 2009, pages replace forms as the main way to display, enter and modify data. Pages provide an easy way to create a taskoriented, professional looking and dynamic user interface. Pages are used in the Microsoft Dynamics NAV RoleTailored client.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-1
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Page Fundamentals The main difference between forms and pages is that events and application logic called by pages are run on the Microsoft Dynamics NAV Service instead of on the client. These make Microsoft Dynamics NAV 2009 a much more secure, scalable and flexible application. The following shows components of a page and how they are related.
FIGURE 4.1 PAGE COMPONENTS AND THEIR RELATION
Pages are created and designed in the Page Designer that is accessed from the Microsoft Dynamics NAV Classic client.
Properties Page properties describe how a page behaves when it is displayed by the RoleTailored client. Pages have less properties than forms, and some are used in a similar manner, such as ID, Name, Caption and SourceTable. Pages also have distinct properties that are not available in forms, they are as follows: •
PageType
•
CardFormID
•
InstructionalTextML
•
LinksAllowed
Page properties are defined on the Properties window that can be edited when the page is opened in the Page Designer. The following steps show how to open the Properties window for the Customer Card page. In Microsoft Dynamics NAV Classic client: 1. On the Tools menu, click Object Designer. The Object Designer opens. 2. Click the Page button to open the Page list.
4-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages 3. Select page 21, Customer Card, and then click the Design button to design the Customer Card page. The Page Designer opens. 4. Scroll down to the blank line at the bottom of the page, and click View, Properties, or click the Properties button on the Toolbar.
NOTE: Alternatively, right-click the blank line at the bottom of the page, and then click Properties. 5. The Page - Properties window opens and shows the properties for the page. Here developers can view and modify properties for the Customer Card page.
FIGURE 4.2 THE CUSTOMER CARD PAGE AND ITS PROPERTIES
Triggers Triggers in pages work exactly like they do in forms. However, some triggers are not supported in the RoleTailored client. When upgrading from an earlier version of Microsoft Navision or Microsoft Dynamics NAV the transformation process converts all C/AL code to C# automatically and removes unsupported triggers. Pages contain fewer triggers than forms for two reasons: •
The RoleTailored client has improved behavior that is implemented directly into the controls that run on it. Some code previously necessary is now obsolete.
•
Pages are designed to optimize performance. This reduces requirements for existing form triggers.
Triggers in a page can be divided into three categories: •
Page triggers
•
Control triggers
•
Action triggers
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-3
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Examples of page triggers include OnOpenPage which contains statements that are executed when the page is opened, and OnModifyRecord which contains statements that are executed before the system accepts changes the user makes to a record. Triggers in a page are edited in the C/AL Editor which is accessed from the Page Designer.
Controls Page controls, just as form controls, are used to display data from the following: •
A database table field.
•
The value of a C/AL expression.
•
Bitmap pictures.
•
Static information such as a descriptive text.
The concept of bound and unbound controls remains the same as in forms. There are several new controls available in pages and some which are reimplemented for the RoleTailored client. New page controls include the following: •
FactBoxes
•
FastTabs
•
Cues
Depending on the page type, each page has a specific set of controls that is available only for that page. For example Cues are only used on Role Center pages and FastTabs are only used on Card and Document pages.
Control Properties Use page control properties to link controls to underlying tables and to determine what happens when information is entered into a field. Different page controls can have different sets of properties. For example, container, group and field controls, each have their own unique sets of properties. Unlike form control properties, page control properties do not describe how a control is positioned as an X and Y position. Page control properties are defined on the Properties window that can be edited when the page is opened in the Page Designer.
4-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages The following steps show how to open the Properties window for one of the controls (the General FastTab) in the Customer Card page. 1. Design page 21, Customer Card, from the Object Designer. 2. Click the line General FastTab (the line that has Caption General the second line from the top) and click View, Properties, or click the Properties button on the Toolbar. NOTE: Alternatively, right-click the General line and click Properties. 3. The Properties window opens and shows the properties for the control. Here developers can view and modify properties for the General FastTab.
FIGURE 4.3 THE GENERAL FASTTAB PROPERTIES
Expression as Property Value Several control properties allow for expressions as their value. This enables dynamic appearance of these controls, depending on the value of expression. For example, in a form, a text box control has a Visible property and its value is limited to Yes or No. In a page, a field's Visible property value is an expression. The field's visibility can be controlled by assigning an expression that returns TRUE or FALSE to its Visible property. The default value of properties that accept expression is instead of .
Control Triggers In pages, only field type controls and action controls have triggers. The following steps show how to view the triggers for the No. field in the Customer Card page. 1. Design page 21, Customer Card, from the Object Designer. 2. Click the No. field (the line that has SourceExpr No. - the third line from the top) and click View, C/AL Code, or click the C/AL Code button on the Toolbar.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-5
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 NOTE: Alternatively, right-click the No. field and then click CAL Code. 3. The C/AL Editor opens and shows the triggers for the No. field. Here developers can write C/AL statements to program certain activities when the any particular trigger is executed, for example, when the No. field is modified. NOTE: The triggers for the Customer Card page are also shown together with the triggers for the No. field.
FIGURE 4.4 THE NO. FIELD TRIGGERS AND THE CUSTOMER CARD PAGE TRIGGERS
Actions In the RoleTailored client for Microsoft Dynamics NAV, menu items are known as actions. Actions are displayed at the top of each page. Actions are created and modified from the Action Designer that is accessed from the Page Designer. Actions have their own properties and triggers, which can be accessed from the Action Designer. There are two locations to add Actions, in the page itself and in Cues. The following steps show how to open the Action Designer and view the properties and triggers of an action in the Customer Card page. 1. Design page 21, Customer Card, from the Object Designer. 2. Scroll down to the blank line at the bottom of the page, and click View, Actions. NOTE: Alternatively, right-click the blank line at the bottom of the page, and then click Actions.
4-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages 3. The Action Designer opens and shows all the Action controls in the Customer Card page.
FIGURE 4.5 THE ACTION DESIGNER
4. Click any of the Action (any of the line), and then click View, Properties. The Properties window opens and shows the properties for the current Action. 5. Close the Properties window. 6. Click any of the Action, and then click View, C/AL Code. The C/AL Editor opens and shows the triggers for the current Action.
Action Properties Action properties let a developer/administrator/super user change an action and decide how it is displayed in the RoleTailored client. For example, changing Promoted property from No to Yes promotes an action to the Action Pane. This makes it more prominent to end-users. The following properties change the way an action is displayed: Action Property
Purpose
Caption
Set the name of the Action that appears in the RoleTailored client.
Promoted
Promotes an action to the Actions Pane.
PromotedIsBig
Increases the size of the promoted action icon.
PromotedCategory
Determines the Actions Pane category. There are three categories to select from: New, Process, or Report.
Image
Lets an image to be associated with an Action.
Similar to page controls, some property value of action controls can be assigned to expressions instead of static selection of values. This enables multiple actions to be dynamically hidden/shown, depending on certain criteria. A good example for this usage is page 6510, Item Tracking Lines.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-7
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Action properties also define what activity is performed when users click the action, for example, the RunObject, RunFormLink and RunFormMode property. The concept is similar to the same properties in command button controls in forms.
Page Designer In Microsoft Dynamics NAV 2009, the introduction of the three-tier architecture together with the new RoleTailored client has entailed implementing some farreaching changes in the C/SIDE development environment. A new Page Designer is introduced to design, create and modify pages. Page Designer is accessed from the Object Designer. This means development is still done in the Object Designer on the Classic client that accesses the database directly and does not use the Microsoft Dynamics NAV Service. After designing pages in the Page Designer, developers save and compile objects in the usual manner and test the results in the RoleTailored client. The RoleTailored client for Microsoft Dynamics NAV displays data in pages. There are several different types of pages, such as List, Card and Role Center pages.
Control Type and Subtype When designing a page, developers specify a hierarchy of page elements and decide which data is displayed by each element instead of positioning controls on forms by specifying the X and Y coordinates. This frees developers from the tedious pixel-level editing and the static layout of Form Designer. The central activity in page design is specifying the contents of the page in relation to the different Microsoft Dynamics NAV page types such as List, Card, Journal, and Worksheet. In turn, when end-users view the pages and interact with the application, they can personalize the appearance of the parts of the application that they have access to. End-users can specify both the placement and the appearance of the elements within the page hierarchy that is defined by the developer/administrator/super user. Microsoft Dynamics NAV 2009 contains more personalization options than earlier versions of Microsoft Navision or Microsoft Dynamics NAV. There are several types of controls that can be added to a page. The following list groups controls into several broad categories.
4-8
Type
Purpose
Container
Act like a placeholder for other controls.
Group
Arrange other controls in a logical manner.
Field
The actual control that displays information.
Part
Display another page, chart or system part in a page.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages Every page element is a control with a specific type and subtype and every page has a container control to start with. There are three subtypes of container, they are as follows: Subtype
Purpose
ContentArea
General usage. An ordinary page (non-role center) has this as the top most element.
RoleCenterArea
Used for RoleCenter Page, instead of ContentArea.
FactboxArea
Used to define FactBox controls in a page.
Every page must have at least a container control as the top most element. The next control type is group. Group control is used to group several other controls together. There are four group subtypes, they are as follows: Subtype
Purpose
Group
Create FastTabs in card pages or group several controls together.
Repeater
Present data in a tabular format, such as in list page.
CueGroup
Create Cues, such as in the SO Processor Activities page.
FixedLayout
Fix layout of other controls, such as controls in the bottom section of Journals, example General Journals.
The other two control types are field and part. They do not have a subtype. Field control is the smallest entity in page elements. It is the actual control that is used to display: •
A database table field.
•
The value of a C/AL expression.
•
Bitmap pictures.
•
Static information such as a descriptive text.
Part control is used to show another page or system data as a part of the current page. There are several important properties for Part, namely: •
PartType
•
PagePartID
•
SystemPartID
•
ChartPartID
These properties define what kind of part is displayed in the page.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-9
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Action Designer In the RoleTailored client, each page has its own set of actions that appear in action menus under the command bar and in the Action Pane. Actions can be role specific and they make frequently used data easily accessed by users. The Action Pane contains actions that are especially important for users in the given context and therefore are promoted. It appears above the command bar and contains duplicates of actions from the action menus. In this manner, users can always find commands that are promoted even if the Action Pane is collapsed. The Action Pane is optional in Microsoft Dynamics NAV 2009. If no actions are promoted, then it collapses by default. For example, the Customer List page has three action menus: •
Actions
•
Related Information
•
Reports
The Customer List page also has three groups of promoted actions in the Action Pane, which are as follows: •
New
•
Process
•
Reports
FIGURE 4.6 THE CUSTOMER LIST PAGE
4-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages In addition to these actions that are located in the page itself, actions can also be positioned in a Cue. The Order Processor Role Center has an activities section which has several Cues with several actions.
FIGURE 4.7 THE ORDER PROCESSOR ROLE CENTER PAGE
When users click an action, another page is displayed or other functionality is triggered, such as displaying a preview of a report. Much of this functionality can be controlled by changing the action properties of the action in the action designer. Users are also able to customize actions by using the personalization dialogs that are available in the RoleTailored client. Some actions are generated by the system, such as View, Edit, New and Delete and cannot be changed, whereas other actions can be added or removed by an administrator/super user from the existing list by using the Action Designer. The Action Designer is accessed from the Page Designer.
Action Type and Subtype There are four types of action in page objects, they are as follows: •
Action Container
•
Action
•
Separator
•
Action Group
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-11
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Action Container is the top level element in the hierarchy and must always have a subtype. Other action types that sit under it do not have subtypes. Subtype is used to decide where in the page, an action will be positioned. Depending on the subtype, action can be put in the following positions: Subtype
Where it is positioned
Where used
Figure 4.8
NewDocumentItems
Action menu, Actions/New Document
All pages
1
ActionItems
Action menu, Actions, under Links
All pages
2
RelatedInformation
Action menu, Related Information
All pages
3
Reports
Action menu, Reports
All pages
4
HomeItems
Navigation pane, Home panel
Role Centers
5
ActivityButtons
Navigation pane, under Home panel
Role Centers
6
FIGURE 4.8 ACTION CONTROL POSITIONING
Action Containers must be unique in a page. There cannot be two Action Containers with the same subtype. For example, there can only be one Action Container with the Reports subtype.
4-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages Action Container must not be indented. Other Actions that sit under the Action Container must be one level indented or more, depending on its placement in the hierarchy. Action Group is used to group several actions that are related. For example, in Customer List page, several actions that show different information about a particular customer (Ledger Entries, Issued Documents and Bank Accounts) are grouped into Customer Action Group. Separator is a special type of action that does nothing. It is used to create a horizontal line to divide actions in the action menu. The action that represents the command itself is defined by using the Action type. An action with the Action type can be used to open another page, preview a report or run a C/AL code defined in the action triggers.
Demonstration: Create a Simple Page The following demonstration shows how to create a simple page, add basic controls to the page and how to work with some of their properties.
Create a Blank Page The following steps show how to create a blank page. 1. In the Object Designer's Page list, click the New button. The New Page window opens. 2. Click OK to create a blank page. The Page designer opens. There is no element yet in the page. 3. Compile and save the page by clicking File, Save As. The Save As dialog box opens. 4. Type 90001 in the ID and Custom Page in the Name, ensure that the Compiled check box is selected, and then click OK. This compiles and saves the page. 5. Close the page by closing the Page Designer. 6. On the Windows taskbar, click Start and then click Run.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-13
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 7. In the Run window, type the following string: dynamicsnav:////runpage?page=90001, where 90001 is the ID of the Custom Page, and then click OK, to run the newly created Custom Page. This opens the Custom Page in the RoleTailored client.
FIGURE 4.9 THE CUSTOM PAGE WITHOUT ANY CONTROLS
8. Close the page.
Select the Page Type and Attach a Source Table A blank page is unbound when it is created. It is not associated with any table. Also, a default page type (Card), is assigned to this page. The following steps show how to associate a blank page with a table and set the page type. 1. Design form 90001, Custom Page, from the Object Designer. 2. Open the Properties window for the page, and set the following property: o PageType: Card o SourceTable: Item
NOTE: SourceTable property accepts either the ID or the name of the table.
FIGURE 4.10 THE PAGE PROPERTIES
4-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages 3. Close the Properties window. 4. Compile, save and close the page. 5. Run page 90001, Custom Page. Notice the value that is shown in the title bar of the page. It shows the first item from the Item table.
FIGURE 4.11 THE CUSTOM PAGE WITH SOURCE TABLE ITEM
6. Close the page. The Custom Page is now attached to the Item table. Unlike the Card form in the Classic client, where records can be travelled through by clicking the Next and Previous button, the Card page in the RoleTailored client shows only a single record. To move between records, use a List page, and then open the Card page for a specific record.
Add a Container The Custom Page is useless without any controls in it. Every page that has controls must have a container control as the top most element of the page, in the Page Designer. The following steps show how to add a container to the page. 1. Design form 90001, Custom Page, from the Object Designer. 2. Type the following on the first line of the Page Designer: Name
Type
SubType
Custom Page
Container
ContentArea
FIGURE 4.12 ADD A CONTAINER TO THE PAGE
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-15
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Add a FastTab FastTab is a new control introduced in Microsoft Dynamics NAV 2009. The concept is similar to a tab control in forms. These steps show how to add a FastTab to the Custom Page. 1. Go to the next blank line. The page elements automatically indent. 2. Type the following: Caption
Type
SubType
General
Group
Group
This is the first FastTab in the page and it is named General.
FIGURE 4.13 ADD A FASTTAB TO THE PAGE
Add Simple Controls Field controls are the actual controls that are used to display data. These steps show how to add several fields into the page. 1. Type the following on the next several lines and ensure that they are indented under the General FastTab:
4-16
Type
SourceExpr
Field
"No."
Field
Description
Field
"Costing Method"
Field
"Profit %"
Field
Picture
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages
NOTE: Instead of typing the SourceExpr, click the Assist-Edit button next to SourceExpr and select from the list of available options. Alternatively, use the Field Menu to select multiple fields at the same time.
FIGURE 4.14 ADD FIELDS TO THE PAGE
2. Compile, save and close the page. 3. Run the page and view the changes.
FIGURE 4.15 THE CUSTOM PAGE WITH SEVERAL CONTROLS
The RoleTailored client displays the fields according to their data type. The Costing Method field is displayed as a drop-down list, the Picture field is displayed as an image and the rest of the fields are displayed as text boxes. This is because the Costing Method is of type Option and the Picture field is of type BLOB. The RoleTailored client adds the labels to the controls and positions the fields automatically.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-17
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 ExtendedDataType ExtendedDataType property is a new property introduced in Microsoft Dynamics NAV 2009. Depending on this property, the RoleTailored client displays fields differently to improve the user experience. The options available are as follows: •
None
•
Phone No.
•
Url
•
E-mail
•
Ratio
For example, a field that has ExtendedDataType property set to E-mail, located in a Card page, is displayed by the RoleTailored client together with a small email button next to the field. When users click this button, the default e-mail client opens with the value from the field copied to the recipient list.
FIGURE 4.16 FIELDS WITH EXTENDEDDATATYPE PROPERTY SET IN THE CUSTOMER CARD PAGE
Display a Progress Indicator An indicator creates a way for the user to easily view the percentage of a value in a graphical manner. The following steps show how to display a progress indicator for the profit of an item by setting the ExtendedDataType property. 1. Design form 90001, Custom Form, from the Object Designer. 2. Set the following properties for the Profit % field: o MaxValue: The same value as the value of the same property of the Profit % field in the Item table
4-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages o
ExtendedDataType: Ratio
FIGURE 4.17 SET THE EXTENDEDDATATYPE PROPERTY
3. Close the Properties window. 4. Compile, save and close the page. 5. Run the page and view the changes.
FIGURE 4.18 THE CUSTOM PAGE WITH AN INDICATOR
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-19
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Add a FixedLayout A FixedLayout control is used to fix certain controls together in a matrix-like format. It is used mostly in statistics pages. The following shows how to add the information about quantity available in inventory, purchase order and several other documents, in a matrix-like format, by using a FixedLayout control. 1. Design page 90001, Custom Page, from the Object Designer. 2. Add a FastTab named Test Fixed Layout and indent it to the same level as the General FastTab. 3. Type the following on the next several lines, under the Test Fixed Layout FastTab: Caption
Type
SubType
Group
FixedLayout
1
Inventory
Group
Group
2
Quantity on...
Field
Purch. Order
Group
Inventory Group
Field Prod. Order
Group Group
Group
Sales Order
Group
Group
Service Order
Group Field
4-20
3 3 2
"Qty. on Component Lines" Group
Field
3
2 "Qty. on Prod. Order"
Field
Indent
2 "Qty. on Purch. Order"
Field Component Lines
SourceExpr
3 2
"Qty. on Sales Order" Group
3 2
"Qty. on Service Order"
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
3
Chapter 4: Pages The Indent column represents how many levels each rows are indented under the Test Fixed Layout FastTab. (The FixedLayout control is one level under the Test Fixed Layout FastTab and the Inventory Group is two levels under the Test Fix Layout FastTab and so on.)
FIGURE 4.19 ADD A FIXEDLAYOUT TO THE PAGE
4. Compile, save, and close the page. 5. Run the page and view the changes.
FIGURE 4.20 THE CUSTOM PAGE WITH A FIXEDLAYOUT
Add a Repeater A repeater control enables the page to display more than one record at a time. The following steps show how to add a repeater to show multiple item records. 1. Design form 90001, Custom Form, from the Object Designer. 2. Add a FastTab named Test Repeater and indent it to the same level as the General FastTab.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-21
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 3. Type the following on the next blank line to add the repeater and ensure that it is indented under the Test Repeater FastTab. Type
SubType
Group
Repeater
NOTE: Adding a repeater to a Card page is not logical. Repeater control is used extensively in a List page. The steps here are only meant to demonstrate how to add and use the repeater control on a page.
Use the Field Menu A repeater without field controls underneath it is like a table box without any text box in it. It shows a grid, without any columns. Add fields to under the repeater to show columns in the repeater. Use the Field Menu to efficiently add fields to a page. 1. Click View, Field Menu or click the Field Menu button on the Toolbar. The Field Menu window opens. 2. Select the No., Description, and Base Unit of Measure, and then click the line under the Repeater. NOTE: Hold the CTRL key while selecting the fields in the Field Menu window to select multiple fields.
4-22
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages 3. Click Yes for the confirmation message.
FIGURE 4.21 ADD REPEATER AND FIELDS
4. Compile, save, and close the page. 5. Run the page, and view the repeater under the Test Repeater FastTab.
FIGURE 4.22 THE CUSTOM PAGE WITH REPEATER
The repeater displays several rows of records from the item table. The title bar of the form changes according to the row selected in the table box.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-23
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Add Actions The following steps show how to add an action that enables end-users to open a related report from the page. 1. Design form 90001, Custom Form, from the Object Designer. 2. Open the Action Designer for the page. 3. Type the following on the first line: Type
SubType
ActionContainer
Reports
FIGURE 4.23 ADD AN ACTION CONTAINER
4. Go to the next blank line. The page element automatically indents. 5. Type the following: Caption
Type
Inventory - List
Action
FIGURE 4.24 ADD AN ACTION
4-24
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages 6. Open the Properties window for the action, and set the following properties: o RunObject: Report Inventory - List o Promoted: Yes o PromotedCategory: Reports
FIGURE 4.25 SET ACTION PROPERTIES
7. Close the Properties window and close the Action Designer. 8. Compile, save, and close the page. 9. Run the page and test the action.
FIGURE 4.26 THE CUSTOM PAGE WITH AN ACTION
Page Types and Characteristics Page type is a new concept introduced in Microsoft Dynamics NAV 2009. Although forms are also categorized in types, they are not strictly bound to these. Pages are different in this case. Pages are interpreted differently in the
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-25
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 RoleTailored client, depending on their page type. Each page type also has different sets of controls that it can use. This makes page type the most important concept to understand when designing pages.
Card Page A Card page enables users to view and edit one record at a time. It is used when there are too many fields to view them all conveniently on only one line. A Card page always has FastTabs, instead of tabs. Even if there are few fields, there is at least one General FastTab, which is always first. Tables that use Card pages only have one field in their Primary Key and this field is always displayed as the first field in the General FastTab.
Naming Card Pages Card pages are named with the name of the associated table, followed by the word Card. For example, the card page associated with the Customer table is named Customer Card.
FIGURE 4.27 THE CUSTOMER CARD PAGE
List Page A List page is a multi-record page that enables users to view multiple records from a table at the same time. The Primary Key fields of the associated table are displayed in the left-most columns.
4-26
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages Naming List Pages If the List page cannot be edited, it is named with the name of the associated table, followed by the word List. For example, the List page associated with the Customer table is named Customer List. If the List page can be edited, it is named with the plural of the name of the associated table. For example, the List page associated with the Currency table is named Currencies.
FIGURE 4.28 THE CUSTOMER LIST PAGE
CardPart Page A CardPart page is used to display fields or a special control like a picture viewer, in a FactBox. Use a CardPart page to create a FactBox that has one column.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-27
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Naming CardPart Pages CardPart pages are named with the associated information, followed by the word FactBox. For example, the CardPart page that displays the sales history of the sell-to customer is named Sales Hist. Sell-to FactBox.
FIGURE 4.29 THE SALES HIST. SELL-TO FACTBOX PAGE
ListPart Page A ListPart page is used to display fields or a special control like a picture viewer, in a FactBox. Use a ListPart page to create a FactBox that has multiple columns.
Naming ListPart Pages ListPart pages are named with the associated information, followed by the word FactBox. For example, the ListPart page that displays the Dimensions is named Dimensions FactBox.
FIGURE 4.30 THE DIMENSIONS FACTBOX PAGE
4-28
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages Worksheet Page A Worksheet page is a multi-record page that enables users to view multiple records from a table and edit them. Worksheet pages differ from ordinary List pages, in that when the user inserts a new record, the record does not jump to another position within the page, but instead, the record stays in the same order in which the user inserted it. This order is done by using the AutoSplitKey property of the page, combined with an integer as the last field in the table's Primary Key. The Primary Key fields of the associated table are not displayed on the Worksheet page.
Naming Worksheet Pages Worksheet pages are named according to the purpose of the associated table. For example, for Journal tables, the name of the Worksheet page ends with the word Journal.
FIGURE 4.31 THE GENERAL JOURNAL PAGE
Document Page A Document page is a page that contains a series of FastTabs and Lines on the same page. It behaves in a similar manner to a Header/Line form in the Classic client.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-29
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Naming Document Pages The name of the Document page is the name of the document that it represents. For example, Sales Invoice.
FIGURE 4.32 THE SALES INVOICE PAGE
Role Center Page A Role Center page resembles a user home page that can be tailored to the needs of the user by adding different parts or controls. A Role Center page can contain a series of links to List pages in the Navigation Pane or can indicate to the user tasks that need their immediate attention, by using Cues in the Activity Centers. System parts can be used to display an Outlook Inbox or a Notes part and FactBoxes can be added to display important information, such as a list of customers.
4-30
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages Naming Role Center Pages Role Center pages are named with the name of the associated role, tailored to them, followed by the word Role Center. For example, the Role Center page associated with the Order Processor role is named Order Processor Role Center.
FIGURE 4.33 THE ORDER PROCESSOR ROLE CENTER PAGE
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-31
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Navigate Page The Navigate system dialog page is used for making searches based on individual posting transactions, such as page 344, Navigate in the Classic client.
FIGURE 4.34 THE NAVIGATE PAGE
ConfirmationDialog Page Use this page to ask the user a question that can be answered with minimal data input. Developers can add input fields so that users can decide how their answer should be formatted. If more than three or four fields are used in this page, consider using a task page instead.
4-32
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages ListPlus Page A ListPlus page contains FastTabs at the top of the page and a list at the bottom. While Document page only contains one list at the bottom of the page, a ListPlus page contains multiple lists. For example, page 397, Sales Invoice Statistics.
FIGURE 4.35 THE SALES INVOICE STATISTICS PAGE
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-33
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Design Pages: Best Practices After knowing the components that comprise a page and how they are defined in Page Designer, the following are some best practices when designing pages: •
Consider the types of users who use the new page and list the tasks that they perform.
•
Create a list of the fields, commands and links needed for the page.
•
Select the page type that best matches the content displayed on the page.
•
Set the source table of the page to the table that contains the primary set of data that the page displays.
•
Design the page by using Page Designer by specifying a hierarchy of page elements. Determine the details of how data is displayed by adjusting the properties of each element on the page.
•
Consider any supplemental sources of information that add value to the page and add these as FactBoxes. Perhaps existing FactBoxes can support the design.
•
Simplify the user experience by reducing what users view by default. This can be achieved by doing the following: o o o
4-34
Promote Actions to appropriate groups with the appropriate sequence and size. Set the Importance property to Additional for fields that are used less than three out of ten times. Display one to three FactBoxes by default.
•
Add the new page to the menu suite so that it is included on the Departments page.
•
If the page is a list place, consider specific user profiles to have a link to this page from their RoleCenter page.
•
If the page is a task page, consider which list places from which it is useful to link to, and add the link.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages
Demonstration: Create a Card Page The following demonstration shows how to create a Card page, add several fields to the card form by using the Field Menu and add parts to the page.
Create a Blank Page The following steps show how to create a Card page. 1. In the Object Designer's Page list, click the New button. The New Page window opens. 2. Type Customer in the Table field. 3. Select Create blank page of type, select Card, and then click OK.
FIGURE 4.36 THE NEW PAGE WINDOW
The Page Designer opens a blank page and automatically sets the Page Type property to Card.
Add a Container, FastTabs and Fields The following steps show how to add a FastTab and Fields to the page. 1. Type the following on the first line of the Page Designer: Name
Type
SubType
My Customer Page
Container
ContentArea
2. Go to the next blank line. The page elements automatically indent. 3. Type the following to add a FastTab named General: Caption
Type
SubType
General
Group
Group
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-35
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 4. Click View, Field Menu or click the Field Menu button on the Toolbar. The Field Menu window opens. 5. Select the No., Name, Address, City and Balance, and then click the line under the General FastTab. 6. Click Yes for the confirmation message. 7. Go to the next blank line, and type the following to add another FastTab named Others: Caption
Type
SubType
Others
Group
Group
8. Indent the Others FastTab to the same level as the General FastTab. 9. Click View, Field Menu or click the Field Menu button on the Toolbar, select the Territory Code, Global Dimension 1 Code, and Global Dimension 2 Code, and then click the line under the Others FastTab. 10. Click Yes for the confirmation message. 11. Compile and save the page with the ID 90002, and the name My Customer Card, and close the page.
FIGURE 4.37 MY CUSTOMER CARD PAGE
12. Run the page, and test the FastTabs and fields.
Add Parts to the Page Supplemental information such as the historical transaction for a Customer and Customer statistical information can be useful when viewing the page. FactBoxes give users a way to view this information as part of a page.
4-36
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages The following steps show how to add parts to a page: 1. Design page 90002, My Customer Page, from the Object Designer. 2. Go to the next blank line, and type the following: Type
SubType
Container
FactBoxArea
3. Indent it at the same level as the first container. 4. Go to the next line, and type Part as the Type. This add a part control to the page. 5. Still on the same line, click View, Properties to open the Properties window for the Part control. 6. Set the following properties: o PartType: Page o PagePartID: Customer Statistics FactBox o SubFormLink: No.=FIELD(No.) This adds the Customer Statistics FactBox of the specific Customer as a part of the page. 7. Repeat steps 4 to 6 for Customer Details FactBox. NOTE: Other PartTypes which include System and Chart can also be added to a page.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-37
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 8. Compile, save, and close the page. 9. Run the page and test the FactBoxes.
FIGURE 4.38 MY CUSTOMER CARD PAGE
Demonstration: Create a List Page The following demonstration shows how to create a List page.
Create a List Page The following steps describe how to create a new List page from scratch. 1. Create a blank page of type List and attach the Customer table as the source table. 2. Set the following page properties: o Name: My Customer List o CardFormID: My Customer Card 3. Specify the ContentArea container and name it My Customer List. 4. Add a group control with a repeater subtype. 5. Add three field controls with SourceExpr No., Name, and Address.
4-38
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages 6. Compile and save the page with the ID 90003, and the name My Customer List, and close the page.
FIGURE 4.39 MY CUSTOMER LIST PAGE
7. Run the page and test the repeater by double-clicking any of the records.
Demonstration: Page and Part Page Pages can also display information from a table other than that page's source table. One way to do this is to display FactBoxes in the page. Another way is to display another page within the first page. This is known as a part and achieved by using a part control. The following demonstration shows how to build two pages that are combined to show the customer records and the customer comments on one page.
Create a ListPart Page The following steps show how to create the page that displays the comment lines for the customer. It is a ListPart page that fits into the part control on the My Customer Card form. 1. In the Object Designer's Page list, click the New button. The New Page window opens. 2. Create a ListPart page that contains the Date and Comment fields from the Comment Line table. 3. Set the AutoSplitKey property of the page to Yes.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-39
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 4. Compile and save the page with the ID 90004 and the name My Customer Subform, and close the page.
FIGURE 4.40 MY CUSTOMER SUBFORM PAGE
Modify the Main Page The following steps show how to modify the main page to include the ListPart page as a Part. 1. Design page 90002, My Customer Card, from the Object Designer. 2. Add a part control under the last field of the General FastTab and name it Comment Lines. Indent it to the same level as the General FastTab.
FIGURE 4.41 ADD THE LISTPART PAGE TO THE MY CUSTOMER CARD PAGE
NOTE: Press F3 to insert a new line in between existing controls. 3. Open the Properties window for the part control, and set the following property: o PartType: Page o PagePartID: My Customer Subform o SubFormLink: Table Name=CONST(Customer),No.=FIELD(No.)
4-40
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages 4. Close the Properties window, and compile, save and close the page. 5. Run the page, and test the Part page. 6. Run page 90003, My Customer List and open My Customer Card for any customer. Test the ListPart page in My Customer Card.
FIGURE 4.42 MY CUSTOMER CARD PAGE WITH A LISTPART PAGE
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-41
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Lab 4.1 - Create a Card, a List and a ListPart Page The following lab tests the basic knowledge on how to create a Card page, and a List page and how to link both pages together. Scenario Simon is a developer working for CRONUS International Ltd. CRONUS International has decided to start selling Microsoft Dynamics NAV training courses as its business. Simon has already created a Course table to record courses information. Now, Simon must create pages to interface the Course table so that his users can insert, edit and delete course records as needed, by using the Microsoft Dynamics NAV RoleTailored client.
Challenge Yourself! 1. Create a Card page for the Course table. 2. Create a List page for the Course table.
Need a Little Help? Create a Card page. 1. 2. 3. 4.
Create a new Card page with the source table Course. Add a ContentArea container. Add a FastTab. Add the following fields: Code, Name, Description, Duration, Price, Type and Active. 5. Compile, save and close the page.
Create a List page. 1. 2. 3. 4. 5. 6.
4-42
Create a new List page with the source table Course. Set the page properties. Add a ContentArea container. Add a repeater. Add the following fields: Code, Name and Description. Compile, save and close the page.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages Step by Step Create a Card page. 1. In the Object Designer's Page List, click the New button. 2. Type Course in the Table field, select Create blank page of type, select Card, and then click OK. 3. Type the following on the first line to add the container control: Caption
Type
SubType
Course Card
Container
ContentArea
4. Type the following on the next line to add the General FastTab: Caption
Type
SubType
General
Group
Group
5. Click View, Field Menu, select Code, Name, Description, Duration, Price, Type and Active, and then click the line under the General FastTab. 6. Click Yes for the confirmation message. 7. Compile and save the page with the ID 90010, and the name Course Card, and close the page.
Create a List page. 1. In the Object Designer's Page List, click the New button. 2. Type Course in the Table field, select Create blank page of type, select List, and then click OK. 3. Open the Properties window for the page and set the following properties: o CardFormID: Course Card o Editable: No 4. Close the Properties window. 5. Type the following on the first line to add the container control: Caption
Type
SubType
Course List
Container
ContentArea
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-43
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 6. Type the following on the next line to add the repeater: Type
SubType
Group
Repeater
7. Click View, Field Menu, select Code, Name and Description, and then click the line under the repeater. 8. Click Yes for the confirmation message. 9. Compile and save the page with the ID 90011, and the name Course List, and close the page.
4-44
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 4: Pages
Summary Pages provide a flexible foundation for building many types of display objects. Compared to the Classic client that has card forms and list forms, the RoleTailored client has equivalent page types and several new ones that help build pages with special layouts. Pages also contain new types of controls that enable advanced representation of system data and shortcuts to system features.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
4-45
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Quick Interaction: Lessons Learned Take a moment and write down three key points you have learned from this chapter 1.
2.
3.
4-46
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Introduction to C/AL Programming
CHAPTER 5: INTRODUCTION TO C/AL PROGRAMMING Objectives The objectives are: •
Understand the concepts and basic use of C/AL code elements.
•
Understand the concepts of data types, simple data types and complex data types.
•
Understand the concepts of identifiers, variables, and syntax.
•
Describe the syntax of identifiers.
•
Describe the scope of variables.
•
Describe the initialization of variables.
•
Create a simple codeunit to show how to define variables, assign data types and investigate several default values initialized for several data types.
Introduction There are many purposes for computer programming languages. However, many of these are already handled by the standard Microsoft Dynamics® NAV objects. For example: •
Data presentation is handled through the form, page and report objects.
•
Data acquisition is mainly handled through form, page, dataport and XMLport objects.
•
Data storage and organization is handled by the table objects together with the built-in Database Management System (DBMS).
To create a coherent application in Microsoft Dynamics NAV, database objects must be made to work together. Client Application Language (C/AL) is the programming language that is used in the Client/Server Integrated Development Environment (C/SIDE), the development environment for Microsoft Dynamics NAV. C/AL code is used to bind all the database objects together to form a unified whole.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-1
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
C/AL Programming C/AL enables developers to create functions that extend the functionality of Microsoft Dynamics NAV. For example, special functions for use anywhere in the database. Not only that, C/AL also enables developers to do the following: •
Design custom functions
•
Connect database objects
•
Read, write, and modify data
In C/SIDE, the main purpose of the programming language is data manipulation. Through C/AL, developers can create business rules to ensure that the data which is stored in the tables is meaningful and consistent with the way customers do business. Through programming, developers can do the following: •
Add new data or transfer data from one table to another, for example, from a journal table to a ledger table.
•
Combine data from multiple tables into one report or display it on one form or page.
Another purpose of C/AL is to control the execution of the various application objects. With C/AL, developers can coordinate objects to meet the business needs of their customers.
Code Statements and Triggers C/AL code can be found in any Microsoft Dynamics NAV object. The codeunit object is used only for programming. Codeunits consist of programming language statements, also known as C/AL statements or code. The following steps show how to open the C/AL Editor to view triggers in the DateFilter-Calc codeunit. In Microsoft Dynamics NAV Classic client: 1. On the Tools menu, click Object Designer. The Object Designer opens.
5-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Introduction to C/AL Programming 2. Click the Codeunit button to open the Codeunit list. 3. Select codeunit 358, DateFilter-Calc, and then click the Design button to design the DateFilter-Calc codeunit.
FIGURE 5.1 THE DATEFILTER-CALC CODEUNIT IN C/AL EDITOR
NOTE: The Codeunit Designer is the C/AL Editor itself. In any other designer, such as the Form Designer, to access the C/AL Editor, click View, C/AL Code, or click the C/AL Code button on the Toolbar, or press F9. Each shaded bar in the codeunit is known as a trigger. The C/AL code under the shaded bar is the trigger code for that trigger. If there is no C/AL code between one trigger and the next trigger, then that trigger is empty. In the DateFilter-Calc codeunit, there is no trigger code in the OnRun trigger section. Therefore the OnRun trigger is empty. There are three kinds of triggers: •
Documentation triggers. A documentation trigger is used to write documentation for a particular object. This is not really a trigger and no code in this trigger is run. Many developers use this space to document their modifications to standard objects. Every object has a documentation trigger.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-3
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 •
Event triggers. The name of these triggers always starts with the word On. The C/AL code in an event trigger is run when the named event occurs. For example, the code in the OnRun event trigger is executed when a codeunit that contains the trigger is run. In the DateFilter-Calc codunit, because there is no trigger code in the OnRun trigger, nothing happens when the codeunit is run. Each object has its own set of predefined event triggers.
•
Function Triggers. These triggers are created when developers create a function in an object. The C/AL code in the function trigger is executed when the function is called. For example, the DateFilterCalc codeunit has three function triggers: CreateFiscalYearFilter, CreateAccountingPeriodFilter and CreateAccountingDateFilter.
Accessing C/AL Reviewing C/AL code in a standard object can help developers to become familiar with the code elements in that object. The following steps show how to access C/AL code in the Customer table. 1. Design table 18, Customer, from the Object Designer. The Customer table opens in the Table Designer. 2. Click View, C/AL Code, or click the C/AL Code button on the Toolbar, or press F9, to open the C/AL Editor. The C/AL Editor opens and shows the triggers for the Customer table and its fields.
FIGURE 5.2 THE CUSTOMER TABLE IN C/AL EDITOR
5-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Introduction to C/AL Programming There are many triggers in this table, many of which are empty. Each field has an OnValidate and an OnLookup trigger. These are event triggers. The code in these triggers is run when the respective event occurs, for example, when the user triggers the event.
Intrinsic Data Types Data are pieces of information. Data refers to information that is available in Microsoft Dynamics NAV. Data types are the classifications of this information. Classifying data is important because it indicates how the application must handle data when running code. Different data types have different values, different meanings for those values, and are manipulated differently. Data types might be numeric or text. For example, if developers have two data values, 25 and 37, and add them, they then obtain different results, depending on the values' data type. If the values are numeric, the result is 62. However, if they are text, the result may be 2537. Constants Constants are data values written directly into programming statements. They are called constants because their values never change while the application is running. Constants can only be changed by changing the C/AL code. Simple Data Types Simple data types are data types that have only one value. They cannot be broken up into other values of different types. Byte A byte is a unit of data storage space that is used in computers. One character stored in the computer uses one byte of storage. The following are several related terms: Byte Type
Number of Bytes
Other Value
Kilobyte (KB)
1,024
Megabyte (MB)
1,048,576
1024 KB
Gigabyte (GB)
1,073,741,824 bytes
1024 MB
Numeric Data Types Numeric data types are all forms of numbers or amounts. There are many automatic methods that are used by Microsoft Dynamics NAV to convert one type of number to another behind the scenes. In many cases, numeric data types can be used interchangeably. However, their differences can be very important, sometimes causing errors and sometimes causing more subtle problems.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-5
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Integer An integer is a whole number that can range in value from -2,147,483,647 to +2,147,483,647. The default value of an integer is zero. Typical constants of type Integer in C/AL are as follows: •
12
•
1000 (there are no commas as they are invalid in numeric constants)
•
-100
•
0
BigInteger BigInteger is used to store large whole numbers. It is a 64-bit integer. An L is added to the constant definition to inform C/AL that an integer must be interpreted and treated as a BigInteger. Typical constants of type BigInteger in C/AL are as follows: •
1L
•
455500000000L
Decimal A decimal is a whole or fractional number that can range in value from 999,999,999,999,999.99 to +999,999,999,999,999.99. The default value of a decimal is zero. In Microsoft Dynamics NAV 2009, the Decimal data type is mapped to the Microsoft .NET 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. Typical constants of type Decimal in C/AL are as follows: •
12.50
•
52000000000 (there are no commas)
•
-2.0
•
0.008
•
-127.9533
Option An option is a special kind of integer that enables developers to define words for each of the value. For example, if a developer creates a variable named Spectrum, he/she can set it to an Option data type with the following OptionString: Red,Orange,Yellow,Green,Blue,Indigo,Violet. The default value of an option is zero, because it is an integer. This represents the first element. In the Spectrum example, this is Red. Therefore, Green is represented by the integer 3. There are no spaces between the elements in the OptionString, as a space becomes part of the element's name.
5-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Introduction to C/AL Programming Char A char is a single character. For syntax purposes, it is considered as numeric data type and can have integer values from zero to 255. It can be used together with other numeric data types in expressions. Typical constants of type Char in C/AL are as follows: •
'b' (with single quotation marks surrounding the character)
•
'C'
•
'3'
•
'?'
String Data Types String data is data that is made up of strings of characters. The data in word processors is a string data. In spreadsheets, where most of the data is considered numeric, string data is entered by using a special prefix to distinguish it. In C/AL, the symbol used to distinguish string data is the single quotation mark, also known as an apostrophe ('). All string constants are enclosed in quotation marks.
Text A text is a string of 0 to 1024 characters (in the earlier version of Microsoft Dynamics NAV, this may be limited to 250 characters). The length of a text is the number of characters in it. Typical constants of type Text in C/AL are as follows: •
'Hello'
•
'127.50' (even though this resembles a number, because it is enclosed in quotation marks, it is a text)
•
'' (this is an empty, 0 length text)
•
' spaces before ... and after '
•
'Here''s how to use an apostrophe' (to put a single apostrophe in a text constant, insert two apostrophes)
Code A code is a special kind of text. All letters in a code are forced to uppercase and all leading and trailing spaces are removed. In addition, when it is displayed to the user, a code is automatically right-justified if all characters in it are numbers. The same text constants earlier, converted to code, are as follows: •
'HELLO'
•
'127.50'
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-7
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 •
''
•
'SPACES BEFORE ... AND AFTER'
•
'HERE''S HOW TO USE AN APOSTROPHE'
When using the Microsoft Dynamics NAV Native Database, to compare and sort two code values use the special right-justification feature. Therefore, for codes, 10 is greater than 9, but 10A is less than 9A. For texts, 10 is less than 9.
Boolean Data Types Boolean data, also known as logical data, is the simplest type of data. The constants of type Boolean in C/AL are as follows: •
TRUE
•
FALSE
If these values are compared, the FALSE value is less than the TRUE value because it is stored as a zero and TRUE is stored as one. However, the integer value is not interchangeable with the constant of TRUE or FALSE. In code, the Boolean variable must be set to TRUE or FALSE, not zero or one.
Date, Time, and DateTime Data Types Date A date is a calendar date that can range in value from 1/3/0001 to 12/31/9999. In addition, the value of a date can be either a Normal Date or a Closing Date. The Closing Date represents the last second of the last minute of the last hour of the day. Therefore, it is greater than the Normal Date with the same calendar value. Typical constants of type Date in C/AL are as follows: •
123197D (December 31, 1997)
•
030595D
•
08171953D (August 17, 1953)
•
0D (The undefined date, less than all other dates)
•
063012D (June 30, 2012)
All these Date constants are Normal Dates. There are no Closing Date constants in C/AL. The general syntax is mmddyyD or mmddyyyyD. Two digits may be used for the year, which is translated differently in different versions of Microsoft Dynamics NAV. For versions 2.6 and later, if the year is from 30 to 99, it is considered in the 1900s and if it is from 00 to 29, it is considered in the 2000s. For version 2.01 through 2.5, the year 19 is considered as 2019, but year 20 is considered as 1920.
5-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Introduction to C/AL Programming The Date data type is defined by using a D at the end. If there is no D, then C/SIDE assumes that it is an integer and an error occurs because an integer cannot be assigned to a date. Also, in code, do not use slashes to separate the month, day, and year. Slashes imply division and an error occurs because an integer or a decimal cannot be assigned to a date variable.
Time A Time data type represents the time of day, and not a time interval. It ranges in value from 00:00:00 to 23:59:59.999. Typical constants of type Time in C/AL are as follows: •
103000T (10:30am)
•
154530T (3:45:30pm)
•
0T (The undefined time, less than all other times)
•
030005.100T (3:00:05.1am)
•
225930.135T (10:59:30.135pm)
The general syntax is hhmmss[.xxx]T, where the fractions of seconds (.xxx) are optional. Similar to the Date data type, the Time data type must have a T at the end to distinguish it from the numeric data type.
DateTime A DateTime data type indicates a date and a 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 zero degrees longitude. The DateTime is always displayed as local time in Microsoft Dynamics NAV. Local time is determined by the time zone regional settings of the computer. DateTime data must be entered as local time. It is then converted to UTC by using the current settings for the time zone and daylight saving time. There is only one constant available for this data type that is the undefined datetime. •
0DT (The undefined DateTime)
Complex Data Types C/AL also contains several complex data types. Complex data types are used when developers work with, for example, records in tables, pictures (bitmaps) or disk files. As C/AL is object-based, each complex data type can include both member variables and member functions.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-9
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 BLOB The Binary Large Object (BLOB) data type is used to store memos (text), bitmaps (pictures), or user-defined types. Variables of this data type differ from ordinary numeric and string data type variables because they have a variable length. The maximum size of a BLOB is usually determined by the system's disk storage capacity, and the upper limit is 2GB.
Record The Record data type is a complex data type that consists of several simpler elements called fields. It 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 (frequently 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.
Form The Form data type is used to store forms. This is a complex data type and can contain several simpler elements called controls. Controls are used to display information to the user or to receive user input.
Codeunit The Codeunit data type is used to store codeunits. This is a complex data type that can contain several user-defined functions.
File The File data type is used to give developers access to operating system files.
Dialog The Dialog data type is used to store dialog windows. Several functions are available for manipulating dialogs.
Report The Report data type is used to store reports. This is a complex data type that can contain several simpler elements called controls. Controls are used to display information to the user.
DateFormula The DateFormula data type is used to provide multi-language capabilities to the CALCDATE function. Variables of this data type contain a date formula that has the same capabilities as the ordinary input string for the CALCDATE function.
5-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Introduction to C/AL Programming GUID The Globally Unique Identifier (GUID) data type is used to give a unique identifying number to any database object. It is used for the global identification of objects, programs, records, and so on. Each value in a GUID is globally unique. This value is generated by an algorithm, developed by Microsoft. This guarantees the 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 textual representation is {12345678-1234-1234-1234-1234567890AB}.
TableFilter The TableFilter data type is used to apply a filter to another table. This data type can only be used when setting security filters from the Permission table.
RecordRef The RecordRef data type is a complex data type that identifies a row in a table. Each record consists of fields that form the columns of the table. A record is typically used to hold information about a fixed number of properties. A RecordRef object can refer to any table in the database. Use the RecordRef.OPEN function to select the table to be accessed. When the RecordRef.OPEN function is used, a new RecordRef object is created. This object contains references to the open table, filters, and the record itself and all the fields that it contains. If one RecordRef variable is assigned to another RecordRef variable, they both refer to the same table instance.
RecordID The RecordID data type is a complex data type that contains the table number and the primary key of a table. A RecordID can be stored in the database but filters cannot be set on a RecordID.
FieldRef The FieldRef data type is a complex data type that identifies a field in a table and gives developers access to this field. The FieldRef object can refer to any field in any table in the database.
KeyRef The KeyRef data type is a complex data type that identifies a key in a table and the fields in this key. This gives developers access to the key and the fields that it contains. The KeyRef object can refer to any key in any table in the database.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-11
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 InStream and OutStream The InStream and OutStream data types let developers read from or write to files and BLOBs. In addition, InStream and OutStream can be used to read from and to write to Automation objects and OCX data types.
Variant This data type can contain the following C/AL data types: •
Record
•
File
•
Action
•
Codeunit
•
Automation
•
Boolean
•
Option
•
Integer
•
Decimal
•
Char
•
Text
•
Code
•
Date
•
Time
•
Binary
•
DateFormula
•
TransactionType
•
InStream
•
OutStream
BigText The BigText data type is a complex data type that is used to contain large text documents. Data of the BigText data type cannot be displayed in the debugger or in a message window. BigText functions are used to extract part of a BigText and put in a text string that can be displayed. The maximum length of a BigText variable is 2,147,483,647 characters. This is the equivalent of 2GB.
5-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Introduction to C/AL Programming
Identifiers, Variables and Syntax An identifier is the name of a programming element. A variable is a location in memory where data of varying values is stored. A syntax can be thought of as the grammatical rules for using identifiers and variables.
Identifier An identifier is a name for something, or a way to identify something. Objects, variables, fields, and functions all have identifiers. They all have names by which they are referred. Not all items found in a program have identifiers. Among those that do not, are constants, operators, and certain reserved words. Instead, these items are referred to directly. One way to understand the difference is that programming elements which refer to something stored elsewhere in memory require an identifier to access them, whereas those that exist in the programming code itself and do not refer to anything outside, do not have an identifier.
Variable A variable is the reference to a value that can vary while the user runs the application. Additionally, a variable has the following characteristics: •
A variable refers to an actual location in memory where data is stored.
•
A variable has a name, also known as the identifier that is used by the developer in the program instead of an actual memory address.
•
A variable has a data type that describes the type of data that can be stored in the memory address.
•
A variable has a value that is the actual data currently stored in that memory address.
Syntax A Syntax is a set of grammatical rules that define the programming language. Programming lines or code that follow these rules are said to follow the correct syntax. The computer does not understand code that does not follow the correct syntax. They cannot be compiled or executed.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-13
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
The Syntax of Identifiers There are two ways that identifiers can be constructed in C/AL. The first is to follow the Pascal syntax. This means that the first character in the identifier must be either an underscore (_) or a letter (either upper or lowercase). Following this first character, developers can have up to 29 additional characters, each of which must either be a letter (upper or lowercase), an underscore, or a digit (a number from zero through nine). The second method does not follow the Pascal syntax. In this case, the identifier must be enclosed in double quotation marks (") when it is used within C/AL. Developers can use any characters except "control" characters (characters whose underlying ASCII code is from zero through 31 or 255) and the double quotation mark character itself ("). Developers can also use spaces. When using the second method, the number of characters in an identifier can still include 30 characters and these 30 do not include the quotation marks. C/SIDE does not differentiate between upper and lowercase letters in identifiers. Therefore, if there are two identifiers, "Account Number" and "Account number," they are seen as identical by C/SIDE. Within one object, all identifiers must be unique. An identifier cannot be the same as one of the reserved words (such as BEGIN or END) or an operator (such as DIV or MOD). If this happens, a syntax error occurs. In addition, two identifiers cannot have the same name in an object. If a reference is ambiguous, that is, if C/SIDE cannot tell what exact programming element is being referred to, it results in an error.
Variable Scope A variable scope can be thought of as the lifetime of a variable. A variable is usable, within its scope.
Global and Local Variables All variables have a defined scope. This is a defined set of locations where the variable can be accessed. A variable is said to have a global scope if it can be accessed anywhere in an object, and a local scope if it can only be accessed in a single trigger in an object. No variables can be accessed outside the object in which they are defined.
System Defined Variables Certain variables are automatically defined and maintained by the system. An example of this variable is Rec, found in table objects. Each object has its own set of system defined variables. Developers can use these variables without creating them or initializing their values.
5-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Introduction to C/AL Programming
Variable Initialization Before any C/AL code is executed, all developer-defined variables are initialized with certain values. •
For all variables with a numeric type, the value is zero (0).
•
For string variables, the value is an empty string (").
•
For Boolean variables, the initial value is FALSE.
•
For Date and Time type variables, the initial value is 0D (the undefined date) and 0T (the undefined time). The DateTime variable is initialized to 0DT.
Demonstration: Data Types and Variables Initialization The following demonstrations show how to create a simple codeunit as a medium to show how to define and use several variables, assign data types and investigate several default values initialized for each variable.
Create a New Codeunit The following steps show how to create a simple codeunit as a medium to work on. 1. In the Object Designer's Codeunit list, click the New button. The C/AL Editor opens. By default, a codeunit has two triggers, the documentation trigger and the OnRun event trigger. 2. Compile and save the codeunit by clicking File, Save As. The Save As dialog box opens. 3. Type 90000 in the ID and My Codeunit in the Name, ensure that the Compiled check box is selected, and then click OK. This compiles and saves the codeunit.
Define Variables Global variables are defined in the C/AL Globals window. They have a global scope. This means that they can be accessed anywhere in the object. The following steps show how to define global variables and assign data types. 1. Click View, C/AL Globals. The C/AL Globals window opens. Here developers can determine variables, text constants and functions.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-15
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 2. In the Variables tab, type the following: Name
DataType
Length
LoopNo
Integer
YesOrNo
Boolean
Amount
Decimal
When Was It
Date
What Time
Time
Description
Text
30
Code Number
Code
10
Ch
Char
Color
Option
FIGURE 5.3 THE C/AL GLOBALS WINDOW
3. Click the Color variable and then click View, Properties, or click the Properties button on the Toolbar. 4. The Color - Properties window opens and shows the properties for the variable. Here developers can view and modify properties for the color variable.
5-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Introduction to C/AL Programming 5. Set the following property: o OptionString: Red,Orange,Yellow,Green,Blue,Violet
FIGURE 5.4 THE COLOR - PROPERTIES WINDOW
6. Close the Color - Properties window and then the C/AL Globals window. 7. Compile and save the codeunit.
Display the Variables The following steps show how to write simple code to display the default value initialized by the system for the global variable. 1. Click the first line under the OnRun trigger, and type the following: MESSAGE('The value of %1 is %2','LoopNo',LoopNo);
2. Compile, save and close the codeunit.
FIGURE 5.5 THE MY CODEUNIT
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-17
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The MESSAGE Function The MESSAGE function enables developers to display a simple window with a single message in it, together with an OK button for the users to press when they have finished reading the message. Following the function identifier MESSAGE, this line of code contains the following: •
An opening parenthesis
•
A text constant
•
A comma
•
Another text constant
•
Another comma
•
The LoopNo variable
•
A closing parenthesis
•
A semicolon
When a function such as this is called, it is followed by its parameters enclosed in parentheses. There are three parameters here, each one separated from the others by a comma. The first parameter is a text and contains the actual message that will be displayed. This text has special substitution strings in it. A substitution string is allowed in certain functions, and consists of a percentage sign followed by a single digit from one to nine. When this function is executed at run time, the first substitution string (%1) is replaced by the first parameter following it, and the second substitution string (%2) is replaced by the second parameter, and so on. If the parameters are not text parameters (for example, the LoopNo parameter), it is automatically converted or formatted into text first before the substitution is performed.
Run the Codeunit The following steps show how to run the codeunit to view the result. 1. In the Object Designer's Codeunit list, select codeunit 90000, My Codeunit, and then click the Run button to run the My Codeunit.
5-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Introduction to C/AL Programming 2. Examine the dialog box.
FIGURE 5.6 THE MESSAGE DIALOG BOX
3. Click OK to close the dialog box. The first substitution string is replaced by the second parameter (the first parameter following the message) that is the text constant 'LoopNo'. The second substitution string is replaced by the third parameter (the second parameter following the MESSAGE function) that is the value of the variable LoopNo. The value of the integer LoopNo is automatically initialized to zero and that value is substituted into the message.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-19
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Lab 5.1 - Investigate Data Types This lab tests the basic knowledge of writing simple C/AL code to display the value of the variables. Scenario Simon is a developer working for CRONUS International Ltd. He is asked to examine the default value initialized for several data types.
Challenge Yourself! 1. Modify the code in the My Codeunit codeunit to display the name of the second variable (YesOrNo) and its value. Run the codeunit and note the resulting message. 2. Do the same for the following: o Amount o When Was It (Do not forget to enclose the variable name in double quotation marks when using it in the third parameter.) o What Time o Description o Code Number o Ch o Color
Need a Little Help? 1. Design the codeunit. 2. Type the code in the OnRun trigger to display each variable. 3. Compile, save and close the codeunit.
5-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Introduction to C/AL Programming Step by Step 1. Design codeunit 90000, My Codeunit from the Object Designer. 2. Click the first line under the OnRun trigger, and type the following: MESSAGE('The MESSAGE('The MESSAGE('The It"); MESSAGE('The MESSAGE('The MESSAGE('The Number"); MESSAGE('The MESSAGE('The
value of %1 is %2','YesOrNo',YesOrNo); value of %1 is %2','Amount',Amount); value of %1 is %2','When Was It',"When Was value of %1 is %2','What Time',"What Time"); value of %1 is %2','Description',Description); value of %1 is %2','Code Number',"Code value of %1 is %2','Ch',Ch); value of %1 is %2','Color',Color);
3. Compile, save and close the codeunit.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-21
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Summary C/AL is the programming language used in C/SIDE. It is found everywhere throughout the application. Like any other programming language, it has its own data types, identifiers, variables and syntaxes. Understanding standard objects help developers to become familiar with how Microsoft Dynamics NAV is programmed and to follow these standards.
5-22
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 5: Introduction to C/AL Programming
Test Your Knowledge 1. What is the programming language of C/SIDE called? 2. List three or more uses of programming code. 3. Where can programming language statements be found? 4. What is used to modify code in an object? 5. List the three basic kinds of triggers. 6. What key is pressed to view or modify code in an object (other than a codeunit object)? 7. What data type is used to store an employee's birthday? 8. What data type is used for an employee's name? 9. What data type is used for an employee's weekly salary (it must be recorded to the penny)? 10. What data type is used to record whether an employee is income tax exempt? 11. Write down the data type of this constant: 'You must enter a positive value.' 12. Write down the data type of this constant: 123197 13. Write down the data type of this constant: 327.01 14. Write down the data type of this constant: 3,498 15. Which complex data type is used to store bitmaps (pictures)? 16. Which complex data type corresponds to a row in a table? 17. What two data types are used to read from and write to objects of the Automation and OCX data types? 18. Which complex data type can contain up to two gigabytes of text data?
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
5-23
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Quick Interaction: Lessons Learned Take a moment and write down three key points you have learned from this chapter 1.
2.
3.
5-24
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Assignment Statements and Expressions
CHAPTER 6: ASSIGNMENT STATEMENTS AND EXPRESSIONS Objectives The objectives are: •
Understand the concepts of assignment, statement, and assignment statement.
•
Describe the syntax of statements and introduce the statement separator.
•
Describe automatic type conversions for string, numeric, and other data types.
•
Use assignment statements and the Symbol Menu.
•
Understand the concepts of expressions, terms, and operators.
•
Describe the syntax of an expression.
•
Describe the string operator.
•
Use the string operator.
•
Describe the MAXSTRLEN and the COPYSTR functions.
•
Use the MAXSTRLEN and the COPYSTR functions in an expression.
•
Define numeric expressions, arithmetic operators, and operator precedence.
•
Describe the arithmetic operators, and provide examples.
•
Use the arithmetic operators and examine the operator precedence.
•
Define relational and logical operators and expressions.
•
Describe the use of relational expressions for comparison.
•
Describe the use of relational expressions for set inclusion.
•
Describe the use of logical expressions.
•
Use logical and relational expressions in a page.
Introduction Assignment statements can be considered as one of the simplest statements in C/AL. There are many kinds of expressions that include string expressions, numeric expressions, relational and logical expressions. Assignment statements and expressions are pieces that are used to create code in C/SIDE. Understanding the assignment statements and the different kinds of expressions help developers write effective code in C/SIDE.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-1
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Assignment Statements Assignment statements assign a value to a variable. This means that a variable can represent different values at different times.
Assignment Assignment means setting a variable to a value. When a variable has a value, it keeps that value until another value is assigned to it or until the current set of code ends and the system no longer keeps track of the variable. C/AL has several assignment methods. One of these is the simple assignment statement.
Statement A statement in programming context is a single complete programming instruction written as code. A statement can be thought of as a code line, because usually developers write one statement per line. However, one statement may use several actual lines in the C/AL Editor and several statements may only be one line in the C/AL Editor.
Assignment Statement The assignment statement is a particular kind of statement that specifically assigns a value to a variable.
The Syntax of Statements Being able to assign different values to variables is a cornerstone for programming. Different programming languages have different syntax for assigning values to variables.
Function Call Statement Certain function calls, such as the MESSAGE function, can be a statement on its own. They are known as Function Call statements. The syntax of a Function Call statement is as follows:
The result of a function call varies depending on which function is called. Similarly, the syntax of the function call itself varies with the function being called.
Assignment Statement The syntax of an assignment statement is almost as simple as the syntax of the function call statement which is as follows: := <expression>
6-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Assignment Statements and Expressions The assignment statement evaluates the expression and assigns the resulting value to the variable. The term evaluation and expression are described in the next few lessons. For now, use either a constant or another variable on the right side of the colon equals, as a simple expression.
Assignment Operator The colon equals (:=) is known as the assignment operator. It is used to assign a value or an expression that evaluates to a value, to a variable.
The Statement Separator A single programming statement might cover several code lines and one code line may consist of multiple statements. Therefore, the C/AL compiler must be able to detect when one statement ends and another statement begins. It recognizes a statement separator as the indicator of a new statement. The statement separator is the semicolon (;). The following is the syntax of a trigger: [ <statement> { ; <statement> } ]
The brackets are used to indicate that whatever is enclosed in them is optional. It can be present or not. The braces are used to indicate optional parts. Whatever is enclosed in the braces is considered optional and can be repeated zero or more times. In other words, it is optional for any statements to appear in a trigger and as many statements as preferred can appear in the trigger, as long as each statement is separated from the other statements by a semicolon. A statement must follow when a semicolon is used. If the last statement in a trigger ends with a semicolon, the C/AL compiler automatically inserts a Null statement after the last semicolon and before the end of the trigger. As the name implies, a Null statement is nothing and does nothing. Although this seems like a moot point now, be aware that the semicolon does not signal the end of a statement (it is not a statement terminator), but instead it signals the arrival of a new statement (it is a statement separator). This difference is important in understanding the syntax of certain other statements.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-3
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Automatic Type Conversions For a variable to be assigned a value, the type of the value must match the type of the variable. However, certain types, within limits, can be automatically converted during the assignment operation.
String Data Types Variables of both the string data types, code and text, can be automatically converted from one to the other. For example, if Description is a variable of type Text, and Code Number is a variable of type Code, the following statement is valid: "Code Number" := Description
The text value in the Description variable is converted into code before it is assigned to the Code Number variable. This means that all the lowercase letters are converted to uppercase and all leading and trailing spaces are deleted. Therefore, the value assigned to the code variable is of type Code. This conversion process does not affect the value that is stored in the Description variable. Variables on the right side of the assignment operator are not modified by the assignment operation. Only the variable on the left side of the assignment operator is modified. NOTE: There are limits to what can be done with the automatic conversion. For example, suppose that the value of the Description text variable has more characters than the maximum characters that can fit in the Code Number code variable. In this case, when the program runs and executes this statement, an error results. This is known as a run-time error.
Numeric Data Types Variables of the numeric data types (integer, decimal, option, and char) can be automatically converted from one to another, with several restrictions as follows:
6-4
•
A decimal value must be a whole number (without decimal components) to be converted to any of the other numeric data types.
•
If the value falls outside the range of the variable type, the conversion does not occur. For example, a decimal cannot be automatically converted to an integer or an option unless the value is between negative 2,147,483,647 and positive 2,147,483,647 which is the valid range for integers.
•
A decimal, integer, or option cannot be converted to a char unless the value is between 0 and 255 which is the valid range for chars. Any attempts of these conversions results in a run-time error.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Assignment Statements and Expressions Other Data Types Although variables of string data types can be automatically converted from one to the other and the same with variables of numeric data types, no other variable types can be automatically converted from one to another during assignment operation.
Demonstration: Use Assignment Statements and the Symbol Menu The following demonstration shows how to use assignment statements on several data types and introduces the C/AL Symbol Menu.
Create a Simple Assignment Statement Start with a simple statement as follows: 1. Design codeunit 90000, My Codeunit from the Object Designer. 2. Delete all code in the OnRun trigger. 3. Type the following code in the OnRun trigger: LoopNo := 25; MESSAGE('The value of %1 is %2','LoopNo',LoopNo);
4. Compile, save, and close the codeunit. 5. Run the codeunit.
Create Multiple Messages Add more code to the codeunit: 1. Design codeunit 90000, My Codeunit from the Object Designer. 2. Type the following code in the OnRun trigger, under the last line of code (assuming the Regional Settings for the date is MM/dd/yyyy): LoopNo := -30; MESSAGE('The value of %1 is %2','LoopNo',LoopNo); Amount := 27.50; MESSAGE('The value of %1 is %2','Amount',Amount); "When Was It" := 093097D; MESSAGE('The value of %1 is %2','When Was It',"When Was It"); "Code Number" := ' abc 123 x'; MESSAGE('The value of %1 is %2','Code Number',"Code Number");
3. Compile, save, and close the codeunit. 4. Run the codeunit.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-5
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The messages appear sequentially. The next message displays every time the OK button is clicked. At the last message (the one displaying the Code Number), the automatic type conversion occurred. The leading and trailing spaces are stripped, and the letters turned to uppercase when the value is converted from type text to type code. Messages do not display until after the processing has ceased. As the MESSAGE functions are called, messages are added to a queue. Only after the codeunit has completed its execution, are the messages read off the queue and displayed on the screen in the order in which they are put into the queue. Because messages do not display immediately, they do not interrupt the processing. This means that they cannot be used to give the users feedback on processing in progress. They can only be used to give the users results of processing.
Use the Symbol Menu Add additional lines to the codeunit, by using the Symbol Menu. 1. Design codeunit 90000, My Codeunit from the Object Designer. 2. Go to a new line at the end of the code in the OnRun trigger. 3. Click View, C/AL Symbol Menu, or press F5, or click the C/AL Symbol Menu button on the Toolbar. The C/AL Symbol Menu opens.
FIGURE 6.1 THE C/AL SYMBOL MENU
In the left panel, there is a list of all the identifiers defined by the developer, among other things. 4. Click the line that says YesOrNo, and then click OK. The C/AL Symbol Menu closes and the word YesOrNo appears in the code. 5. After YesOrNo, type the following:
6-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Assignment Statements and Expressions So that the line now reads: YesOrNo := TRUE;
6. Press ENTER and type the following on the next line: MESSAGE('The value of %1 is %2','
7. With the cursor just after the single quotation mark, press F5 again, ensure YesOrNo is selected in the C/AL Symbol Menu, and then click OK. 8. Type a single quotation mark (') and a comma (,). Press F5 again, and then press ENTER, which is the same as clicking OK on the C/AL Symbol Menu. 9. Type a closing parenthesis ()) and a semicolon (;). The result is as follows: YesOrNo := TRUE; MESSAGE('The value of %1 is %2','YesOrNo',YesOrNo);
10. Use this method again for Description, but set the value (located after the Assignment Operator) to 'Now is the time.' The result is as follows: Description := 'Now is the time. '; MESSAGE('The value of %1 is %2', 'Description',Description);
11. Again, use the C/AL Symbol Menu to enter another two lines setting and displaying "What Time". Set its value to 153000T. The result is as follows: By using the Symbol Menu, the double quotation marks are automatically inserted when it is necessary. In this case, the double quotation marks inside the single quotation marks are not needed. Therefore, go back and remove them. The results are as follows: "What Time" := 153000T; MESSAGE('The value of %1 is %2','What Time',"What Time");
12. Compile, save, close and run the codeunit. The Time and Date displays depend on the settings in the client system Control Panel (Regional Settings). On most United States systems, for example, the time is displayed in the format, 3:30:00 PM. However, a simple change on the Control Panel changes this display to 15:30:00. This does not require a code change, or even a recompile, under C/SIDE. The change in the Control Panel itself is sufficient.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-7
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Set Char Constants Because of automatic type conversion, a Char variable can be set by using either a number or a one character text. 1. Design codeunit 90000, My Codeunit from the Object Designer. 2. Type the following code in the OnRun trigger, under the last line of code: Ch := 65; MESSAGE('The value of %1 is %2','Ch',Ch); Ch := 'A'; MESSAGE('The value of %1 is %2','Ch',Ch);
3. Compile, save, and close the codeunit. 4. Run the codeunit. Both 65 and 'A' result in the same value displayed in the message. This is because 65 is the ASCII code for the uppercase A. Experiment with several other numbers to see what the results are. The ASCII codes can be used for characters in C/SIDE, and also in most other programs and computer systems.
Add Option Constants An option variable can be assigned by using a numeric value. In C/SIDE, there is one other syntax to write option constants and to assign option variables. 1. Design codeunit 90000, My Codeunit from the Object Designer. 2. Type the following code in the OnRun trigger, under the last line of code: Color := 2; MESSAGE('The value of %1 is %2','Color',Color); Color := Color::Yellow; MESSAGE('The value of %1 is %2','Color',Color);
3. Compile, save, and close the codeunit. 4. Run the codeunit. The results are the same for both messages. The first option is always numbered 0. So, the third option, in this case Yellow, is numbered 2. The syntax used for option constants is the Variable identifier, followed by two colons, followed by the Option identifier.
6-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Assignment Statements and Expressions Test Run-time Errors Not every value can be converted automatically to a value of another type. An attempt to convert types that cannot be automatically converted results in error messages. 1. Design codeunit 90000, My Codeunit from the Object Designer. 2. Type the following lines in the OnRun trigger, one-by-one. Compile, save, close and run the codeunit between each line of code, to view what kinds of error messages appear. Description := 'Now is the time. Here is the place.'; LoopNo := 27.5; YesOrNo := 1; Amount := 27.5; LoopNo := Amount;
Only the first and the fourth lines actually compile, as the compiler does not compile code that it recognizes not to work. For the first line, because both the constant and the variable are of type text, it is not until the codeunit is executed that the compiler discovers the overflow: Description is defined as 30 characters long. But the constant is 36. For the fourth line of code, the fact that the Amount contained a value that cannot be converted to an integer only found until the codeunit is executed. These kinds of errors are known as run-time errors. When a run-time error occurs, it stops all additional processing and produces an error message.
Expressions, Terms, and Operators Expressions, terms and operators are part of statements. An operator operates on one or more terms that makes up to an expression which in turn evaluates to a value.
Expression An expression is like an equation put into a program, a formula telling the computer exactly how to generate a desired value. Similar to a variable and a constant, an expression has a type and a value. A constant's value is known at all times and a variable's value is determined at run time. The system must look it up in memory. However, an expression must be evaluated at run time to determine its value. The following are examples of expressions: •
FunctionX + 7
•
Quantity * UnitCost
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-9
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Evaluation To evaluate an expression means to actually follow the instructions set out in the formula and determine the expression's type and value at that time. Depending on the values of the variables included in the expression, the value may be different every time that the expression is evaluated, although its type does not change.
Term A term is the part of an expression that evaluates to a value. It can be a variable, a constant or a function call, as long as the function returns a value. A term can also be another expression enclosed by parentheses. This kind of term is also known as a sub-expression. The previous examples of expressions have the following terms: •
FunctionX
•
7
•
Quantity
•
UnitCost
Operator An operator is the part of an expression that acts upon either the term directly following it (for example, a unary operator), or the terms on either side of it (for example, a binary operator). Operators are represented by symbols, such as +, >, /, =) or reserved words, such as DIV and MOD. They are defined by the C/AL and cannot be added or modified by the developer. When an expression evaluates and the operator operates on its terms, it results in a value that may be the value of the expression, or a term that is used by another operator. Some examples of operators and their uses are as follows:
6-10
Example
Remarks
5 + (-8)
The + is a binary arithmetic operator, the - is a unary arithmetic operator.
TotalCost/Quantity
The / is a binary operator.
'cat' + ' and dog'
The + is now used as a binary string operator.
(Quantity > 5) OR (Cost <= 200)
The OR is a binary logical operator. The > and <= are binary relational operators.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Assignment Statements and Expressions
The Syntax of an Expression Because of its complexity, describing an expression's syntax requires several more syntax statements than seen previously. The following list shows valid syntax for several kinds of operator. Operator Type
Valid Syntax
+ | - | NOT
<string operator>
+
<arithmetic operator>
+ | - | * | / | DIV | MOD
< | > | = | <= | >= | <> | IN
NOT | OR | AND | XOR
<string operator> | <arithmetic operator> | |
<simple term>
| | | (<expression>)
<simple term> | <simple term>
<expression>
{ }
The braces enclosing an element mean zero or more repetitions of that element.
The String Operator There is only one string operator and that is the plus sign (+) which indicates concatenation. Concatenation is the operation that joins two or more strings together to make one string. The concatenation operator is a binary operator. This means that it operates on the term preceding it and the term following it. Both terms must be strings. That is, either of type Code or Text. If both terms are of type Code, the resulting concatenation will be of type Code. Otherwise, it will be of type Text.
Evaluating Expressions The following code lines show an example of an expression and how it is evaluated. CodeA := 'HELLO THERE'; TextA := 'How Are You? '; CodeB := CodeA + '. ' + TextA;
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-11
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The third line of code is evaluated as follows: •
The value of CodeA is obtained. Then, the constant value is concatenated to the end. Because CodeA is a Code while the constant (a dot and a trailing space) is a Text, the result is a Text and the value is 'HELLO THERE. '. This value becomes the first term for the next concatenation operator.
•
The value of TextA is obtained. Then, this value is concatenated to the end of the previously generated text. Because both values are Text, the result is also of type Text and the value is 'HELLO THERE. How Are You?'. This is the end of the expression. Therefore, this result becomes the result of the expression, both the type and the value.
•
When the expression is evaluated, the new value is assigned to the CodeB variable by using the assignment operator. Because the expression is of type Text and CodeB is of type Code, the result of the expression must be converted to Code by using the automatic type conversion. The result of this conversion is 'HELLO THERE. HOW ARE YOU?' which is assigned to CodeB.
Demonstration: Use the String Operator The following demonstration shows how to use the string operator.
Use the String Operator 1. Create a new codeunit, and save it as codeunit 90001, My Codeunit 2. 2. Define the following global variables: Name
DataType
Length
CodeA
Code
30
CodeB
Code
50
TextA
Text
50
TextB
Text
80
3. Type the following code in the OnRun trigger: CodeA := 'HELLO THERE'; TextA := 'How Are You? '; CodeB := CodeA + '. ' + TextA; MESSAGE('The value of %1 is %2','CodeB',CodeB);
4. Compile, save, and close the codeunit. 5. Run the codeunit and examine the result.
6-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Assignment Statements and Expressions
Function Calls in Expressions When too many characters are assigned to a string variable, more than its maximum length, it results in a run-time error. One way to prevent this is to carefully design the program so that this error never occurs. However, it is not always possible to design the program to avoid errors caused by string length.
The MAXSTRLEN Function The MAXSTRLEN is a function that returns the maximum defined length of a string variable. This function has one parameter which is the string variable in question. The return value is of type Integer.
The COPYSTR Function The COPYSTR is a function that copies a substring of any length, from a specific position in a string (text or code) to a new string. This function has three parameters: •
The first parameter is the string to copy from (original string).
•
The second is the position of the first character to copy. For example, if the second parameter is 1, the function starts to copy from the first character, and if the second parameter is 5, the function starts to copy from the fifth character.
•
The third parameter is the number of characters to copy. This is optional and if it is not specified, the function copies from the start position specified in the second parameter, to the last character of the original string. If the number of characters to copy is more than the characters in the original string, the maximum number of characters of the original string is copied instead.
The return value is a string either of type Text or Code, depending on the type of the original string in the first parameter.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-13
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Demonstration: Use the MAXSTRLEN and the COPYSTR Function The following demonstration shows how to use the MAXSTRLEN and COPYSTR functions in an expression.
Use the MAXSTRLEN Function 1. Design codeunit 90001, My Codeunit 2 from the Object Designer. 2. Define the following global variables: Name
DataType
MaxChar
Integer
Description
Text
Length 30
3. Type the following code in the OnRun trigger, under the last line of code: MaxChar := MAXSTRLEN(Description); MESSAGE('The value of %1 is %2','MaxChar',MaxChar);
The result is that MaxChar is set to 30 which is the length of the Description variable. By using the MAXSTRLEN function, developers can know how many characters a variable can hold so that they can prevent overflowing the variable by carefully writing the code. 4. Type the following code, under the last line of code: Description := 'The message is: ' + CodeB; MESSAGE('The value of %1 is %2','Description',Description);
5. Compile, save, close and run the codeunit. The expected run-time error occurs. The assignment statement assigns the value of the expression on its right to the variable on its left. In this case, the expression results in a string that is longer than the maximum that the Description variable can hold, that is 30 characters.
Use the COPYSTR Function To copy a part of a string, or a substring, use the COPYSTR function. 1. Design codeunit 90001, My Codeunit 2 from the Object Designer. 2. Go to the line that assigns the Description variable. Description := 'The message is: ' + CodeB;
6-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Assignment Statements and Expressions 3. Edit the line to the following: Description := COPYSTR('The message is: ' + CodeB,1,MAXSTRLEN(Description));
4. Compile, save, close, and run the codeunit. The run-time error disappears. Instead, the value of the Description only includes the characters that fits, that is 30 characters.
How the COPYSTR Function Works The expression is what is to the right side of the assignment statement. Here is the original expression: COPYSTR('The message is: ' + CodeB,1,MAXSTRLEN(Description))
First, to evaluate a function like COPYSTR, evaluate each of its parameters. The first step, to evaluate the first parameter, is to obtain the value of CodeB and concatenate it (note the plus sign) with the string constant. The result is as follows: COPYSTR('The message is: HELLO THERE. HOW ARE YOU?',1,MAXSTRLEN(Description))
The next step is to evaluate the second parameter. Because this is a constant, it is straightforward. After that, evaluate the third parameter. This parameter is a function that returns the defined length of its parameter, which must be a variable, not an expression. The result is as follows: COPYSTR('The message is: HELLO THERE. HOW ARE YOU?',1,30)
Finally, the COPYSTR function itself can be evaluated. In this case, it copies characters from the text in the first parameter, starting with the first character, the second parameter, and copying up to 30 characters, the third parameter. The result is as follows: 'The message is: HELLO THERE. H'
Now that the expression is evaluated, the assignment can be performed: Description := 'The message is: HELLO THERE. H';
And the Description variable has its new value.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-15
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Numeric Expressions Numeric expressions are expressions that result in a numeric value. The individual terms in a numeric expression may not necessarily be numeric. Numeric expressions use at least one arithmetic operator. When a numeric expression is evaluated, the result is a numeric data type. This can be one of the following: decimal, integer, option, or char.
Arithmetic Operator Arithmetic operator is used in numeric expressions to operate on numeric or nonnumeric terms. Examples of arithmetic operators include addition, subtraction, multiplication, and division symbols.
Numeric Expression A numeric expression is an expression that results in a numeric value. The following are examples of numeric expressions: •
5+2*3
•
10 / 2
Operator Precedence Operator precedence is the order that operators are evaluated in an expression. Operators with a higher precedence are evaluated before operators with a lower precedence. For example, the multiplication operator (*) has a higher precedence than the addition operator (+). Therefore, the expression 5 + 2 * 3 evaluates to 11, instead of 21. This is the same under the normal left to right rule.
Arithmetic Operators There are six arithmetic operators in C/AL:
6-16
•
Plus Operator (+)
•
Minus Operator (-)
•
Times Operator (*)
•
Divide Operator (/)
•
Integer Divide Operator (DIV)
•
Modulus Operator (MOD)
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Assignment Statements and Expressions The Plus (+) Operator The plus operator is used for several purposes. It can be used as unary or a binary operator. If the terms on either side of the plus operator are both strings, the plus operator is used as a string operator, to concatenate the two strings. The plus operator that is used with the string term is not an example of an arithmetic operator, because the result is not numeric. If the plus operator has no term preceding it, it is used as a unary operator. When it is used as a unary operator, its purpose is not to change the sign of the term following it. It actually does nothing and is rarely used. If it is used, its purpose is to explicitly show that the value of the term is positive. The following is an example of an expression by using the plus operator as a unary operator, and then the same expression without it which evaluates to the same result. •
IntVariable * +11
•
IntVariable * 11
The plus operator is usually used as a binary operator. The purpose is to add the term following it to the term preceding it. Both terms can be numeric, or one term a numeric and the other a date or a time. The expression results to a different data type, depending on the type of the terms. •
If either term is a decimal value, the result is decimal.
•
If both terms are char values and the sum is less than 256, the result is char; otherwise, the result is integer.
•
If both terms are option or integer values and the sum is in the allowed values for integers, the result is integer; otherwise, the result is decimal.
•
If the term preceeding the operator is a date and the term following the operator is an integer, the result is a date that is the integer number of days away from the date term. Therefore, the result of 03202001D + 7 is 03272001D. If the resulting value is an invalid date, a run-time error occurs.
•
If the term preceeding the operator is a time and the term following the operator is an integer, the result is a time that is the integer number of milliseconds away from the time term. Therefore, the result of 115815T + 350000 is 120405T. If the resulting value is an invalid time, a run-time error occurs.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-17
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The plus operator used with a date or a time term is not an example of an arithmetic operator, because the result is not numeric. The following list shows combinations of the preceding and following terms, and their results. Plus (+)
Char
Option
Integer
Decimal
Date
Time
Char
Char
Integer
Integer
Decimal
N/A
N/A
Option
Integer
Integer
Integer
Decimal
N/A
N/A
Integer
Integer
Integer
Integer
Decimal
N/A
N/A
Decimal
Decimal
Decimal
Decimal
Decimal
N/A
N/A
Date
Date
Date
Date
N/A
N/A
N/A
Time
Time
Time
Time
N/A
N/A
N/A
The left column indicates the type of the term preceding the plus operator, whereas the top row indicates the type of the term following the plus operator. If the result is a char, but the value is not a valid char value, the result type changes to an integer. If the result is an integer but the value is not a valid integer value, the result type changes to a decimal.
The Minus (-) Operator Just as the plus operator, the minus operator can also be used as a binary operator or a unary operator. When it is used as a unary operator, its purpose is to change the sign of the term following it. When it is used as a binary operator, the minus operator's purpose is to subtract the term following it from the term preceding it. Both terms can be numeric, and both can be a date or a time, or the preceding term can be a date or a time when the following term is an integer. The expression results to a different data type, depending on the type of the terms.
6-18
•
If the first term is a date and the second is an integer, the result is a date that is the integer number of days before the date term. Therefore, the result of 02252001D - 7 is 02182001D. If the resulting value is an invalid date, a run-time error occurs.
•
If the first term is a time and the second is an integer, the result is a time that is the integer number of milliseconds before the time term. Therefore, the result of 115815T - 350000 is 115225T. If the resulting value is an invalid time, a run-time error occurs.
•
If one date is subtracted from another, the result is the integer number of days between the two dates. If one time is subtracted from another, the result is the integer number of milliseconds between the two times.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Assignment Statements and Expressions The following list shows combinations of the preceding and following terms, and their results. Minus (-)
Char
Option
Integer
Decimal
Date
Time
Char
Char
Integer
Integer
Decimal
N/A
N/A
Option
Integer
Integer
Integer
Decimal
N/A
N/A
Integer
Integer
Integer
Integer
Decimal
N/A
N/A
Decimal
Decimal
Decimal
Decimal
Decimal
N/A
N/A
Date
Date
Date
Date
N/A
Integer
N/A
Time
Time
Time
Time
N/A
N/A
Integer
The left column indicates the type of the term preceding the minus operator, whereas the top row indicates the type of the term following the minus operator. If the result is a char, but the value is not a valid char value, the result type changes to an integer. If the result is an integer but the value is not a valid integer value, the result type changes to a decimal.
The Times (*) Operator The times operator (or the multiplication operator) is used only as a binary operator. Its purpose is to multiply the numeric term preceding it by the numeric term following it. The following list shows combinations of the preceding and following terms, and their results. Times (*)
Char
Option
Integer
Decimal
Char
Char
Integer
Integer
Decimal
Option
Integer
Integer
Integer
Decimal
Integer
Integer
Integer
Integer
Decimal
Decimal
Decimal
Decimal
Decimal
Decimal
The automatic conversion rules, from char to integer, and integer to decimal, apply.
The Divide (/) Operator The divide operator is used only as a binary operator. Its purpose is to divide the numeric term preceding it by the numeric term following it. The result of this division is always of type Decimal. If the second term is zero (0), a run-time error occurs.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-19
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The Integer Divide (DIV) Operator The integer divide operator is used only as a binary operator. Its purpose is to divide the numeric term preceding it by the numeric term following it. The result type of this division is always of type Integer. If the second term is zero (0), a run-time error occurs. Any decimals that resulted from an ordinary division are dropped. Therefore, the result of 17 DIV 8 is 2, whereas the result of 17 DIV 9 is 1.
The Modulus (MOD) Operator The modulus operator (or the remainder operator) is used only as a binary operator. Its purpose is to divide the numeric term preceding it by the numeric term following it by using the integer division method and then return the remainder of that division. The result of this operation is always of type Integer. If the second term is zero (0), a run-time error occurs. The following shows examples of modulus operator usage. •
17 MOD 8 = 1
•
17 MOD 9 = 8
The modulus operator requires two numbers. The first number is the one that is converted by using the modulus function and the second number represents the number system being used. By definition the number system starts at zero and ends at the second number minus one. For example, if the second number is ten, the number system that is used is from zero to nine. Therefore, the modulus represents what the first number converts to, if the numbering system only had the number of values indicated by the second number and the first number is forced to restart from zero. The following example shows several modulus operations: •
15 modulus 10 is 5 (because 9 is the last number available, 10 is represented by going back from the start, or zero, 11 is 1, 12 is 2, and so on)
•
6 modulus 10 is 6
•
10 modulus 10 is 0
•
127 modulus 10 is 7
The result is the same if the first number is divided by the second by using an integer only and the remainder is returned as the value.
6-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Assignment Statements and Expressions Operator Precedence Levels There are three levels of operator precedence used for arithmetic operators. •
The highest level is the unary operator level. This includes both positive (+) and negative (-).
•
The second is the multiplicative operator level. This includes multiplication (*), both kinds of divides (/, DIV) and modulus (MOD).
•
The lowest precedence level is the additive operator level. This includes both addition (+) and subtraction (-) binary operators.
General evaluations of expressions proceed from left to right. However, if one operator has a higher precedence level than another, it is evaluated first. To override these, developers can create sub-expressions by enclosing parts of an expression with parentheses. Sub-expressions are always evaluated first.
Demonstration: Use the Arithmetic Operators The following demonstration shows how to use the arithmetic operators and examine the operator precedence.
Use the Arithmetic Operators 1. Create a new codeunit, and save it as codeunit 90002, My Codeunit 3. 2. Define the following global variables: Name
DataType
Int1
Integer
Int2
Integer
IntResult
Integer
Amt1
Decimal
Amt2
Decimal
AmtResult
Decimal
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-21
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 3. Type the following code in the OnRun trigger: Int1 := 25 DIV 3; Int2 := 25 MOD 3; IntResult := Int1 * 3 + Int2; MESSAGE('The value of %1 is %2','IntResult',IntResult); Amt1 := 25 / 3; Amt2 := 0.00000000000000001; AmtResult := (Amt1 - Int1) * 3 + Amt2; MESSAGE('The value of %1 is %2','AmtResult',AmtResult);
4. Compile, save, and close the codeunit. 5. Run the codeunit and examine the result. The result shows that the IntResult is 25 and AmtResult is 1.
Examine Operator Precedence This exercise shows the various division functions that includes normal division, integer division, and modulus. Examine the code and the results thoroughly to understand how it works. If it is necessary, insert other messages to view the intermediate results. 1. Design codeunit 90002, My Codeunit 3 from the Object Designer. 2. Type the following code in the OnRun trigger, under the last line of code: Int1 := 5 + 3 * 6 - 2 DIV -2; MESSAGE('The value of %1 is %2','Int1',Int1);
3. Compile, save, close and run the codeunit. The result is 24.
Examine the Precedence Rules These steps describe the precedence rules used to evaluate this code: 1. The times operator (*) is evaluated, multiplying its preceding term (3) by its following term (6) and resulting in a new term of 18, leaving the following: Int1 := 5 + 18 - 2 DIV -2
2. The integer divide operator (DIV) is evaluated, dividing its preceding term (2) by its following term (-2) and results in a new term of minus one: Int1 := 5 + 18 - (-1)
6-22
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Assignment Statements and Expressions 3. The plus operator (+) is evaluated, adding its following term (18) to its preceding term (5) and results in a new term of 23: Int1 := 23 - (-1)
4. The binary minus operator (-) is evaluated, subtracting its following term (-1) from its preceding term (23) and results in the value of the complete expression, which is 24 (23 minus a negative 1 is 24).
Add Sub-Expressions 1. Now, create sub-expressions by adding parentheses as follows: Int1 := (5 + 3) * (6 - 2) DIV -2;
2. Close, save, compile, and then run the codeunit. The result is negative 16.
Examine the Effect of Sub-Expressions Because sub-expressions are evaluated first, this code evaluates as follows: 1. The first sub-expression is evaluated. The plus operator (+) adds its following term (3) to its preceding term (5) and results in the subexpression value of 8. This value now becomes a term of the complete expression. Int1 := 8 * (6 - 2) DIV -2;
2. The next sub-expression is evaluated. The binary minus operator (-) subtracts its following term (2) from its preceding term (6) and results in the value of 4 for the sub-expression. Again, this value is now a term of the complete expression. 3. The unary minus operator (-) and its following term (2) is evaluated and results in a value of negative 2 (-2). 4. The times operator (*) is evaluated, multiplying its preceding term (8) by its following term (4) and results in a new term of 32. Int1 := 32 DIV -2;
5. The integer divide operator (DIV) is evaluated, dividing its preceding term (32) by its following term (-2) and results in the value of the complete expression, which is negative 16 (-16). Int1 := -16;
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-23
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Relational and Logical Expressions Logical and relational expressions are expressions that result in a Boolean value. These expressions use logical or relational operators to determine their value. When logical and relational expressions are evaluated, the result is always either TRUE or FALSE.
Relational Operator A relational operator is used in a relational expression to test a relationship between the term preceding it and the term following it. The available relational operators are as follows: •
= (equal to)
•
< (less than)
•
> (greater than)
•
<= (less than or equal to)
•
>= (greater than or equal to)
•
<> (not equal to)
•
IN (included in set)
Relational Expression A relational expression is an expression that compares values and results in a Boolean value. The individual terms in a relational expression usually are not of type Boolean. However, they must be comparable with one another. For example, an integer is comparable with a decimal, because both are numeric. But an integer is not comparable to a text, because one is numeric and the other is string. The following are examples of relational expressions: •
5 <= IntVar
•
DecVar <> IntVar
Logical Operator A logical operator is used in a logical expression with one or two Boolean terms. The available logical operators are as follows: •
AND
•
OR
•
XOR
•
NOT
Except for NOT, which is a unary operator, the rest of the logical operators are binary operators.
6-24
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Assignment Statements and Expressions Logical Expressions A logical expression is also an expression that compares values and results in a Boolean value. The difference from a relational expression is that the terms in a logical expression must all be of type Boolean. The following are examples of logical expressions: •
TRUE AND FALSE (This logical expression has two terms and it results to FALSE.)
•
FALSE OR NOT FALSE (This logical expression has two terms and two logical operators and it results to TRUE.)
•
(Quantity > 5 ) OR (Quantity <= 10) OR (Price < 100) (This expression is a combination of relational and logical expressions.)
Relational Expressions for Comparison Except for IN, all relational operators compare two values. These two values must be of the same type, or of comparable types. All the various numeric types (for example, integer and decimal) are comparable. Both the string types (text and code) are also comparable.
Numeric Comparisons If a comparison is performed between two numbers, the numeric rules apply. The following are examples of relational expressions for numeric comparisons: •
57 = 57 is TRUE
•
57 = 58 is FALSE
•
57 < 58 is TRUE
•
57 <= 58 is TRUE
•
57 > 58 is FALSE
•
57 >= 57 is TRUE
•
57 <> 58 is TRUE
String Comparisons In the Microsoft Dynamics® NAV Native Database, string comparisons use a modified alphabetical order, not the ASCII order. One difference is that special characters in languages such as the ø in Danish or the ñ in Spanish are positioned in their proper alphabetical order and not relegated to the end as they are in ASCII order. Another difference is that the digits are positioned after the letters in alphabetical order, whereas in ASCII order, they are positioned before the letters.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-25
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Finally, in alphabetical order, the lowercase letters are positioned before the uppercase letters, whereas in ASCII order, the lowercase letters are positioned after the uppercase letters. The following are examples of relational expressions for string comparisons: Relational Expression
In Native Database
'X' = 'X'
TRUE
'X' = 'x'
FALSE
'ark' > 'arc'
TRUE
'arC' > 'arc'
TRUE
'10' > '2'
FALSE
'00' <= 'OO'
FALSE
'é' > 'f'
FALSE
'abc' < 'ab'
FALSE
' a' <> 'a'
TRUE
There are some special rules when a code variable is used in a string comparison. All trailing and leading spaces are removed and all letters are converted to uppercase. In addition, code values that consist of only digits are right-justified before comparison. Therefore, in Native Database, the fifth expression in the previous example ('10' > '2') evaluates to TRUE if those values are assigned into variables of type Code before comparison.
Date and Time Comparisons Date and Time values are compared using the general calendar rule. Dates (or times) that are later in the future are greater than dates (or times) that are in the past. A Closing Date which represents the last second of the last minute of the last hour of the day, is greater than the Normal Date for the same day and less than the Normal Date for the next day.
Boolean Comparisons Usually, Boolean values are not compared by using relational operators. However, when they are, TRUE is considered greater than FALSE.
Relational Operator Precedence The relational operators have the lowest precedence of any operator. Relational comparison is performed after the expressions on either side of the relational operator are evaluated.
6-26
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Assignment Statements and Expressions Therefore, the following example evaluates to TRUE: •
5*7<6*6
The expression on the left side of the relational operator (5 * 7) is first evaluated to 35. Then the expression on the right side of the relational operator (6 * 6) is evaluated to 36. Then the value 35 is compared to 36.
Relational Expressions for Set Inclusion The IN relational operator is used to determine inclusion. It operates on two terms, and determines whether the preceding term is in the following term. The following term must be a list of values, or a set, to compare to. This list is part of the relational expression and is known as a set constant.
Set Constant There are no variables of type set. But there are constants of type set. A set constant is made up of an opening bracket ([) followed by a list of values separated by commas, and followed by a closing bracket (]). For example, a set of all the even numbers from one to ten looks as follows: [2,4,6,8,10]
In addition to individual values, a member of a set can also be a range of values. A set of all the numbers from one to twenty not evenly divisible by ten looks as follows: [1..9,11..19]
In addition, a specific value or a value that is used as part of a range can be an expression. A set of list of numbers from 10 to 20, but excluding the variable n (as long as n is from 10 to 20), looks as follows: [10..n-1,n+1..20]
The IN Operator The IN operator's operation is simple. It checks whether the value of the term preceding it is included in the term following it (the set). The following are examples of relational expressions for set inclusion: •
5 IN [2,4,6,8,10] is FALSE
•
5 IN [2,4..6,8,10] is TRUE
•
10 IN [1..9,11..19] is FALSE
•
'M' IN ['A'..'Z'] is TRUE
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-27
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Logical Expressions A logical expression evaluates Boolean terms and results in a Boolean value. In some cases, the Boolean terms are results of relational expressions.
Logical Operator Results The following reviews the logical operator results: •
The NOT operator, is a unary operator that logically negates the term following it. This changes TRUE to FALSE and FALSE to TRUE.
•
The AND operator results in TRUE if both of the terms on either side of it are TRUE and otherwise results in FALSE.
•
The OR operator results in FALSE if both of the terms on either side of it are FALSE and otherwise results in TRUE.
•
The XOR operator results in TRUE if both of the terms on either side of it are not the same and otherwise results in FALSE
The truth tables summarize these facts as follows:
FIGURE 6.2 THE LOGICAL OPERATOR TRUTH TABLES
Logical Operator Precedence The NOT operator has the same precedence as the other unary operators, positive (+) and negative (-) that is the highest precedence. This means that it is evaluated before any other operator in the same expression. The AND operator has the same precedence as the multiplicative operators, whereas the XOR and OR operators have the same precedence as the additive operators. The relational operators have the lowest precedence of all.
6-28
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Assignment Statements and Expressions The following table summarizes the operator precedence of all the operators covered to this point: Type of Operator
Operator
Comments
Sub-expression or Terms
( ) [ ] . ::
Sub-expression in parentheses is evaluated first.
Unary
+ - NOT
Highest precedence in an expression.
Multiplicative
* / DIV MOD AND
Additive
+ - OR XOR
Relational
< <= = >= > <> IN
Lowest precedence in an expression.
Range
..
Used in Set Constants.
When dealing with logical expressions, be aware that the relational operators are lower in precedence than the logical operators. For example, to see whether a variable N is between 10 and 20 exclusively, the following expression cannot be used: •
N >= 10 AND N <= 20
This is because, the first operator to be evaluated is the AND operator, and the preceding (10) and following (N) terms are an integer, and not Boolean terms. This causes an error. Instead, use parentheses to force the relational operators to be evaluated first, as follows: •
(N >= 10) AND (N <= 20)
With the parentheses, the two relational expressions are evaluated first and results in two Boolean terms. Then the logical expression with the AND logical operator and the two Boolean terms, can be evaluated.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-29
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Demonstration: Use Logical and Relational Expressions in a Page The following demonstration shows how to use logical and relational expressions in a page.
Create a New Page and add Variables to the Page 1. Create a new blank page, and save it as page 90005, My Test Page 1. 2. Design page 90005, My Test Page 1, from the Object Designer. 3. Click View, C/AL Globals and define the following global variables: Name
DataType
Value1
Integer
Value2
Integer
Result
Boolean
4. Close the C/AL Globals window. 5. Compile and save the page.
Add Controls to the Page 1. Type the following on the first line of the Page Designer, to specify the ContentArea container and name it My Test Page 1: Caption
Type
SubType
My Test Page 1
Container
ContentArea
2. Go to the next line and type the following to add a FastTab named General. Ensure it is indented under the container control. Caption
Type
SubType
General
Group
Group
3. Go to the next line and type the following to add a group control with Caption Input. Ensure it is indented under the General FastTab.
6-30
Caption
Type
SubType
Input
Group
Group
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Assignment Statements and Expressions 4. Go to the next line and type the following to add two field controls with SourceExpr Value1 and Value2. Ensure they are indented under the Input group. Caption
Type
SourceExpr
Value 1
Field
Value1
Value 2
Field
Value2
5. Go to the next line and type the following to add a group control with Caption Output. Indent it to the same level as the Input group. Caption
Type
SubType
Output
Group
Group
6. Go to the next line and type the following to add a field control with SourceExpr Result. Ensure it is indented under the Output group. Caption
Type
SourceExpr
Result
Field
Result
FIGURE 6.3 MY TEST PAGE 1
7. Compile and save the page.
Add an Action and C/AL Code to the Page 1. Open the Action Designer for the page. 2. Type the following on the first line of the Action Designer to add an ActionContainer. Type
SubType
ActionContainer
ActionItems
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-31
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 3. Go to the next line and type the following to add an action. Ensure that it is indented under the ActionItems ActionContainer. Caption
Type
Execute
Action
FIGURE 6.4 THE ACTION DESIGNER
4. Still on the same line, click View, C/AL Code to open the C/AL Editor. 5. Locate the OnAction trigger for the action. Code in this trigger is executed when the action is clicked. 6. Type the following code into the OnAction trigger of the action: Result := Value1 > Value2;
7. Close the C/AL Editor and close the Action Designer. 8. Compile, save, and close the page.
Test the Page 1. Run page 90005, My Test Page 1. 2. Type 10 into the Value 1 text box, type 2 in the Value 2 text box, and then click Execute in the Action menu.
FIGURE 6.5 MY TEST PAGE 1
6-32
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Assignment Statements and Expressions The Result check box is automatically updated with the result of the expression in the assignment statement in the OnAction trigger. Because 10 is greater than 2, the expression in the code evaluates to TRUE and the Result check box is selected. Try several values in each text box, including some negative values. 3. Try replacing the previous code in the OnAction trigger with the following line: Result := (Value1 >= Value2) AND (Value1 <= 2 * Value2);
4. Run the page and test the result.
Summary Assignment statements provide the basic foundation of developing an application by using C/AL. It lets developers assign values to variables. There are occasions when assignment statements involve automatic type conversions. There are many kinds of expressions in C/SIDE. These include string expressions, numeric expressions, relational and logical expressions. Each kind of expression is identified by its operator. For example, numeric expressions are identified by arithmetic operators and logical expressions are identified by logical operators. Operator precedence rule governs the use of all operators. Assignment statements and expressions are pieces that comprise code in C/SIDE. Understanding the assignment statements and the different kinds of expressions help developers write effective code in C/SIDE.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-33
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Test Your Knowledge 1. Underline the expression in this assignment statement: TextA := TextB; 2. In mathematics, the things that operators operate on are called "operands." What are these things called in programming expressions? 3. What does the plus operator (+) do to text variables or constants? 4. Underline the expression in this assignment statement: TextA := 'The ' + TextB; 5. Underline the operator(s) in the expression: TextA := 'The ' + TextB; 6. Underline the term(s) in the expression: TextA := 'The ' + TextB; 7. Write down the result type and value of each of these expressions: a. b. c. d. e. f. g. h. i. j.
57 * 10 57 / 10 57 DIV 10 57 MOD 10 2000000 * 3000 9 / 4 - 9 DIV 4 (3 - 10) * - 5 - 10 + 2.5 * 4 02201996D + 14 02101996D - 14 01201996D - 02101996D
8. For each question, write down the value of the result of evaluating the logical or relational expression: a. b. c. d. e. f. g. h. i.
6-34
5*7>3 5 * -7 > -36 (3 > 5 - 1) OR (7 < 5 * 2) (27 MOD 5 = 2) AND (27 DIV 5 = 5) (5 > 3) XOR (7 = 7) AND (9 >= 10) (10 > 2) AND ('10' > '2') NOT (11 + 7 < 15) OR ('Great' > 'Greater') AND ('Less' < 'Lesser') TRUE OR FALSE = TRUE Given that X is a Boolean Variable: NOT (X AND TRUE OR FALSE) = (NOT X OR FALSE) AND TRUE
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 6: Assignment Statements and Expressions
Quick Interaction: Lessons Learned Take a moment and write down three key points you have learned from this chapter 1.
2.
3.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
6-35
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
6-36
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements
CHAPTER 7: C/AL STATEMENTS Objectives The objectives are: •
Define conditional statements and Boolean expressions.
•
Describe the IF statement, the IF-THEN and IF-THEN-ELSE syntax.
•
Describe the EXIT statement and code indentation.
•
Describe the CASE statement and the syntax of the CASE statement.
•
Define compound statements and comments.
•
Describe the syntax of compound statements with BEGIN and END.
•
Understand the concepts of nested IF statements and the convention of proper indentation.
•
Describe the syntax of comments.
•
Use the IF, EXIT, CASE and compound statements in a page.
•
Test knowledge on the C/AL statements.
•
Define arrays and describe the components of arrays.
•
Describe the syntax of arrays.
•
Explain the power of arrays.
•
Describe how to use strings as arrays of characters.
•
Introduce repetitive statements available in C/SIDE.
•
Use arrays and repetitive statements in a page.
•
Describe the WITH statement, record variables and the syntax of the WITH statement.
Introduction There are many kinds of statements in C/AL. These statements can be grouped into conditional statements, repetitive statements, compound statements and other statements that do not fall into these categorizations.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-1
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Conditional statements are statements that have one or more conditions and by these conditions, one or more other statements are executed. There are several kinds of conditional statements in C/AL. To execute several other statements in conditional statements, these statements must be grouped together by using a special construct. These statements are known as compound statements. Repetitive statements are statements that are used to repeat several other statements multiple times. They are differentiated by the number of repetition times and how the number is determined. Repetitive statements can be used together with arrays. Arrays are complex variables that hold multiple values of the same data type. They are used mostly in storing addresses in Microsoft Dynamics® NAV report. Understanding different kinds of statements help developers decide the best method to write code to achieve certain functionalities.
Conditional Statements and Boolean Expressions Understanding the concepts behind conditional statements and Boolean expressions helps lay the groundwork for understanding the IF, CASE and EXIT statements.
Conditional Statement A conditional statement is a statement that tests a condition and executes one or several other statements based on the condition. The most frequently used conditional statement is the IF statement. It is used when there are only two possible values for the condition, either TRUE or FALSE.
Boolean Expression A Boolean expression is an expression that results in a Boolean value. It can be a Boolean variable or constant, a relational expression, or a logical expression.
The IF Statement Use the IF statement to execute one or several statements if the condition is TRUE and one or several other statements if the condition is FALSE. There are two ways of writing an IF statement.
IF - THEN Syntax Use the following syntax to execute a statement, if the condition is TRUE: IF THEN <statement>
A Boolean expression states a TRUE or FALSE condition. If the Boolean expression evaluates to TRUE, the statement following the reserved word, THEN, is executed. If the Boolean expression evaluates to FALSE, the statement following THEN, is not executed.
7-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements For example, to test whether an integer value is negative and if it is, to change it to positive, use the following IF statement: IF Amount < 0 THEN Amount := -Amount;
If the relational expression, Amount < 0, evaluates to TRUE, the assignment statement is executed and the Amount becomes positive. If the relational expression evaluates to FALSE, the assignment statement is not executed and the Amount remains positive. NOTE: The statement that is to be executed if the relational expression evaluates to TRUE, is positioned under the IF - THEN line and indented by two spaces. This is a convention that makes code easier to read. C/SIDE works with or without this indentation and it works even if this statement appears on the first line, right after THEN.
IF - THEN - ELSE Syntax Use the following syntax to execute a statement if the condition is TRUE and to execute another statement if that condition is FALSE: IF THEN <statement 1> ELSE <statement 2>
A Boolean expression states a TRUE or FALSE condition. If the Boolean expression evaluates to TRUE, the statement following the reserved word, THEN, is executed. If the Boolean expression evaluates to FALSE, the statement following the reserved word, ELSE, is executed. Either of the two statements is executed, but not both. For example, to find the unit price of an item, divide the total price by the quantity. However, if the quantity is zero, division results in a run-time error. To prevent this, it is necessary to test whether the quantity is zero. If it is, instead of doing the division, give the unit price a valid value. IF Quantity <> 0 THEN UnitPrice := TotalPrice / Quantity ELSE UnitPrice := 0;
If the relational expression, Quantity <> 0, evaluates to TRUE (quantity is not zero), the total price is divided by the quantity and the resulting value is assigned to the unit price. If the relational expression evaluates to FALSE, the unit price is set to zero.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-3
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 NOTE: The two statements that are optionally executed are indented by two spaces, and the ELSE reserved word is aligned with the IF reserved word. Even though C/SIDE works the same regardless of any spaces or new lines, this convention is helpful as a visual cue, as to which ELSE matches which IF. Also it helps determine which condition triggers the ELSE. The first assignment statement does not have a semicolon following it. This is because the IF statement is not finished yet, as the ELSE is a part of the IF statement. A semicolon (statement separator) suggests that a new statement is coming up, in this case, the ELSE, and there is no ELSE-only statement.
The EXIT Statement Generally, code in a trigger executes sequentially from the top to the bottom. There are cases when developers do not want to execute the rest of the code in a trigger. The EXIT statement is used for this purpose. When an EXIT statement is executed, C/SIDE exits the current trigger, back to the object that calls the trigger, if any, or back to the user.
Example of the Use of an EXIT Statement The EXIT statement is frequently used with the IF statement to stop executing code under certain conditions. Suppose in the previous code example, instead of testing whether the quantity is not zero, use the EXIT statement to skip the assignment statement, if the quantity is, in fact, zero. IF Quantity = 0 THEN EXIT; UnitPrice := TotalPrice / Quantity;
If the relational expression, Quantity = 0, evaluates to TRUE, the EXIT statement is executed. This skips the rest of the code. If the relational expression evaluates to FALSE, the EXIT statement is not executed and therefore the next statement, which is the assignment statement, is executed. NOTE: This assignment statement is not indented, because it is not part of the IF statement.
Code Indentation To indent several lines of code, select those several lines and press TAB. The code indents with two spaces to the right, every time that TAB is pressed. To indent several lines of code to the left, select those lines, and press SHIFT+TAB. This indents the code with one space to the left, every time that SHIFT+TAB is pressed. Block indentation enables developers to indent 15 lines of code in only three keystrokes (one for highlighting the code and two for pressing SHIFT and TAB.)
7-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements
The CASE Statement The CASE statement is also a conditional statement. Use the CASE statement when there are more than two possible values for the condition.
The Syntax of the CASE Statement The CASE statement has the following syntax: CASE <expression> OF : <statement 1>; : <statement 2>; : <statement n>; [ELSE <statement n+1>] END
A value set is similar to the constant set used with the IN operator, except without the brackets. It can contain a single value, multiple values separated by commas, ranges of values, multiple ranges of values separated by commas, and so on. All the values in the value sets must have a type comparable with the type of the expression. 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. The ELSE clause is optional in the CASE statement. When the CASE statement is executed, the expression is evaluated first. This expression is known as the selector. Then, in turn, each value in each value set is evaluated. If one of the values in the first value set matches the value of the expression, the first statement is executed. If one of the values in the second value set matches the value of the expression, the second statement is executed. This continues to the last value set. If the last value set is reached and no statement is executed, the ELSE clause is checked. If there is an ELSE clause, the statement following it, is executed. If there is no ELSE clause, no statement is executed for the CASE statement. Only one of the statements is executed. If there is more than one value set that contains the value that matches the expression, the statement following the earliest value set, is executed.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-5
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Compound Statements and Comments Understanding the concepts behind compound statements and comments helps lay the groundwork for understanding the nested IF statements.
Compound Statement A compound statement is multiple statements. It improves the capabilities of the conditional statement. For example, in an IF statement, when a condition tests to TRUE, use a compound statement after the THEN to perform two or more assignments. Usually, after the THEN, only one statement is executed. However, if that statement is a compound statement, multiple assignment statements can be performed in it.
Comment A comment is a description that developers write in their code. The purpose is to explain the code, or to document who made a modification or why it was made. Because a comment is a description, and not an actual piece of code, developers do not want the compiler to read it. Two slash marks (//) or a set of braces ({}) indicate to the compiler that lines of code are comments, and the compiler does not translate them.
The Syntax of Compound Statements Use the following syntax for compound statements: BEGIN <statement> {; <statement>} END
The braces ({}) indicate that whatever is included inside can be repeated zero or more times. In other words, there may not be a second statement, or there may be two or five, or as many as needed.
IF - THEN Compound Statement A compound statement can be used wherever, syntactically, a single statement can be used. For example, to calculate a unit price from an extended price and to add the extended price to the total price, but only if the quantity is not zero, then use the following IF statement: IF Quantity <> 0 THEN BEGIN UnitPrice := ExtendedPrice / Quantity; TotalPrice := TotalPrice + ExtendedPrice; END;
NOTE: The statements in a compound statement are indented two spaces from the BEGIN and the END, which are aligned with one another.
7-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements If this convention is followed strictly, together with the general indentation conventions for IF statements, the result is as follows: IF Quantity <> 0 THEN BEGIN UnitPrice := ExtendedPrice / Quantity; TotalPrice := TotalPrice + ExtendedPrice; END;
To prevent this double indentation, but still making the code easy to read, there is a special indentation convention for IF statements. In an IF statement, the BEGIN is positioned on the same line as the THEN and the END is aligned with the beginning of the line that contains the BEGIN.
IF - THEN - ELSE Compound Statement For example, if the Quantity is zero, to set the unit price to zero and skip the rest of the trigger, use the ELSE clause. The general indentation conventions look as follows: IF Quantity <> 0 THEN BEGIN UnitPrice := ExtendedPrice / Quantity; TotalPrice := TotalPrice + ExtendedPrice; END ELSE BEGIN UnitPrice := 0; EXIT; END;
There are special indentation conventions to use with ELSE clauses. To reduce the number of lines of code (keeping more on the screen at one time), but still making the code easy to read, there are two changes from the previous code sample. First, the ELSE appears on the same line as the END from its corresponding IF. Second, the BEGIN appears on the same line as the ELSE. Therefore, the Microsoft Dynamics NAV standard indentation for the previous IF statement is as follows: IF Quantity <> 0 THEN BEGIN UnitPrice := ExtendedPrice / Quantity; TotalPrice := TotalPrice + ExtendedPrice; END ELSE BEGIN UnitPrice := 0; EXIT; END;
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-7
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Compound Statement by Using Nested IF Statements In a nested IF statement, the statement following the THEN or the ELSE clause of an IF statement is another IF statement, instead of simple assignments.
Nested IF Statements Rule The rule for nested IF statements is that the ELSE clause matches the closest IF above it that does not have an ELSE clause. Unindented lines of code can be very difficult to read and understand, especially with nested IF statements present. For example, examine the following code: IF Amount <> 0 THEN IF Amount > 0 THEN Sales := Sales + Amount ELSE IF Reason = Reason::Return THEN IF ReasonForReturn = ReasonForReturn::Defective THEN Refund := Refund + Amount ELSE Credits := Credits + Amount ELSE Sales := Sales - Amount;
In the previous code sample, it is difficult to tell in what circumstances the Sales are to be reduced by the Amount without carefully diagnosing the code. What makes it even more difficult is if it is indented incorrectly, it can be misleading. IF Amount <> 0 THEN IF Amount > 0 THEN Sales := Sales + Amount ELSE IF Reason = Reason::Return THEN IF ReasonForReturn = ReasonForReturn::Defective THEN Refund := Refund + Amount ELSE Credits := Credits + Amount ELSE Sales := Sales - Amount;
7-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements Proper Nested IF Statements Indentation By using the rule that the ELSE clause matches the closest IF without an existing ELSE clause, and the standard indentation conventions, the code sample can be rewritten as follows: IF Amount <> 0 THEN IF Amount > 0 THEN Sales := Sales + Amount ELSE IF Reason = Reason::Return THEN IF ReasonForReturn = ReasonForReturn::Defective THEN Refund := Refund + Amount ELSE Credits := Credits + Amount ELSE Sales := Sales - Amount;
In all these code samples, the code executes the same way, because the compiler ignores all spaces and new lines. However, in the last code sample, it is much easier for the developer to know what is going on.
Variable Naming Another important concept is variable naming. Even if the same code is indented correctly, but the variables' names are not meaningful, it is difficult to understand what the code is meant to do. The following code sample shows badly named variables: IF Amt1 <> 0 THEN IF Amt1 > 0 THEN Amt2 := Amt2 + Amt1 ELSE IF OptA = 1 THEN IF OptB = 3 THEN Amt3 := Amt3 + Amt1 ELSE Amt4 := Amt4 + Amt1 ELSE Amt2 := Amt2 - Amt1;
The difference between poor programming and good programming frequently is in how well the code documents itself. Some good strategies for writing clear, organized code are as follows: •
Use proper indenting.
•
Use meaningful variable names.
•
Use Booleans to designate yes or no choices.
•
Use the option type and option constants instead of integers to designate selections with more than two choices.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-9
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Code that follows these guidelines is easy to read. Sometimes, it is also useful to provide additional documentation to the code. In these cases, add comments to the code.
The Syntax of Comments Depending on the situation, there are two ways of writing comments.
Single-Line Comment Use a single-line comment to comment out a single line in the code. To comment out means to make a particular section of code become a comment that is ignored by the compiler. The comment is created by putting two slashes next to one another (//) on a line. Everything on that line after those two slashes is considered a comment and is ignored by the compiler. The following code sample shows single-line comments: // Calculate the Unit Price IF Quantity <> 0 THEN // Do not allow division by zero UnitPrice := TotalPrice / Quantity ELSE // that is, if Quantity = 0 UnitPrice := 0;
The first comment is an example of a code line used completely for a comment. The other two (the second and fourth lines) show how to have some code on a line that followed with a comment. In each case, the compiler ignores anything following the two slashes on that line.
Block of Comments Use a block of comments to comment out a block of code. If an opening brace ({) is inserted in the code, the compiler ignores it and everything following it until the matching closing brace (}) occurs. The compiler also ignores new lines in this case. The following code sample shows a block of comments: {The following code is used to calculate the Unit Price. Note that it compares the Quantity to zero in order to prevent division by zero. In this case, the code sets the Unit Price to zero.} IF Quantity <> 0 THEN UnitPrice := TotalPrice / Quantity ELSE UnitPrice := 0;
7-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements Nested Comments One common use of a block of comments is when developers are tracking problems. An opening brace is inserted at the beginning of a section of code and a matching closing brace is inserted at the end of the section of code. This comments out the whole section of code and enables developers to concentrate their efforts on the remaining parts of the code, or eliminate a part of the code as the cause of a problem. Block of comments can be nested. When the compiler reaches an opening brace, it treats everything as a comment until it reaches the matching closing brace. Therefore, in a trigger code, a closing brace must match every opening brace. The following code sample shows nested block of comments: {The following code temporarily removed on 8/15/01... {The following code is used to calculate the Unit Price. Note that it compares the Quantity to zero to prevent division by zero. In this case, the code sets the Unit Price to zero.} IF Quantity <> 0 THEN UnitPrice := TotalPrice / Quantity ELSE } UnitPrice := 0;
When the code in the example is run, only the line that sets the unit price to zero (the last line) is actually executed. The other lines are skipped.
Demonstration: Use the IF, EXIT, CASE and Compound Statements in a Page The following demonstration shows how to use the IF, EXIT, CASE and compound statements in a page.
Create a New Page and Add Variables The following steps show how to create a new page and define several global variables. 1. Create a new blank page, and save it as page 90006, Test Statements Page.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-11
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 2. Click View, C/AL Globals and define the following global variables: Name
DataType
Quantity
Integer
UnitPrice
Decimal
TotalSales
Decimal
TotalCredits
Decimal
GrandTotal
Decimal
Result
Decimal
3. Close the C/AL Globals window. 4. Compile and save the page.
Add Controls The following steps show how to add several controls to display the value of the global variables in the page. 1. Type the following on the first line of the Page Designer, to specify the ContentArea container and name it My Test Page 1: Caption
Type
SubType
Test Statements Page
Container
ContentArea
2. Go to the next line and type the following to add a FastTab named General. Ensure that it is indented under the container control. Caption
Type
SubType
General
Group
Group
3. Go to the next line and type the following to add a group control with Caption Input. Ensure that it is indented under the General FastTab.
7-12
Caption
Type
SubType
Input
Group
Group
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements 4. Go to the next line and type the following to add two field controls that have SourceExpr Quantity and UnitPrice. Ensure that they are indented under the Input group. Caption
Type
SourceExpr
Quantity
Field
Quantity
Unit Price
Field
UnitPrice
5. Set the MinValue property for the UnitPrice field to 0. 6. Go to the next line and type the following to add a group control with Caption Output. Indent it to the same level as the Input group. Caption
Type
SubType
Output
Group
Group
7. Go to the next line and type the following to add four controls that have SourceExpr Result, TotalSales, TotalCredits and GrandTotal. Ensure that they are indented under the Output group. Caption
Type
SourceExpr
Result
Field
Result
Total Sales
Field
TotalSales
Total Credits
Field
TotalCredits
Grand Total
Field
GrandTotal
FIGURE 7.1 TEST STATEMENTS PAGE
8. Set the Editable property for all the four controls to FALSE. 9. Compile and save the page.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-13
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Use the IF and the EXIT Statement The following steps show how to add an action with IF and EXIT statements in the action trigger. 1. Open the Action Designer for the page. 2. Type the following on the first line of the Action Designer to add an ActionContainer. Type
SubType
ActionContainer
ActionItems
3. Go to the next line and type the following to add an action. Ensure that it is indented under the ActionItems ActionContainer. Caption
Type
Execute IF
Action
4. Go to the next line and type the following to add another action. Ensure that it is indented under the ActionItems ActionContainer. Caption
Type
Clear
Action
FIGURE 7.2 THE ACTION DESIGNER
5. Click View, C/AL Code to open the C/AL Editor.
7-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements 6. Locate the OnAction trigger for the Execute IF action. 7. Type the following code into the OnAction trigger of the action: IF Quantity = 0 THEN EXIT; Result := Quantity * UnitPrice; IF Result < 0 THEN TotalCredits := TotalCredits + Result ELSE TotalSales := TotalSales + Result; GrandTotal := GrandTotal + Result;
8. Locate the OnAction trigger for the Clear action. 9. Type the following code into the OnAction trigger of the action: Quantity := 0; UnitPrice := 0; Result := 0; TotalSales := 0; TotalCredits := 0; GrandTotal := 0;
FIGURE 7.3 THE C/AL EDITOR
10. Close the C/AL Editor and close the Action Designer. 11. Compile, save, and close the page.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-15
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Test the Page The following steps show how to test the page by running the action and viewing the result. 1. Run page 90006, Test Statements Page. 2. Type a value into the Unit Price and Quantity text box, and then click the Execute IF action. Observe what happens.
FIGURE 7.4 TEST STATEMENTS PAGE
3. Type another value into the Quantity text box, and then click the Execute IF action again. Observe what happens. 4. Try entering a negative value in the Quantity text box, (for example -4) and then click the Execute action. Observe what happens. 5. Click the Clear action and observe what happens.
Use Compound Statements The following steps show how to add an action with compound statements in the action trigger. 1. Design page 90006, Test Statements Page, from the Object Designer. 2. Click View, C/AL Globals and define the following global variables:
7-16
Name
DataType
TotalQtySales
Integer
TotalQtyCredits
Integer
GrandQtyTotal
Integer
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements 3. Close the C/AL Globals window 4. Go to the last line of the Page Designer and type the following to add three field controls that have SourceExpr TotalQtyCredits, TotalQtySales and GrandQtyTotal. Ensure that they are indented under the Output group. Caption
Type
SourceExpr
Total Qty Sales
Field
TotalQtySales
Total Qty Credits
Field
TotalQtyCredits
Grand Qty Total
Field
GrandQtyTotal
FIGURE 7.5 TEST STATEMENTS PAGE
5. Set the Editable property for all the three field controls to FALSE. 6. Open the Action Designer for the page. 7. Go to the next line and type the following to add an action. Ensure that it is indented under the ActionItems ActionContainer. Caption
Type
Execute Compound
Action
FIGURE 7.6 THE ACTION DESIGNER
8. Click View, C/AL Code to open the C/AL Editor.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-17
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 9. Locate the OnAction trigger for the Execute Compound action. 10. Type the following code into the OnAction trigger of the action: IF Quantity = 0 THEN EXIT; Result := Quantity * UnitPrice; IF Result < 0 THEN BEGIN TotalCredits := TotalCredits + Result; TotalQtyCredits := TotalQtyCredits + Quantity; END ELSE BEGIN TotalSales := TotalSales + Result; TotalQtySales := TotalQtySales + Quantity; END; GrandTotal := GrandTotal + Result; GrandQtyTotal := GrandQtyTotal + Quantity;
11. Close the C/AL Editor and close the Action Designer. 12. Compile, save and close the page. 13. Run the page and test the changes.
Use the CASE Statement The following steps show how to add an action with the CASE statement in the action trigger. 1. Design page 90006, Test Statements Page, from the Object Designer. 2. Open the Action Designer for the page. 3. Go to the next line and type the following to add an action. Ensure that it is indented under the ActionItems ActionContainer. Caption
Type
Execute CASE
Action
FIGURE 7.7 THE ACTION DESIGNER
7-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements 4. Click View, C/AL Code to open the C/AL Editor. 5. Locate the OnAction trigger for the Execute CASE action. 6. Type the following code into the OnAction trigger of the action: Result := Quantity * UnitPrice; CASE TRUE OF Quantity = 0: EXIT; Quantity < 0: BEGIN TotalCredits := TotalCredits + Result; TotalQtyCredits := TotalQtyCredits + Quantity; END; Quantity > 0: BEGIN TotalSales := TotalSales + Result; TotalQtySales := TotalQtySales + Quantity; END; END; GrandTotal := GrandTotal + Result; GrandQtyTotal := GrandQtyTotal + Quantity;
7. Close the C/AL Editor and close the Action Designer. 8. Compile, save and close the page. 9. Run the page and test the changes.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-19
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Test Your Knowledge The questions on this self-test relate to the following code. Hand-execute this code to determine the answers. Draw a line from each ELSE to its matching IF statement for the following set of statements. IF A1 A1 X7 IF IF A2 A2 IF
(X1 > X2) OR B3 THEN BEGIN IF X7 < X2 THEN := (X1 + X7) / 2 ELSE IF X6 < X2 THEN := (X1 + X6) / 2; := X6 + 1; END ELSE IF (X1 < X2) AND B5 THEN X6 > X7 THEN BEGIN B2 THEN A2 := X1 / 2 + X7 / 2 ELSE := X1 * 2 + X7 * 2; END ELSE A1 := X1 ELSE := X2; B1 THEN EXIT;
HINT: It may be more efficient to rewrite the set of statements from the top to bottom with correct indentation. After executing the following set of statements, what is the value of variable A5? {Initialize Variables} A5 := 7; // Initialize answer B1 := {TRUE;} FALSE; B2 := TRUE; // FALSE; A1 := { 5 // be sure to set this one correctly A2 := 3 * A5; A3 := 10 } 11; // either one is OK A2 := 2 * A5; // IF B2 THEN A5 := A5 + 1 IF (A1 < A5) OR {B2 AND} B1 THEN A5 := 3 * A5 // ELSE A5 := A2 / A5; ELSE A5 := A1 + A5;
7-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements
Lab 7.1 - Use Conditional and Compound Statements The following lab tests the basic knowledge on how to use conditional and compound statements. Scenario Simon is a developer working for CRONUS International Ltd. CRONUS International has decided to start selling Microsoft Dynamics NAV training courses as its business. Simon has already created a Course table to store courses information, a Course Card page and a Course List page to enter and display the courses information. Now, Simon must improve the List page to add several extension fields to make the page more user friendly. The Course List page must have three extension fields, Level, Suggestion and SPA (Solution Provider Agreement.) The Level and Suggestion are string fields whereas the SPA field must be displayed as a check box. Depending on the Difficulty of the Course, the Level and Suggestion varies. Also, depending on the Passing Rate and the Difficulty of the Course, the SPA varies.
Challenge Yourself! 1. Create three global variables for Level, Suggestion and SPA in the Course List page with their respective data type. 2. Create three field controls in the Course List page and set their SourceExpr property to the respective global variables created earlier. 3. Write code by using the CASE statement to assign the value of Level and Suggestion variables based on these conditions: Difficulty
Level
Suggestion
1 to 5
Beginner
Take e-Learning or remote training
6 to 8
Intermediate
Attend instructor-led
9 to 10
Advanced
Attend instructor-led and self study
4. Write code by using the IF statement to assign the value of the SPA variable based on these conditions: Passing Rate
Difficulty
SPA
>= 70
>= 6
Yes
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-21
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
HINT: Write the code in the OnAfterGetRecord trigger of the page. Do not forget to initialize the global variables to their default value.
Need a Little Help? 1. Add three global variables to the Course List page. Name
DataType
Length
Level
Text
30
Suggestion
Text
80
SPA
Boolean
2. Add three field controls to the Course List page. Caption
Type
SourceExpr
Level
Field
Level
Suggestion
Field
Suggestion
SPA
Field
SPA
3. Add code to the OnAfterGetRecord trigger of the page. Level := ''; Suggestion := ''; SPA := FALSE; CASE Difficulty OF 1..5: BEGIN Level := 'Beginner'; Suggestion := 'Take e-Learning or remote training'; END; 6..8: BEGIN Level := 'Intermediate'; Suggestion := 'Attend instructor-Led'; END; 9..10: BEGIN Level := 'Advanced'; Suggestion := 'Attend instructor-Led and self study'; END; END; IF ("Passing Rate" >= 70) AND (Difficulty >= 6) THEN SPA := TRUE;
4. Compile, save and close the page
7-22
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements Step by Step 1. Design page 90011, Course List, from the Object Designer. 2. Click View, C/AL Globals and define the following global variables: Name
DataType
Length
Level
Text
30
Suggestion
Text
80
SPA
Boolean
3. Close the C/AL Globals window. 4. Go to the last line of the Page Designer and type the following to add three field controls that have SourceExpr Level, Suggestion and SPA. Ensure that they are indented at the same level as the other field controls. Caption
Type
SourceExpr
Level
Field
Level
Suggestion
Field
Suggestion
SPA
Field
SPA
5. Click View, C/AL Code to open the C/AL Editor. 6. Locate the OnAfterGetRecord trigger of the page.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-23
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 7. Type the following code into the OnAfterGetRecord trigger of the page: Level := ''; Suggestion := ''; SPA := FALSE; CASE Difficulty OF 1..5: BEGIN Level := 'Beginner'; Suggestion := 'Take e-Learning or remote training'; END; 6..8: BEGIN Level := 'Intermediate'; Suggestion := 'Attend instructor-Led'; END; 9..10: BEGIN Level := 'Advanced'; Suggestion := 'Attend instructor-Led and self study'; END; END; IF ("Passing Rate" >= 70) AND (Difficulty >= 6) THEN SPA := TRUE;
8. Close the C/AL Editor. 9. Compile, save and close the page
7-24
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements
Arrays Arrays are complex variables that contain a group of variables, with the same data type. They are special variables that have more functionalities than other variables discussed to this point.
Data Types and Variables Simple data types are a type of data that only have a single value. A simple variable is a variable defined by using a simple data type. A complex data type is a type of data with multiple values. A complex variable is a variable with a complex data type. That is, a variable that has multiple values.
Array An array is a complex variable that holds a group of variables. This group is defined all at the same time with a single identifier and a single data type. For example, a developer can create an array variable with the following identifier and data type: •
Identifier: QuantityArray
•
Data Type: Integer
Element Element is a single variable in an array. An array is made up of one or more elements. Although developers can create an array with one element, this is rarely done, because it is no more useful than a simple variable. All elements in an array have the same data type as whatever data type the array is defined as. The previous array must have the number of elements defined. This looks as follows: •
Elements: 5
Index An index is used to refer to a single element in an array. To access a single element in an array, use both the array variable name and the index, which is a number, to indicate the desired array element. To access the fourth element in the previous array, use the following: •
QuantityArray[4]
Dimension An array can have one or more dimensions. The simplest array is a onedimensional array, which is by default defined in the definition of arrays. This array only has elements in one dimension. This can be compared to having only elements on the x-axis of a graph.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-25
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 In the previous example, there are a grand total of five elements that consist of one line, or a dimension, of five defined elements. If the array is defined to have two dimensions, it has a total of 25 elements (five elements in one dimension times five elements in the second dimension.) This can be compared to having a two dimensional graph that uses the x-axis and yaxis. Each line has five elements (one through five), but provides a combination of 25 different points (by using only integers). Arrays can have up to 10 Dimensions in C/AL. To use a particular element in a multidimensional array, specify an index value for each dimension. Therefore, there is the same number of index values as the defined dimensions. These index values must be integers.
The Syntax of Arrays The difference between calling a simple variable and an array is the addition of the element index.
Variable Syntax Use the variable identifier when referring to any variable or an array as a whole. For example, CLEAR, a built-in function has the following syntax: CLEAR()
This function clears the variable used as the parameter. If the variable is a numeric type, the CLEAR function sets it to zero. If the variable is a string type, the CLEAR function sets it to an empty string. If the variable is an array, the CLEAR function sets each element in the array to its own cleared value. For example, for a one-dimensional array named SaleAmount of type Decimal, use the following function call to set all elements in SaleAmount to zero: CLEAR(SaleAmount);
Array Element Syntax Refer to a single element of an array by using its identifier and its index, according to the following syntax: [{,}]
7-26
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements The brackets ([]) here are literal brackets, whereas the braces ({}) indicate that whatever is included inside can be repeated zero or more times. A onedimensional array requires a single index expression, whereas a two-dimensional array requires two index expressions, separated by a comma. Each index expression must result in an integer value when evaluated. To set the fifth element of the SaleAmount array to zero, use the following assignment statement: SaleAmount[5] := 0;
How to think about Arrays An easy way to think about a one-dimensional array is to think of a row of boxes as follows:
FIGURE 7.8 ONE-DIMENSIONAL ARRAY ILLUSTRATION
This is a one-dimensional array, with the identifier Box and eight elements. Each element of the array is a single box. The fourth element of the array contains the value of 17. To refer to the fourth element of the array, use Box[4]. It is also easy to picture a two-dimensional array, just as a checkerboard or a multiplication table.
FIGURE 7.9 TWO-DIMENSIONAL ARRAY ILLUSTRATION
Here is a two-dimensional array with the identifier Box, and a total of 30 elements, broken up into five rows of six elements. The first dimension can be thought of as the row number, whereas the second dimension is thought of as a column number. To identify a specific element, developers must identify both the row and the column. For example, to have the value of the element in row 4, column 6, refer to Box[4,6] and the value is 24. Three or more dimensions are more difficult to visualize. The index must be thought of as a list of critieria. Fortunately, there are few reasons to have more than one-dimensional array in Microsoft Dynamics NAV, although up to ten are allowed.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-27
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
The Power of Arrays If all that the developer can do with an array is access a particular element, such as the element shown here, it is not very useful: •
SaleAmount[5]
At this point, creating an array with 10 elements only saves the developer from creating ten different variables.
Expressions as an Index Value The true power of an array is the fact that the index value can be an expression. •
SaleAmount[Counter]
This enables the element to be determined at run time. In this example, the element is determined by whatever value Counter has. However, this does bring up a possible problem that a developer might not know, at run time, whether the value of the index expression is a valid element number. If an array is defined to have eight elements, and the code refers to element number 12, it results in a run-time error. To avoid this error, it is necessary to use an IF statement to test the value of the variable before using it to index an array. For example: IF Counter <= 8 THEN SaleAmount[Counter] := Answer;
ARRAYLEN Function However, the problem with this method is that the array might actually be defined to have seven elements and the problem might only be identified at run time. To address this problem, C/AL has a built-in function known as ARRAYLEN that has the following syntax: Result := ARRAYLEN(<array variable>)
The code in this example indicates that the ARRAYLEN function results in a value, in this case of type Integer. By using the previous syntax, the result is the number of elements in the array variable used as the parameter. For example, if a one-dimensional array is defined to have eight elements, the following function has the integer value of 8: ARRAYLEN(SaleAmount)
NOTE: ARRAYLEN can also be used for multidimensional arrays.
7-28
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements The advantage of using ARRAYLEN is that changes to the defined length of an array do not require developers to go back through their code to update references to the defined length. Therefore, in the first ARRAYLEN example, developers can test to see whether an index value is valid as follows: IF Counter <= ARRAYLEN(SaleAmount) THEN SaleAmount[Counter] := Answer;
Because the number eight is never used, nothing here says the array must have exactly eight elements. If it turns out the array is actually defined to have seven elements, this code still works perfectly.
Strings as Arrays of Characters A string variable, or variable of type Text or Code, can be thought of as an array of characters. Because of this, C/AL allows for access to each character as an element in an array.
Characters of Elements Each element is considered a variable of type Char. For example, running the following code, results in the message Walk in the dark : Str := 'Walk in the park'; Str[13] := 'd'; MESSAGE(Str);
Because Char is a numeric type, ASCII codes can be used for characters when using strings in this manner. For example, when importing a text line, tab characters (ASCII code 9) can be checked as follows: IF Str[idx] = 9 THEN MESSAGE('There is a TAB character at position %1 in the text.',idx);
The length of a string cannot be accessed in this manner. Regardless of which characters are read or set, the length of the string remains the same. The elements beyond the string's length are considered undefined. In the first string example, if the 25th element is set (instead of the 13th) to 'd,' the message displays Walk in the park. There are no changes, because the 25th character is beyond the length of the string. However, in the RoleTailored client, this causes a run-time error. Similarly, in the second example, if idx was greater than the length of Str, it still might find a tab character there. However, it will only be garbage, not actually part of Str.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-29
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 To know the number of elements in a string being used as an array of characters, use the MAXSTRLEN function, instead of the ARRAYLEN function.
Repetitive Statements A repetitive statement is a statement that enables execution of one or more statements multiple times. There are several types of repetitive statements. The differences between repetitive statements lie in the number of times these statements are executed and how that number is determined. A repetitive statement is known as a loop because when the execution reaches the end of the repetitive statement, it loops back to the beginning.
The FOR Statement Use the FOR statement when a statement is to be executed a predetermined number of times.
The FOR...TO Statement The FOR...TO statement has the following syntax: FOR := <start value> TO <end value> DO <statement>
The control variable must be a variable of type Boolean, Date, Time, or any numeric type. The start value and the end value must be either expressions that evaluate to the same data type as the control variable, or variables of the same data type as the control variable. The following code sample shows a FOR...TO statement: FOR idx := 4 TO 8 DO Total := Total + 2.5;
7-30
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements In this case, the control variable (idx), the start value (4) and the end value (8) are all integers. The following steps describe what happens: Step
Code
1. The start value expression is evaluated and the control variable is set to the result.
idx := 4
2. The end value expression (after the TO) is evaluated.
End value is 8
3. The control variable is compared to the end value. If it is greater than the end value, the FOR statement is ended.
IF idx > 8, THEN The FOR statement ends.
4. The statement (after the DO) is executed.
Total := Total + 2.5
5. The control variable is incremented by one.
idx := idx + 1 (5)
6. Go to step 3 and test the control variable again. For this example, the Total variable is increased by two and one half for five times. Therefore, it is increased by 12.5. Both the start value and the end value are evaluated only one time, at the beginning of the FOR statement. The control variable must not be changed in the FOR loop, as the result of doing this, is not predictable. The control variable value outside the FOR loop (after it ends) is not defined. If several statements must be run inside the loop, create a compound statement by adding BEGIN and END. The following code sample shows how to execute two statements in a loop: FOR idx := 4 TO 8 DO BEGIN Total := Total + 2.5; GrandTotal := GrandTotal + Total; END;
The FOR...DOWNTO Statement The FOR...DOWNTO statement has the following syntax: FOR := <start value> DOWNTO <end value> DO <statement>
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-31
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The rules for the control variable, start value and end value are the same as for the FOR…TO statement. The only difference between the two is that in the FOR…TO statement, the control variable increases in value until it is greater than the end value, whereas in the FOR.. DOWNTO statement, the control variable decreases in value until it is less than the end value. The following code sample shows a FOR...DOWNTO statement with an array and a compound statement: FOR idx := 9 DOWNTO 1 DO BEGIN TotalSales := TotalSales + Sales[idx]; NumberSales := NumberSales + 1; END;
The following steps describe what happens: Step
Code
1. The start value expression is evaluated and the control variable is set to the result.
idx := 9
2. The end value expression (after the DOWNTO) is evaluated.
End value is 1
3. The control variable is compared to the end value. If it is less than the end value, the FOR statement is ended.
IF idx < 1, THEN The FOR statement ends.
4. The statement (after the DO) is executed.
TotalSales := TotalSales + Sales[9]; NumberSales := NumberSales + 1;
5. The control variable is decreased by one.
idx := idx - 1 (8)
6. Go to step 3 and test the control variable again. Through each execution of the first statement in the compound statement, a different element of the Sales array is accessed - first the ninth and then the eighth, and so on.
The WHILE...DO Statement Use the WHILE loop when a statement is to be executed as long as some condition is true. It has the following syntax: WHILE DO <statement>
7-32
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements The WHILE...DO statement is simpler than the FOR statement. As long as the Boolean expression evaluates to TRUE, the statement is executed repeatedly. As soon as the Boolean expression evaluates to FALSE, the statement is skipped and the execution continues with the statement following it. The following code sample shows a WHILE...DO statement with a compound statement: WHILE Sales[idx + 1] <> 0 DO BEGIN idx := idx + 1; TotalSales := TotalSales + Sales[idx]; END;
The following steps describe what happens: Step
Code
1. The Boolean expression is evaluated. If it evaluates to TRUE, go to step 2. If it is not, the WHILE statement is ended.
Is Sales[idx + 1] <> 0?
2. The statement (after the DO) is executed.
idx := idx + 1; TotalSales := TotalSales + Sales[idx];
3. Go to step 1 and test the Boolean expression again. The Boolean expression is tested before the statement is even executed one time. If it evaluates to FALSE from the beginning, the statement is never executed. The Sales[idx] that is added to Total Sales in the WHILE loop is the same value that was tested in the Sales[idx + 1] at the beginning of the WHILE loop. The intervening idx := idx + 1 statement is what causes this. As soon as the WHILE loop has ended, idx still refers to the last nonzero element in the Sales array. Unlike in FOR statements, it is the developer's responsibility to ensure that the expression evaluates to FALSE at some point. This is to prevent a never-ending loop.
The REPEAT...UNTIL Statement Use the REPEAT statement when one or more statements are to be executed until some condition becomes true. It has the following syntax: REPEAT <statement> { ; <statement> } UNTIL
There are several differences between the REPEAT and WHILE statements: •
There can be more than one statement between the REPEAT and the UNTIL, even if no BEGIN and END is used.
•
The Boolean expression is not evaluated until the end, after the statements are already executed one time.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-33
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 •
When the Boolean expression is evaluated, it loops back to the beginning if the expression evaluates to FALSE and ends the loop if the expression evaluates to TRUE.
The following code sample shows a REPEAT...UNTIL statement that achieves the same thing with the WHILE statement code sample: REPEAT idx := idx + 1; TotalSales := TotalSales + Sales[idx]; UNTIL Sales[idx] = 0;
The following steps describe what happens: Step
Code
1. The statements (between the REPEAT and the UNTIL) are executed.
idx := idx + 1; TotalSales := TotalSales + Sales[idx];
2. The Boolean expression is evaluated. If it evaluates to TRUE, the REPEAT statement is ended. If it is not, go back to step 1.
Is Sales[idx] = 0?
Because the Boolean expression is not evaluated until the end, the statements incrementing the index and adding the TotalSales are executed even though the value of those Sales might be zero. Therefore, at the end of this loop, idx refers to the first Sales which equals zero, instead of the last nonzero Sales as in the WHILE statement. The Boolean expression had to be rewritten, because a FALSE condition is required to continue the loop, instead of a TRUE condition as in the WHILE statement. Just as in the WHILE...DO statement, it is the developer's responsibility to ensure that the Boolean expression evaluates to TRUE at some point to prevent a neverending loop.
7-34
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements
Demonstration: Use Arrays and Repetitive Statements The following demonstration shows how to use arrays and repetitive statements in a page. The objective is to create a page that takes 10 input numbers from the user, store them in arrays and sort them by using several repetitive statements.
Create a New Page and Add Variables The following steps show how to create a new page and define several global variables. 1. Create a new blank page, and save it as page 90007, Test Array Page. 2. Click View, C/AL Globals and define the following global variables: Name
DataType
Purpose
InputNumber
Integer
This is used to store the input numbers.
OutputNumber
Integer
This is used to store the output numbers.
LoopCount
Integer
This is used to count how many loops are required for the sorting routine.
SwapCount
Integer
This is used to count how many swaps actually occur in the sorting routine.
idx
Integer
This is used as an expression for the array's index.
IsSorted
Boolean
This is used as a flag for whether a repetitive statement must be repeated.
LowestSwitch
Integer
This is used to improve the sorting routine.
TempNumber
Integer
This is used for temporary holding values to be swapped.
3. Open the Properties window for the InputNumber variable, and set the following property: o Dimensions: 10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-35
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
NOTE: This means that InputNumber is a one-dimensional array variable of type Integer, with a maximum number of elements of the first (and only) dimension, 10, which means that there are 10 elements. To create a two-dimensional array, put two numbers in the Dimensions property, separated by a semicolon (;). For example, to create a two-dimensional array for which the maximum number of elements of the first dimension is five and the maximum number of elements of the second dimension is seven , put 5;7 in the Dimensions property. This means that there are 35 elements. 4. Do the same for the OutputNumber variable. 5. Close the Properties window and close the C/AL Globals window. 6. Compile and save the page.
Add Controls The following steps show how to add several controls to display the value of the global variables in the page. 1. Type the following on the first line of the Page Designer, to specify the ContentArea container and name it Test Array Page: Caption
Type
SubType
Test Array Page
Container
ContentArea
2. Go to the next line and type the following to add a FastTab named General. Ensure that it is indented under the container control. Caption
Type
SubType
General
Group
Group
3. Go to the next line and type the following to add a group control with Caption Input. Ensure that it is indented under the General FastTab.
7-36
Caption
Type
SubType
Input
Group
Group
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements 4. Go to the next line and type the following to add 10 field controls with SourceExpr InputNumber and its element index. Ensure that they are indented under the Input group. Caption
Type
SourceExpr
InputNumber[1]
Field
InputNumber[1]
InputNumber[2]
Field
InputNumber[2]
InputNumber[3]
Field
InputNumber[3]
InputNumber[4]
Field
InputNumber[4]
InputNumber[5]
Field
InputNumber[5]
InputNumber[6]
Field
InputNumber[6]
InputNumber[7]
Field
InputNumber[7]
InputNumber[8]
Field
InputNumber[8]
InputNumber[9]
Field
InputNumber[9]
InputNumber[10]
Field
InputNumber[10]
NOTE: This creates the input column in the page. 5. Go to the next line and type the following to add a group control with Caption Output. Indent it to the same level as the Input group. Caption
Type
SubType
Output
Group
Group
6. Go to the next line and type the following to add 10 field controls with SourceExpr OutputNumber and its element index. Ensure that they are indented under the Output group. Caption
Type
SourceExpr
OutputNumber[1]
Field
OutputNumber[1]
OutputNumber[2]
Field
OutputNumber[2]
OutputNumber[3]
Field
OutputNumber[3]
OutputNumber[4]
Field
OutputNumber[4]
OutputNumber[5]
Field
OutputNumber[5]
OutputNumber[6]
Field
OutputNumber[6]
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-37
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Caption
Type
SourceExpr
OutputNumber[7]
Field
OutputNumber[7]
OutputNumber[8]
Field
OutputNumber[8]
OutputNumber[9]
Field
OutputNumber[9]
OutputNumber[10]
Field
OutputNumber[10]
NOTE: This creates the output column in the page. 7. Set the Editable property for all the ten output field controls to FALSE. 8. Go to the next line and type the following to add a group control with Caption Counter. Indent it to the same level as the Input group. Caption
Type
SubType
Counter
Group
Group
9. Go to the next line and type the following to add two field controls with SourceExpr LoopCount and SwapCount. Ensure that it is indented under the Counter group. Caption
Type
SubType
Loop Count
Field
LoopCount
Swap Count
Field
SwapCount
NOTE: This creates a section in the page to show the performance of the sorting routine. The less loop count, the better the sorting routine.
7-38
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements 10. Set the Editable property for the two counter field controls to FALSE.
FIGURE 7.10 TEST ARRAY PAGE
11. Compile and save the page.
Add Code to Clear the Page The following steps show how to add an action to clear the page (set all variables to zero.) 1. Open the Action Designer for the page. 2. Type the following on the first line of the Action Designer to add an ActionContainer. Type
SubType
ActionContainer
ActionItems
3. Go to the next line and type the following to add an action. Ensure that it is indented under the ActionItems ActionContainer. Caption
Type
Clear
Action
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-39
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 4. Click View, C/AL Code to open the C/AL Editor. 5. Locate the OnAction trigger for the Clear action. 6. Type the following code into the OnAction trigger of the action: CLEAR(InputNumber); CLEAR(OutputNumber); LoopCount := 0; SwapCount := 0;
NOTE: This adds an action to clear the page, by clearing the arrays and setting all the variables displayed in the page to 0. 7. Close the C/AL Editor.
Add Code to Generate Input The following steps show how to add an action to generate 10 randomly generated numbers for the input column in the page. 1. In the Action Designer, go to the next line and type the following to add another action. Ensure that it is indented under the ActionItems ActionContainer. Caption
Type
Generate Input
Action
2. Click View, C/AL Code to open the C/AL Editor. 3. Locate the OnAction trigger for the Generate Input action. 4. Type the following code into the OnAction trigger of the action: LoopCount := 0; SwapCount := 0; FOR idx := 1 TO ARRAYLEN(InputNumber) DO InputNumber[idx] := RANDOM(ARRAYLEN(InputNumber));
NOTE: A built-in C/AL function, RANDOM, is used to achieve this result. A BEGIN is not needed after the DO in the FOR statement because there is only one statement following the FOR statement. 5. Close the C/AL Editor.
7-40
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements Add Code to Populate Output The following steps show how to add an action to populate the output column in the page from the input column, by assigning the InputNumber variables to the OutputNumber variables. 1. In the Action Designer, go to the next line and type the following to add another action. Ensure that it is indented under the ActionItems ActionContainer. Caption
Type
Populate Output
Action
2. Click View, C/AL Code to open the C/AL Editor. 3. Locate the OnAction trigger for the Populate Output action. 4. Type the following code into the OnAction trigger of the action: LoopCount := 0; SwapCount := 0; idx := 1; WHILE (idx <= ARRAYLEN(InputNumber)) AND (idx <= ARRAYLEN(OutputNumber)) DO BEGIN OutputNumber[idx] := InputNumber[idx]; idx += 1; END;
5.
Close the C/AL Editor.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-41
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Add Code to Sort the Output The following steps show how to add an action to sort the output column in the page. 1. In the Action Designer, go to the next line and type the following to add another action. Ensure that it is indented under the ActionItems ActionContainer. Caption
Type
Sort
Action
FIGURE 7.11 THE ACTION DESIGNER
2. Click View, C/AL Code to open the C/AL Editor. 3. Locate the OnAction trigger for the Sort action. 4. Type the following code into the OnAction trigger of the action: LoopCount := 0; SwapCount := 0; REPEAT IsSorted := TRUE; FOR idx := ARRAYLEN(OutputNumber) DOWNTO 2 DO BEGIN LoopCount += 1; IF OutputNumber[idx] < OutputNumber[idx-1] THEN BEGIN TempNumber := OutputNumber[idx]; OutputNumber[idx] := OutputNumber[idx-1]; OutputNumber[idx-1] := TempNumber; SwapCount += 1; IsSorted := FALSE; END; END; UNTIL IsSorted
7-42
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements NOTE: First the code initializes the two variables, LoopCount and SwapCount to zero. Then the REPEAT...UNTIL statement loops until the output column does not require sorting any more. The FOR...DOWNTO statement inside the REPEAT...UNTIL statement, loops the output column, to sort from the last element to the first element. 5. Close the C/AL Editor. The FOR statement only goes down to two, instead of all the way to one because when idx is one this causes it to refer to an array element of zero. The three lines of the compound statement (between BEGIN and END) in the FOR loop does the actual swapping between elements of the array. The IsSorted variable is used as a signal to tell whether sorting is finished. Set the IsSorted variable to TRUE at the beginning of each REPEAT loop, and if ever there is a need to swap two elements because the list is not in order, set it to FALSE. At the end of the REPEAT loop check whether it is TRUE. If it is, all the elements are in order, because none needed to be swapped. Now exit the loop. If not, the loop is repeated again. A Boolean variable that is used as a signal in this manner is known as a flag. It is not possible to tell whether the list is sorted unless it is run through at least one time. That is why the REPEAT is used here, instead of the WHILE loop.
Improve the Sorting Routine Code To this point the sorting routine is sufficient. It works well for small arrays, but it can take any size arrays. If there are 100 elements, 1,000 elements, or 10,000 elements, a more efficient sorting routine is required. Nested loops are created when one loop (the FOR loop) is put inside another loop (the REPEAT loop). With nested loops, there is always a potential for inefficiency, especially as the number of elements increase. The question is how many times the innermost loop will be executed. The LoopCount variable keeps track of this. In the previous sorting routine, when the FOR loop is executed one time, the IF statement is executed nine times, because the length of the array is 10 and it goes all the way to two. If the REPEAT loop has to be executed nine times, the FOR loop will be executed nine times and the IF statement will be executed 9 * 9 = 81 times. However, if the array length goes up to 100, the IF statement will be executed 99 times per FOR statement and the FOR statement may be executed by the REPEAT loop up to 99 times. In this situation, it is possible that the IF statement might be executed up to 99 * 99 = 9,801 times.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-43
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 This can be reduced significantly by remembering what happened when the FOR loop is executed. Every time that it runs, the lowest element rises to the top. That means that the first element never has to be tested again, after the first FOR loop runs. After the second FOR loop runs, there is no need to test the first two elements again. Each loop needs fewer and fewer tests to do its job, and this is the worst case. The following steps show how to add an action with code to improve the sorting routine: 1. In the Action Designer, go to the next line and type the following to add another action. Ensure that it is indented under the ActionItems ActionContainer. Caption
Type
Improved Sort
Action
2. Click View, C/AL Code to open the C/AL Editor. 3. Locate the OnAction trigger for the Improved Sort action. 4. Type the following code into the OnAction trigger of the action: LoopCount := 0; SwapCount := 0; LowestSwitch := 2; REPEAT IsSorted := TRUE; FOR idx := ARRAYLEN(OutputNumber) DOWNTO LowestSwitch DO BEGIN LoopCount += 1; IF OutputNumber[idx] < OutputNumber[idx-1] THEN BEGIN TempNumber := OutputNumber[idx]; OutputNumber[idx] := OutputNumber[idx-1]; OutputNumber[idx-1] := TempNumber; SwapCount += 1; IsSorted := FALSE; LowestSwitch := idx + 1; END; END; UNTIL IsSorted
5. Close the C/AL Editor and close the Action Designer. 6. Compile, save and close the page. Instead of sorting down to two (comparing with one) every time, now the FOR loops says to sort down to LowestSwitch (comparing with LowestSwitch - one). LowestSwitch starts out as two. But every time that two values are switched (in the THEN clause of the IF statement), it is reset to one more than the element currently being switched.
7-44
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements Because the FOR loop works down, at the end, LowestSwitch is the lowest element to test next time around. Even in the worst case, it is one greater than the previous value and it might be several greater. For example, if the array has ten elements, in the worst case, it will execute the innermost IF statement 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 times = 45 times. If the array has 100 elements, the worst case goes from 9,801 executions down to 4,950. In other words, this simple modification makes the sort runs two times as fast and therefore takes half as long to execute.
Test the Page 1. Run page 90007, Test Arrays Page. 2. Type values into the input column, and then click the Populate Output action. Observe what happens. 3. Click the Sort action and observe what happens. 4. Click the Populate Output action and then click the Improved Sort action. Observe what happens. 5. Click the Clear action and observe what happens. 6. Click the Generate Input action, the Populate Output action and then the Sort action. Observe what happens. 7. Click the Populate Output action and then click the Improved Sort action. Observe what happens.
The WITH Statement Use the WITH statement to ease coding with record variables. Understanding the concepts behind record variables helps lay the groundwork for understanding the WITH statement.
Record Variables A record variable is a complex data type. Similar to an array variable, a record variable contains multiple values. In an array, all the values have the same name and type and are distinguished by an element number, or index. In a record, the various values, known as fields, each has its own name and type. To distinguish these values, a period (.) is used to separate the name of the record variable from the name of the field. Therefore, if a record called Customer has a field that is named Name, to access that field, use Customer.Name. A record represents a row, or a record, in a database table. The fields that comprise a record are defined by using a Table object.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-45
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The Syntax of the WITH Statement The following code sample shows how to assign data in an array, to a record variable: Customer.Name := Txt[1]; Customer.Address := Txt[2]; Customer.City := Txt[3]; Customer.Contact := Txt[4]; Customer."Phone No." := Txt[5];
The WITH statement is used to make this kind of code easier to write and, under many circumstances, easier to read. It has the following syntax: WITH DO <statement>
Within the statement, which can be a compound statement, the record name is no longer needed. Instead, the fields of that record can be used as if they were variables themselves. Therefore, the previous code sample can be rewritten by using the WITH statement as follows: WITH Customer DO BEGIN Name := Txt[1]; Address := Txt[2]; City := Txt[3]; Contact := Txt[4]; "Phone No." := Txt[5]; END;
C/SIDE associates the fields with the Customer record. If there are variable names that are the same as the field names, C/SIDE uses the field from the record, instead of the variable. This ambiguous reference must be avoided.
Implied WITH Statements In many important places that use the WITH statement, the WITH statement is not noticeable. These are implied WITH statements found in the various objects. For example, in a table object, there is an implied WITH statement, covering the whole object. Every reference to a field that is defined in that table has the implied record variable, known as Rec, and a period automatically and invisibly added in front of it.
7-46
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements
Summary There are many kinds of statements in C/AL. These include conditional statements, for example the IF and the CASE statement, compound statements that use the BEGIN and END construct, different kinds of repetitive statements, for example the FOR and the REPEAT...UNTIL statement, and many more. These statements are used everywhere in Microsoft Dynamics NAV. They provide the foundation of how a complete application is written. In addition to simple variables, arrays and records introduce a different way to store values. Both arrays and records are complex variables that hold multiple values. The use of the WITH statement eases the use of record variables to make code easier to read. Understanding the different kinds of statements helps developers decide the best method to write code to achieve certain functionalities.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-47
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Test Your Knowledge 1. In each of these examples, explain if this is an allowable application for arrays. a. You have a list of students, numbered from 1 to 99. Each student takes a test. You want to put the numeric score (from 0 to 100) for each student into an array, with student 1's score going in element 1, student 2's score in element 2, and so on. b. You have a list of students, numbered from 1 to 99. Each student takes a test. You want to create a two-dimensional array with two rows of 99 columns. In the first row, put the corresponding student's name, with student 1's name in element 1,1, student 2's name in element 1,2, and so on. In the second row, put the corresponding student's numeric test score (from 0 to 100), with student 1's score going in element 2,1, student 2's score going in element 2,2, and so on. c. You create an array containing the number of households in each ZIP code. There is one array element for each five-digit ZIP code and each element contains the number of households in that ZIP code. The number of households that have a ZIP code of 30071 goes into element 30071, and so on. d. You create an array containing the number of households in each state. There is one array element for each two-character postal state code and each element contains the number of households in that state. The number of households in Georgia goes into element 'GA', and so on. 2. Which repetitive statement must be used if how many times the statements have to be executed is known? 3. Which repetitive statement does not require a BEGIN and END to execute more than one statement repetitively? 4. Which repetitive statements test the condition at the beginning of each loop? 5. Rewrite the following WHILE statement as a REPEAT statement. Describe the differences in how it is executed. WHILE X > 0 DO BEGIN Y := A * X * X + B * X + C; X := X - 1; END;
7-48
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 7: C/AL Statements
Quick Interaction: Lessons Learned Take a moment and write down three key points you have learned from this chapter 1.
2.
3.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
7-49
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
7-50
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions
CHAPTER 8: C/AL FUNCTIONS Objectives The objectives are: •
Understand the concepts of functions and parameters.
•
Review several built-in functions in the C/AL Symbol Menu.
•
Use the DATE2DMY function in a codeunit.
•
Test knowledge on functions and parameters.
•
Describe the use and syntax of essential C/AL functions.
•
Describe the use and syntax of user communications functions.
•
Describe the use and syntax of string functions.
•
Describe the use and syntax of system functions.
•
Describe the use and syntax of date functions.
•
Describe the use and syntax of number functions.
•
Describe the use and syntax of array functions.
•
Describe the use and syntax of several other important functions.
•
Provide an overview of benefits from creating custom functions.
•
Describe aspects of parameters to consider when creating custom functions.
•
Understand the concepts of local functions and local variables.
•
Create custom functions in a page and call the functions from Actions.
Introduction Sometimes the exact code must be run from different locations. Other times similar code with different variable values must be run from different locations. Writing these codes in a function when they need to be called from different locations not only saves developers' time in development, but also eases developers' tasks in managing and debugging the code. C/SIDE provides many built-in functions in C/AL. These functions can be used in most parts of the application without defining them. They are predefined to achieve certain tasks, such as perform string operations, retrieve a system date, and so on. Understanding C/AL built-in functions and creating custom functions completes developers' skills to build custom application in C/SIDE.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-1
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Functions and Parameters Functions are a fundamental programming element. A function is a named part of a program, also known as a subprogram or subroutine, because, when code that is running reaches a function, the main application is paused while the function code is handled.
Functions When the function name, which is known as the identifier, is used, the current program is suspended and the trigger code for the specified function is executed. Using the identifier in this manner "calls" the function. When the trigger code in the called function is completed, the function "returns" to where it is called from. How the function is called determines what happens when it returns. A function can be used as an expression. For example, the following code uses a function named CalculatePrice as an expression: TotalCost := Quantity * CalculatePrice;
The CalculatePrice function must return a value that is used in evaluating the expression. This return value is then multiplied by the Quantity variable and that result is assigned to the TotalCost variable. A function can also be called by using a function call statement. This statement only calls the function and does not return any value. The following is an example of calling a function named RunFunction: IF Quantity > 5 THEN RunFunction;
The RunFunction returns no data back to the calling trigger.
Parameter A parameter is one or more variables or expressions sent to the function through the function call. The parameter provides information to the function, and the function can modify that information. If a function has parameters, the function identifier has a set of parentheses that follows it. Within these parentheses are one or more parameters. If there is more than one parameter, the parameters are separated by commas.
8-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions Pass by Value When a parameter is passed to a function strictly to give information to the function, the parameter is said to be passed by value. The parameter knows only the value of the variable or expression that is used for the parameter. Because it is only a value, any change that the function does to this parameter does not affect any variables in the calling trigger.
Pass by Reference When a parameter is passed to the function and the function modifies that parameter, the parameter is said to be passed by reference. The parameter knows the variable's location in the computer memory, and it passes the computer memory location to the new function. Any changes that the function makes to this kind of parameter are permanent and affect variables in the calling trigger. If a parameter is passed by value, any expression can be used for that parameter. However, if a parameter is passed by reference, a variable must be used for that parameter so that its value can be changed. A variable has a location in memory, whereas an expression or a constant does not.
Built-in Function A built-in function is a function that is provided within C/SIDE. Its trigger code cannot be viewed, because it is built into C/SIDE. The following table describes some built-in functions: Function Name
Description
MESSAGE
Displays a message on the screen.
MAXSTRLEN
Returns the defined length of a string variable.
COPYSTR
Returns a part of a string.
CLEAR
Clears the passed in variable.
ARRAYLEN
Returns the number of elements in an array.
Functions such as MESSAGE and CLEAR, have no return value. They can only be called by using a function call statement. Functions such as COPYSTR and MAXSTRLEN return a value, and they can be used in an expression. The CLEAR function changes the passed in parameter. It is an example of pass by reference, whereas the other functions are examples of pass by value.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-3
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Review Built-in Functions The C/AL Symbol Menu is a useful tool to review available variables and functions in the current scope of the trigger. It also shows the built-in functions available to developers, together with their syntax.
The C/AL Symbol Menu The following steps show how to open the C/AL Symbol Menu. 1. In the Object Designer's Codeunit List, click the New button. 2. Click the first line under the OnRun trigger, and then click View, C/AL Symbol Menu. 3. Click through the elements in the left column, and view what functions are displayed.
FIGURE 8.1 THE C/AL SYMBOL MENU
8-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions The MESSAGE Function The following steps show how to review the MESSAGE function in the C/AL Symbol Menu. 1. In the left column of the C/AL Symbol Menu, click the DIALOG element to view some built-in functions that are listed. 2. In the right side column, click the MESSAGE function.
FIGURE 8.2 THE MESSAGE FUNCTION IN THE C/AL SYMBOL MENU
The syntax of the MESSAGE function is displayed at the bottom of the frame, above the command buttons in the C/AL Symbol Menu window. The MESSAGE function has the following syntax: MESSAGE(String [, Value1] …)
The syntax tells the following: •
There is no return value.
•
There is one mandatory parameter (String.)
•
There are multiple optional parameters (the square brackets indicate an optional parameter and the ellipsis indicates multiples.)
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-5
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The ERROR Function The following steps show how to review the ERROR function in the C/AL Symbol Menu. 1. In the left column of the C/AL Symbol Menu, click the DIALOG element. 2. In the right side column, click the ERROR function.
FIGURE 8.3 THE ERROR FUNCTION IN THE C/AL SYMBOL MENU
The syntax of the ERROR function is displayed. It has the following syntax: ERROR(String [, Value1] …)
The syntax of the ERROR function is identical to that of the MESSAGE function, except for the function identifier and the functionality. When an ERROR function is called in a function call statement, the processing stops with an error condition and the message is displayed in a similar manner as the MESSAGE function.
The DATE2DMY Function The following steps show how to review the DATE2DMY function in the C/AL Symbol Menu. 1. In the left column of the C/AL Symbol Menu, click the SYSTEM element. The middle column lists various function groupings, such as string functions, numeric (mathematical) functions, and so on. Depending on the selection in the middle column, the right side column shows different functions.
8-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions 2. In the middle column, click the Date group, and in the right side column, click the DATE2DMY function.
FIGURE 8.4 THE DATE2DMY FUNCTION IN THE C/AL SYMBOL MENU
The syntax of the DATE2DMY function is displayed. It has the following syntax: Number := DATE2DMY(Date, What)
The syntax tells the following: •
The function has a return value, that is a number, indicated by the 'Number :=' right before the function identifier.
•
The first parameter (Date) is an expression of type Date.
•
The second parameter (What) is described in more detail in the online Help.
3. Press F1. The online Help opens and displays information for the DATE2DMY function. A complete description of what the function does and what it returns is shown. The What parameter is an integer expression that resolves to one of three values: •
If it is a 1, this function returns the day of the month.
•
If it is a 2, this function returns the month (from 1 to 12).
•
If it is a 3, this function returns the year (the full 4 digits).
4. Close the codeunit without saving it.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-7
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Demonstration: Use the DATE2DMY Function The following demonstration shows how to use the DATE2DMY function. 1. Create a new codeunit, and save it as codeunit 90003, My Codeunit 4. 2. Define the following global variables: Name
DataType
When Was It
Date
Description
Text
Length 30
3. Type the following code in the OnRun trigger: "When Was It" := TODAY; CASE DATE2DMY("When Was It",2) OF 1:Description := 'January'; 2:Description := 'February'; 3:Description := 'March'; 4:Description := 'April'; 5:Description := 'May'; 6:Description := 'June'; 7:Description := 'July'; 8:Description := 'August'; 9:Description := 'September'; 10:Description := 'October'; 11:Description := 'November'; 12:Description := 'December'; END; MESSAGE('%1 is in %2',"When Was It",Description);
4. Compile, save, and close the codeunit. The first line in the code uses the TODAY function. This function has no parameters. It always returns the current date from the client's computer operating system, also known as the system date. 5. Run the codeunit and examine the result.
8-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions
Test Your Knowledge The questions on this self-test relate to the following code. Hand-execute this code to determine the answers. Use the C/AL Symbol Menu and online Help to determine what the various functions do. All these functions can be found in the String group of the SYSTEM element. Do not actually run this code in the test codeunit until reaching question seven. // UserInput is a Text variable of length 100. The other variables are Integers. UserInput := 'The colors are red, orange, yellow, green, blue and violet.'; Count := 0; REPEAT Comma := STRPOS(UserInput,','); //Q1 IF Comma > 0 THEN BEGIN //Q2 Count := Count + 1; UserInput := DELSTR(UserInput,Comma,1); //Q3 UserInput := COPYSTR(INSSTR(UserInput, ' and',Comma),1,MAXSTRLEN(UserInput)); END; UNTIL Comma <= 0; // Display Results MESSAGE('The sentence is "%1". Number of commas is %2.',UserInput,Count); EXIT(Qty * Unit);
1. What is the value of Comma after the statement labeled Q1 is executed the first time? 2. Is the value of Comma ever less than zero in this code (refer to the statement labeled Q2)? 3. What is the value of UserInput after the statement labeled Q3 is executed the first time? 4. What is the value of Count when the comment line is reached the first time? 5. Suppose that UserInput is redefined so that it is a Text of length 60. Now, what is its value when the MESSAGE function after the comment line is reached?
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-9
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 6. The end of the sentence can be lost under these circumstances. Modify the UNTIL clause of the REPEAT statement so that it looks as follows: UNTIL (Comma <= 0) OR (STRLEN(UserInput) + 3 > MAXSTRLEN(UserInput));
Although better, this is not the result desired. Why did it not work? 7. Run this code in a codeunit. Do not forget to define the variables. Make the simplest change possible to address the problem uncovered in question seven. Write down the changes.
Essential C/AL Functions Although there are more than 100 C/AL built-in functions in C/SIDE, developers only use several of these functions repeatedly and the rest of the functions occasionally. Approximately 20 different functions are used most frequently during basic application development. This does not mean that the rest of the C/AL functions are obsolete or never used. It means that becoming comfortable with this set of essential functions can help new developers in C/AL programming. Those who have to add more specialized functionality to their applications can familiarize themselves with the full set of functions.
Searching for Records The functions in this group are used to search for records. When searching for records, remember the difference between GET and FIND - and how to use FIND and NEXT together.
GET The GET function retrieves one record, based on the value of the primary key. For example, if the No. field is the primary key of the Customer table, the GET function can be used as follows: GET(Customer,'4711');
The result is that the record of customer no. 4711 is retrieved. The GET function produces a run-time error if it fails, and the return value is not inspected by the code. The code can look as follows: IF GET(Customer,'4711') THEN .... // do some processing ELSE .... // do some error processing
8-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions The GET function searches for records, regardless of current filters, and it does not change any filters. It always searches among all records in a table.
FIND The differences between the GET function and the FIND function are as follows: •
The FIND function respects (and is limited by) the current setting of filters.
•
The FIND function can be instructed to look for records where the key value is equal to, larger than, or smaller than the search string.
•
The FIND function can find the first or the last record, given the sorting order defined by the current key.
These features can be used in various ways. When developing applications under a relational database management system, developers frequently have one-tomany relationships between tables. An example is the relations between the Item table that records items, and the Sales Line table that records the detail lines from Sales Orders. A 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. An item record in the Item table must not be deleted while there are still open Sales Orders that include the item. The following code sample can be put in the OnDelete trigger of the Item table, and shows how to check for this condition: SalesOrderLine.SETCURRENTKEY("Document Type",Type,"No."); SalesOrderLine.SETRANGE("Document Type",SalesOrderLine."Document Type"::Order); SalesOrderLine.SETRANGE(Type,SalesOrderLine.Type::Item); SalesOrderLine.SETRANGE("No.","No."); IF SalesOrderLine.FIND('-') THEN ERROR('You cannot delete because there are one or more outstanding sales orders that include this item.');
FINDFIRST, FINDLAST and FINDSET To find the first record in a table, depending on the current key and filter, use the FINDFIRST function. The FINDFIRST function must be used instead of FIND('-') when only the first record is needed. To find the last record in a table, depending on the current key and filter, use the FINDLAST function. The FINDLAST function must be used instead of FIND('+') when only the last record is needed. To find a set of records in a table, depending on the current key and filter, use the FINDSET function. The FINDSET function must be used when developers want to loop through a recordset, in combination with REPEAT...UNTIL. It only lets to loop the recordset from the top down. To loop from the bottom up, use FIND('+') instead.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-11
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 NEXT The NEXT function is frequently used with FIND and FINDSET to step through records of a table. The following code sample shows how to use the NEXT function: FINDSET; REPEAT // process record UNTIL NEXT = 0;
The FINDSET function is used to locate the first record of the table. Afterward, the NEXT function is used to step through every record, until there are no more (then, NEXT returns zero.)
Sorting and Filtering Records The functions in this group are used to filter records in a table so that only a subset of the records are displayed, modified, or deleted. Other functions can be used to change the sorting of the records in a table. The following functions are related to sorting and filtering: •
SETCURRENTKEY
•
SETRANGE
•
SETFILTER
•
GETRANGEMIN
•
GETRANGEMAX
SETCURRENTKEY The SETCURRENTKEY function is used to select a key for a record. This sets the sorting order used for the associated table. It has the following syntax: [Ok :=] Record.SETCURRENTKEY(Field1, [Field2],...)
Some characteristics of the SETCURRENTKEY function are as follows: •
Inactive fields are ignored.
•
When searching for a key, C/SIDE selects the first occurrence of the specified field(s).
For example, even if a developer specifies only one field as a parameter when calling SETCURRENTKEY, the key that is actually selected may consist of more fields.
8-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions If no keys can be found that include the specified field or fields, a run-time error occurs unless the Boolean return value of SETCURRENTKEY is handled in the code. If a developer handles the return value, the developer has to decide what the program must do if the function returns FALSE, because without the run-time error, the program continues to run even though no matching key is found.
SETRANGE The SETRANGE function is used to set a delimitation on a field. It sets a simple filter. It has the following syntax: Record.SETRANGE(Field [,From-Value] [,To-Value]);
The following code sample shows how to use the SETRANGE function: Customer.SETRANGE("No.",'10000','90000');
This limits the Customer table by selecting only those records where the No. field has a value between 10000 and 90000. The SETRANGE function removes previous filters. If it is used without the From-Value or To-Value parameters, the function can be used to remove any filters that might already be set. If only the From-Value parameter is used, the To-Value parameter is set to the same value as the From-Value parameter.
SETFILTER The SETFILTER function sets a filter in a more general way than SETRANGE. It has the following syntax: Record.SETFILTER(Field, String [, Value], ...];
The Field parameter is the name of the field to set a delimitation on. The String parameter is a filter expression that can contain operators and placeholders such as %1, %2 and so on to indicate locations where the system inserts values given as the Value parameters. The following code sample shows how to use the SETFILTER function: Customer.SETFILTER("No.", '>10000 & <> 20000');
This code selects records where the No. is larger than 10000 and not equal to 20000. The following code sample performs the same thing as the previous one, if the variable Value1 is assigned 10000 and Value2 is assigned 20000: Customer.SETFILTER("No.",'>%1&<>%2',Value1, Value2);
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-13
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 GETRANGEMIN The GETRANGEMIN function retrieves the minimum value of the delimitation currently in effect for a field. It has the following syntax: Record.GETRANGEMIN(Field);
The GETRANGEMIN function causes a run-time error if the filter currently in effect is not a range. For example, if a filter is set as follows: Customer.SETFILTER("No.",'10000|20000|30000');
Then the following fails, because the filter is not a range: BottomValue := Customer.GETRANGEMIN("No.");
GETRANGEMAX The GETRANGEMAX function works like the GETRANGEMIN function, except that it retrieves the maximum value of the delimitation currently in effect.
Inserting, Modifying, and Deleting Records The functions in this group are used to maintain the database by adding, modifying, and removing records. Generally, these functions return a Boolean value that indicates whether they have succeeded or not. If developers do not handle the return value in their code, a run-time error occurs when a function returns as FALSE. If developers handle the return value, they have to decide what the program must do if the function returns as FALSE. The following functions are related to inserting, modifying, and deleting: •
INSERT
•
MODIFY
•
MODIFYALL
•
DELETE
•
DELETEALL
INSERT The INSERT function inserts a record in a table. The following code sample shows how to use the INSERT function: Customer.INIT; Customer."No." := '4711'; Customer.Name := 'John Doe'; Customer.INSERT;
8-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions This code inserts a new record, with the No. and Name having the assigned values, whereas the other fields have their default values. Supposing that No. is the primary key of the Customer table, the record is inserted in the Customer table unless there already is a record in the table with the same primary key. In that case, since the return value is not handled, a run-time error occurs.
MODIFY The MODIFY function is used to modify an existing record. Similar to the INSERT function, it returns a Boolean value (TRUE if the record to be modified exists and FALSE otherwise.) The following code sample shows how to use the MODIFY function: Customer.GET('4711'); Customer.Name := 'Richard Roe'; Customer.MODIFY;
The code changes the name of customer 4711 to Richard Roe.
MODIFYALL The MODIFYALL function is used to do a bulk update of records. It respects the current filters, meaning that developers can perform the update on a specified set of records in a table. The MODIFYALL function does not return any value, nor does it cause an error if the set of records to be changed is empty. The following code sample shows how to use the MODIFYALL function: Customer.SETRANGE("Salesperson Code",'PS','PS'); Customer.MODIFYALL("Salesperson Code",'JR');
The SETRANGE statement selects the records where the Salesperson Code is PS, and the MODIFYALL function changes these records to have the Salesperson Code set to JR.
DELETE The DELETE function is used to delete a record from the database. The record to be deleted must be specified, by using the values in the primary key fields, before calling the function. The DELETE function takes filters into consideration. The DELETE function returns a Boolean value (TRUE if the record to be deleted exists and FALSE otherwise.) The following code sample shows how to use the DELETE function: Customer."No." := '4711'; Customer.DELETE;
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-15
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 DELETEALL The DELETEALL function is used to delete all records that are selected by the filter settings. If no filters are set, all records in the table are deleted. The following code sample shows how to use the DELETEALL function to delete all records where the Salesperson Code is PS from the Customer table: Customer.SETRANGE("Salesperson Code", 'PS', 'PS'); Customer.DELETEALL;
Transactions Usually, developers do not have to be concerned about transactions and table locking when they develop applications in C/SIDE. There are some situations where developers must lock a table explicitly. For example, if developers inspect data in a table at the beginning of a function, and then use this data to perform various checks and calculations, and finally want to write-back a record, based on the result of this processing, they want the values that are retrieved at the beginning to be consistent with the data in the table now. In short, other users must not be able to update the table while the function is busy doing its calculations.
LOCKTABLE The solution to keeping others from using a table that is making calculations is to lock the table manually, at the beginning of the function, by using the LOCKTABLE function.
Working with Fields The following functions perform actions on fields: •
CALCFIELDS
•
CALCSUMS
•
FIELDERROR
•
FIELDNAME
•
INIT
•
TESTFIELD
•
VALIDATE
CALCFIELDS The CALCFIELDS function is used to update FlowFields. FlowFields are automatically updated when they are used as direct source expressions of controls. However, they must be explicitly calculated when they are not. That is, when they are part of a more complex expression.
8-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions When using FlowFields in C/AL functions, they must be updated, and this is what the CALCFIELDS function is used for. The following code sample shows how to use the SETRANGE function to set a filter and the CALCFIELDS to update the FlowFields. SETRANGE("Date Filter",0D,TODAY); CALCFIELDS(Balance,"Balance Due");
The CALCFIELDS function calculates the Balance and Balance Due fields by taking account of filter setting and calculations that are defined as the CalcFormula properties of the FlowFields.
CALCSUMS The CALCSUMS function is used to calculate the sum of one or more fields that are SumIndexFields in the record. For the CALCSUMS function to work, a key that contains the SumIndexFields must be selected as the current key. Similar to the CALCFIELDS function, the CALCSUMS function takes the current filter settings into account when performing the calculation. The following code sample shows the selection of the appropriate key, the filters setting, and the summation. SETCURRENTKEY("Customer No."); SETRANGE("Customer No.",'10000','50000'); SETRANGE(Date,0D,TODAY); CALCSUMS(Amount);
FIELDERROR The FIELDERROR function triggers a run-time error after displaying a fieldrelated error message. This function is similar to the ERROR function, but it is easier to use and has some benefits. Most importantly, if the name of a field is changed, for example, translated to another language in the Table Designer, the message from the FIELDERROR function reflects the current name of the field. The following code sample shows how to use the FIELDERROR function: Item.GET('70000'); IF Class <> 'HARDWARE' THEN FIELDERROR(Class);
This causes an appropriate message to be displayed, depending on whether Class currently is empty or has a value.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-17
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Custom text can be added if the default text does not suit the application. The following code sample shows how to use the FIELDERROR function with a custom text: IF Class < '4711' THEN FIELDERROR(Class,'must be greater than 4711');
FIELDNAME The FIELDNAME function returns the name of a field. By using the FIELDNAME function, messages that are created are still meaningful even if the field name is later changed. The FIELDNAME function can be used together with the FIELDERROR function. The following code sample shows this construction: FIELDERROR(Quantity,'must not be less than ' + FIELDNAME("Quantity Shipped"));
INIT The INIT function initializes a record. If a default value for a field is defined, by the InitValue property, this value is used for the initialization; otherwise, the default value of each data type is used. The INIT function does not initialize the fields of the primary key.
TESTFIELD The TESTFIELD function is used to test a field against a value. If the values are not the same, the test fails, an error message is displayed, and a run-time error is triggered. This means that any changes made to the record are discarded. If the value to test against is the empty string, the field has to have a value other than blank or zero. The following code sample shows how to use the TESTFIELD function to generate an error message: Code := 'DK' TESTFIELD(Code,'ZX');
VALIDATE The VALIDATE function is used to call the OnValidate trigger of a field. The following code sample shows how to use the VALIDATE function to call the OnValidate trigger of the Total Amount field: VALIDATE("Total Amount");
8-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions The VALIDATE function is useful for centralizing processing. It makes applications easier to maintain. Suppose that the OnValidate trigger of the Total Amount field performs a calculation with values from three other fields as operands. If the contents of any of these fields changes, the calculation must be performed. Avoid entering the calculation formula in the OnValidate triggers of every field because there are many possibilities for errors if the calculation formula must be changed later. Instead, perform the calculation in the OnValidate trigger in only one of the fields, and call this trigger code from the OnValidate triggers of the other fields by using the VALIDATE function.
User Communication Functions The following functions give users feedback and an opportunity to input information into the program: •
MESSAGE
•
CONFIRM
•
STRMENU
•
ERROR
MESSAGE The MESSAGE function has the following syntax: MESSAGE (String [, Value1, ...])
The MESSAGE function is frequently used for debugging, such as displaying values of variables. However, if an error occurs, the process stops and the message is not displayed, because it is run non-modally. If there is no error, the MESSAGE function displays a message to the user, only after the process is completed. The message window remains open until the user clicks the OK button (or presses the ENTER key). Several characters are used for special purposes in the String parameter. •
The plus character (+) is used to concatenate text.
•
The backslash character (\) is used to start a new line.
•
The % and # symbols can be used as variable placeholders. The percent symbol is used for free format and the pound symbol is for fixed formats.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-19
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The following code sample shows how to use the MESSAGE function: Value1 := 12345.678; Value2 := 987.65; MESSAGE('The Free Format of Value1 is %1 \' + 'The Fixed Format of Value2 is #2#########', Value1, Value2);
When this code is run, the result is as follows:
FIGURE 8.5 THE MESSAGE FUNCTION
CONFIRM The CONFIRM function has the following syntax: CONFIRM (String [, Default] [, Value1, ...])
The CONFIRM function is similar to the MESSAGE function. It displays a message to the user. The difference is that the CONFIRM function enables the user to answer a question by clicking the Yes or No button and returns a Boolean value (TRUE or FALSE), that corresponds to the user's selection. The CONFIRM function is run modally. Therefore, the system waits for the user's response. The CONFIRM function is frequently used to confirm that the user wants to continue with a process. Microsoft Dynamics® NAV uses the CONFIRM functions before posting records. The user is given an opportunity to stop the posting process or to continue. The Default parameter specifies the default button in the message window. If it is FALSE, the No button is set as the default button and is active. If the user only presses ENTER, the function returns a FALSE. If the Default parameter is TRUE, the Yes button is set as the default button instead. The following code sample shows how to use the CONFIRM function: IF NOT CONFIRM('Do you want to post the Journal Lines?') THEN EXIT; // Otherwise run the posting routine.
8-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions When this code is run, the result is as follows:
FIGURE 8.6 THE CONFIRM FUNCTION
The CONFIRM function responses are limited to Yes and No. If other responses are needed, use the STRMENU function.
STRMENU The STRMENU function has the following syntax: STRMENU (OptionString [, DefaultNumber])
The STRMENU is used to create and display a menu window with an option group. It returns an integer value of the user's selection. If the DefaultNumber parameter is not set, the first element in the option string is defaulted as the choice, with a value of one. A zero value is returned if ESC is pressed. This indicates no choice by the user. The following code sample shows how to use the STRMENU function: MESSAGE('Your selection returns the value of %1', STRMENU('Yes, No, N/A'));
When this code is run, the result is as follows:
FIGURE 8.7 THE STRMENU FUNCTION
ERROR The ERROR function has the following syntax: ERROR(String [, Value1, ...])
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-21
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The ERROR function raises an error condition and leaves the current process, canceling the whole process, not only the function. If the code is in a transaction, the transaction is stopped and all uncommitted data is rolled back. The ERROR function displays an error message to the user that informs the user why additional processing is not allowed. The String parameter specifies this error message. The following example uses the ERROR function: Number := -1; IF Number <= 0 THEN BEGIN ERROR('Number must be positive. Current value: %1.', Number); MESSAGE('This Message is never displayed'); END;
When this code is run, the result is as follows:
FIGURE 8.8 THE ERROR FUNCTION
String Functions The following functions enable the developer to manipulate strings: •
STRPOS
•
COPYSTR
•
PADSTR, STRLEN, MAXSTRLEN
•
LOWERCASE and UPPERCASE
•
CONVERTSTR
•
DELCHR
•
INCSTR
•
SELECTSTR
•
STRCHECKSUM
STRPOS The following example uses the STRPOS function: Position := STRPOS(String, SubString)
8-22
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions This function is used to search for the first occurrence of a substring in a string. It returns the position of the first character of the substring within the string. If the substring is not found within the string, the function returns a zero. As with all string functions, the STRPOS function is case-sensitive.
COPYSTR The COPYSTR function has the following syntax: NewString := COPYSTR(String, Position [, Length])
This function is used to copy a substring of any length from a specific position in a string to a new string. If the Length parameter is omitted, the result includes all characters from Position to the end of the string.
PADSTR The PADSTR function has the following syntax: NewString := PADSTR(String, Length [, FillCharacter])
This function is used to change the length of a string to another length. If the Length parameter is smaller than the actual length of the string, the string is truncated. Otherwise, it adds the filler characters to the end of the string. If the FillCharacter parameter is omitted, then blanks are added.
DELSTR and INSSTR There are two other functions similar to PADSTR function. They are as follows: •
The DELSTR function which is used to delete a substring from a string.
•
The INSSTR function which is used to insert a substring into a string at a specified position.
These functions have the following syntax: NewString := DELSTR(String, Position [, Length]) NewString := INSSTR(String, SubString, Position)
STRLEN The STRLEN function has the following syntax: Length := STRLEN(String)
This function returns an integer that is the length of the string in the parameter.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-23
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 MAXSTRLEN The MAXSTRLEN function has the following syntax: MaxLength := MAXSTLEN(String)
Similar to the STRLEN function, the MAXSTRLEN function also returns an integer. However, that integer represents the maximum length defined for that string variable.
LOWERCASE and UPPERCASE The LOWERCASE and UPPERCASE functions have the following syntax: NewString := LOWERCASE(String), NewString := UPPERCASE(String)
They convert a string to an all lower-case or upper-case string, respectively.
CONVERTSTR The CONVERTSTR function has the following syntax: NewString := CONVERTSTR(String, FromCharacters, ToCharacters)
This function converts the characters in a string, depending on the characters in the strings FromCharacter and ToCharacters parameters that serve as conversion tables.
DELCHR The DELCHR function has the following syntax: NewString := DELCHR(String [, Where] [, Which])
This function is used to delete one or more characters in a string. It can delete characters from either end of the string or all instances throughout the string. This function can be used to trim strings of blanks as follows: DELCHR(StringVar, '<>', ' ');
INCSTR The INCSTR function has the following syntax: NewString := INCRSTR(String)
8-24
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions This function is used to increase a positive number or decrease a negative number inside a string by one (1). If there is more than one number in a string, it changes the first number.
SELECTSTR The SELECTSTR function has the following syntax: NewString := SELECTSTR(Number, CommaString)
This function retrieves a substring from a comma-separated string. The substrings are numbered starting with one.
STRCHECKSUM The STRCHECKSUM function has the following syntax: CheckNumber := STRCHECKSUM(String [,WeightString] [, Modulus])
This function is used for various different applications such as bar codes. It calculates a checksum for a string that contains a number.
System Functions System functions do not require any parameters because they return information that is stored in the system. They include the following: •
USERID
•
COMPANYNAME
•
TODAY and TIME
•
WORKDATE
•
GETLASTERRORTEXT and CLEARLASTERROR
•
APPLICATIONPATH
•
TEMPORARYPATH
USERID The following code sample shows how to use the USERID function: Name := USERID;
This function returns the ID of the current user.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-25
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 COMPANYNAME The following code sample shows how to use the COMPANYNAME function: Name := COMPANYNAME;
This function returns the current company that is used by the Microsoft Dynamics NAV client.
TODAY and TIME The following code sample shows how to use the TODAY and TIME functions: DateVar := TODAY; TimeVar := TIME;
These functions return the operating system's date and time.
WORKDATE The WORKDATE function has the following syntax: [WorkDate] := WORKDATE([NewDate])
This function returns the current work date or can be used to set the work date. However, according to Microsoft Dynamics NAV standard, the work date must not be changed by code.
GETLASTERRORTEXT and CLEARLASTERROR The GETLASTERRORTEXT function returns the standard error text presented in an error dialog window. The function returns the last error text. If no error has occurred, it returns an empty string. The returned string cannot exceed 1024 characters. This is the maximum string length in Microsoft Dynamics NAV. The CLEARLASTERROR function clears any previous error text so that the next calls to GETLASTERRORTEXT returns an empty string.
APPLICATIONPATH In some cases, the application must know where the Microsoft Dynamics NAV client is installed on the hard disk. For example, the application might have to read files that are installed with Microsoft Dynamics NAV, such as company setup templates or the End-User License Agreement. The APPLICATIONPATH function returns a string specifying the installation directory, ending with a backslash ("\") and without the executable file. The string cannot exceed 255 characters.
8-26
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions The following code sample shows how to use the APPLICATIONPATH function to display the path of the End-User License Agreement: StrPath := APPLICATIONPATH + 'EULA.rtf'; MESSAGE(StrPath);
The run time system interprets backslashes as line feeds. Therefore, assuming that Microsoft Dynamics NAV is installed in the default location, the result is as follows:
FIGURE 8.9 THE APPLICATIONPATH FUNCTION
TEMPORARYPATH The TEMPORARYPATH function returns the name of the folder where temporary files are created. The TEMPORARYPATH function returns the path and not a file name, so developers can determine the name of the temporary file that is created in the temporary folder. The tradeoff is that there is no guarantee that the name of the file is unique. Temporary files that are created in the temporary folder through the TEMPORARYPATH function are not deleted automatically when they are closed. The following code sample shows how to use the TEMPORARYPATH function: TempName := TEMPORARYPATH + 'AppTemplate.HTM'; FileCreated := TempFile.CREATE(TempName); IF FileCreated THEN MESSAGE('created file: ' + TempName) ELSE MESSAGE('failed to create file');
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-27
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 When this code is run, the result is as follows:
FIGURE 8.10 THE TEMPORARYPATH FUNCTION
Date Functions The following functions provide specific information about a given date: •
DATE2DMY
•
DATE2DWY
•
CALCDATE
•
NORMALDATE
•
CLOSINGDATE
DATE2DMY The DATE2DMY has the following syntax: IntegerVar := DATE2DMY(Date, Integer)
This function returns information about the Date parameter, depending on the Integer parameter.
8-28
Integer value
Usage
1
Returns the day of the month (1-31)
2
Returns the month (1-12)
3
Returns the year (0001-9999)
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions DATE2DWY The DATE2DWY has the following syntax: IntegerVar := DATE2DWY(Date, Integer)
This function also returns information about the Date parameter, depending on the Integer parameter. Integer value
Usage
1
Returns the day of the week (1-7), where day 1 is Monday
2
Returns the week of the year (1-53)
3
Returns the year (0001-9999)
CALCDATE The CALCDATE function has the following syntax: CALCDATE(DateExpression [, Date])
The CALCDATE function is a powerful function. It calculates a new date based on a date expression and a reference date. The following are some examples of a date expression: Date Expression
Usage
CQ + 1M - 10D
Last Day of Current Quarter + 1 Month - 10 Days
-WD2
Last second Day of the Week, (last Tuesday)
CM + 30D
Last Day of Current Month + 30 Days
The following code sample shows how to use the CALCDATE function: CALCDATE('CM +15D', 030502D);
In this code sample, the CALCDATE function starts with March 5, 2002 as the reference date and goes to the last day of that current month (CM). This brings the calculation to 03/31/02. Then it adds 15 days that results in April 15, 2002. The date expression can be of any length. It must have at least one subexpression. The system interprets the string from left to right, one sub-expression at a time. The sub-expression is either a positive or negative Term value.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-29
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The Term value can be a combination of the following: •
Number-Unit
•
Unit-Number
•
Prefix-Unit
The Number is a positive integer. The Unit can be one of the following: Term
Definition
D
Date
WD
WeekDay
W
Week
M
Month
Q
Quarter
P
Period
Y
Year
There is one Prefix, C, that represents the closing date of that period. The closing date for a quarter represents 11:59:59 PM of the last day of the last month in the quarter. Every date, from 01/03/0001 to 12/31/9999 has a corresponding normal date and closing date, used for closing journal entries. To the system, a closing date represents 11:59:59 PM of that date. Closing dates are sorted immediately after the corresponding normal date, but before the next normal date. The letter D indicates a normal date, and C indicates a closing date. The NORMALDATE and CLOSINGDATE functions determine which type of date is being used.
NORMALDATE The NORMALDATE function has the following syntax: ReturnDate := NORMALDATE(Date)
This function returns the corresponding normal date of a date. A common location to view this function is in the posting routines. For example, posting dates or invoice dates must be normal dates. The following code sample ensures that only normal dates are posted, by using the NORMALDATE function: IF "Posting Date" <> NORMALDATE("Posting Date") THEN ERROR('Posting Date cannot be a closing date');
8-30
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions CLOSINGDATE The CLOSINGDATE function has the following syntax: ReturnDate := CLOSINGDATE(Date)
This function is the opposite of the NORMALDATE function. It returns the corresponding closing date of a date.
Number Functions The majority of number functions are rarely used, except for the ROUND function. The ROUND function is used very frequently when dealing with currency and tax. The number functions include the following: •
ABS
•
POWER
•
ROUND
•
RANDOMIZE
•
RANDOM
ABS The ABS function has the following syntax: NewNumber := ABS(Number)
This function returns the absolute value of the number.
POWER The POWER function has the following syntax: NewNumber := POWER(Number, Power)
This function raises the Number parameter to the Power parameter. It can also be used to calculate roots. For example, to calculate the square root of 16, use POWER(16, 0.5) which returns 4.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-31
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 ROUND The ROUND function has the following syntax: NewNumber := ROUND(Number [,Precision] [, Direction])
This function returns a rounded number. The Precision parameter specifies the precision used when rounding off. The default value is .01, although the settings in the General Ledger Setup affect this. The Direction parameter specifies how to round and has the following options: Direction Parameter
Rounding Direction
=
Rounds to the nearest value (default)
<
Rounds down
>
Rounds up
RANDOMIZE The RANDOMIZE function has the following syntax: Randomize([Seed])
This function generates a set of random numbers. The Seed parameter is an optional integer value that is used to create a unique set of numbers. The same seed number results in the same set. If the Seed parameter is omitted, the total number of milliseconds since midnight is calculated for the current system time and is used as the seed.
RANDOM The RANDOM function has the following syntax: Number := RANDOM(MaxNumber)
This function returns a pseudo-random number between 1 and MaxNumber by using the random number set from the RANDOMIZE function. Until the RANDOMIZE is called again, the RANDOM function chooses a number from the same set of numbers.
Array Functions Arrays are often used in reports for address and label information. The array functions include the following: •
8-32
ARRAYLEN
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions •
COMPRESSARRAY
•
COPYARRAY
ARRAYLEN The ARRAYLEN function has the following syntax: Length := ARRAYLEN(Array [, Dimension])
This function returns the total number of elements in an array or the number of elements in a specific dimension of the array. A three-dimensional array has valid dimensions of one, two, and three. If the Dimension parameter is omitted, the return value represents the number of elements in the whole array, and not any dimension.
COMPRESSARRAY The COMPRESSARRAY function has the following syntax: [Count :=] COMPRESSARRAY(StringArray)
This function is only useful for text or code arrays. It moves all the non-empty strings of the array to the beginning of the array. The array contains the same number of elements. The empty entries and those that contain only blanks appear at the end of the array. If a return value is handled, it represents the number of non-empty strings the system compressed. A good example of how to use this function is when printing names and addresses. This function is useful to remove blank lines in account statements or from multiline addresses.
COPYARRAY The COPYARRAY function has the following syntax: COPYARRAY(NewArray, Array, Position [, Length])
This function copies one or more elements from an array to a new array. The Position parameter specifies the position of the first array element to copy, whereas the optional Length parameter specifies the number of array elements to copy. If the Length parameter is omitted, all array elements from Position to the last element are copied. The COPYARRAY function is only used for onedimensional arrays. It can be used repeatedly to copy more dimensions.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-33
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Other Functions The following functions are several other important functions that are used throughout Microsoft Dynamics NAV: •
EXIT
•
CLEAR
•
CLEARALL
•
EVALUATE
•
FORMAT
EXIT The EXIT function has the following syntax: EXIT (Value)
This function leaves the current function or trigger immediately. If there is a parent function that calls this current function or trigger, the Value parameter of the EXIT function is returned to the calling function. The EXIT function causes no error condition nor does it roll back any data. The following code sample shows how to use the EXIT function: Function AddTen (Number : Integer) : Integer BEGIN EXIT(Number + 10); MESSAGE('This line is never read.'); END;
CLEAR The CLEAR function has the following syntax: CLEAR(Variable)
This function clears the value of a single variable, or all elements of an array, to the following:
8-34
Variable Type
Clearing Result
Number
0 (zero)
String
Empty string
Date
0D (undefined date)
Time
0T (undefined time)
Boolean
FALSE
Number
0 (zero)
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions CLEARALL The CLEARALL function clears all internal variables in the current object and in any called objects such as reports, and units of code, that contain C/AL code. It works by calling CLEAR repeatedly for each variable. The CLEARALL function has no parameter. When an object is called repeatedly within the same process, the system retains all values for variables and filters in memory between calls. The CLEARALL function clears all of these.
EVALUATE The EVALUATE function has the following syntax: [Ok :=] EVALUATE(Variable, String[, Number])
This function converts a string expression into another appropriate data type. The result is assigned to the Variable parameter.
FORMAT The FORMAT function has the following syntax: String := FORMAT(Value [, Length] [, FormatNumber | FormatString])
This is a powerful function. At the basic level, it can convert any type of variable to a string variable. The following code sample shows how to use the FORMAT function to convert a decimal variable to a string: TextVar := FORMAT(DecimalVar);
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-35
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The Length parameter is an integer value that ensures that if the value is larger than the maximum length that the String allows for, a run-time error does not occur. Length value
Usage
0
The system returns the whole value. This is the default.
>0
Returned string is exactly Length characters. • If Value is less than Length characters, either leading or trailing spaces are inserted, depending on the format that is selected.
<0
•
If Value is an integer that exceeds Length digits, Length asterisks are placed in String.
•
If Value is not an integer and it exceeds Length characters, String is truncated accordingly.
Returned string will have the maximum length of Length characters. • If Value is less than Length characters, the length of String will equal the length of Value. •
If Value is an integer that exceeds Length digits, Length asterisks are placed in String.
•
If Value is not an integer and it exceeds Length characters, String is truncated accordingly.
Only one of the next two parameters is used at any time. The FormatNumber parameter specifies the format the system uses. The basic options are as follows: Format Number value
Usage
0
Standard Display Format (the default for all data types)
1
Standard Display Format 2 (edit)
2
C/AL Code Constant Format
Other options are available depending on the data type. The FormatString parameter is a literal string that specifies a format as in the Format property. The Format property describes the various predefined formats in detail, and how to create customized formats. The following code sample shows how to use the FORMAT function: MESSAGE('The formatted value: %1', FORMAT(-123456.78, 15, 0));
8-36
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions When this code is run, the message window displays the message:
FIGURE 8.11 THE FORMAT FUNCTION MESSAGE('The formatted value: %1', FORMAT(-123456.78, 5, 3)); // Changed Length to 5
When this code is run, the message window displays the following message:
FIGURE 8.12 THE FORMAT FUNCTION MESSAGE('Today is %1', FORMAT(TODAY,0,'<Month Text> .'));
When this code is run, the message window displays the following message:
FIGURE 8.13 THE FORMAT FUNCTION
Sometimes, negative numbers must be displayed as strings enclosed in parentheses instead of being preceded by a minus sign (-). If these numbers are part of a vertical list of numbers, usually a trailing space must be added at the end of the positive numbers (so that the negative numbers enclosed in parentheses are aligned with the positive numbers).
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-37
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The following code sample shows how to use the FORMAT function to achieve this: DecimalVar := -1234.56; IF DecimalVar < 0 THEN BEGIN StringVar := FORMAT(DecimalVar, 0, '(<decimals>)'); MESSAGE(StringVar); END ELSE BEGIN StringVar := FORMAT(DecimalVar, 0, '<decimals> '); MESSAGE(StringVar); END;
The < and > signs are part of the FormatString parameter. For the negative numbers, the parenthesis is inside the single quotation marks. For the positive values, there is a space before the last single quotation mark for alignment. When this code is run, the message window displays the following message:
FIGURE 8.14 THE FORMAT FUNCTION
Create Custom Functions Creating custom functions helps make code more efficient. This includes adding, removing, or editing code one time in a function that is used several times in an application, and the change is applied in every instance of the function.
Reasons to Create Custom Functions Some reasons to create custom functions include the following:
8-38
•
To organize the program. A function is to code what the headings are to a well-organized written document. They make the program easier to follow, not only for the original developer, but also for other developers who may have to modify the code later.
•
To simplify developers tasks. When designing a program, developers can break a complex problem into multiple smaller tasks. Each of these tasks can become a function in the program and the whole program can be built from these smaller tasks. If a function proves to be too complex, developers can do the same thing again: break it apart into smaller tasks and create a new function for each task.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions •
To make code reusable, reducing work. If exactly the same thing or very similar things are done in two separate parts of a program, consider creating a function to do that task. Then, instead of writing the same or similar code in two or three locations, write it in one location and call it from other locations.
•
To reduce the possibility of errors. A function can be tested thoroughly by itself. Therefore, when it is used in another location, it is a known quantity; when developers are searching for errors, they can reduce the search. Similarly, if an error is found in a function, it can be fixed in one place and it is automatically fixed in all the locations that called that function. If developers have to fix it in each location, they might forget one or add another bug.
•
To make modifications easier. If developers have to modify the way a program works and they have similar code in many locations, their modifications must be made to each of those locations. If the common code is put in a function, developers can make modifications to one location and every other location that uses that function is updated also. This reduces work and reduces the possibility of introducing more errors.
•
To localize data. When a function performs a task, it can have its own local data that cannot be tampered with by other functions in the same object. Similarly, by using its own local data, it does not tamper with data that is owned by other functions. If global variables are used by many tasks throughout the program, there is a good chance that this data can become corrupted.
•
To reduce the size of the objects. Although a minor consideration, it can be worthwhile, especially when trying to locate something in the code.
There are many good reasons to create functions. In fact, when designing code for an object, the first thing to do is determine the major tasks and create, or define, a function for each one. Then, as similar things are organized in different locations, consider adding another function to handle that task. Another reason to create functions, which is specific to C/SIDE, is that functions are one of the main ways to communicate between objects. Variables cannot be shared across objects, but functions can.
Formal and Actual Parameters It is important to understand the underlying elements for a function. Understanding the concepts of formal and actual parameters helps with the choices involved in creating a custom function.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-39
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Formal Parameter The formal parameter is defined in the function definition. For example, the DELSTR function has the following syntax: NewString := DELSTR(String, Position [, Length])
The words that appear in parentheses are the formal parameters.
Actual Parameter The actual parameter is used when the function is called. The following example shows an example of calling the DELSTR function: UserInput := DELSTR(UserInput,Comma,1);
The constant and variables that appear in the parentheses are the actual parameters. There is a one-to-one correspondence between the actual parameters and the formal parameters. The actual parameter UserInput becomes the formal parameter String, the actual parameter Comma becomes the formal parameter Position and the actual parameter 1 becomes the formal parameter Length. Because this code uses a pass-by value for all three parameters, what is actually being passed to the function are the values of the three actual parameters. Therefore, the actual parameters are not changed when the formal parameters are changed inside the function. If the code uses a pass-by reference instead, it passes the variable references (memory addresses) to the function. Then the actual parameters are changed if the corresponding formal parameters are changed inside the function. Because constants cannot be changed, 1 cannot be used as an actual parameter if Length is passed by reference.
Local Functions, Variables and the EXIT Statement Some functions and variables have a limited scope. They can only be used in the location where they are defined.
Local Function A local function is a function that can only be called in the object in which it is defined. Any function that is not defined as a local function can be called from other objects and from the object in which it is defined.
8-40
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions Local Variable A local variable is a variable that scope is limited to a single function. This means that in the particular function trigger code, a local variable can be used like any other variable. However, throughout the rest of the object, this variable cannot be accessed. If the name of a local variable is referred to outside the function in which it is defined, a syntax error occurs. The formal parameters of a function are also treated as local variables in that function.
The EXIT Statement The EXIT statement is used to stop the execution of a trigger. It can be used for function triggers also. However, in functions, the EXIT statement has an additional use. When a function call is used in an expression, the function is required to return a value. When writing a function that has a return value, signal to the system to return a value by using the EXIT statement. The EXIT statement has the following syntax: EXIT(<expression>);
For example, create a function named SQUARE that is used to square a value. The following expression results in the Answer variable being assigned the value 29. Answer := 4 + Square(5);
The SQUARE function trigger code can be written as follows, if the formal parameter is named Param: EXIT(Param * Param);
The EXIT statement's parameter is the expression that squared the parameter and that is what the function returns to its caller.
Demonstration: Create Custom Functions The following demonstration shows how to create custom functions and add actions that calls the functions, in a page.
Set the Page Instead of creating a new page from scratch, design page 90006, Test Statements and save it as a new page. 1. Design page 90006, Test Statements, from the Object Designer. 2. Compile and save it as page 90008, Test Functions Page.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-41
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Create a Custom Function The following steps show how to create a custom function in a page. 1. Click View, C/AL Globals. 2. Click the Functions tab. This is where developers define custom functions. 3. Type Accumulate in the Name column. This is the name of the first custom function. 4. Click View, Properties, to open the Properties window for the Accumulate function. 5. Set the Local property to Yes. This sets the function to a local function. This function can only be called within the page itself and not from any object outside this page. 6. Close the Properties window. 7. In the C/AL Globals window, click the Locals button. The Accumulate - C/AL Locals window opens. This window is used to complete the definition of the Accumulate function. The four tabs at the top of this window indicate that developers can set the formal Parameters, the Return Value, Local Variables and Text Constants for the function. 8. Type the following in the Parameters tab: Name
DataType
Qty
Integer
The column named Var, an abbreviation for Variable, is used to set this parameter to be passed by reference. A parameter that is passed by reference must be a variable, not an expression. In this case, do not select this column. 9. Close the Accumulate - C/AL Locals window to return to the C/AL Globals window. The definition of the Accumulate function is now completed.
Create another Custom Function The following steps show how to create another custom function in a page. 1. In the Functions tab of the C/AL Globals window, type Extend in the Name column. This is the name of the second custom function. 2. Set its Local property to Yes. 3. Click the Locals button and create two parameters: o Qty of type Integer o Unit of type Decimal
8-42
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions 4. Click the Return Value tab on the C/AL Locals window. 5. Click the Return Type drop-down arrow, and select Decimal. This sets decimal as the return type for this function. 6. Close the C/AL Locals window and close the C/AL Globals window. The definition of the Extend function is now completed.
Add Code to the Functions The following steps show how to add the code to the function trigger. 1. In the Page Designer, click View, C/AL Code to open the C/AL Editor. 2. Type the following code into the Accumulate function trigger: Result := Extend(Qty,UnitPrice); IF Result < 0 THEN BEGIN TotalCredits := TotalCredits + Result; TotalQtyCredits := TotalQtyCredits + Qty; END ELSE BEGIN TotalSales := TotalSales + Result; TotalQtySales := TotalQtySales + Qty; END; GrandTotal := GrandTotal + Result; GrandQtyTotal := GrandQtyTotal + Qty;
3. Type the following code into the Extend function trigger: EXIT(Qty * Unit);
4. Close the C/AL Editor.
Call the Function from an Action The following steps show how to add an action that calls the custom function. 1. Open the Action Designer for the page. 2. Go to the last line and type the following to add an action. Ensure that it is indented under the ActionItems ActionContainer. Caption
Type
Execute Sale
Action
3. Click View, C/AL Code to open the C/AL Editor.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-43
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 4. Locate the OnAction trigger for the Execute Sale action. 5. Type the following code into the OnAction trigger of the action: IF Quantity = 0 THEN EXIT; Accumulate(Quantity);
6. Close the C/AL Editor.
Call the Function from another Action One of the assets of having a function is that for similar code, developers do not have to write the code multiple times. The following steps show how to add another action that calls the same custom function, but with different actual parameter. 1. Still in the Action Designer, go to the last line and type the following to add another action. Ensure that it is indented under the ActionItems ActionContainer. Caption
Type
Execute Credit Action 2. Click View, C/AL Code to open the C/AL Editor. 3. Locate the OnAction trigger for the Execute Credit action. 4. Type the following code into the OnAction trigger of the action: IF Quantity = 0 THEN EXIT; Accumulate(-Quantity);
The code in both actions is similar. The only difference is that the Execute Credit action changes the Quantity to negative before calling the functions. This means that users no longer enter negative quantities, instead, they only enter quantities, and then click either the Execute Sale or the Execute Credit action, depending on what kind of transaction it is. 5. Close the C/AL Editor and close the Action Designer. 6. Open the Properties window for the Quantity field control, and set the MinValue property to be 0 (zero). 7. Close the Properties window 8. Compile, save and close the page.
8-44
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions Test the Page The following steps show how to test the page by running the action and viewing the result. 1. Run page 90008, Test Functions Page. 2. Type a value into the Unit Price and Quantity text box, and then click the Execute Sale action. Observe what happens. 3. Type another value into the Quantity text box, and then click the Execute Credit action again. Observe what happens. 4. Try entering a negative value in the Quantity text box (for example 4) and observe what happens.
Summary C/SIDE provides many built-in functions that can be used by developers. These built-in functions are predefined with their syntax. C/SIDE also lets developers create custom functions, to extend their application. Understanding the concepts of functions, when to use built-in functions and when to create custom functions helps developers to efficiently develop custom solutions for Microsoft Dynamics NAV.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-45
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Test Your Knowledge In the Object Designer, locate codeunit 358, DateFilter-Calc. Design this codeunit, and answer the following questions by looking at this object. Remember, if a question is about the Function Definition, it is best to examine the Function tab in the C/AL Globals window, and at the C/AL Locals window. If a question is about the code, it is best to examine the trigger code. 1. How many Parameters does the CreateFiscalYearFilter function have? 2. What type of value (if any) is returned by the CreateAccountingPeriodFilter function? 3. In the CreateAccountingDateFilter function, is the first parameter (Filter) passed by value or passed by reference? 4. In the CreateAccountingDateFilter function, is the third parameter (FiscalYear) passed by value or passed by reference? 5. In the CreateAccountingDateFilter function, how many local variables are defined?
8-46
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 8: C/AL Functions
Quick Interaction: Lessons Learned Take a moment and write down three key points you have learned from this chapter 1.
2.
3.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
8-47
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
8-48
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports
CHAPTER 9: REPORTS Objectives The objectives are: •
Understand the concepts of reports and report components.
•
Provide an overview of different report types and their characteristics.
•
Describe the difference between the logical and the visual design of reports and introduce the Report Designer.
•
Describe the logical design of a report.
•
Create the data model for a new report by defining data items in the Report Designer.
•
Describe the visual design of a report and introduce the Section Designer and Microsoft Visual Studio Report Designer.
•
Create several types of sections for the report in the Section Designer.
•
Improve the report by using some useful properties.
•
Design the report layout for the RoleTailored client.
•
Introduce the Request Options Designer.
•
Design the request options form.
•
Design the request options page.
•
Understand the concepts of grouping in a report.
•
Create grouping in the report by using table keys and indentation.
•
Understand the concepts of totaling in a report.
•
Create the subtotal and the grand total for one or more data items in the report.
•
Create a grouping and totaling for the report in the RoleTailored client.
•
Add some advanced features to the report.
Introduction Reports print information from a database and they can structure and summarize information. Reports can be used to print documents such as invoices, and they can also be used to process data without printing anything. Creating reports includes designing both the business logic that covers the kind of information the report will contain, and the layout that deals with how the report will look when it is printed. In addition, developing reports for the RoleTailored client requires additional design consideration.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-1
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Reports Fundamentals In Microsoft Dynamics® NAV, reports have several purposes. They are as follows: •
Reports structure and print information from a database. For example, report 108, Customer - Order Detail lists all customers and all sales orders for each customer.
•
Reports print and display documents in the application. For example, report 206, Sales - Invoice prints an invoice together with its relevant information.
•
Reports are used to automate many recurring tasks, such as updating all prices in the item list. This can be performed by using C/AL code in a codeunit, but to use a report makes it much easier because of the powerful data modeling available for report design. For example, report 794, Adjust Item Costs/Prices.
A report consists of the report description. The report description specifies how data is collected and presented on the screen or printed on the paper when the report is run. The report description is not directly visible to the user. When a developer creates a report, he or she assigns the report name, ID number, specifies data items and designs the visual element of the report. This establishes the report description.
9-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports The report description contains properties, triggers, sections, controls, a request form, a request page and RDL data. The last two components are required for reports that are developed for the RoleTailored client. The following shows components of a report and how they are related:
FIGURE 9.1 REPORT COMPONENTS AND THEIR RELATION
Properties The report description contains properties that are related to the report itself and properties that are related to the other components of the report, such as data items, sections, request form or request page. A property is an attribute of an object, or its component, that characterizes and specifies behavior of the parent in some ways, such as whether it is visible.
Triggers Certain predefined events that occur to a report cause the system to execute a user-definable C/AL function. The event and the function together are called a trigger. Triggers in a report can be divided into six categories: •
Report triggers
•
Data item triggers
•
Section triggers
•
Request form triggers
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-3
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 •
Request page triggers
•
Control triggers
Examples of report triggers include OnPreReport that contains statements that are executed right before the report is run, and OnPostReport that contains statements that are executed right before the report execution is completed. Triggers in a report are edited in the C/AL Editor which is accessed from the Report Designer.
Data Items The data model of a report is built from data items. A data item corresponds to a table. When the report is run, each data item is iterated for all records in the underlying table. When a report is based on more than one table, establish a hierarchy of data items to control how the information is collected by indenting data items. For example, to create a report that prints a list of customers, and also sales orders created by each customer, define two data items: •
One that corresponds to the Customer table.
•
One that corresponds to the Sales Order table.
The second data item is indented - as the report works its way through the records in the Customer table, for each customer, all sales orders that are related to this customer must be found by going through the records in the Sales Order table.
Sections Reports in Microsoft Dynamics NAV can be a printing or nonprinting report. A nonprinting report is used for processing a certain task and does not produce a displayed output. A printing report displays the result in the screen or prints output on the paper. This display is controlled by the visual element of the reports. In Microsoft Dynamics NAV, there are two different visual elements, they are as follows: •
Classic report layout which is the report sections.
•
Client report definition which is the RDL data.
A section is a visual element of a report. It can be thought of as a block of information to print on the paper. In a printing report, each data item can have one or more sections. The report itself is composed of several sections, including those that are printed:
9-4
•
Only one time, such as a grand total.
•
One time per page, such as a header.
•
For each record that is retrieved from the database.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports The visual element of a report includes the sections. In a printing report, one or more sections can be attached to each data item. There are several types of sections. Each has a specific function. Usually, the bulk of the data is printed in the Body section of a data item, whereas the Header section of the data item is used to print information before any record of the data item is printed, such as column captions. There can be reports where the Body section is not used at all, and all information is printed in other sections. The report in the following figure prints sales statistics information and retrieves all its data from one table. It demonstrates a range of the features that are available for designing reports: •
Before any record from the table is printed, there is a header that contains a title and information about the filter that is used on the customer numbers.
•
Each Body section prints information about a customer on several lines. The "Profit %" lines are calculated as the report is run.
•
After all records selected by the filter are printed, a Footer section is printed that contains totals for the selected customers.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-5
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 •
In the Body section and in the Footer section, a filter is applied to create columns where data is collected and totaled for different periods.
FIGURE 9.2 THE SALES STATISTICS REPORT
Controls The information that is printed in the sections is made of controls. The available controls are as follows: •
Text boxes - They are used for printing the result of the evaluation of any valid C/AL expression, such as the contents of a table field. They are also used for printing the results of complex calculations.
•
Labels - They are used for printing static text, such as a caption for a column of data.
•
Shapes, images, and picture boxes - They are used for printing bitmap pictures and graphical elements, such as lines and circles.
Controls are also available in the request form and the request page.
9-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports Request Form The request form is the form that is run before the actual report begins execution. It is used to collect requests and options from the user of the report of things such as sort order or level of detail. The request form is run when the report is run in the Classic client.
Request Page The request page has the same purpose as the request form, to collect request and options from users before the actual report begins execution. The request page is run when the report is run in the RoleTailored client.
RDL Data The RDL data is also a part of the visual element of a report. The RDL data is used, instead of the sections, when the report is run in the RoleTailored client. The RDL data is designed in Microsoft Visual Studio Report Designer which is accessed from the C/SIDE Report Designer.
Types of Printing Reports There are several types of printing reports in Microsoft Dynamics NAV. The types of reports are not as strictly established as compared to the types of pages, or even to types of forms and tables.
List Reports A List report prints a list of records from a table. A List report usually contains a single data item. This data item represents the table being listed. The table is either a Master table or a Supplemental table. Each column contains a field from the table. Most data are printed from that table and sometimes brought in or calculated from other tables. The name of the List report is usually the name of the table followed by the word List. The following are examples of List reports: •
Report 101, Customer - List
•
Report 301, Vendor - List
Test Reports A test report is printed from a Journal Table. Its purpose is to test each Journal Line according to certain criteria that are used for posting so that all the errors can be found and fixed before posting.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-7
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 As soon as an error is found during posting, processing stops and the error must be fixed before posting can be tried again. Therefore, a test report is a good way to find errors in a journal that has multiple errors. The name of the Test report is usually the name of the corresponding Journal, followed by the word Test. The following are examples of Test reports: •
Report 2, General Journal - Test
•
Report 1005, Job Journal - Test
Posting Reports A Posting report prints from the Register table. It lists all the transactions (ledger entries) that are posted into that Register. A Posting report can be printed as part of the Post and Print option in a Journal. The name of the Posting report is usually the name of either the Register table or the Master table of the corresponding ledger entries. The following are examples of Posting reports: •
Report 3, G/L Register
•
Report 103, Customer Register
•
Report 1015, Job Register
Transaction Reports A Transaction report has the following characteristics: •
It lists all the ledger entries for each record in the Ledger table.
•
It contains a subtotal for each Master table record, and a grand total for all tables printed.
•
It is used to view all transactions for a particular Master record.
•
It has no standard naming convention.
A Transaction report usually has one or more data items, including the Master table and the corresponding Ledger table. The following are examples of Transaction reports:
9-8
•
Report 4, Detail Trial Balance
•
Report 104, Customer - Detail Trial Bal.
•
Report 1007, Job - Transaction Detail
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports Document Reports A Document report prints a document. Document reports differ from most other reports, in that, many of the fields are not displayed in columns. An example of this type of report is the Sales Invoice. The header information in a Sales Invoice is printed as if filling out an invoice document. This header information is repeated at the top of each page, and no page has information from more than one header. The lines for the invoice print more like an ordinary report in rows and columns. The lines correspond to the header on the same page, and lines from other invoices are not displayed on the same page. The following are examples of Document reports: •
Report 206, Sales - Invoice
•
Report 116, Statement
•
Report 405, Order
Other Reports Reports are more loosely defined than other application objects because they are frequently customized for a particular client. However, most reports consist of a tabular listing with records listed horizontally and each field displaying in its own column. Many times, there is a group heading or total to split the lines among various categories and to subtotal the lines by the categories. The following are examples of other reports: •
Report 113, Customer/Item Sales
•
Report 313, Vendor/Item Purchases
•
Report 1012, Jobs per Customer
Report Design Process The report design process is divided into two distinct phases that reflect different aspects of creating a report. They are as follows: •
Defining the logical structure (the data model).
•
Designing the visual element.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-9
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 In addition, there are occasions where a user must be able to input certain options before running the report through a request form or request page. Therefore, the report design process also includes the following: •
Designing the request form.
•
Designing the request page.
Logical Design The logical design of a report means defining the data model, meaning, defining how the data for the report is collected. This includes the following: •
Defining the tables that are used by the report, by defining data items.
•
Defining relationships between data items if the report uses more than one table.
•
Defining the key, sort order, and filters to use with the data items.
•
Defining which elements the user can change at run time.
•
Defining how data is to be grouped.
•
Defining how subtotals and totals are to be calculated.
•
Writing C/AL code in data item triggers to obtain advanced functionality.
Visual Design The visual design of a report means designing the report's visual elements which involves the following: •
Creating report sections for a report that is run in the Classic client.
•
Creating RDL data for a report that is run in the RoleTailored client.
The Report Designers Both logical and visual design of the report is defined in the Report Designer which is accessed from the Object Designer. The Report Designer contains three additional designers:
9-10
•
The Section Designer which is used to design the report sections.
•
The Request Options Form Designer which is used to design request options forms.
•
The Request Options Page Designer which is used to design request options pages.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports There is also one external designer which is: •
Microsoft Visual Studio Report Designer which is used to create the RDL data for layout of reports in the RoleTailored client.
The following steps show how to open the Report Designer: In Microsoft Dynamics NAV Classic Client: 1. On the Tools menu, click Object Designer. 2. Click the Report button to open the Report list. 3. Select any report and then click the Design button to open the Report Designer and design the report, or click the New button to open the Report Designer and design a new report.
Design the Data Model The data model is defined in the Report Designer window, by adding data items. In this window, specify the tables that the report reads. Any table listed in this window is read in its entirety when the report is run. To limit the number of records the report reads, link and filter data items. A report can read the same table multiple times (in the same report) if the table is listed multiple times in the Report Designer. For example, a report can be set up to read the customer records two times, first the customers that are not blocked, and then the customers that are blocked. The listed tables become data items in the report. Data items are record variables that enable the report to access the data of a table. The following figure shows the Customer List report in the Report Designer.
FIGURE 9.3 THE CUSTOMER LIST REPORT
The Customer table is the data item for this report. The Name column in the Report Designer displays the name that is used by the report for the data item. Just as all variable names, these names must be unique within the report.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-11
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Ordering and Indenting Data Items The order in which the data items are listed is the order in which the report reads the data from the tables. At the bottom of the Report Designer window, there are four arrow buttons. Use the up and down arrow buttons to reorder the data items and use the right and left arrow buttons to indent or unindent a data item. If a data item is indented under another data item (parent data item), for every record read from the parent data item, all records are read from the indented data item, taking into account any filters or links. This concept is similar to a nested FOR loop. For example, if the Sales Line table is added as a data item under the Customer table, and then indented, the report reads a customer, and then the relevant sales line information for that customer, before moving to the next customer and that next customer’s sales lines.
Linking a Data Item Each data item has the DataItemLinkReference property and the DataItemLink property. These properties are used to define a Master/Detail relationship between two tables. In the DataItemLinkReference property of a data item, select the parent data item to link to (the data item must be indented under the parent data item.) In the DataItemLink property of the indented data item, specify a filter for this data item by matching fields in this data item with fields from the parent data item in the DataItemLinkReference property.
Demonstration: Create a Data Model Several demonstrations here help to understand some of the basic design principles of creating a report in Microsoft Dynamics NAV. The report created in these demonstrations, shows a list of customers by salespersons. The following demonstration shows how to create a data model by defining data items, create linking between the data items and define appropriate sorting for the data item in the Report Designer.
9-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports Prepare the Customer Table Before getting started with the report, add a key to the Customer table: 1. Design table 18, Customer, from the Object Designer. 2. Click View, Keys and add Salesperson Code to the list of keys.
FIGURE 9.4 THE CUSTOMER TABLE KEYS
3. Close the Keys window and compile, save, and close the table.
Create the Report Data Model The following steps show how to create the business logic for the report in the Report Designer: 1. In the Object Designer's Report List, click the New button. The New Report window opens. In this demonstration, do not use the Report Wizard. 2. Select Create a Blank Report and then click the OK button. The Report Designer opens. 3. Click the first empty line in the Report Designer, and type or select the number or name of table 13, Salesperson/Purchaser in the DataItem column. By the default, the Name column is set to the table name. 4. Click the next line, and add the table 18, Customer. The report must show customers by salesperson. Therefore, it must first read the Salesperson/Purchaser table, and for each salesperson record, it must read all the customers for that salesperson. To do this, indent the Customer data item under the Salesperson/Purchaser data item, and link the two.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-13
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 5. While the Customer data item is still selected, click the right arrow button at the bottom of the Report Designer to indent the Customer data item.
FIGURE 9.5 THE CUSTOMER DATA ITEM INDENTED UNDER THE SALESPERSON/PURCHASER DATA ITEM
6. Open the Properties window for the Customer data item. 7. Locate the DataItemLinkReference property, and verify that it is set to Salesperson/Purchaser. 8. Locate the DataItemLink property and click the Assist-Edit button on the DataItemLink property. The DataItem Link window opens. 9. Type the following in the DataItem Link window: Field
Reference Field
Salesperson Code
Code
This links the Salesperson Code field from the Customer table to the Code field from the Salesperson/Purchaser table. 10. Click OK to close the DataItem Link window. Notice that the DataItemLink property is set to Salesperson Code=FIELD(Code). 11. Locate the DataItemTableView property and then click the AssistEdit button on the DataItemTableView property. The Table View window opens.
9-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports 12. In the Key field, select Salesperson Code, and then click OK to close the Table View window. Notice that the DataItemTableView property is set to Sorting(Salesperson Code). This sorts the indented data item by the indicated field. This is a good practice when linking two data items.
FIGURE 9.6 THE CUSTOMER DATA ITEM PROPERTIES
13. Close the Properties window. 14. Compile and save the report by clicking File, Save As. The Save As dialog box opens. 15. Type 90000 in the ID and Customer by Salesperson in the Name, ensure that the Compiled check box is selected, and then click OK. This compiles and saves the report. The report data model is now completed. The next step is to design the visual element of the report.
Design the Visual Element Reports can be run from both the Classic and the RoleTailored client. The report's visual elements are designed in the Section Designer and the Microsoft Visual Studio Report Designer.
The Section Designer The Section Designer is used to design the visual element (report sections) of a report, section-by-section. Each data item can have one or more sections. The Section Designer is accessed from the Report Designer. The following steps show how to open the Section Designer. 1. Open the Report Designer from the Object Designer. 2. In the Report Designer, click View, Sections.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-15
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 NOTE: If the report has its Processing Only property set to Yes, no sections can be created. A section is a sub-object of a data item. To create a section, select the data item that the section is associated with, and specify a type of section. To delete a section, in the Section Designer, click the gray bar for the section and press F4. There are several types of sections available to a data item. The following list shows a brief description of the types of sections in a report: Section
Description
Body
This section prints one time for every record that is processed by the data item. If a record is skipped or filtered out, this section does not print for that record.
Footer
This section prints last for a data item. By default it only prints one time every time that the data item is processed, but it can be set to print on every page. This section can be specified to be printed at the bottom of the page.
GroupFooter
This section prints right after the last record in a group that is processed. This section only prints if the GroupTotalFields property for the data item is set, and the data item is appropriately sorted.
GroupHeader
This section prints right before the first record in a group that is processed. This section only prints if the GroupTotalFields property for the data item is set, and the data item is appropriately sorted.
Header
This section prints first for a data item. By default, it only prints one time every time that the data item is processed. However, it can be set to print on every page.
TransFooter
This section prints at the bottom of a page for a data item that is continued on the next page.
TransHeader
This section prints at the top of a page for a data item that is continued from the previous page.
Each section works like a small form, with the SourceTable property set to the data item's table. Controls on sections have no triggers, but have the same properties as controls in a form. NOTE: Colors are visible for controls that are set in the Section Designer; however, these colors do not print when the report is run. The only way to print colors is to use Image or PictureBox controls.
9-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports Microsoft Visual Studio Report Designer The RDL Data is a report component that is used by Microsoft Dynamics NAV to display the report in the RoleTailored client. Microsoft Visual Studio Report Designer is an external designer that is used to design the visual element (the RDL data) of a report to be run in the RoleTailored client. It is accessed from the Report Designer. The following steps show how to open the Microsoft Visual Studio Report Designer. 1. Open the Report Designer from the Object Designer. 2. In the Report Designer, click View, Layout. The Report Designer provides two options about layout creation: •
Create Layout Suggestion
•
Delete Layout
These two options can be accessed on the Tools menu in C/SIDE. The Create Layout Suggestion option creates a suggestion for the report layout in Microsoft Visual Studio Report Designer based on the sections designed in the Section Designer. The Delete Layout option deletes the current report layout. If a report without RDL data (no layout is defined in Visual Studio) is run in the RoleTailored client, it is run as if in the Classic client.
Demonstration: Design the Report Section The following demonstration shows how to create different types of sections in the Section Designer and examines the effect of data item indentation and linking to the report sections.
Design Sections The following steps show how to design the visual element of a report by adding several sections and controls to the report in the Section Designer. 1. Design report 90000, Customer by Salesperson from the Object Designer.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-17
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 2. Click View, Sections. The Section Designer opens. There are two sections already created for the report: the Salesperson/Purchaser, Body (1) and the Customer, Body (1). Both are Body sections of each data item. The number in the brackets indicates that they are the first section of their respective data item.
FIGURE 9.7 THE SECTION DESIGNER
3. Click the Salesperson/Purchaser Body section, and then Press F3 to insert another section. The Insert New Section window opens. 4. Select Salesperson/Purchaser in the Data Item drop-down list, and select the Header in the Section Type option, and then click OK.
FIGURE 9.8 THE INSERT NEW SECTION WINDOW
A Header section for the Salesperson/Purchaser data item is inserted in the Section Designer. The Header section for a data item is always located before the Body section. The Body section of the Salesperson/Purchaser data item now has the number 2 instead of 1, because it is now the second section of that data item.
9-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports 5. Repeat step 4 to insert a Header section for the Customer data item.
FIGURE 9.9 THE SECTION DESIGNER
The report now has four sections. They have no control on them. If the report is run, nothing appears in the screen or prints in the paper. 6. Click the Salesperson/Purchaser Body section, and then click View, Field Menu. The Field Menu window opens. 7. Press and hold the CTRL key, and select the Code and Name fields. 8. Place the cursor over the Salesperson/Purchaser Body section and then click to enable the Section Designer, and then click to put the fields on the section. Notice that the labels and text boxes are created differently on a report section than on a form. The labels are positioned above the text boxes in columns. Move the controls around just as if in forms. 9. Drag the labels one at a time from the Body section to the Header section of the Salesperson/Purchaser data item and line them up above the corresponding text boxes.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-19
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 10. Repeat steps 7 to 9 for the Customer Body section. Add the No., Name, City, and Phone No. fields from the Customer table. Move the labels to the Header section of the Customer data item.
FIGURE 9.10 THE SECTION DESIGNER
11. Compile, save, and close the report.
Run the Report in the Classic Client The following steps show how to run a report in the Classic client. 1. In the Object Designer's Report list, select report 90000, Customer by Salesperson, and then click the Run button.The request form opens.
FIGURE 9.11 THE REQUEST FORM
This form enables users to enter filters for the data items or change the sorting of the data items. Users can also select to print or preview the report. There is only one tab in the form which is the Salesperson/Purchaser tab. This tab corresponds to the Salesperson/Purchaser data item. By default, each data item has a tab in the request form. In this case, the tab that corresponds to the Customer data item is hidden, because the Customer data item is sorted (the DataItemTableView property is set) and the ReqFilterFields property is not set.
9-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports 2. Click Preview.
FIGURE 9.12 THE PRINT PREVIEW WINDOW IN THE CLASSIC CLIENT
The report shows all salespersons and all their customers. NOTE: To be able to print or preview any reports, at least one printer driver must be loaded in the client PC.
Examine the Effect of Indentation and Linking The following steps show the difference in the sections without indentation and linking. 1. Design report 90000, Customer by Salesperson, from the Object Designer. 2. Click View, Sections to open the Section Designer.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-21
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 3. Insert a Footer section for each data item. 4. On the footer for each data item, add a label from the Toolbox, and change the caption for each to SP-Footer and Cust-Footer respectively.
FIGURE 9.13 THE SECTION DESIGNER
5. Close the Section Designer.
9-22
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports 6. Compile and save the report. 7. Click File, Run to run the report, and then click the Preview button in the Request Form.
FIGURE 9.14 THE FOOTER SECTION
The report shows all salespersons and their customers. The Footer section for the customer is printed for every salesperson that has customers. In this case it is printed two times. (There are only two distinct salespersons that have customers.) The Footer section for the salesperson is printed one time, at the end of the report. 8. Close the report preview. 9. Click the Customer data item and then click the left arrow button at the bottom of the Report Designer to unindent the Customer data item. 10. Open the Properties window for the Customer data item and clear the values of the DataItemLink property. 11. Close the Properties window and then run and preview the report. Without the indentation, the report shows all salespersons and then all customers. The Footer section of each data item is printed one time, right after the iteration of each data item is finished. 12. Close the report preview.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-23
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 13. Click the Customer data item and then click the right arrow button at the bottom of the Report Designer to indent the Customer data item. 14. Run and preview the report. With indentation but no linking, the report shows all salespersons and for each salesperson, all customers. The Footer section for the Customer data item is printed for every salesperson. The Footer section for the Salesperson data item is printed one time, at the end of the report. 15. Close the report preview and close the report without saving it.
Use the PrintOnEveryPage Property The customers for some salespersons extend to more than one page. However, on the second page, the report does not print any headings that indicate which salesperson that the customers are associated with. The following steps show how to use the PrintOnEveryPage property of the section. 1. Design report 90000, Customer by Salesperson, from the Object Designer. 2. Click View, Sections to open the Section Designer. 3. Select each Header section on the report and change the PrintOnEveryPage property of the Header section to Yes.
9-24
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports 4. Compile, save and close the report. 5. Run and preview the report.
FIGURE 9.15 THE HEADER SECTION AFTER SETTING THE PRINTONEVERYPAGE PROPERTY
The Salesperson header and the Customer header appear at the top of every page. This still does not tell which salesperson those customers are associated with. A section that prints at the top of the pages that are continuations of the previous page and show the current salesperson is needed. This is the purpose of TransHeader sections.
Add a TransHeader First, determine which data item is for the TransHeader section and then determine which data item the report is in the middle of printing when it extends to the next page. In this case, a TransHeader for the Customer data item is needed. The following steps show how to add a TransHeader section to the report. 1. Design report 90000, Customer by Salesperson, from the Object Designer. 2. Click View, Sections to open the Section Designer. 3. Insert a TransHeader section for the Customer data item.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-25
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The TransHeader section is positioned between the Header and the Body sections of the data item. In the Customer TransHeader section, display the current salesperson. 4. Click the Salesperson Body section, and select both the Code and Name fields. 5. Click Edit, Copy or press CTRL+C to copy these controls to the clipboard. 6. Click the Customer TransHeader section, and then click Edit, Paste or press CTRL+V to paste the two controls to this section. 7. Align the controls with the original controls. To display fields from the Salesperson data item in the Customer TransHeader section, include the Salesperson data item in the SourceExpr property of the controls. 8. Open the Properties window for the Code text box in the Customer TransHeader section and set the SourceExpr property to "Salesperson/Purchaser".Code. 9. Repeat step 8 for the Name text box, but change the SourceExpr property to "Salesperson/Purchaser".Name. 10. Close the Properties window. 11. Add a label to the Customer TransHeader section with caption Continued.
FIGURE 9.16 THE CUSTOMER TRANSHEADER SECTION
12. Close the Section Designer and compile, save, and close the report. 13. Run and preview the report.
9-26
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports Add a TransFooter A TransFooter works exactly like a TransHeader. However, it prints at the bottom of the page that is to be continued. The following steps show how to add a TransFooter section to the report. 1. Design report 90000, Customer by Salesperson, from the Object Designer. 2. Click View, Sections to open the Section Designer. 3. Insert a TransFooter section for the Customer data item. 4. Add a label to the Customer TransFooter section with caption Continued.
FIGURE 9.17 THE CUSTOMER TRANSFOOTER SECTION
5. Close the Section Designer and compile, save, and close the report. 6. Run and preview the report.
Demonstration: Modify Report Properties The following demonstration shows how to improve the report by setting some useful properties.
Use the NewPagePerRecord Property The NewPagePerRecord property is used to create a page break whenever the report shows a new record. The following steps show how to use the NewPagePerRecord to set the Customer by Salesperson report to start a new page for every salesperson. 1. Design report 90000, Customer by Salesperson, from the Object Designer.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-27
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 2. Open the Properties window for the Salesperson/Purchaser data item and set the NewPagePerRecord property to Yes. 3. Close the properties window and compile, save and close the report. 4. Run and preview the report.
FIGURE 9.18 THE REPORT PREVIEW AFTER SETTING THE NEWPAGEPERRECORD PROPERTY
Use the PrinOnlyIfDetail Property The PrintOnlyIfDetail property is used to limit printing a data item that does not have a detailed data item. For example, the report does not show any customers for salesperson Annette Hill. She is not really a Salesperson. She is a Purchaser. The following steps show how to use the PrintOnlyIfDetail property to change the report to only include those salespersons that actually have Customers. 1. Design report 90000, Customer by Salesperson, from the Object Designer. 2. Open the Properties window for the Salesperson/Purchaser data item and set the PrintOnlyIfDetail property to Yes.
9-28
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports 3. Close the properties window and compile, save and close the report. 4. Run and preview the report.
FIGURE 9.19 THE REPORT PREVIEW AFTER SETTING THE PRINTONLYIFDETAIL PROPERTY
Use the ReqFilterFields Property The ReqFilterFields property is used to specify which fields the user sees on the request form that can be used for filtering. The following steps show how to use the ReqFilterFields property to let filtering on the Code and Name fields of the Salesperson/Purchaser table on the request form. 1. Design report 90000, Customer by Salesperson, from the Object Designer. 2. Open the Properties window for the Salesperson/Purchaser data item and set the ReqFilterFields property to Code,Name.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-29
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 3. Close the properties window and compile, save and close the report. 4. Run the report and view the request form.
FIGURE 9.20 THE REQUEST FORM AFTER SETTING THE REQFILTERFIELDS PROPERTY
NOTE: Sorting a data item (setting the DataItemTableView property) that does not have ReqFilterFields causes its tab on the request form to disappear.
Use the ReqFilterHeading Property The ReqFilterHeading property is used to change the name of the tab on the request form. By default, the name of the tab follows the name of the data item. The following steps show how to use the ReqFilterHeading property to change the Salesperson/Purchaser tab on the request form to only Salesperson. 1. Design report 90000, Customer by Salesperson, from the Object Designer. 2. Open the Properties window for the Salesperson/Purchaser data item and set the ReqFilterHeading property to Salesperson.
9-30
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports 3. Close the properties window and compile, save and close the report. 4. Run the report and view the request form.
FIGURE 9.21 THE REQUEST FORM AFTER SETTING THE REQFILTERHEADING PROPERTY
Demonstration: Design the Report Layout The following demonstration shows how to design the report layout in Microsoft Visual Studio Report Designer for a report to be run in the RoleTailored client.
Prepare the Layout The following steps show how to design the report layout in Microsoft Visual Studio Report Designer. 1. Design report 90000, Customer by Salesperson, from the Object Designer. 2. Click View, Layout. Microsoft Visual Studio Report Designer opens with a Dataset Result from the report section. NOTE: The name of each field in the dataset is created from the DataSetFieldName property of each control in the report section. If this property is not defined, C/SIDE assigns a default name, and then set the DataSetFieldName property. C/SIDE also creates the caption and the format fields (the fields that have the suffix Caption and Format.) Use the caption fields for column headers (or other text purposes) instead of hard-coded text and use the format fields to set the Format property of the respective fields (usually decimal fields.) 3. Drag a Table control from the toolbox to the report layout.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-31
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 4. Click one of the columns, right-click and then click Insert Column to the Right. 5. Repeat step 4 two times to add two more columns.
FIGURE 9.22 THE TABLE WITH SIX COLUMNS
Now, the layout has a table with six columns. NOTE: Instead of designing the layout manually, try the Create Layout Suggestion by clicking Tools, then Create Layout Suggestion in the Report Designer, and modify from there when it is necessary. This overwrites the current layout, if any.
Add Column Headers The following steps show how to add column headers to the report layout. 1. Drag the Salesperson_Purchaser_CodeCaption from the DataSet Result to the first column of the first row of the table. NOTE: Use the caption fields for column headings instead of hard-coded text, to support a multilanguage scenario. 2. Repeat step 1 for the Salesperson_Purchaser_NameCaption, Customer__No__Caption, Customer_NameCaption, Customer_CityCaption and Customer__Phone_No__Caption fields from the DataSet Result to the appropriate columns of the first row of the table. NOTE: These can also be achieved by going to the individual text box in the table and typing the Value property appropriately.
9-32
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports Now, the layout looks as follows:
FIGURE 9.23 THE REPORT LAYOUT
Add a Grouping A dataset result in Visual Studio is flattened data. This means the Salesperson/Purchaser table and the Customer table are joined. Unlike in the Classic client where the hierarchy is defined by indenting data items, in the RoleTailored Client, the hierarchy is defined in each control, in this case the table control. The following steps show how to add the grouping of the customers by their salesperson. 1. Select the table control, right-click and then click Properties. The Table Properties window opens. 2. Click the Groups tab and then click Add. The Grouping and Sorting Properties window opens.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-33
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 3. Type or select the following: o Expression: =Fields!Salesperson_Purchaser_Code.Value
FIGURE 9.24 THE GROUPING AND SORTING PROPERTIES WINDOW
4. Leave the rest as it is, click OK and then click OK. Now, the layout looks as follows:
FIGURE 9.25 THE REPORT LAYOUT
9-34
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports The table has six columns and five rows. Table Row
Remarks
First
Table header
Second
Group header of the group that is created in the Add Grouping section.
Third
Group detail of the group that is created in the Add Grouping section.
Fourth
Group footer of the group that is created in the Add Grouping section.
Fifth
Table footer
Add Fields The following steps show how to add fields to the report layout. 1. Drag the Salesperson_Purchaser_Code and Salesperson_Purchaser_Name fields from the DataSet Result to the first and second column of the second row of the table, respectively. 2. Repeat step 1 for the Customer__No__, Customer_Name, Customer_City and Customer__Phone_No__ fields from the DataSet Result to the appropriate columns of the third row of the table.
FIGURE 9.26 THE REPORT LAYOUT
3. Close Visual Studio and then click Yes when prompted to save the changes. 4. Click anywhere in the Report Designer and then click Yes to load the saved changes from Visual Studio. NOTE: Remember to click Yes in steps 3 and 4. If this is not the case, the changes made to the report layout are not saved. 5. Compile, save and close the report.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-35
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Run the Report in the RoleTailored Client In the RoleTailored client, usually, a report is run from a page. However, to test the changes, run the report from the Run window. The following steps show how to run a report in the RoleTailored client. 1. On the Windows taskbar, click Start and then click Run. 2. In the Run window, type the following string: dynamicsnav:////runreport?report=90000, where 90000 is the ID of the Customer by Salesperson report, and then click OK, to run the report. The request page opens. This page enables users to enter filters for the data items or change the sorting of the data items. Users can also select to print or preview the report.
FIGURE 9.27 THE REQUEST PAGE
NOTE: Instead of tabs as in the request form, FastTabs that correspond to the data items are shown in the request page. In this case, the FastTab that corresponds to the Salesperson/Purchaser data item is shown and the FastTab that corresponds to the Customer data item is hidden, just as in the Classic client. The effect of setting the PrintOnlyIfDetail, ReqFilterFields and ReqFilterHeading property is the same as in the request form.
9-36
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports 3. Click Preview.
FIGURE 9.28 THE PRINT PREVIEW WINDOW IN THE ROLETAILORED CLIENT
The report shows all salespersons and for each salesperson that has customers, all its customers. NOTE: Several fields, such as the Name fields, are wide and require more space. These fields grow to the second line. The CanGrow property defines this behavior.
Print Header on Every Page The customers for some salespersons extend to more than one page. However, on the second page, the report does not print any headings that indicate which salesperson that the customers are associated with. The following steps show how to achieve a similar result like when setting the PrintOnEveryPage property in the section to print a header on every page. 1. Design report 90000, Customer by Salesperson, from the Object Designer.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-37
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 2. Click View, Layout. 3. Open the Properties window for the table control and select Repeat header rows on each page.
FIGURE 9.29 THE TABLE PROPERTIES WINDOW
4. Click OK to close the Properties window, close Visual Studio and then click Yes when prompted to save the changes. 5. Click anywhere in the Report Designer and then click Yes to load the saved changes from Visual Studio. 6. Compile, save and close the report. 7. Run the report to view the changes.
Print Subheader on Continuous Page The following steps show how to achieve a similar result like when creating the TransHeader section to print a subheader for a continuous page. 1. Design report 90000, Customer by Salesperson, from the Object Designer. 2. Click View, Layout. 3. Open the Properties window for the table control.
9-38
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports 4. Click the Groups tab, select the group and then click Edit. 5. Select Repeat group header and then click OK.
FIGURE 9.30 THE GROUPING AND SORTING PROPERTIES WINDOW
6. Click OK to close the Properties window, close Visual Studio and then click Yes when prompted to save the changes. 7. Click anywhere in the Report Designer and then click Yes to load the saved changes from Visual Studio. 8. Compile, save and close the report. 9. Run the report to view the changes.
Show New Record in a New Page The following steps show how to achieve a similar result like when setting the NewPagePerRecord property to show a new record in a new page. 1. Design report 90000, Customer by Salesperson, from the Object Designer. 2. Click View, Layout. 3. Open the Properties window for the table control. 4. Click the Groups tab, select the group and then click Edit. 5. Select Page break at start and then click OK. 6. Click OK to close the Properties window, close Visual Studio and then click Yes when prompted to save the changes.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-39
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 7. Click anywhere in the Report Designer and then click Yes to load the saved changes from Visual Studio. 8. Compile, save and close the report. 9. Run the report to view the changes.
The Request Options Designer The request form is displayed when the report is run in the Classic client and the request page is displayed when the report is run in the RoleTailored client. They have the same purpose which is to let the user provide additional input before previewing or printing the report.
The Request Options Form Designer The request form contains some default elements that reflect the data items in a report. When a new report is created, a request form is automatically created for the report. In addition, custom options can be created on the Options tab in the request form. These options are designed by using the Request Options Form Designer which is accessed from the Report Designer. The following steps show how to open the Request Options Form Designer. 1. Open the Report Designer from the Object Designer. 2. In the Report Designer, click View, Request Form. The Options tab is always displayed as the last tab of the request form, and is displayed only if there are controls in it. Only the Options tab of the request form can be customized. The rest of the tabs which correspond to the data items cannot be modified, although they can be hidden by sorting the data item (setting the DataItemTableView property) and clearing the ReqFilterFields property of the data item. Designing the Options tab is similar to designing any other form and usually requires coding in some triggers.
The Request Options Page Designer The request page has the same purpose as the request form. It is displayed when the report is run in the RoleTailored client. When a new report is created, a request page is automatically created for the report. In addition, custom options can be created in the request page. These options are designed by using the Request Options Page Designer which is accessed from the Report Designer. The following steps show how to open the Request Options Page Designer. 1. Open the Report Designer from the Object Designer. 2. In the Report Designer, click View, Request Page. The Request Options Page Designer is similar to the Page Designer. Here developers can add controls, such as FastTabs and fields to the request page. Controls that are created in the Request Options Page Designer are always displayed above the FastTabs that correspond to data items.
9-40
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports
Demonstration: Design the Request Options Form The following demonstration shows how to design the request options form, add and remove tabs from it, add a control to the Options tab and use the control to affect the output of the report.
Add and Remove Tabs on the Request Form Every data item has a tab on the request form, although it can be hidden by setting certain properties. Currently the Customer by Salesperson report has two data items, the Salesperson/Purchaser data item and the Customer data item. When it is run, the request form for this report shows one tab, the Salesperson tab. The following steps show how to add and remove tabs on the request form. 1. Design report 90000, Customer by Salesperson from the Object Designer. 2. Open the Properties window for the Customer data item and clear the DataItemTableView property. 3. Close the Properties window, and compile, save and run the report in the Classic client. The request form now shows two tabs, the Salesperson and the Customer tabs. 4. Close the request form. 5. Open the Properties window for the Customer data item and set the DataItemTableView property to SORTING("No."). 6. Close the Properties window, and compile, save and run the report. The request form now shows one tab, the Salesperson tab. 7. Close the request form. 8. Open the Properties window for the Customer data item and set the ReqFilterFields property to "No." 9. Close the Properties window, and compile, save and run the report. The request form now shows two tabs, the Salesperson and the Customer tabs. 10. Close the request form and close the report.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-41
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Add a Check Box to the Options Tab To add a data control to the Options tab of the request form, create a global variable for the control to be bound to. The user changes the value of the variable through the control. The following steps show how to create a global variable and a check box to the Options tab of the request form. 1. Design report 90000, Customer by Salesperson, from the Object Designer. 2. Click View, C/AL Globals. The C/AL Globals window opens. 3. Type the following in the Variables tab: Name
DataType
ShowDetails
Boolean
4. Close the C/AL Globals window. 5. Click View, Request Form. The Request Options Form Designer opens. 6. Add a check box and label to the form (use the Add Label option). 7. Open the Properties window for the check box and set the following properties: o Caption: Show Details (This also changes the Caption of the attached label.) o SourceExpr: ShowDetails 8. Close the Properties window and close the Request Options Form Designer.
9-42
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports 9. Compile, save, and close the report. 10. Run the report in the Classic client.
FIGURE 9.31 THE REQUEST FORM
The request form now shows three tabs, the Salesperson, the Customer and the Options tabs. The Options tab has a check box labeled Show Details in it.
Set the Request Form to Save Variable Values Every time that the report is run, the ShowDetails variable is set to its default value which is FALSE. The following steps show how to set the request form to save its variable value so that the value is saved in the ZUP file and is remembered. 1. Design report 90000, Customer by Salesperson, from the Object Designer. 2. Click View, Request Form. The Request Options Form Designer opens. 3. Open the Properties window for the request form and set the SaveValues property to Yes. 4. Close the Properties window and close the Request Options Form Designer. 5. Compile, save, and close the report. 6. Run the report in the Classic client. 7. Select the Show Details check box and preview the report. Then, close the report preview and rerun the report. The request form remembers the ShowDetails variable value from the previous run.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-43
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Skip Sections in a Report Use the value of the check box added in the request form to display or not display a section in the report. The following steps show how to conditionally show the Body section of the Customer data item, depending on the value of the Show Details check box in the request form. 1. Design report 90000, Customer by Salesperson, from the Object Designer. 2. Click View, Sections to open the Section Designer. 3. Click the gray bar for the Cust. Ledger Entry Body section. This selects that section. 4. Click View, C/AL Code or press F9 to open the C/AL Editor. 5. In the OnPreSection trigger, type the following: CurrReport.SHOWOUTPUT(ShowDetails);
6. Close the C/AL Editor and close the Section Designer. 7. Compile, save and close the report. 8. Run the report in the Classic client, select the Show Details check box in the Options tab of the request form and then click the Preview button. 9. Close the report preview, rerun the report, and this time, clear the Show Details check box and then click the Preview button and view the changes.
Demonstration: Design the Request Options Page The following demonstration shows how to design the request options page, add and remove FastTabs from it, add a control to the Options FastTab and use the control to affect the output of the report.
Add and Remove FastTabs on the Request Page Every data item has a FastTab on the request page. It behaves the same as tabs in the request form. It can be hidden or shown by setting exactly the same properties as in the request form.
Create Options FastTab and Add a Check Box The following steps show how to create a check box to the Options FastTab of the request page. 1. Design report 90000, Customer by Salesperson, from the Object Designer.
9-44
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports 2. Click View, Request Page. The Request Options Page Designer opens. It resembles the Page Designer. 3. Type the following on the first line of the Page Designer: Caption
Type
SubType
Request Page
Container
ContentArea
4. Go to the next blank line. The page elements automatically indent. 5. Type the following: Caption
Type
SubType
Options
Group
Group
This creates the Options FastTab. 6. Type the following on the next line and ensure that it is indented under the Options FastTab: Caption
Type
SourceExpr
Show Details
Field
ShowDetails
FIGURE 9.32 THE REQUEST OPTIONS PAGE DESIGNER
7. Close the Request Options Page Designer.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-45
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 8. Compile, save, and close the report. 9. Run the report in the RoleTailored client.
FIGURE 9.33 THE REQUEST PAGE
The request page now shows three FastTabs, the Options, the Salesperson, and the Customer FastTabs. The Options FastTab has a check box labeled Show Details in it.
Skip Lines in a Report Use the value of the check box added in the request page to display or not display a section in the report. The following steps show how to conditionally show the detail of the Customer, depending on the value of the Show Details check box in the request page. 1. Design report 90000, Customer by Salesperson, from the Object Designer. 2. Click View, Sections to open the Section Designer. 3. Add a text box in the Body section of the customer data item, and set the following properties: o Visible: No o SourceExpr: ShowDetails
9-46
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports 4. Close the Section Designer. NOTE: The purpose of steps 1 to 3 is to add ShowDetail as one of the fields in the dataset result in Visual Studio. This is a hidden field which is added to achieve a similar result as CurrReport.SHOWOUTPUT, because section triggers are not supported in the RoleTailored Client. 5. Click View, Layout. 6. Select the third row (the Detail row) and set the following property: o Visibility, Hidden: =IIF(Fields!ShowDetails.Value,false,true) 7. Close Visual Studio and then click Yes when prompted to save the changes. 8. Click anywhere in the Report Designer and then click Yes to load the saved changes from Visual Studio. 9. Compile, save and close the report. 10. Run the report in the RoleTailored client, select the Show Details check box in the Options FastTab of the request page and then click the Preview button. 11. Close the report preview, rerun the report, and this time, clear the Show Details check box and then click the Preview button and view the changes.
Grouping Within a Classic Report Typically, a report must print subtotals to separate groups of records based on certain fields within the records. In Microsoft Dynamics NAV, developers must indicate which fields to be monitored for these events in the report. The report monitors the fields, and when they change to a new value, special sections can be printed on the report. These special sections are not printed unless the report has grouping on fields. Grouping is not needed if indentation can be used to link and filter the data items. But grouping must be used if the field that is to be grouped on is not related to another table. The most common use for grouping is to subtotal a report by Date. Date fields are not related to a table, but signify important groups within the table. For example, developers may want to examine Customer Ledger Entries by Customer and for each Customer, by Date. They can group the entries by Customer by using indentation. But they still have to group on one field which is the Date field. NOTE: In most cases, it is easier to use indentation instead of grouping. Grouping on more than one field is sometimes difficult and requires writing some code. Indentation is a more natural way to use in the Report Designer.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-47
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The GroupTotalFields Property The GroupTotalFields property is the key for grouping. It is used to specify fields to be grouped on by the report. It enables printing special sections which usually are used to show subtotals in the report. Although, this property has nothing to do with totals or indentation, the name of the property is somewhat misleading. To correctly use this field, developers must be aware of the following: •
The fields specified in this property must also be in the key that is specified in the DataItemTableView property.
•
If the DataItemTableView does not have the correct key, the fields specified in the GroupTotalFields property are ignored by the report.
•
Special sections must be created in the Section Designer. Grouping causes these sections to be printed at the correct time.
The GroupHeader and GroupFooter Sections Grouping enables developers to print the special sections which are the GroupHeader and the GroupFooter sections in the report. As their names imply, these groups are printed before a group starts and after a group is finished. The GroupHeader section prints after any Header sections and before any Body sections for the current group, or right after the previous group's GroupFooter section. The GroupFooter section prints after the last Body section for the current group and before the GroupHeader of the next group, or before the Footer section.
Demonstration: Create Grouping For The Classic Report The following demonstration shows how to create grouping in the report by using table keys and GroupTotalFields property and also indentation.
9-48
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports Prepare the Cust. Ledger Entry Table Before getting started with the report, add a key to the Cust. Ledger Entry table: 1. Design table 21, Cust. Ledger Entry, from the Object Designer. 2. Click View, Keys and add Posting Date to the list of keys.
FIGURE 9.34 THE KEYS WINDOW
3. Close the Keys window and compile, save, and close the table.
Create a New Report The following steps show how to create a new report that uses grouping. 1. In the Object Designer's Report list, click the New button. The New Report window opens. In this demonstration, do not use the Report Wizard. 2. Select Create a Blank Report and then click the OK button. The Report Designer opens. 3. Click the first empty line in the Report Designer, and type or select the number or name of table 21, Cust. Ledger Entry. 4. Open the Properties window for the Cust. Ledger Entry data item and set the following properties: o DataItemTableView: SORTING(Posting Date) o GroupTotalFields: Posting Date
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-49
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 NOTE: The GroupHeader section will not be printed without the correct setting, and the correct sorting and key in the DataItemTableView property. 5. Close the Properties window. 6. Click View, Sections to open the Section Designer. 7. Insert a Header and a GroupHeader section for the Cust. Ledger Entry data item. 8. In the Body section, add the Posting Date, Customer No., Document Type,Document No., Description and Amount (LCY) fields from the Cust. Ledger Entry table. Move the labels to the Header section of the Cust. Ledger Entry data item. 9. Select the Posting Date text box, and drag it to the GroupHeader section.
FIGURE 9.35 THE SECTION DESIGNER
10. Compile and save the report with the ID 90001 and the name Customer Detail, and close the report. 11. Run and preview the report in the Classic client. The report shows the Customer's ledger entries grouped by the Posting Date.
Use Grouping Together With Indentation Change this report so that it groups the Customer Ledger Entries, first by Customer then by Posting Date. Instead of adding Customer No. to the GroupTotalFields property, use indentation with another data item. The following steps show how to use grouping together with indentation. 1. 2. 3. 4.
9-50
Design report 90001, Customer Detail, from the Object Designer. Press F3 to insert a line above the Cust. Ledger Entry data item. Select the Customer table for this new data item. Indent the Cust. Ledger Entry data item under the Customer data item.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports 5. Open the Properties window for the Cust. Ledger Entry data item and set the following properties: o DataItemTableView: SORTING(Customer No.,Posting Date) o DataItemLink: Customer No.=FIELD(No.) 6. Close the Properties window, and then click View, Sections to open the Section Designer. 7. Insert a Header section for the Customer data item. 8. In the Body section of the Customer data item, add the No., Name, City, and Phone No. fields from the Customer table. Move the labels to the Header section of the Customer data item. 9. Move the controls on the Cust. Ledger Entry sections to the right side to show the indentation. To do this, select all the controls on a section and move them to the right side. The > symbol in the gray bar of the sections of the Cust. Ledger Entry data item signifies that this data item is indented.
FIGURE 9.36 THE SECTION DESIGNER
10. Close the Section Designer and compile, save, and close the report. 11. Run and preview the report in the Classic client.
Totaling in a Report A report is usually designed to give the user summary information about what is in the database. This usually requires adding one or more fields that are displayed or read by the report, and then displaying the sum. This process is known as totaling the report. Microsoft Dynamics NAV uses subtotals and grand totals. Subtotals are shown after a logical grouping of records. Grand totals are shown at the end of the report. Subtotals sum the group and grand totals sum the whole report, meaning, grand totals sum all subtotals.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-51
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The TotalFields Property The TotalFields property is used to specify which fields that developers want to sum. The report tracks the totals of those fields specified in this property. This property does not tell the report to display the totals.
How to Display the Totals To display the total amounts for the fields specified in the TotalFields property, developers must to do the following: •
Create a section to display the Totals. The report only displays total amounts on several types of sections: Footer, GroupFooter, TransFooter, or TransHeader.
•
Create controls with the SourceExpr property set to the fields in that section. Because the fields are displayed on a footer type section, the report shows the total amounts of the fields instead of the current value of the fields.
Demonstration: Create Totals For The Classic Report The following demonstration shows how to create subtotal and grand total for one or more data items in the report.
Add Subtotal and Grand Total The following steps show how to add the subtotal and the grand total for the Cust. Ledger Entry data item. 1. Design report 90001, Customer Detail, from the Object Designer. 2. Open the Properties window for the Cust. Ledger Entry data item and set the TotalFields property to Amount (LCY). This tells the report to calculate totals for the Amount (LCY) field as the Cust. Ledger Entry data item is iterated. 3. Close the Properties window, and then click View, Sections. 4. Insert a GroupFooter section and a Footer section for the Cust. Ledger Entry data item.
9-52
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports 5. In the GroupFooter section and the Footer section of the Cust. Ledger Entry data item, add the Amount (LCY) field from the Cust. Ledger Entry table. 6. Delete the labels and align the text boxes under the Amount (LCY) text box in the Body section.
FIGURE 9.37 THE SECTION DESIGNER
7. Close the Section Designer and compile, save, and close the report. 8. Run and then preview the report in the Classic client.
Add the Grand Total with More than One Data Item The following steps show how to add the grand total for the Customer data item. 1. Design report 90001, Customer Detail, from the Object Designer. 2. Click the Customer data item and then click View, C/AL Code or press F9 to open the C/AL Editor. 3. In the OnPreDataItem trigger, type the following: CurrReport.CREATETOTALS("Cust. Ledger Entry"."Amount (LCY)");
4. Close the C/AL Editor and then click View, Sections to open the Section Designer. 5. Insert a Footer section for the Customer data item. 6. In the footer section, established in step 5, manually add a text box. 7. Open the Properties window for the text box and set the SourceExpr property of the text box to "Cust. Ledger Entry"."Amount (LCY)". 8. Close the Properties window and close the Section Designer.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-53
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 9. Compile, save, and close the report. 10. Run and preview the report in the Classic client
FIGURE 9.38 THE REPORT IN THE CLASSIC CLIENT
Demonstration: Create Grouping and Totals For The RoleTailored Report The following demonstration shows how to create a grouping, the subtotal and the grand total for the Customer Detail report to be run in the RoleTailored client.
Prepare the Layout The following steps show how to design the report layout in Microsoft Visual Studio Report Designer. 1. Design report 90001, Customer Detail, from the Object Designer. 2. Click View, Layout. 3. Drag a Table control from the toolbox to the report layout.
9-54
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports 4. Click one of the columns, right-click and then click Insert Column to the Right. 5. Repeat step 4 two times to add two more columns.
FIGURE 9.39 THE TABLE WITH SIX COLUMNS
Add Column Headers To add column headers to the report layout, drag the Customer__No__Caption, Customer_NameCaption, Customer_CityCaption and Customer__Phone_No__Caption fields from the DataSet Result to the first to fourth columns of the first row of the table.
FIGURE 9.40 THE TABLE WITH COLUMN HEADERS
Add Groupings The following steps show how to add the grouping of the records, first by Customer, and then by Posting Date. 1. Select the table control, right-click and then click Properties. The Table Properties window opens. 2. Click the Groups tab and then click Add. The Grouping and Sorting Properties window opens. 3. Type or select the following: o Expression: =Fields!Customer__No__.Value 4. Leave the rest as it is, and then click OK. 5. Click Add again and type the following: o Expression: =Fields!Cust__Ledger_Entry__Posting_Date_.Value o Parent Group: =Fields!Customer__No__.Value
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-55
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 6. Leave the rest as it is, click OK, and then click OK.
FIGURE 9.41 THE TABLE WITH SIX COLUMNS AND SEVEN ROWS
Add Subheaders and Fields The following steps show how to add fields and subheaders to the report layout. 1. Drag the Customer__No__, Customer_Name, Customer_City and Customer__Phone_No__ fields from the DataSet Result to the appropriate columns of the second row of the table. This creates the header. 2. Drag the Cust__Ledger_Entry__Posting_Date_Caption and the Cust__Ledger_Entry__Posting_Date_ fields from the DataSet Result to the first and second columns of the third row of the table. This creates the subheaders. 3. Drag the Cust__Ledger_Entry__Document_Type_Caption, Cust__Ledger_Entry__Document_No__Caption, Cust__Ledger_Entry_DescriptionCaption and Cust__Ledger_Entry__Amount__LCY__Caption fields from the DataSet Result to the third to sixth columns of the third row of the table. This creates the subheaders.
9-56
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports 4. Drag the Cust__Ledger_Entry__Document_Type_, Cust__Ledger_Entry__Document_No__, Cust__Ledger_Entry_Description and Cust__Ledger_Entry__Amount__LCY__ fields from the DataSet Result to the third to sixth columns of the fourth row of the table. This creates the detail.
FIGURE 9.42 THE TABLE WITH FIELDS
Add Totals and Set Format Property The following steps show how to add totals to the report layout. 1. Drag the Cust__Ledger_Entry__Amount__LCY__ field from the DataSet Result to the sixth column of the fifth row of the table. Notice that Sum is selected as the aggregate function. This creates the total for every posting date. 2. Drag the Cust__Ledger_Entry__Amount__LCY__ field from the DataSet Result to the sixth column of the sixth row of the table. This creates the total for every customer. 3. Drag the Cust__Ledger_Entry__Amount__LCY__ field from the DataSet Result to the sixth column of the seventh row of the table. This creates the total for the whole report. 4. Select the Amount LCY text box (the sixth column of the fourth row) and set the following property: o Format: =Fields!Cust__Ledger_Entry__Amount__LCY__Format.Value
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-57
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 5. Repeat step 4 for all the text boxes that represent the Amount LCY and the sum of Amount LCY.
FIGURE 9.43 THE TABLE WITH TOTALS
6. Close Visual Studio and then click Yes when prompted to save the changes. 7. Click anywhere in the Report Designer and then click Yes to load the saved changes from Visual Studio. 8. Compile, save and close the report. 9. Run and preview the report in the RoleTailored client.
FIGURE 9.44 THE REPORT IN THE ROLETAILORED CLIENT
9-58
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports
Demonstration: Add Some Advanced Features The following demonstration shows how to add advanced features to the report including the use of FlowFilters, and features a specific report in the RoleTailored client such as interactive sorting, hide/collapse an item, and charts.
Use FlowFilters The following steps show how to add the ability to filter the report that uses the Date Filter field in the Customer table: 1. Design report 90001, Customer Detail, from the Object Designer. 2. Open the Properties window for the Customer data item and set the ReqFilterFields property to include the Date Filter field.
FIGURE 9.45 THE CUSTOMER PROPERTIES WINDOW
3. Open the Properties window for the Cust. Ledger Entry data item and set the DataItemLink property to Customer No.=FIELD(No.),Posting Date=FIELD(Date Filter).
FIGURE 9.46 THE DATAITEM LINK WINDOW
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-59
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 4. Close the Properties window and then compile, save and close the report. 5. Run the report. 6. In the Customer tab of the request form, type the range 01/01/01..12/31/01 in the Filter column for the Date Filter field, and then click the Preview button. Check whether there are any records outside the range that is set.
Add Interactive Sorting The following steps show how to add interactive sortings to the Customer by Salesperson report. In the Object Designer's Report list: 1. Design report 90000, Customer by Salesperson, from the Object Designer. 2. Click View, Layout. 3. Select the text box in the first column of the table header row (Salesperson_Purchaser_CodeCaption) and set the following properties: o UserSort, SortExpression: =Fields!Salesperson_Purchaser_Code.Value o UserSort, SortExpressionScope: table1_Group1
FIGURE 9.47 THE USERSORT PROPERTIES
4. Repeat step 3 for the rest of the text boxes in the table header row with their respective SortExpression. However, for text boxes that belong to customer table, leave the SortExpressionScope property blank. 5. Close Visual Studio and then click Yes when prompted to save the changes. 6. Click anywhere in the Report Designer and then click Yes to load the saved changes from Visual Studio.
9-60
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports 7. Compile, save and close the report. 8. Run the report in the RoleTailored client to view the changes.
FIGURE 9.48 THE REPORT WITH INTERACTIVE SORTING
Add Hide/Collapse Item The following steps show how to add the hide/collapse feature to the Customer by Salesperson report. 1. Design report 90000, Customer by Salesperson, from the Object Designer. 2. Click View, Layout. 3. Select the first group detail row (third row) and set the following property: o Visibility, ToggleItem: Salesperson_Purchaser_Code 4. Select the text box in the first column, second row (Salesperson_Purchaser_Code) and set the following property: o InitialToggleState: Expanded 5. Close Visual Studio and then click Yes when prompted to save the changes. 6. Click anywhere in the Report Designer and then click Yes to load the saved changes from Visual Studio.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-61
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 7. Compile, save and close the report. 8. Run the report in the RoleTailored client to view the changes.
FIGURE 9.49 THE REPORT WITH HIDE/COLLAPSE ITEM
Add a Chart Charts are a graphical representation of data, and help present information in a summarized, yet concise manner. In the Classic client, creating charts in a report is a cumbersome effort and requires lots of consideration and programming. In the RoleTailored client, this is made easier and possible with minimal effort. The following steps show how to add a chart to the Customer by Salesperson report to represent how many customers, a salesperson has. 1. Design report 90000, Customer by Salesperson, from the Object Designer. 2. Click View, Layout. 3. Drag a Chart control from the toolbox to the report layout. 4. Select the chart control, right-click and then click Properties. The Chart Properties window opens.
9-62
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports 5. At the General tab, set the following: o Title: Customer by Salesperson o Chart Type: Pie
FIGURE 9.50 THE CHART PROPERTIES WINDOW
6. Click the Data tab and set the following: o Dataset name: DataSet_Result
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-63
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 7. Click the Add button at the Values section. The Edit Chart Values window opens. 8. At the Values tab, clear the Series label and set the following: o Value: =Count(Fields!Customer__No__.Value)
FIGURE 9.51 THE EDIT CHART VALUES WINDOW
9. Click OK. 10. Click the Add button at the Series groups section. The Grouping and Sorting Properties window opens.
9-64
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports 11. At the General tab, set the following: o Expression: =Fields!Salesperson_Purchaser_Code.Value o Label: =Fields!Salesperson_Purchaser_Name.Value
FIGURE 9.52 THE GROUPING AND SORTING PROPERTIES WINDOW
12. Click OK. 13. Click OK to close the Chart Properties window. 14. Close Visual Studio and then click Yes when prompted to save the changes. 15. Click anywhere in the Report Designer and then click Yes to load the saved changes from Visual Studio.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-65
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 16. Compile, save and close the report. 17. Run the report in the RoleTailored client to view the changes.
FIGURE 9.53 THE REPORT WITH A CHART
9-66
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports
Lab 9.1 - Create a Basic Report The following lab tests the basic knowledge on how to create a report for both the Classic and the RoleTailored client. Scenario Simon is a developer working for CRONUS International Ltd. CRONUS International has decided to start selling Microsoft Dynamics NAV training courses as its business. Simon has already created a Course table to record course information. Now, Simon must create a report to list all the courses available. The report must be able to run in both the Classic and the RoleTailored client.
Challenge Yourself! 1. Create a report that has the following requirements: a. Prints all the course information. b. Filters by the course type. 2. Enable this report to be run in the RoleTailored client together with advanced features: a. Interactive sorting. b. A bar chart that represents courses and the cost of investment (price) for each course.
Step by Step Create a new report using a wizard. 1. In the Object Designer's Report List, click the New button. 2. Type Course in the Table field. 3. Select Create a Report using a wizard, select Tabular-Type Report Wizard and then click OK. 4. Select all the fields by clicking the Double Right Arrow button, and then click Next. 5. Select No, I don't want a special sorting of my data and then click Next. 6. Click Finish.
Add a filter. 1. Open the Properties window for the Course data item. 2. Set the ReqFilterFields property to Type. 3. Close the Properties window.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-67
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Enable the report to be run in the RoleTailored client. 1. Click View, Layout. 2. Drag a Table control from the toolbox to the report layout. 3. Click one of the columns, right-click and then click Insert Column to the Right. 4. Repeat step 3 five times to add five more columns. 5. Drag the Course_CodeCaption, Course_NameCaption, Course_DescriptionCaption, Course_TypeCaption, Course_DurationCaption, Course_PriceCaption, Course_ActiveCaption, Course_DifficultyCaption and Course_Passing_Rate_Caption fields from the DataSet Result to the appropriate columns of the first row of the table. 6. Drag the Course_Code, Course_Name, Course_Description, Course_Type, Course_Duration, Course_Price, Course_Active, Course_Difficulty and Course_Passing_Rate_ fields from the DataSet Result to the appropriate columns of the second row of the table.
Add Interactive Sorting. 1. Select the text box in the first column of the table header row (Course_CodeCaption) and set the following properties: o UserSort, SortExpression: =Fields!Course_Code.Value 2. Repeat step 1 for the rest of the text boxes in the table header row with their respective SortExpression.
Add a Chart. 1. Drag a Chart control from the toolbox to the report layout. 2. Select the chart control, right-click and then click Properties. 3. At the General tab, set the following: o Title: Course Price o Chart Type: Bar 4. Click the Data tab and set the following: o Dataset name: DataSet_Result 5. Click the Add button at the Values section. 6. At the Values tab, clear the Series label and set the following: o Value: =(Fields!Course_Price.Value) 7. Click OK. 8. Click the Add button at the Series groups section.
9-68
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports 9. At the General tab, set the following: o Expression: =Fields!Course_Code.Value o Label: =Fields!Course_Name.Value 10. Click OK. 11. Click OK to close the Chart Properties window. 12. Close Visual Studio and then click Yes when prompted to save the changes. 13. Click anywhere in the Report Designer and then click Yes to load the saved changes from Visual Studio. 14. Compile and save the report as 90011, Course List and then close the report.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-69
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Summary An organization's ability to collect dependable, timely business intelligence is fundamental to its health, and reports are a way to obtain that intelligence. A C/SIDE developer is expected to create robust reports on demand. This involves an understanding not only of the mechanics of report creation, but of business needs. Reports print information from a database and they can structure and summarize information. Reports can be used to print documents such as invoices, and they can also be used to process data without printing anything. Creating reports includes designing both the business logic that covers the kind of information the report will contain, and the layout that deals with how the report will look when it is printed. In addition, developing reports for the RoleTailored client requires additional design consideration.
9-70
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 9: Reports
Test Your Knowledge 1. True or False: All reports must print at least one page. 2. List the names of the three Designers used with reports, and describe their function. 3. How many times does a Header section print on a report for an indented data item (assume PrintOnEvery page is turned off and there is data in the table)? What if the data item is not indented? 4. What data item property can be used to remove the Data Items tab on the request form (assume there are no request filter fields set)? 5. What two properties of a data item must be set to print a subtotal of a field on a group footer section? 6. When does a TransHeader section print for a data item? 7. What property can be set to start a new page every time that a record is read? 8. What two properties can be used to print a footer at the bottom of every page? 9. What C/AL code can be written that most closely resembles a report that has two data items, with the second indented? 10. What property can be used to filter an indented data item based on fields in the unindented data item above it?
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
9-71
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Quick Interaction: Lessons Learned Take a moment and write down three key points you have learned from this chapter 1.
2.
3.
9-72
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports
CHAPTER 10: DATAPORTS AND XMLPORTS Objectives The objectives are: •
Understand the concepts of a dataport and its components.
•
Provide an overview of designing dataports.
•
Create dataports for export with fixed and a variable format of the external file.
•
Create dataports for import with a fixed and a variable format of the external file.
•
Understand the concepts of XMLport and its components.
•
Provide an overview of designing XMLports.
•
Create XMLports to be run in the Classic client.
•
Create XMLports to be run in the RoleTailored client.
Introduction Dataports and XMLports are objects that are used for importing data from and exporting data to external files. Dataports are used to export data from Microsoft Dynamics® NAV to external text files, and to import data from external text files into Microsoft Dynamics NAV. Importing and exporting data is useful when data is collected outside Microsoft Dynamics NAV and must be incorporated into the database, or when it must be distributed from the Microsoft Dynamics NAV database to an external location. XMLports are used to export and import data to and from external XML document files. These are similar to dataports, only the XMLport encapsulates the data in XML format. This lets developers exchange information between different computer systems in a streamlined way. In Microsoft Dynamics NAV 2009, XMLport is also used to import and export data to and from external text files, when using the RoleTailored client.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-1
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Dataport Fundamentals Dataports are used to export and import data to and from external text files. Dataports can be defined to specifically be used for import or export data, or both. If the dataport is used for both import and export, only on execution does the dataport determine whether the process is an import or an export and the name of the file to read from or to write to. There are several options for the format of the external file which includes fixed and variable formats. The following shows components of a dataport and how they are related.
FIGURE 10.1 DATAPORT COMPONENTS AND THEIR RELATION
The dataport description is the complete description of the dataport and it is stored in the database. It determines: •
How data is collected.
•
How data is formatted when written to the output file.
•
What the dataport consists of.
Dataports are created and designed in the Dataport Designer which is accessed from the Object Designer.
10-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports Properties A property is an attribute of an object, or its component, that characterizes and specifies behavior of the parent in some ways, such as length and position of a dataport field in a line during import. The dataport description contains properties that are related to the dataport itself and properties that are related to the other components of the dataport, such as data items, dataport fields or request forms.
Triggers Certain predefined events that occur to a dataport cause the system to execute a user-definable C/AL function. The event and the function together are called a trigger. Triggers in a dataport can be divided into four categories: •
Dataport triggers
•
Data item triggers
•
Dataport field triggers
•
Request form triggers
Examples of dataport triggers include OnPreDataport that contains statements that are executed right before the dataport is run, and OnPostDataport that contains statements that are executed right before the dataport execution is completed. Triggers in a dataport are edited in the C/AL Editor that can be opened from the Dataport Designer.
Data Items The data model of a dataport is built from data items. A data item corresponds to a table. To retrieve information from tables in the database, define data items. Data items in a dataport cannot be indented. They have to be processed one at a time.
Dataport Fields A dataport field refers to a field in an external file from which data is to be imported. Dataport fields in the external file are defined either as having a fixed length, or as delimited by certain characters. Dataport fields are specified in the Field Designer which can be opened from the Dataport Designer.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-3
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Request Form The request form is the form that is run before the actual dataport begins execution. It is used to collect requests and options from the user of the dataport of things such as the name of the external file.
Design Dataports Designing a dataport involves several tasks. They are as follows: •
Designing the data model.
•
Defining the layout of the external file.
These tasks consist primarily of setting various properties in the dataport objects, such as dataport properties, data item properties and dataport field properties.
Data Model The data model is designed by designing data items. A data item corresponds to a table. When a dataport is used to export data, each data item in the dataport is iterated for all records in the underlying table. Sorting order, keys and table views can be set accordingly. Developers can decide whether the result is written to the external file or not. When a dataport is used to import data, records read from the external file are inserted to the table that corresponds to the data item. Developers can examine the records before inserting them, specify whether records are inserted automatically and decide whether records already in the database are overwritten or updated when a record with the same primary key is read from the external file. Developers may also determine to omit this record.
External File The layout of the external file is defined by setting properties which include setting dataport properties and dataport field properties. When a dataport is used to export data, these properties describe how the dataport fields and records must be written to the file. When a dataport is used to import data, these properties describe how the input stream must be broken up into records and dataport fields.
10-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports Dataport Properties Dataport properties describe the dataport in general. Several properties, such as the Import and FileName properties, can be set and reset dynamically. For example, developers can create a dataport where the user can do one of the following: •
Select whether to import or export.
•
Select the name of the external file to read from or write to.
•
Generate a file name automatically when the dataport is run.
The FileFormat property determines the format of the external file. In other words, it determines the dataport fields' behavior in a record. The following list shows the options available for the FileFormat property and the dataport fields' behavior for each option. FileFormat Property Value
Remarks
Fixed
The dataport fields in a record have a fixed width. Developers define the starting position and the width of each dataport field in the record in the Dataport Field Designer.
Variable
The dataport fields in a record have varying widths. Developers define the characters that separate the dataport fields in the FieldSeparator property.
Data Item Properties Data Item properties describe the data items of the dataport. Most of these properties are the same and have the same function as the corresponding properties of a data item in a report. There are three properties which are special for data items in a dataport: AutoSave, AutoUpdate, and AutoReplace. They are used as follows: Property
Remarks
AutoSave
This property determines whether imported records are automatically inserted in a C/SIDE table.
AutoUpdate
This property determines whether imported records are initialized with values from an existing record with the same primary key.
AutoReplace
This property determines whether imported records automatically replace existing records with the same primary key.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-5
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 These three properties determine how records that are read from the external file are handled. They are also used to resolve the conflict that arises when a record that is read from the external file during import has the same primary key as a record that already exists in the database table. The following table shows combinations of these properties values and their result. AutoSave
AutoUpdate
AutoReplace
Record exists in the database and in the external file
Record exists only in the external file
No
N/A
N/A
The record in the database is not automatically updated or replaced.
The record from the external file is not automatically inserted to the database.
Yes
No
No
A runtime error occurs and the import is stopped.
The record from the external file is automatically inserted to the database.
Yes
No
Yes
The record from the external file replaces the record in the database.
The record from the external file is automatically inserted to the database.
Yes
Yes
N/A
The record from the external file updates the record in the database.
The record from the external file is automatically inserted to the database.
If the AutoSave property is set to No, the settings of AutoReplace and AutoUpdate properties have no effect. The insertion or modification is not done automatically and must be done through C/AL code. The AutoUpdate property is useful in some particular situations. Its functionality is best explained by the following example: •
10-6
Suppose that a developer has a table that is an item list. The developer updates the prices by exporting a list that has item numbers (the primary key) and prices to an external file and then does some calculations on the prices on a spreadsheet.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports •
When the prices are calculated and the developer is ready to import the file that has the new prices, it is obvious that the records read from the external file have the same primary key as records that are already in the database.
•
Using AutoSave and AutoReplace does not resolve this problem. If the developer is replacing every record with the corresponding record from the import file, all the information except the item numbers and the prices are lost, assuming that the table contains information other than the item numbers and the prices, such as name and description of the items.
•
AutoUpdate solves this dilemma. When a record is imported, it actually replaces the existing record, but fields that are not present in the imported record are initialized with the data from the already existing record instead of being left empty. The existing record is updated with the revised information.
Dataport Field Properties Dataport Field properties describe the dataport fields of a record. If the FileFormat property is set to Fixed, developers use the StartPos and Width properties of each dataport field to define how a record that is read from the external file is to be broken into dataport fields during import. During export, these properties determine how data from the database is written to the external file. During import, when a value is too large for the data type or the defined width of the database table field where it is to be inserted, an error occurs and stops the execution. Because the whole dataport is inside a transaction, no traces are left of this aborted run in the database. During export, data is converted to text before the export. When the Width property is smaller than the actual width of the data after conversion, the contents are truncated from the right until the defined Width. A number is not rounded or truncated as a number, but as text, from the right. Developers receive an error at design time if they defined dataport fields that have starting positions and widths that cause these dataport fields to overlap. This error prevents compilation of the dataport. However, it is possible to have gaps between dataport fields. The starting position of the next dataport field does not have to be exactly where the previous dataport field ended. These gaps may skip unnecessary information or create blank columns in the file.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-7
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 If the Field Menu is used to add dataport fields in the Field Designer, the Width property is set to several default values, depending on the field data type. The following table shows the default values for the Width property for each field data type. Data Type of the Field
Width
Code
If actual length > 10, actual length is used; otherwise, 10.
Text
If actual length > 30, actual length is used; otherwise, 30.
Date
11
Time
10
Option
10
Decimal
12
Integer
7
Boolean
10
Design and Run Dataports Dataports are created and modified in the Dataport Designer which is accessed from the Object Designer. Usually, dataports are run from the Navigation Pane in the Classic client, or from command buttons in a form, also in the Classic client. The RoleTailored client does not support dataport objects. Dataports can also be run from the Object Designer or directly from the Dataport Designer. If the dataport is run directly from the Dataport Designer and the dataport is used for import process, no records are actually saved in the database table.
Demonstration: Create Dataports For Export There are four fundamental kinds of dataports: importing and exporting, each with a fixed and a variable format of the external file. The following demonstration shows how to create dataports for export by using different file formats.
10-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports Create a Dataport to Export to a Fixed Format Text File The database table that is used in this demonstration is the G/L Account table. There are several FlowFields among the dataport fields that are exported, and they have to be calculated when exported. The following steps show how to create a simple dataport to export fields from the G/L Account table, by using a fixed format external file. 1. In the Object Designer's Dataport List, click the New button. The Dataport Designer opens. 2. Open the Properties window for the dataport and set the following properties: o Import: No (This specifies the dataport to be used only for export.) o FileFormat: Fixed (This specifies the external file to have fixed format.) 3. Close the Properties window. 4. Click the first empty line in the Dataport Designer, and type or select the number or name of table 15, G/L Account in the DataItem column. By the default, the Name column is set to the table name. 5. While the G/L Account data item is still selected, click View, Dataport Fields. The Field Designer opens. 6. Type the following in the Field Designer: SourceExpr
StartPos
Width
"No."
1
20
Name
22
30
"Balance at Date"
53
12
"Net Change"
66
12
NOTE: Instead of typing the fields manually, use the Field Menu to add multiple fields from the table to the Field Designer. 7. Close the Field Designer and open the Properties window for the G/L Account data item, and set the following property: o CalcFields: Balance at Date,Net Change NOTE: Instead of typing the value directly to the CalcFields property, click the Assist-Edit button on the CalcFields property to open the Field List window. Add the fields in the Field List window and then click OK. 8. Close the Properties window.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-9
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 9. Compile and save the dataport by clicking File, Save As. The Save As dialog box opens. 10. Type 90000 in the ID field and G/L Account Export Fixed in the Name field, ensure that the Compiled check box is selected, and then click OK. This compiles and saves the dataport. 11. Close the dataport.
Run the Dataport The following steps show how to run the dataport from the Object Designer. 1. In the Object Designer's Dataport list, select dataport 90000, G/L Account Export Fixed, and then click the Run button. The request form opens. 2. Click the Options tab, and then click the Assist-Edit button on the File Name text box. The Dataport Export File Name dialog opens. 3. Select Desktop in the Save In drop-down list, type GLAccountFixed in the File Name text box, and then click Save. 4. Click OK on the request form. The dataport runs and creates the GLAccountFixed.txt file in the Desktop. 5. Open the GLAccountFixed.txt in a Notepad.
FIGURE 10.2 THE GLACCOUNTFIXED.TXT IN NOTEPAD
Refine the Dataport Several things can be done to refine the newly created dataport to make it more user-friendly. This includes the following:
10-10
•
Removing the first tab in the request form so that users cannot set filters and keys.
•
Setting the dataport to export only accounts where the Account Type is Posting or End-Total.
•
Formatting the numbers as thousands. There must be no thousand separators, no decimals, and the sign must be prefixed.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports Change the Request Form The UseReqForm property specifies whether the dataport displays the request form before its execution. If no file name is set, setting this property to No (disabling the request form) causes a run-time error. To remove the tabs that correspond to the data items in the request form, clear the ReqFilterFields property and set a sorting key in the DataItemTableView property of the data items. The following steps show how to remove the G/L Account tab from the request form. 1. Design dataport 90000, G/L Account Export Fixed from the Object Designer. 2. Open the Properties window for the G/L Account data item and set the DataItemTableView property to SORTING(No.) 3. Close the Properties window and then compile, save and close the dataport. 4. Run the dataport. Notice the request form only shows one tab, the Options tab.
FIGURE 10.3 THE REQUEST FORM
Select Specific Filters The following steps show how to select only some account types, by creating a table filter through setting DataItemTableView property. 1. Design dataport 90000, G/L Account Export Fixed from the Object Designer. 2. Open the Properties window for the G/L Account data item. 3. Click the Assist-Edit button on the DataItemTableView property to open the Table View window.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-11
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 4. Click the Assist-Edit button on the Table Filter field to open the Table Filter window, and type the following: Field
Type
Value
Account Type
Filter
Posting|EndTotal
This creates a table filter that selects records where Account Type is Posting or End-Total (the character between the two values is a | (pipe) which means OR). 5. Click OK to close the Table Filter window, and then click OK to close the Table View window. The DataItemTableView is set to SORTING(No.) WHERE(Account Type=FILTER(Posting|EndTotal)). 6. Close the Properties window, and then compile, save and close the dataport. 7. Run the dataport, save the external file as GLAccountFixed2.txt and view the text file.
Change the Formatting of Numbers The following steps show how to export the decimal fields, Balance at Date and Net Change as thousands so that the number 1,444,723.67 is exported as 1444, by setting the SourceExpr property of these fields. 1. Design dataport 90000, G/L Account Export Fixed from the Object Designer. 2. With the G/L Account data item selected, click View, Dataport Fields. The Field Designer opens. 3. Open the Properties window for the Balance at Date field, and set the following property: o SourceExpr: FORMAT(ROUND("Balance at Date"/1000,1,'='),0,1) In this expression, the Balance at Date field is first divided by 1000. The result is rounded by the ROUND function, and then the FORMAT function is used to display the return value from the ROUND function in format 1 (which for a decimal value means <Sign>). 4. Open the Properties window for the Net Change field, and set the following property: o SourceExpr: ROUND("Net Change"/1000,1,'=') o Format: <Sign> NOTE: This achieves the same effect as setting the SourceExpr property with FORMAT function, as in the Balance at Date field.
10-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports 5. Close the Properties window, and then compile, save and close the dataport. 6. Run the dataport, save the external file as GLAccountFixed3.txt and view the text file.
FIGURE 10.4 THE GLACCOUNTFIXED3.TXT IN NOTEPAD
Create a Dataport to Export to a Variable Format Text File Now create a dataport that exports the same records as in the previous example, but in a variable format. Each dataport field in a record is delimited by characters that are defined in the FieldSeparator property and has the width of only the actual data of the dataport field, in each record. The following steps show how to create a dataport to export fields from the G/L Account table, by using a variable format external file. 1. Design dataport 90000, G/L Account Export Fixed from the Object Designer. 2. Compile and save the dataport with the ID 90001, and the name G/L Account Export Variable. 3. Open the Properties window for the dataport, set the following properties: o FileFormat: Variable o FieldStartDelimiter: o FieldEndDelimiter: o FieldSeparator: ; The semicolon is used as the field separator because the dataport fields include both space characters and commas. Another solution is to use the delimiters. In that case, the field separator can be a comma. Set these properties appropriately, depending on the target application for the exported file or which formats that the application supports when it is importing text files. Leave the RecordSeparator and the DataItemSeparator properties as they are. This means the records are separated by new lines and data items are separated by two new lines. Setting the FileFormat property to Variable tells C/SIDE to ignore values set in the StartPos and Width properties of the dataport fields.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-13
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 4. Close the Properties window, and compile, save and close the dataport. 5. Run the dataport, save the external file as GLAccountVariable.txt and view the text file.
FIGURE 10.5 THE GLACCOUNTVARIABLE.TXT IN NOTEPAD
Demonstration: Create Dataports For Import The following demonstration shows how to create dataports for import by using different file formats.
Create a Fixed Format Text File Creating a dataport for import is no different from creating a dataport for export. However, consider how the imported records must be inserted in the database table. This is especially relevant if the table already contains records with the same primary key as some records to be imported. The database table that is used in this demonstration is the Vehicle table (created earlier in the course - Chapter 2: Tables.) Before creating the dataport for import, create the text file to be used as the import file. The following steps show how to create a fixed format text file that contains records to be imported to the Vehicle table. 1. Open the Notepad. 2. Type the following: FIAT MAZDA FIAT MAZDA
1000 7500 2000 5500
Black Blue Ivory Red
5-Speed Automatic Automatic 5-Speed
01/31/10 01/15/10 03/31/10 02/10/10
3. Save the file as VehicleFixed.txt and close the Notepad.
10-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports Create a Dataport to Import from a Fixed Format Text File The following steps show how to create a dataport to import fields from an external file to the Vehicle table, by using a fixed format external file. 1. In the Object Designer's Dataport List, click the New button. The Dataport Designer opens. 2. Open the Properties window for the dataport and set the following properties: o Import: Yes (This specifies the dataport to be used only for import.) o FileFormat: Fixed (This specifies the external file to have fixed format.) 3. Close the Properties window. 4. Click the first empty line in the Dataport Designer, and type or select the number or name of table 90000, Vehicle in the DataItem column. By the default, the Name column is set to the table name. Decide how the lines in the import file are broken down into dataport fields; each line becomes a record in the data item. The lines have a fixed format, and by carefully looking at the layout of the lines, deduce the field starting positions. 5. While the Vehicle data item is still selected, click View, Dataport Fields. The Field Designer opens. 6. Type the following in the Field Designer: SourceExpr
StartPos
Width
Model
1
7
"Serial No."
8
6
Description
14
8
Transmission
22
11
"List Price"
33
7
"Date of Manufacturing"
40
11
7. Close the Field Designer. 8. Compile and save the dataport with the ID 90002, and the name Vehicle Import Fixed, and close the dataport. 9. Run table 90000, Vehicle, from the Object Designer. 10. Delete all the records in the table, and close the table. 11. Run the dataport. The request form opens.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-15
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 12. In the request form Options tab, select VehicleFixed.txt created earlier as the file to import, and then click OK. 13. Run table 90000, Vehicle and view the changes. The table now contains the imported record.
FIGURE 10.6 THE VEHICLE TABLE
Because Model and Serial No. are the fields in the primary key of the table, the records are displayed in an order determined by these fields, not the in the order shown in the import file.
Possible Errors Always test imports carefully before using them for production. It is easy to make errors when deciding how to divide up the lines in the import file. In some cases, the rearrangement of records generates a run-time error when the dataport is run. Consider, for example, if an error is made in setting up a dataport field (of type Integer in the table) so that it is assigned a width that is one character too wide. For most of the import file, this makes no difference at all - the resulting trailing space is ignored. But the line that begins with "112Oven..." can provoke a run-time error if C/SIDE reads 112O instead of 112. The "O" (uppercase "O") cannot be inserted into an integer field. In cases such as these, it is fortunate to provoke a run-time error. In other cases, the error may not be detected by C/SIDE, for example, if the cut between two text fields is positioned incorrectly.
Create a Variable Format Text File The following steps show how to create a variable format text file that contains records to be imported to the Vehicle table. 1. Open the Notepad. 2. Type the following: FIAT,1000,Black,5-Speed,15000,01/31/10 FIAT,2000,Ivory,Automatic,40000,03/31/10 MAZDA,5500,Red,5-Speed,30000,02/10/10 MAZDA,7500,Blue,Automatic,25000,01/15/10
10-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports 3. Save the file as VehicleFixed.txt and close the Notepad.
Create a Dataport to Import from Variable Format Text File The following steps show how to create a dataport to import fields from an external file to the Vehicle table, by using variable format external file. 1. Design dataport 90002, Vehicle Import Fixed, from the Object Designer. 2. Compile and save the dataport with the ID 90003, and the name Vehicle Import Variable. 3. Open the Properties window for the dataport, and set the following properties: o FileFormat: Variable o FieldSeparator: , o FieldStartDelimiter: o FieldEndDelimiter: These are the only differences between the fixed format dataport and variable format dataport. 4. Close the Properties window, and compile, save and close the dataport. 5. Run table 90000, Vehicle, from the Object Designer. 6. Delete all the records in the table, and close the table. 7. Run the dataport. The request form opens. 8. In the request form Options tab, select VehicleVariable.txt as the file to import, and then click OK. 9. Run table 90000, Vehicle and view the changes. The table now contains the imported record. The result of running this dataport is the same as running the dataport with a fixed format.
XMLPort Fundamentals XMLports are used to export and import data to and from external XML document files. XML documents created by XMLports encapsulate the data in XML format. This enables exchanging information between different computer systems in a streamlined manner. In Microsoft Dynamics NAV 2009, XMLports replace dataports as means of exporting and importing data in the RoleTailored client. This means, XMLports are not only limited to only XML document files, but also support text files, when they are run in the RoleTailored client.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-17
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The following shows components of an XMLport and how they are related.
FIGURE 10.7 XMLPORT COMPONENTS AND THEIR RELATION
The XMLport description is the complete description of the XMLport and it is stored in the database. It determines: •
How data is collected.
•
How data is formatted when written to the output file.
•
What the XMLport consists of.
XMLports are created and designed in the XMLport Designer which is accessed from the Object Designer.
Properties A property is an attribute of an object, or its component, that characterizes and specifies behavior of the parent in some ways, such as the type of a node in XMLport. The XMLport description contains properties that are related to the XMLport itself and properties that are related to the other components of the XMLport, such as nodes and request pages.
Triggers Certain predefined events that occur to an XMLport cause the system to execute a user-definable C/AL function. The event and the function together are called a trigger. Triggers in an XMLport can be divided into three categories:
10-18
•
XMLport triggers
•
Node triggers
•
Request page triggers
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports Nodes Instead of fields, XMLports have nodes. Nodes form the structure of XMLport and the structure of the XML document or text file which is to be imported from or exported to. Each node has several important properties, some can be accessed directly from the XMLport Designer. They are as follows: Node Property
Remarks
Node Name
Used to specify the XML node name of the XML element or attribute. Node names must be entered in the order in which they appear in the XML document. Parent elements must precede their child elements. Indent the node names of child elements under their parent elements by using one indentation per level. List attributes under the elements that they define and indent them to the child level.
Node Type
Used to specify whether the name in the Node Name represents data of type element or attribute. The drop-down list in the NodeType field contains two options: Element and Attribute. The default setting is Element.
Source Type
Used to specify the data structure that the Node Name corresponds to. The SourceType field contains a drop-down list that contains three options: Text, Table, and Field. The default setting is Text.
Data Source
Used together with the Source Type to specify the data source from the data structure.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-19
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The following list explains more about Source Type options: Source Type Value
Remarks
Text
Select this option when the XML data cannot be mapped directly to the database or when the database does not need the information. The value of the Text field is put into a text variable specified in the VariableName property. Otherwise the node name is used by default. The text variable functions like a global C/AL text variable. The text source type can be changed into a big text variable by setting the TextType property to BigText.
Table
Select this option to indicate that a node is equal to a table or that a table record must be initialized. As with the Text option, specify a variable name for the table which also functions like a global record variable. By default, the variable name is the name of the table.
Field
Select this option to indicate that a node is equal to a field in the database. However, for this selection to be valid, a table must be declared as the parent of the field. Failure to do this causes an error when compiling the XMLport object.
The Data Source has the following interactions with the Source Type: •
If Table is specified as the Source Type, clicking the Assist-Edit button on the DataSource field opens the Table List window. Select a table from the Table List window or by setting the SourceTable property of the node. o
o
•
10-20
If a variable name is defined for the table, the format of the value that is shown in the DataSource field will be TableVariableName(tablename). If a variable name is not defined, the format of the value is displayed as (tablename).
If Field is specified as the Source Type, clicking the Assist-Edit button on the DataSource field opens the Field Lookup window. Select a field from the Field Lookup window or by setting the Sourcefield property of the node. The format of the value is displayed as tablevariablename::fieldname.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports Request Page The request page is the page that is run before the actual XMLport begins execution. It is used to collect requests and options from the user of the XMLport of things such as filtering. Generally, request pages in XMLports and request pages in reports are similar. They have similar filter functionality grouped in FastTabs and developers can add more controls by creating other FastTabs. Request page in XMLport only has OK and Cancel buttons (compared to Print, Preview and Cancel buttons in request page in reports) regardless whether the XMLport is used for importing or exporting text or XML documents. Request page is displayed only when XMLports are run in the RoleTailored client.
Design XMLports An XML document contains XML nodes which determine the nature of the content that they contain. To create an XMLport to import data from an XML document, specify all the XML nodes (specify node names) and indicate the type of each, whether it represents an element or an attribute. Map these nodes to corresponding data structures (tables, records or fields) in the Microsoft Dynamics NAV database. When an XMLport object is called to handle an incoming XML document, it reads the incoming data stream and performs the processing and database actions. To create an XMLport to export data to an XML document, build the node structure of the XML document by using the XMLport Designer and map the data. When an XMLport object is called to export data, it reads the required data from the database, adds the necessary XML nodes to form the XML document, and writes the document to a data stream. XMLports do not handle XML documents that do the following: •
Modify existing data in the database.
•
Find and delete data in the database.
•
Query the database for data, such as item catalog information.
For incoming documents of these types, use C/AL code to perform the necessary database manipulation to achieve the desired result. Designing an XMLport is actually designing the structure of the external file, whether it is an XML document or a text file. This consists primarily of setting various properties in the XMLport objects, such as XMLport properties and Node properties.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-21
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 XMLport Properties The XMLport properties describe the XMLport in general. Several properties, such as the Direction and FileName properties, can be set and reset dynamically. For example, developers can create an XMLport where the user can do one of the following: •
Select whether to import or export.
•
Select the name of the external file to read from or write to.
•
Generate a file name automatically when the XMLport is run.
The Format property determines the format of the external file. In other words, it determines the XMLport nodes behavior in a record. The following list shows the options available for the Format property. Format Property Value
Remarks
XML
The XMLport handles XML documents.
Fixed Text
The XMLport handles text file that has fixed format.
Variable Text
The XMLport handles text file that has variable format.
Node Properties The node properties describe the node of the XMLport which defines the structure of the XMLport. The following list shows examples of node properties.
10-22
Property Name
Remarks
Indentation
Sets the indentation level of an element or attribute in the XMLport Designer.
NodeName
Specifies the name of a node in an XML document. This property can also be accessed directly in the XMLport Designer.
NodeType
Specifies whether an XML object is an element or an attribute.
SourceType
Specifies what a particular node in the XMLport designer corresponds to in the Microsoft Dynamics NAV database. This property can also be accessed directly in the XMLport Designer.
SourceTable
Selects the table to be mapped to XML data (import) or the table from which data is to be exported. This property can also be accessed from the Data Source field in the XMLport Designer.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports
Property Name
Remarks
SourceField
Selects the field that is to be mapped to XML data. This propery can also be accessed from the Data Source field in the XMLport Designer.
TextType
Specifies which type of text this element or attribute contains.
FieldValidate
Specifies whether the values in the source field must be validated by the OnValidate trigger for the field.
VariableName
Specifies a variable name for the table specified in the SourceTable property. Also used to specify a variable name for the text if it is specified in the SourceType property.
SourceTableView
Used to filter the data in the table set as the source for this XML item.
CalcFields
Calculates automatically the information for FlowFields entered here.
AutoCalcField
Determines whether the value in the FlowField must be recalculated before the field is exported.
LinkTable
Determines to which table the XML item must be linked, and can only be used for the SourceType of Table.
LinkTableForceInsert
Specifies whether data from the linked table must be forcibly inserted into a table to prevent the system from generating an error.
LinkFields
Specifies the fields from the two tables that are linked by the LinkTable property. This is available only for XML items with Table as the data source.
Temporary
Creates a temporary table in the XMLport.
MinOccurs
Specifies the minimum number of times that an element can occur.
MaxOccurs
Specifies the maximum number of times that an element can occur.
Occurrence
Specifies whether an attribute must occur in the data being imported or exported.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-23
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Properties for Handling Text Files There are several properties of XMLport and XMLport node which are specific for XMLports that handle text files, when they are run in the RoleTailored client. These properties are as follows:
10-24
Name
Type
Property Of
Description
Format
Option
XMLport
Determines the import/export format of the XMLport. The options are as follows: • XML •
Variable Text
•
Fixed Text
Width
Integer
Nodes (elements and/or attributes)
Determines the width of the fixed width field. If Fixed Length is selected in the Format property, all elements and attributes of type Text and Field should have their Width property value set to greater than 0, or it gives compilation errors.
FieldDelimiter
String
XMLport
Determines what the text delimiter is for a field. The default value is a quotation mark (").
FieldSeparator
String
XMLport
Determines what the field separator is for fields. The default value is a comma (,).
RecordSeparator
String
XMLport
Determines what the record separator is for records. The default value is .
TableSeparator
String
XMLport
Determines what the table separator is for tables. The default value is .
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports Design and Run XMLports XMLports are created and modified in the XMLport Designer which is accessed from the Object Designer. However, XMLports are always run from another object. They cannot be run directly from the Object Designer. To test run an XMLport before integrating it to the rest of the application, create a test codeunit that calls the XMLport and streams data to or from a file, depending on whether it is an import or an export process. The following shows a test codeunit to run an XMLport.
FIGURE 10.8 THE TEST CODEUNIT
The four functions in the OnRun trigger perform the following: •
Open the Import.xml file.
•
Create an InStream object so that the XML data can be streamed from the file.
•
Load a specific XMLport object and give it the source from which it shall read and parse the incoming XML data stream.
•
Close the Import.xml file.
In Microsoft Dynamics NAV 2009, XMLports can be run from: •
Menu suites designed for the RoleTailored Client.
•
RunObject property of controls in page objects.
•
Codeunits.
An XMLport instance can be created as a variable of type XMLport and the instance has a RUN method, similar to the dataport RUN method.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-25
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Demonstration: Create XMLports For Use In The Classic Client The following demonstration shows how to create XMLports for the Classic client.
Create an XMLport to Export to XML Documents The following steps show how to create an XMLport to export data from the G/L Account table to an external XML document. 1. In the Object Designer's XMLport List, click the New button. The XMLport Designer opens. 2. Open the Properties window for the XMLport and set the following properties: o Direction: Export (This specifies the XMLport to be used only for export.) o Format: Xml (This specifies the external file to be an XML document.) 3. Close the Properties window. 4. Click the first empty line in the XMLport Designer, and type the following: Node Name
Node Type
Source Type
Root
Element
Text
5. Go to the next line and type the following to add a source table. Ensure that it is indented under the Root element. Node Name
Node Type
Source Type
Data Source
GLAccount
Element
Table
15
NOTE: The G/L Account table ID is 15. Instead of typing 15 directly to the Data Source field, use the LookUp button on the Data Source field and select the G/L Account table.
10-26
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports 6. Go to the next line and type the following on the next few lines to add several fields from the G/L Account table. Ensure that they are indented under the GL Account element. Node Name
Node Type
Source Type
Data Source
No
Element
Field
G/L Account::No.
Name
Element
Field
G/L Account::Name
BalanceAtDate
Element
Field
G/L Account::Balance at Date
NetChange
Element
Field
G/L Account::Net Change
NOTE: Instead of typing the value to the Data Source field, use the LookUp button to open the Field Lookup window and select the fields from the Field Lookup window. 7. Open the Properties window for the G/L Account element, and set the following property: o SourceTableView: SORTING(No.) WHERE(Account Type=FILTER(Posting|End-Total)) o CalcFields: Balance at Date,Net Change NOTE: Instead of typing the value directly to the CalcFields property, click the Assist-Edit button on the CalcFields property to open the Field List window. Add the fields in the Field List window and then click OK. Also, instead of typing the value to the SourceTableView property, use the Assist-Edit button to open the Table View window and assign the property value. 8. Close the Properties window.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-27
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 9. Compile and save the XMLport by clicking File, Save As. The Save As dialog box opens. 10. Type 90000 in the ID field and G/L Account Export XML in the Name field, ensure that the Compiled check box is selected, and then click OK. This compiles and saves the XMLport.
FIGURE 10.9 THE G/L ACCOUNT EXPORT XML XMLPORT
11. Close the XMLport.
Create a Codeunit to Run the XMLport The following steps show how to create a codeunit to run the XMLport. 1. In the Object Designer's Codeunit List, click the New button. The C/AL Editor opens. 2. Click View, C/AL Globals. 3. In the Variables tab, type the following: Name
DataType
TestFile
File
TestStream
OutStream
4. Close the C/AL Globals window. 5. Click the first line under the OnRun trigger, and type the following: TestFile.CREATE('C:\GL Account Export.xml'); TestFile.CREATEOUTSTREAM(TestStream); XMLPORT.EXPORT(XMLPORT::"G/L Account Export XML",TestStream); TestFile.CLOSE; MESSAGE('G/L Account Export Xml completed!');
This codeunit creates a new text file "C:\GL Account Export.xml."
10-28
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports 6. Compile and save the codeunit by clicking File, Save As. TheSave As dialog box opens. 7. Type 90004 in the ID field and XML Export - G/L Account in the Name field, ensure that the Compiled check box is selected, and then click OK. This compiles and saves the codeunit. 8. Run the codeunit and view the result. 9. Locate the new file "C:\GL Account Export.xml" on the system. Double-clicking this file opens it in the browser. The following figure shows the XML file:
FIGURE 10.10 THE GL ACCOUNT EXPORT.XML
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-29
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Create an XML Input File The database table that is used in the following demonstration is the Vehicle table (created earlier in the course - Chapter 2: Tables.) Before creating the XMLport for import, create the XML file to be used as the import file. The following steps show how to create an XML file containing records to be imported to the Vehicle table. 1. Open the Notepad. 2. Type the following: <Model>FIAT <SerialNo>1000 15,000 <Model>FIAT <SerialNo>2000 40,000 <Model>MAZDA <SerialNo>5500 30,000 <Model>MAZDA <SerialNo>7500 25,000
3. Save the file as VehicleXML.xml and close the Notepad.
Create an XMLport to Import from XML Documents The following steps show how to create an XMLport to import data from an external XML document to the Vehicle table. 1. In the Object Designer's XMLport list, click the New button. The XMLport Designer opens. 2. Open the Properties window for the XMLport and set the following properties: o Direction: Import (This specifies the XMLport to be used only for import.) o Format: Xml (This specifies the external file to be an XML document.)
10-30
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports 3. Close the Properties window. 4. Click the first empty line in the XMLport Designer, and type the following: Node Name
Node Type
Source Type
Root
Element
Text
5. Go to the next line and type the following to add a source table. Ensure that it is indented under the Root element. Node Name
Node Type
Source Type
Data Source
Vehicle
Element
Table
90000
6. Go to the next line and type the following on the next few lines to add several fields from the Vehicle table. Ensure that they are indented under the Vehicle element. Node Name
Node Type
Source Type
Data Source
Model
Element
Field
Vehicle::Model
SerialNo
Element
Field
Vehicle::Name
ListPrice
Element
Field
Vehicle::List Price
7. Compile and save the XMLport by clicking File, Save As. The Save As dialog box opens. 8. Type 90001 in the ID field and Vehicle Import XML in the Name field, ensure that the Compiled check box is selected, and then click OK. This compiles and saves the XMLport. 9. Close the XMLport.
Create a Codeunit to Run the XMLport The following steps show how to create a codeunit to run the XMLport. 1. In the Object Designer's Codeunit list, click the New button. The C/AL Editor opens.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-31
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 2. Click View, C/AL Globals. 3. In the Variables tab, type the following: Name
DataType
TestFile
File
TestStream
InStream
4. Close the C/AL Globals window. 5. Click the first line under the OnRun trigger, and type the following: TestFile.OPEN('C:\VehicleXML.xml'); TestFile.CREATEINSTREAM(TestStream); XMLPORT.IMPORT(XMLPORT::"Vehicle Import XML",TestStream); TestFile.CLOSE; MESSAGE('Vehicle Import Xml completed!');
This codeunit imports an XML file "C:\VehicleXML.xml." 6. Compile and save the codeunit by clicking File, Save As. TheSave As dialog box opens. 7. Type 90005 in the ID field and XML Import - Vehicle in the Name field, ensure that the Compiled check box is selected, and then click OK. This compiles and saves the codeunit. 8. Run table 90000, Vehicle, from the Object Designer.
10-32
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports 9. Delete all the records in the table, and close the table. 10. Run the codeunit and then run table 90000, Vehicle, from the Object Designer and view the result. The table now contains the imported record.
FIGURE 10.11 THE VEHICLE TABLE
Demonstration: Create XMLports For Use In The RoleTailored Client The following demonstration shows how to create XMLports for the RoleTailored client.
Transfer a File From NAV Server to the Client The codeunit 90004, XML Export - G/L Account which is created in the earlier demonstration, exports data from the G/L Account table to an XML document. In the new three-tier architecture, the business logic is run on the middle-tier server and not on the client. This means that in Microsoft Dynamics NAV, files are created on the Microsoft Dynamics NAV service and not locally on the client computer as is the case in the Classic client. There are several built-in functions which are used to transfer files from and to Microsoft Dynamics NAV service to the RoleTailored client, such as the DOWNLOAD and the UPLOAD functions. In addition, the ISSERVICETIER function is used to determine whether code is run in the Classic client or Microsoft Dynamics NAV service.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-33
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The following steps show how to run the codeunit 90004, XML Export - G/L Account, from a page in the RoleTailored client. 1. Design codeunit 90004, XML Export - G/L Account from the Object Designer. 2. Add the following global variables: Name
DataType
ToFile
Variant
3. Modify the code in the OnRun trigger as follows: TestFile.CREATE('C:\GL Account Export.xml'); TestFile.CREATEOUTSTREAM(TestStream); XMLPORT.EXPORT(XMLPORT::"G/L Account Export XML",TestStream); TestFile.CLOSE; ToFile := 'thefile.xml'; IF ISSERVICETIER THEN DOWNLOAD('C:\GL Account Export.xml','Downloading file..','C:\','',Tofile); MESSAGE('G/L Account Export Xml completed!');
4. Compile, save and close the codeunit.
Run the Codeunit From a Page The following steps show how to run the codeunit from page 90001, Custom Page. 1. Design page 90001, Custom Page, from the Object Designer. 2. Open the Action Designer for the page. 3. Type the following on the empty line: Caption
Type
Run Codeunit
Action
4. Set the RunObject property of the action to Codeunit XML Export G/L Account. 5. Compile, save and close the page. Run the page and run the action.
10-34
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports Run an XMLport Directly From a Page An XMLport can be run directly from an action in a page. The following steps show how to run an XMLport directly from a page in the RoleTailored client. 1. Design page 90001, Custom Page, from the Object Designer. 2. Open the Action Designer for the page. 3. Type the following on the empty line: Caption
Type
Run XMLport
Action
4. Set the RunObject property of the action to XMLport G/L Account Export XML. 5. Compile, save and close the page. Run the page and run the action.
Create an XMLport to Export to Variable Format Text File 1. Design XMLport 90000, G/L Account Export Xml, from the Object Designer. 2. Compile and save the XMLport with the ID 90002, and the name G/L Account Export Variable. 3. Open the Properties window for the XMLport, and set the following properties: o Format: Variable Text o FieldSeparator: , o FieldDelimiter: 4. Close the Properties window, and compile, save and close the XMLport. 5. Design page 90001, Custom Page, from the Object Designer. 6. Open the Action Designer for the page and type the following on the empty line: Caption
Type
Run XMLport Variable Text
Action
7. Set the RunObject property of the action to XMLport G/L Account Export Variable. 8. Compile, save and close the page. Run the page and run the action.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-35
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Lab 10.1 - Create XMLports The following lab tests the basic knowledge on how to create XMLports. Scenario Simon is a developer working for CRONUS International Ltd. CRONUS International has decided to start selling Microsoft Dynamics NAV training courses as its business. Simon has already created a Course table to record course information and Card and List pages to interface the Course table. Now, Simon must create XMLports to export all the course details from the Course List page, in the following format: •
Comma-separated text file.
•
XML file.
Challenge Yourself! 1. Create an XMLport for export to variable format text file. 2. Create an XMLport for export to XML document. 3. Add actions in the Course List page to run the XMLports.
Need a Little Help? Create an XMLport for export to variable format text file. 1. Create a new XMLport. 2. Set the XMLport properties for variable format. 3. Define the XMLport nodes.
Create an XMLport for export to XML document. 1. Design and save the previous XMLport to a new XMLport. 2. Set the XMLport properties for XML document.
Add actions in the Course List page to run the XMLports. 1. Design page 90011, Course List, from the Object Designer. 2. Add ActionContainer and two actions. 3. Set the two actions property to run the respective XMLport.
10-36
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports Step by Step Create an XMLport for export to variable format text file. 1. In the Object Designer's XMLport List, click the New button. The XMLport Designer opens. 2. Open the Properties window for the XMLport and set the following properties: o Direction: Export (This specifies the XMLport to be used only for export.) o Format: Variable Text (This specifies the external file to be an XML document.) o FieldSeparator: , o FieldDelimiter: 3. Close the Properties window. 4. Click the first empty line in the XMLport Designer, and type the following: Node Name
Node Type
Source Type
Root
Element
Text
5. Go to the next line and type the following to add a source table. Ensure that it is indented under the Root element. Node Name
Node Type
Source Type
Data Source
Course
Element
Table
90010
6. Go to the next line and type the following on the next few lines to add several fields from the G/L Account table. Ensure that they are indented under the GL Account element. Node Name
Node Type
Source Type
Data Source
Code
Element
Field
Course::Code
Name
Element
Field
Course::Name
Description
Element
Field
Course::Description
Type
Element
Field
Course::Type
Duration
Element
Field
Course::Duration
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-37
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Node Name
Node Type
Source Type
Data Source
Price
Element
Field
Course::Price
Active
Element
Field
Course::Active
Difficulty
Element
Field
Course::Difficulty
PassingRate
Element
Field
Course::Passing Rate
7. Compile and save the XMLport by clicking File, Save As. The Save As dialog box opens. 8. Type 90010 in the ID field and Course Export Variable in the Name field, ensure that the Compiled check box is selected, and then click OK. This compiles and saves the XMLport. 9. Close the XMLport.
Create an XMLport for export to XML document. 1. Design XMLport 90010, Course Export Variable, from the Object Designer. 2. Compile and save the XMLport with the ID 90011, and the name Course Export XML. 3. Open the Properties window for the XMLport, and set the following properties: o Format: Xml 4. Close the Properties window, and compile, save and close the XMLport.
Add actions in the Course List page to run the XMLports. 1. Design page 90011, Course List, from the Object Designer. 2. Open the Action Designer for the page. 3. Type the following on the empty line:
10-38
Type
SubType
ActionContainer
ActionItems
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports 4. Type the following on the next lines and indent them under the ActionContainer. Caption
Type
Run XMLport Variable
Action
Run XMLport XML
Action
5. Open the Properties window for the RunXMLport Variable action and set the RubObject property to XMLport Course Export Variable. 6. Open the Properties window for the RunXMLport XML action and set the RubObject property to XMLport Course Export XML. 7. Close the Properties window. 8. Compile, save and close the page.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-39
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Summary Dataports and XMLports are objects that are used for importing data from and exporting data to external files. Use dataports to export data from Microsoft Dynamics NAV or import data into Microsoft Dynamics NAV instead of XMLports in the following scenarios: •
To support businesses that use earlier versions of Microsoft Dynamics NAV.
•
To modify Microsoft Dynamics NAV data in a tool that does not support XML.
The Microsoft Dynamics NAV RoleTailored client uses XMLports as ways to export and import data from and to Microsoft Dynamics NAV database. Therefore, in the RoleTailored client, XMLport functionalities are extended to handle text files, both in the fixed and variable format. Special precautions are needed when transferring files from Microsoft Dynamics NAV service to the client.
10-40
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 10: Dataports and XMLports
Test Your Knowledge 1. What is the difference between the description of a report and the description of a dataport? 2. What cannot be done with a data item in a dataport that can be done with a data item in a report? 3. In an import dataport, what must the dataport fields created in the Dataport Field Designer match? 4. In an import dataport, if the AutoSave property is set to No and the AutoUpdate property is set to Yes, what does the dataport do with the records from the external file? 5. When must the StartPos and Width properties of a dataport field be used? 6. True or False. Every dataport field must be bound to a real field in the data item. 7. What does the Calcfields property do on a data item? 8. When exporting, which dataport file type lines up the information in columns? 9. When exporting, which dataport file type creates the smallest possible file? 10. When importing, which dataport properties can be set so that the user cannot view the options tab? 11. What is the main difference between a Dataport and an XMLport? 12. The XML node name information is stored in what field? 13. Which field is used to specify whether the name in the NodeName field represents data of the type element or attribute? 14. Which field specifies the data structure that the node name corresponds to in the Microsoft Dynamics NAV database? 15. How are the XMLports run? 16. True or False. An XMLport cannot modify existing data in the database. 17. What is the purpose of the Direction property in the XMLport?
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
10-41
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Quick Interaction: Lessons Learned Take a moment and write down three key points you have learned from this chapter 1.
2.
3.
10-42
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Codeunits
CHAPTER 11: CODEUNITS Objectives The objectives are: •
Understand the concepts of codeunits.
•
Provide an overview of designing codeunits.
•
Provide an overview using codeunits.
•
Define Variables, Text Constants and Functions in a Codeunit.
•
Use the SMTP Mail codeunit.
Introduction Codeunits are like containers for code. One benefit of codeunits is that they can hold functions that are used repeatedly throughout large application projects. This enables the functions to be easily incorporated instead of having to rewrite the same lines of code. In addition, there are several standard codeunits that can be used to enrich application features, such as codeunit 400, SMTP Mail.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-1
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Codeunit Fundamentals C/AL code can be stored in a form, report, or other objects. In simple applications, the general approach is to place the code in the object that calls the functions. However, as applications grow, developers often find that the same functions are used repeatedly throughout the applications. Instead of declaring the same functions over and over again, it is useful to define them just once. This is where the C/SIDE codeunits become useful. Think of a codeunit as a container for C/AL code to be used in many application objects. In codeunits, developers can define functions, global variables, and temporary tables.
Functions A function is a sequence of C/AL statements that developers define to create new functionality. Each function that is created in a codeunit is displayed as a separate trigger, known as a function trigger, and it has its own set of statements. A codeunit can be thought of as a container for multiple functions.
Local Variables Within each function, developers can define local variables. A local variable's scope is limited to the function in which it is defined.
Global Variables A global variable's scope covers all the functions in the codeunit.
Temporary Tables A temporary table is actually a record variable which has the Temporary property set to Yes. It resembles an actual table, but it is not stored in the database. Temporary tables are mainly used as structured variables that hold data temporarily while developers work on it.
Triggers All codeunits include two default triggers known as Documentation and OnRun. In the Documentation trigger, developers can add optional information about the code such as the purpose of the codeunit, a version number, and more. In the OnRun trigger, developers can include code that they want the system to execute when the codeunit is run. NOTE: A codeunit can be run by using .Run. When a codeunit is run, the code which is written in the OnRun trigger is executed.
11-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Codeunits
Design Codeunits Codeunits are designed in the C/AL Editor which is accessed directly from the Object Designer.
Use the C/AL Editor The C/AL Editor is where code is viewed and modified. The following shortcut keys can be used when working in the C/AL Editor. Shortcut Key
Description
CTRL+ X
Cut the selected text to the clipboard.
CTRL+ C
Copy the selected text to the clipboard.
CTRL+ V
Paste the text on the clipboard into the codeunit in the cursor position.
CTRL + F
Open the Find window and search for text.
Use the C/AL Symbol Menu The C/AL Symbol Menu can be accessed from the C/AL Editor. Use the C/AL Symbol Menu to get an overview of: •
All variables defined in the codeunit.
•
All C/AL functions.
Open the C/AL Symbol Menu by clicking View, C/AL Symbol Menu or pressing F9.
FIGURE 11.1 THE C/AL SYMBOL MENU
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-3
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The information in the C/AL Symbol Menu is divided into columns. The column on the left shows all defined variable names and function categories. The second column shows the sub-categories, and the third column, on the right shows the functions in the selected category. Observe the syntax in the bottom of the window, and click the OK or the Apply button to make C/SIDE insert this string in the C/AL Editor. Clicking the OK button closes the Symbol Menu window automatically, but clicking the Apply button leaves it open. In some cases, for example, when a control on a form is a subform or when a field is a BLOB field, there are more than three columns. Use the right arrow button to scroll the Symbol Menu columns to the right, and the left arrow button to scroll them to the left.
Use Codeunits By using codeunits, developers eliminate the need to duplicate code and make the code easier to maintain. If the same code is used repeatedly in pages or reports, create a function in a codeunit and access it by using the following syntax: .
Accessing Codeunits By using the previous method, functions in any application objects (not just codeunits) can be accessed by writing the name of the variable that represents the application object followed by the name of the function. Codeunits can be accessed through codeunit variables either by explicitly declaring a variable of type Codeunit or by setting the RunObject property, such as in an action on a page, 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.
FIGURE 11.2 THE RELATION BETWEEN CODEUNIT VARIABLES AND THE CODEUNIT
11-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Codeunits Codeunits may contain internal variables defined as global variables. These variables are not accessible directly from code outside the codeunit, but they can be accessed through user-defined functions on the codeunit. Whenever 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.
Codeunits Assignment Codeunits can be treated as objects. One codeunit variable can be assigned to another codeunit variable. This creates a new reference to the same codeunit instance. In other words, the codeunit variables then use the same set of internal variables.
CLEAR on Codeunits When using the function CLEAR on a codeunit variable that has a reference to a codeunit instance with two or more references, it deletes the reference to the codeunit and not the actual codeunit instance. In other words, the codeunit stays intact and can still be used by other codeunit variables that may be assigned a reference to this codeunit. To delete a codeunit instance, clear all references to the codeunit with the CLEAR function. To clear the internal variables in a codeunit, use the CLEARALL function from a user-defined function within the codeunit. When a local codeunit variable goes out of scope, meaning that it is no longer used by the codeunit, it is automatically cleared.
Single Instance Codeunits In some cases, only one instance of a codeunit must exist. This means that all the codeunit variables of a particular codeunit use the same set of variables. When the SingleInstance property of the codeunit is set to Yes, all the codeunit variables for that codeunit use the same instance, and this allows developers to create global variables. NOTE: It is recommended to avoid using global variables for most code. However, in certain situations, it may be necessary to use them, for example, to ensure that only one instance of an external variable is used. A single instance codeunit is instantiated when it is used for the first time. Other codeunit instances (codeunits that do not have the SingleInstance property set to Yes) are deleted when the last codeunit variable that uses that codeunit instance goes out of scope. However, single instance codeunits remain instantiated until the current company is closed from the Microsoft Dynamics® NAV client.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-5
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Codeunits Limitations 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 functions which are created in the codeunit (user-defined functions.) All C/AL functions can be used in a codeunit, although, a function name cannot be the same name as a built-in function. Two or more user-defined functions cannot have the same name, unless they are part of different application objects.
Demonstration: Define Variables, Text Constants and Functions in a Codeunit The following steps show how to add global variables, text constants and functions in the C/AL Globals window. 1. In the Object Designer's Codeunit list, click the New button. The C/AL Editor opens. 2. Click View, C/AL Globals to open the C/AL Globals window.
Add Global Variables To add global variables: 1. Click the Variables tab in the C/AL Globals window. 2. Type the Name and DataType to add global variables. NOTE: If the data type selected corresponds to an application object, select a subtype, that is, the name of a specific object in the database. If the data type selected is a Text or Code, define a length for the variable. The default length is ten characters for Code, and 30 for Text. If the data type selected is OCX or Automation, also select a subtype.
Add Text Constants To add text constants: 1. Click the Text Constants tab in the C/AL Globals window. 2. Type the Name and ConstValue to add text constants.
Add Functions To add functions: 1. Click the Functions tab in the C/AL Globals window. 2. Type the Name to add functions. 3. Click the Locals button to define the parameters, return value, and local variables for each function. The C/AL Locals window opens.
11-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Codeunits 4. Click the Parameters tab to define parameters. o For each parameter, specify the calling method, a name, and a data type. The subtype and length are optional depending on the data type. o The calling method can be specified as Var which means that 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. o When the calling method is not specified as Var, only a copy of the variable is passed to the function. If the function changes that value, the change affects only the copy and not the variable itself. 5. Click the Return Value tab to define the return value for the function. 6. Type a name for the return value, and select a return type from the drop-down list. Select a length, but only if the return type is text or code. 7. Click the Variables tab to define local variables. 8. For each local variable, specify the name and data type. NOTE: If the data type selected corresponds to an application object, select a subtype, that is, the name of a specific object in the database. If the data type selected is a Text or Code, define a length for the variable. The default length is ten characters for Code, and 30 for Text. If the data type selected is OCX or Automation, also select a subtype. 9. Click the Text Constants tab to define text constants for the function. 10. Type the Name and ConstValue to add text constants.
SMTP One other feature of Microsoft Dynamics NAV 2009 is the ability to send e-mail by using Simple Mail Transfer Protocol (SMTP). Unlike sending e-mail programmatically by using Mail Application Programming Interface (MAPI), sending e-mail by using SMTP does not require an e-mail client and account to be configured on the server.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-7
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 SMTP Mail Setup Before using the SMTP functionality, the SMTP server and account information must be provided by using the SMTP Mail Setup window (form / page 409).
FIGURE 11.3 THE SMTP MAIL SETUP FORM
With the SMTP server information in place, the functions defined in the SMTP Mail codeunit (codeunit 400) can be used.
SMTP Mail Codeunit The SMTP Mail codeunit defines the following functions:
11-8
•
CreateMessage
•
Send
•
AddRecipients
•
AddCC
•
AddBCC
•
AppendBody
•
AddAttachment
•
CheckValidEmailAddresses
•
CheckValidEmailAddress
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Codeunits For simple e-mail, only the first two functions are necessary. The CreateMessage function is used to configure the message, and the Send function performs the actual sending. For example, assuming that codeunit 400 is declared as a global variable named SMTPCU, the following code sends a simple e-mail message: SMTPCU.CreateMessage( 'CRONUS International Ltd.', '[email protected]' (mailto:'[email protected]'), '[email protected]' (mailto:'[email protected]'), 'Issue Status', 'Your issue has been resolved', FALSE); SMTPCU.Send;
Several functions can be used after the CreateMessage function and before the Send function, to append additional information to the message. These functions are as follows: Function
Description
AddRecipients
This function is used if there are more receiver e-mail addresses than the one that fit into the 1024 characters allowed for the Recipients parameter in the CreateMessage function.
AddCC
This function is used to add carbon copy recipients.
AddBCC
This function is used to add blind carbon copy recipients.
AppendBody
This function is used if the message body is longer than the 1024 characters allowed in the Body parameter in the CreateMessage function.
AddAttachment
This function is used to provide the path of the file to be attached in the e-mail message.
The last two functions are used to check whether a text string is for a valid e-mail address or is for valid multiple e-mail addresses.
Summary Codeunits are application objects that are primarily used as containers for code to ease development and code management. They are created and modified in the C/AL Editor. Unlike other objects, a codeunit can be set as a single instance object so that every variable that refers to it refers to the same instance of the codeunit. There are several standard codeunits that can be used to enrich application features, such as codeunit 400, SMTP Mail.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-9
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Test Your Knowledge 1. What triggers are available in every codeunit? 2. What key can be pressed to open the Symbol Menu? 3. What must be done to call a function in a codeunit from another object? 4. Can two codeunit variables refer to the same instance of a codeunit? 5. Can two codeunit variables declared in the same object refer to different instances of a codeunit? 6. What change needs to be made to a codeunit variable to point to the same instance of a codeunit as another codeunit variable? 7. What function can be used to make a codeunit variable point to a new instance of a codeunit? 8. If a codeunit is designed as a single instance codeunit, can two codeunit variables refer to different instances of that codeunit? 9. What is the correct way to address a global variable of a codeunit from an object that has a variable, called CU, for that codeunit? 10. Can a function named Power be created in a codeunit?
11-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 11: Codeunits
Quick Interaction: Lessons Learned Take a moment and write down three key points you have learned from this chapter 1.
2.
3.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
11-11
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
11-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: MenuSuites
CHAPTER 12: MENUSUITES Objectives The objectives are: •
Understand the concepts of MenuSuites.
•
Provide an overview of creating and designing MenuSuites.
•
Understand the concepts of upgrading MenuSuites.
•
Create a new MenuSuite for the Classic client.
•
Create a new MenuSuite for the RoleTailored client.
Introduction MenuSuite objects contain the main menu content that is displayed in the Navigation Pane in the Classic client and in the Departments Page in the RoleTailored client. In the Classic client, application objects, such as forms and reports, are accessed from the Navigation Pane which displays menus that are contained in a MenuSuite object. In the RoleTailored client, application objects, such as pages and reports, are accessed from either the Departments page which displays menus that are also contained in a MenuSuite object or the Role Center page.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-1
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
MenuSuite Fundamentals A MenuSuite is a set of menus. Each menu contains content for a specific departmental area, such as Financial Management, Jobs, or Manufacturing. MenuSuites are designed in the Navigation Pane Designer in the Classic client. The Navigation Pane Designer can be accessed from the Object Designer and also directly on the Tools Menu in the Classic client. A MenuSuite object has the following characteristics: •
It consists of a set of menus.
•
A menu contains a collection of menu nodes which are displayed in the Navigation Pane in the Classic client or in the Departments page in the RoleTailored client.
•
The Navigation Pane is organized in a tree structure.
•
A menu node can be either a group or a menu item.
•
A menu node has a Globally Unique Identifier (GUID) and various properties.
•
A group contains a collection of menu nodes.
•
A menu item is the lowest level in the tree. When a menu item is clicked, its associated application object is run.
Navigation Pane The Navigation Pane contains the entire suite of functionality as licensed and available to the company. It is made of MenuSuite objects with layered item structure.
Departments Page The Departments page also contains the entire suite of functionality as licensed and available to the company. In this way, the Departments page in the RoleTailored client is similar to the Navigation Pane in the Classic client. The Departments page also comprises MenuSuite objects with layered item structure but is designed specifically for the RoleTailored client.
Create and Design MenuSuites In Microsoft Dynamics® NAV 2009, when creating a new MenuSuite object, select either the Classic client or the RoleTailored client as the target. NOTE: If both the Classic client and the RoleTailored client are supported, maintain two sets of MenuSuite objects.
12-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: MenuSuites Unlike any other application objects, the ID of the MenuSuite is defined by C/SIDE depending on the target client and the MenuSuite level. The ID of a MenuSuite for the RoleTailored client is the ID of the MenuSuite for the Classic client with the same level, plus 1000, as shown in the following table. Level
MenuSuite Object in the Classic Client
MenuSuite Object in the RoleTailored Client
MBS
10 MBS
1010 Dept - MBS
Add-on 1
51 Add-on 1
1051 Dept - Add-on 1
Company
90 Company
1090 Dept - Company
The following steps show how to open the Navigation Pane Designer. In Microsoft Dynamics NAV Classic client: 1. On the Tools menu, click Object Designer. 2. Click the MenuSuite button to open the MenuSuite List. 3. Click the New button to create a new MenuSuite, or select an existing MenuSuite and click the Design button to design an existing MenuSuite.
Create a New MenuSuite When creating a new MenuSuite, the first window that opens is the Design Level window. This is where developers specify the MenuSuite target client and the MenuSuite level.
FIGURE 12.1 THE DESIGN LEVEL WINDOW
Once developers select a target client and level, the Navigation Pane Designer opens in the Navigation Pane.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-3
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 MenuSuite Levels MenuSuite has different levels. The Navigation Pane and the Departments page display menus from a combination of different MenuSuites of different levels. There are several MenuSuite levels, they are as follows: •
MBS
•
Region
•
Country
•
Add-on
•
Partner
•
Company
For example, the MenuSuite changes when the application undergoes localization changes, which takes place at the Country level. Microsoft Dynamics partners customize the MenuSuite at the Partner level. Administrators of the company configure the MenuSuite at the Company level. The MenuSuite level that is currently designed is shown in the header of the Navigation Pane Designer.
FIGURE 12.2 THE NAVIGATION PANE DESIGNER SHOWING COMPANY LEVEL MENUSUITE
Changes made to a MenuSuite are stored as the differences between the MenuSuite of the previous level and the current MenuSuite. For example, when a company administrator configures a MenuSuite at the Company level, the modifications are stored as the differences between the Company level MenuSuite and the Partner level MenuSuite which is the previous level. If a MenuSuite is exported in text format and then opened, the information shown is only about the changes made in relation to the previous level.
12-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: MenuSuites With the exception of the Add-on level, there can only be one MenuSuite for each level. The Add-on level can have a maximum of 10 MenuSuites.
Create Menu Items Developers customize a MenuSuite in the Navigation Pane Designer. To access design options, right-click menus, groups, menu items, or click anywhere in the content pane area. To create a menu item, right-click a group, a menu item or click anywhere in the content pane area, and select Create Item. The Create Item window opens. This is where developers specify the menu item Object Type, Object ID, Caption and CaptionML (Multilanguage caption.) The Create Item window for MenuSuite that is created for the Classic client shows a slight difference than the MenuSuite that is created for the RoleTailored client. The following list shows the difference. Difference
For Classic Client
For RoleTailored Client
Object Type
Table, Form, Report, Dataport, Codeunit
Report, Codeunit, XMLport, Page
Department Category
NA
Lists, Tasks, Reports and Analysis, Documents, History, Administration
For example, to add a report as a menu item to a particular menu, select Report in the Object Type field, and use the Lookup button on the Object ID field to select the report from the Report List. The Caption field is automatically filled with the name of the report, rename it when necessary. The CaptionML field displays the code for the language that is used on the client computer and the name of the menu item by default. For a menu item that is used in different languages by different users, give the menu item a name in each language. Click the Assist-Edit button on the field to open the Multilanguage Editor window where menu item name for each language code can be specified. Once finished, click the OK button to create the menu item and close the Create Item window.
Set Properties To open the properties of a menu item, right-click the menu item and click Properties. There are five properties that can be set for a menu item in the Item Properties window: •
Object Type
•
Object ID
•
Caption
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-5
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 •
CaptionML
•
Department Category (only for the menu item for the RoleTailored client)
Designing an Existing MenuSuite To design an existing MenuSuite, select the existing MenuSuite from the Object Designer's MenuSuite List and click the Design button. The Navigation Pane Designer opens with the content of the selected MenuSuite. The MenuSuite level is shown in the header of the Navigation Pane Designer. Options in the Navigation Pane Designer include the following: Option
How to access
Import / Export MenuSuite
On the File menu, click Import or Export.
Translate
On the Tools menu, click Translate, Import or Translate, Export.
To close the Navigation Pane Designer, right-click the header of the Navigation Pane, then click Close Navigation Pane Designer. A MenuSuite cannot be run.
Upgrade MenuSuite Menus in a menu suite that are inherited from the previous MenuSuite object level have the symbol ">>" on the menu to the left of the menu name.
FIGURE 12.3 MENUS INHERITED FROM THE PREVIOUS MENUSUITE LEVEL
These menus are upgraded when developers upgrade the corresponding MenuSuite object. Any changes made to these menus are merged into the new MenuSuite. For example, a menu item added to a group in which the contents changed after an upgrade, is placed as the last menu item in the group.
12-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: MenuSuites Lost Items Group There are cases where a straightforward merge cannot be carried out. For example, if developers added a menu item to a group that is no longer a part of the menu after an upgrade, no merge can be made. Instead, the menu item is placed in a Lost Items group at the bottom of the menu tree.
FIGURE 12.4 LOST ITEMS GROUP
Lost Items Menu Another example is when developers added one or more menu items to a menu that is no longer present in the MenuSuite after an upgrade. In such a situation, the menu items are placed in a Lost Items menu.
FIGURE 12.5 LOST ITEMS MENU
After an upgrade, developers can take action on the menu items in a Lost Items group or menu - either by inserting them somewhere in the current menu, in the case of Lost Items, or in another menu, or by deleting them. A Lost Items group or menu is not visible in the Navigation Pane at run time.
New Menus New menus are not affected by an upgrade. New menu items to be added in upgraded menus must be added manually.
Demonstration: Create a MenuSuite For The Classic Client The following demonstration shows how to create a new MenuSuite for the Classic client by creating a menu, a group and a menu item.
Create a Menu The following steps show how to create a new menu. 1. In the Object Designer's MenuSuite List, click the New button. 2. Select Classic Client in the Design for field, select Company and then click OK. 3. Right-click anywhere in the menu and then click Create Menu.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-7
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 4. Type the following in the Create Menu window. o Caption: My Customer
FIGURE 12.6 THE CREATE MENU WINDOW
5. Click OK.
Create a Group The following steps show how to create a new group. 1. Right-click anywhere in the content area of the My Customer menu, and then click Create Group. 2. Rename the group to My Customer.
FIGURE 12.7 CREATE A GROUP
Create Menu Items The following steps show how to create a new menu item. 1. Open the My Customer group. 2. Right-click the Empty Group item, and then click Create Item.
12-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: MenuSuites 3. Type the following in the Create Item window. o Object Type: Form o Object ID: My Customer Card
FIGURE 12.8 THE CREATE ITEM WINDOW
4. Click OK. 5. Right-click the header of the Navigation Pane and then click Close Navigation Pane Designer. 6. Ensure the Compiled check box is selected, and then click Yes.
The New Menu in Navigation Pane
FIGURE 12.9 THE MY CUSTOMER MENU
Demonstration: Create A MenuSuite For The RoleTailored Client The following demonstration shows how to create a new MenuSuite for the RoleTailored client by creating a menu, a group and a menu item.
Create a Menu The following steps show how to create a new menu. 1. In the Object Designer's MenuSuite List, click the New button. 2. Select RoleTailored Client in the Design for field, select Dept Company and then click OK. 3. Right-click anywhere in the menu and then click Create Menu. 4. Type the following in the Create Menu window. o Caption: My Customer 5. Click OK.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-9
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Create a Group The following steps show how to create a new group. 1. Right-click anywhere in the content area of the My Customer menu, and then click Create Group. 2. Rename the group to My Customer.
Create Menu Items The following steps show how to create a new menu item. 1. Open the My Customer group. 2. Right-click the Empty Group item, and then click Create Item. 3. Type the following in the Create Item window. o Object Type: Page o Object ID: My Customer List o Department Category: Lists
FIGURE 12.10 THE CREATE ITEM WINDOW
4. Click OK. 5. Right-click the header of the Navigation Pane and then click Close Navigation Pane Designer. 6. Ensure the Compiled check box is selected, and then click Yes.
12-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: MenuSuites The New Menu in the Departments Page
FIGURE 12.11 THE MY CUSTOMER MENU
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-11
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Lab 12.1 - Create MenuSuites The following lab tests the basic knowledge on how to create MenuSuites for both the Classic and the RoleTailored client. Scenario Simon is a developer working for CRONUS International Ltd. CRONUS International has decided to start selling Microsoft Dynamics NAV training courses as its business. Simon has already created forms and pages to access the Course table for his users. Now, Simon must create a menu for both the Classic client and the RoleTailored client, to access the Course's forms and pages.
Challenge Yourself! 1. Create a new MenuSuite by creating a menu, a group and a menu item to access the Course Card from the Navigation Pane in the Classic client. 2. Create a new MenuSuite by creating a menu, a group and a menu item to access the Course Card from the Departments page in the RoleTailored client.
Need a Little Help? Create a MenuSuite for the Classic client. 1. Create a Menu. 2. Create a Group. 3. Create a Menu Item for the Course Card.
Create a MenuSuite for the RoleTailored client. 1. Create a Menu. 2. Create a Group. 3. Create a Menu Item for the Course List.
Step by Step Create a MenuSuite for the Classic client. 1. In the Object Designer's MenuSuite List, click the New button. 2. Select Classic Client in the Design for field, select Company and then click OK. 3. Right-click anywhere in the menu and then click Create Menu.
12-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: MenuSuites 4. Type the following in the Create Menu window. o Caption: Course 5. Click OK. 6. Right-click anywhere in the content area of the Course menu, and then click Create Group. 7. Rename the group to Course. 8. Open the Course group. 9. Right-click the Empty Group item, and then click Create Item. 10. Type the following in the Create Item window. o Object Type: Form o Object ID: Course Card 11. Click OK. 12. Right-click the header of the Navigation Pane and then click Close Navigation Pane Designer. 13. Ensure the Compiled check box is selected, and then click Yes.
Create a MenuSuite for the RoleTailored client. 1. In the Object Designer's MenuSuite List, click the New button. 2. Select RoleTailored Client in the Design for field, select Dept Company and then click OK. 3. Right-click anywhere in the menu and then click Create Menu. 4. Type the following in the Create Menu window. o Caption: Course 5. Click OK. 6. Right-click anywhere in the content area of the Course menu, and then click Create Group. 7. Rename the group to Course. 8. Open the Course group. 9. Right-click the Empty Group item, and then click Create Item. 10. Type the following in the Create Item window. o Object Type: Page o Object ID: Course List o Department Category: Lists 11. Click OK. 12. Right-click the header of the Navigation Pane and then click Close Navigation Pane Designer. 13. Ensure the Compiled check box is selected, and then click Yes.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-13
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Summary MenuSuites are the container of application objects. They display a menu in either the Navigation Pane or the Departments page depending on which client is used. Links in the form of menu items, must be created in the MenuSuites for new application objects, so that they can be accessed by the users. In addition, menus and groups categorize menu items so that they are organized and can be easily found, whether it is in the Navigation Pane or in the Departments page. Developing the MenuSuites completes the development of the application objects in C/SIDE.
12-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 12: MenuSuites
Test Your Knowledge 1. True or False. A MenuSuite cannot be accessed programmatically. 2. What is the name of the design area used to work with the MenuSuites? 3. With the exception of the Add-on level, how many instances of a MenuSuite can there be for each Design Level? 4. How many instances of the MenuSuite can there be for the Add-on level? 5. What are the two ways to open the Navigation Pane Designer? 6. True or False. A MenuSuite object can be run from the Object Designer. 7. When creating a new item in a MenuSuite and Report is selected as the Object Type, what is displayed when the Lookup button on the Object ID is clicked? 8. Name the six selections available in the Object Type field for a menu item that is created for the Classic client. 9. What are the levels on which a MenuSuite can be categorized?
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
12-15
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Quick Interaction: Lessons Learned Take a moment and write down three key points you have learned from this chapter 1.
2.
3.
12-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options
CHAPTER 13: INTEGRATION OPTIONS Objectives The objectives are: •
Describe the concepts of Microsoft Dynamics NAV Web Services.
•
Create a codeunit Web service, expose a page and a codeunit Web service and consume them from an external application.
•
Describe the concepts of Microsoft Dynamics NAV ODBC, its requirements, installation and limitations.
•
Use Microsoft Dynamics NAV ODBC.
•
Describe the concepts of C/FRONT, its requirements, installation and limitations.
•
Describe the concepts of OCX, its installation, registration and limitations.
•
Use OCX controls.
•
Describe the concepts of Automation, its requirements, installation and limitations.
•
Create a report with Automation.
Introduction Microsoft Dynamics® NAV 2009 offers some integration possibilities by using the following technologies: •
Web service
•
Microsoft Dynamics® NAV ODBC
•
C/FRONT
•
OCX
•
Automation
These integration options have their own pros and cons, and sometimes choosing the best technology, depends on a case by case basis. Microsoft Dynamics NAV 2009 offers Web services support as a new method of interacting programmatically with the system. It can be accessed over a network and enables execution on a remote system. It stands as a widely-used, industry standard, which means it is used by other systems and products across the industry.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
13-1
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Web Services Web services are a standardized way for independent software systems to communicate with one another over standard Internet protocols. Web services architecture is designed for dynamic program-to-program interaction. Many kinds of distributed systems can be implemented in Web services architecture. Examples of distributed systems include synchronous and asynchronous messaging systems, distributed computational clusters, mobilenetworked systems, grid systems, and peer-to-peer environments. The broad spectrum of requirements for program-to-program interactions means that the protocols that are used by Web services are more flexible than Web protocols. However, just as the World Wide Web, Web services also rely on a few specific protocols, such as SOAP . Microsoft Dynamics NAV 2009 supports Web services, which makes it easy to integrate Microsoft Dynamics NAV with other systems. This is possible with the introduction of Microsoft Dynamics NAV Server. Web services are designed to facilitate the highly dynamic data interchange that is required in business transactions. Web services, as standardized integration technologies, bring value to businesses by breaking down data silos that are created by proprietary integration options. These proprietary integration technologies make it difficult to obtain information in and out of the different systems. Web services are described by using machine-readable metadata, which provide a robust development and operational environment. Web service metadata serves several purposes. The metadata is used to describe the message interchange formats that a Web service supports, and the valid message exchange patterns of a service. Metadata is also used to describe the capabilities and requirements of a service. Web Services Description Language (WSDL), which is an XML-based language for defining Web services, is used to express the interchange formats and message exchange patterns of the Web services Most major software development environments, such as Microsoft® Visual Studio® 2008, can be used to build applications that use Web services. Moreover, because Web services are XML based, Web services can be built across platforms and programming languages.
Architecture The Web service integration with Microsoft Dynamics NAV is facilitated through Web service enabled codeunits and pages. External systems read and write data on pages and call codeunits as defined by the common Web service protocols, with correct authentication and authorization. The Web service capabilities in Microsoft Dynamics NAV help customers reap the benefits of a service-oriented architecture (SOA). 13-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options Microsoft Dynamics NAV Web services are useful to customers and partners who want to use business logic or use a standard interface to access data from outside Microsoft Dynamics NAV.
FIGURE 13.1 MICROSOFT DYNAMICS NAV WEB SERVICES ARCHITECTURE
There are several simple types of Web services that can be published by Microsoft Dynamics NAV. The types of Web services correspond to the degree of complexity required in the Web service interface. All Web services can run C/AL code and validation triggers. There are several types of Web service in Microsoft Dynamics NAV 2009: •
The simplest Web service type is developed by using the page object. By using the page object, Microsoft Dynamics NAV constructs a default Web service that has a fixed set of methods. Generally, it corresponds to general data access, such as get and set individual values or retrieve and update lists of values.
•
Another Web service type involves including codeunits and the functions from those codeunits in the Web service.
•
The last type of Web service includes the ability to pass complex data types by using an XMLport object as a parameter in a codeunit function.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
13-3
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 How Microsoft Dynamics NAV integrates Web services saves the complexity of manually setting up Web service frameworks, such as managing the WSDL descriptions. To publish any type of Microsoft Dynamics NAV Web service (page or codeunit), add it to the Web Service table.
Microsoft Dynamics NAV Web Services Support Pages and codeunits that are added to the Web Service table in Microsoft Dynamics NAV are immediately published and available for Web service requests over the network. Consumers of these Web services, which are systems integrating with Microsoft Dynamics NAV, only have to know the network name (or address) of the computer that is running Microsoft Dynamics NAV Server and the names given to the individual pages and codeunits. For example, with the following configurations: •
Computer name that runs Microsoft Dynamics NAV Service: NAV_Server1
•
Web service port: 7047
•
Microsoft Dynamics NAV Server instance: DynamicsNAV
•
Company Name: CRONUS International Ltd.
•
The published page Web service: MyCustomer
Then the MyCustomer Web service is available at the following URL: http://Nav_Server1:7047/DynamicsNAV/WS/CRONUS_International _Ltd/Page/MyCustomer (http://nav_server1:7047/DynamicsNAV/WS/CRONUS_Internationa l_Ltd/Page/MyCustomer)
Microsoft Dynamics NAV manages Web service requests exactly like it handles requests from end-users. User rights authorization and validation, input data validation, business logic invocation, and concurrency control are all managed in the same manner as requests from a Microsoft Dynamics NAV client. This guarantees that the integrity of the Microsoft Dynamics NAV data is not compromised by using Web services. It also means that code that validates data or invokes business logic for systems that use the Web services that are provided by Microsoft Dynamics NAV does not have to be replicated. When writing code for Web services, avoid using any end-user confirmation dialog boxes or message boxes. The code for Web services cannot interact with the client that called the code. It cannot respond to a dialog box or any other client interaction requests. Running code with client interaction causes an exception to be thrown. The exception can be caught and handled, but the Web service task will not be completed.
13-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options The GUIALLOWED function is a function which is used to check whether the C/AL code is allowed to show any information on the screen. When the code is run from Web services, GUIALLOWED always returns FALSE. This is the same with when the code is run in Microsoft Dynamics NAV Application Server.
Opportunities Integration with other systems and communicating with different entities outside Microsoft Dynamics NAV is always a challenge in any implementation scenarios. In most cases, customers have different systems that are running together and not only Microsoft Dynamics NAV. Not only that, they may have to exchange data with entities outside their organization, which may use a different system or even a different platform and operating systems.
Advantages Web services support in Microsoft Dynamics NAV offers great value and benefits over its predecessors, these are as follows: •
Standard integration method, which takes advantage of developer skill sets. This in turn increases development speed and reduces the cost of implementation.
•
Increase return on Microsoft Dynamics NAV investment with the integration of data and business logic. Codes have to be written one time and do not have to be redeveloped because the same codes are run whenever using Web services or using Microsoft Dynamics NAV Client.
•
Consistent integration point, which reduces management overhead, because of the same security, validation and business logic as using Web services and Microsoft Dynamics NAV Client.
•
It also benefits from all other advantages of Web services as an industry standard.
Suitable Candidates Web services are suited for communication across platforms and programming language. With Microsoft Dynamics NAV 2009, it is easy to integrate with other systems and benefit from the flexibility that Web services offer. The following are candidates for Web services: •
Solutions that have to execute business logic or read data from Microsoft Dynamics NAV.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
13-5
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 •
Solutions that write data to Microsoft Dynamics NAV and use the system to validate the data by using the existing business logic.
•
Solutions that extend Microsoft Dynamics NAV with additional information such as customer information, exchange rates, or product information and have the extension that can be accessed from other systems.
The following are examples of several scenarios that are suited to Web services implementation: •
When a new order is created in the system, a Web service communicates with the shipping companies directly to ensure transportation of the order items, checking prices and availability.
•
Integration with exchange rates, ensuring that the system is continuously updated with the latest exchange rates, which provides precise calculations of data.
•
Integration with a Web service that retrieves the latest address information when new customers are added to the system to ensure accuracy in data.
•
Integration with production planning, CRM, data warehouses, other ERP systems, specialized budgeting, planning or reporting systems, mobile solutions and many more.
Demonstration: Create, Expose and Consume Web Services The following demonstration shows how to: •
Create a simple codeunit.
•
Register the codeunit Web service and a page Web service and publish them.
•
Create console applications and consume these two Web services.
Create a Codeunit Web Service The following steps show how to create a simple codeunit, with a function to capitalize lowercase input string. In Microsoft Dynamics NAV Classic client: 1. 2. 3. 4. 5.
Click Tools, Object Designer. The Object Designer opens. Click the Codeunit button to open the Codeunit list. Click New. The C/AL Editor opens. Click View, C/AL Globals. The C/AL Global window opens. Click the Functions tab, and type the following: o Name: Capitalize
6. Click the Locals button. The C/AL Locals window opens.
13-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options 7. In the Parameters tab, type the following: o Name: InputString o DataType: Text o Length: 250 8. Click the Return Value tab, and type the following: o Name: OutputString o ReturnType: Text o Length: 250 9. Close the C/AL Locals window and then close the C/AL Globals window. 10. In the Capitalize function, type the following: OutputString := UPPERCASE(InputString);
11. Save the codeunit by clicking File, Save As. The Save As dialog box opens. 12. Type 90001 in the ID and MyCodeunit in the Name and then click OK.
FIGURE 13.2 THE CODEUNIT
13. Close the C/AL Editor.
Expose the Web Services After the codeunit is created and saved, register it in the Web Services form and select the Published check box. The following steps show how to register Web services: In the Object Designer: 1. Click the Form button to open the Form list.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
13-7
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 2. Select form 810, Web Services and then click Run. The Web Services form opens. 3. Type the following: Object Type
Object ID
Service Name
Codeunit
90001
DemoCU
Page
21
Customer
The first line registers the codeunit Web service that is created in the previous steps. The second line registers a page Web service, in this case the Customer page. 4. Select the Published check box on both lines to publish the Web services.
FIGURE 13.3 THE WEB SERVICES FORM
When the Web service is marked as published in the Web Services form, it is immediately available for requests over the network. 5. Close the Web Services form.
Check the WSDL Before continuing, it is recommended to check that the Web services that previously published are available. Also, ensure that the Microsoft Dynamics NAV Business Web Services is running. The following steps show how to browse to the WSDL document to ensure that the Web services are available. 1. Start Internet Explorer. 2. In the Address bar, type the following: http://localhost:7047/DynamicsNAV/WS/CRONUS_International_L td/Services
NOTE: This address is based on the name of the computer that is running the Microsoft Dynamics NAV Service and the company that is used. The company
13-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options name is case-sensitive. In this case, localhost is used instead of the computer name. 3. The page lists the Web services registered and published in the Expose the Web Services section.
FIGURE 13.4 THE WEB SERVICES LISTED IN INTERNET EXPLORER
4. Close Internet Explorer.
Create a Console Application to Consume the Codeunit Web Service The codeunit Web service is available. The following steps show how to create a simple console application in Visual Studio to consume the codeunit Web service. These steps start with creating a new project in Visual Studio and then adding a Web Reference for the Web services published from Microsoft Dynamics NAV. 1. Open Visual Studio. 2. Click File, New, and then click Project. The New Project window opens. 3. Expand the Visual C# node, and select Console Application. 4. Type the following: o Name: UseDemoCU 5. Click OK. The UseDemoCU project initiates with default files and references.
Add Codeunit Web Service as a Web Reference The next step is to add the published Web service as a Web reference into the project.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
13-9
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 In Visual Studio: 1. In the Solution Explorer, right-click the References node in the project, and then click Add Service Reference. The Add Service Reference window opens. 2. Click Advanced. The Service Reference Settings window opens. 3. Click Add Web Reference. The Add Web Reference window opens. 4. Type the following in the URL bar: http://localhost:7047/DynamicsNAV/WS/CRONUS_International_L td/Services
NOTE: This address is the same as the address that is used when checking the WSDL by using Internet Explorer. 5. Click GO. The DemoCU service is displayed together with other services that are available.
FIGURE 13.5 THE ADD WEB REFERENCE WINDOW
6. Click View Service for the DemoCU service and then click Add Reference. The DemoCU service is added as a Web Reference in the project.
13-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options Type the Code The following steps show how to create a code to consume the codeunit Web service. In Visual Studio: 1. On the Program.cs tab, type the following: using System; using System.Collections.Generic; using System.Text; namespace UseDemoCU { using localhost; // using the web reference class Program { static void Main(string[] args) { // Create a new instance of the service. DemoCU ws = new DemoCU(); // Use default credentials for authenticating // against Microsoft Dynamics NAV. ws.UseDefaultCredentials = true; ws.Url = "http://localhost:7047/DynamicsNAV/WS/CRONUS_International_ Ltd/Codeunit/DemoCU"; // Declare variables to work with. string InputString =""; string OutputString =""; Console.WriteLine("Input lowercase sentence, end by [ENTER]"); InputString = Console.ReadLine(); // Call the Microsoft Dynamics NAV codeunit Web service. try { OutputString = ws.Capitalize(InputString); } catch (Exception e) { Console.WriteLine(e.Message.ToString()); } // Write output to the screen. Console.WriteLine("Result: {0}", OutputString);
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
13-11
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 // Keep the console window up until you press ENTER. Console.ReadLine(); } } }
2. Click File, Save All to save all the changes in the project.
FIGURE 13.6 THE CODE IN VISUAL STUDIO
Consume the Codeunit Web Service The following steps show how to test the console application and consume the codeunit Web service: In Visual Studio: 1. Click Debug, Start Debugging, or press F5 to run the application in debug mode. The console window opens. 2. Type the following: o this is a lowercase sentence
13-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options 3. Press ENTER. Now, the console application looks like the following:
FIGURE 13.7 THE CONSOLE APPLICATION RESULT
The input string 'this is a lowercase sentence' is capitalized by using the codeunit Web service that is running on Microsoft Dynamics NAV Service. The result in the output string is 'THIS IS A LOWERCASE SENTENCE.' 4. Press ENTER to close the console window.
Create a Console Application to Consume the Page Web Service In the Expose the Web Services section, two Web services are exposed and published. The previous sections show how to create a console application to consume the first Web service, which is the codeunit Web service. The next section shows how to create a console application to consume the second Web service, which is the page Web service. In Visual Studio: 1. Click File, New, and then click Project. The New Project window opens. 2. Expand the Visual C# node, and select Console Application. 3. Type the following: o Name: UseDemoPage 4. Click OK. The UseDemoPage project initiates with default files and references.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
13-13
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Add Page Web Service as a Web Reference The next step is to add the published Web service as a Web reference into the project. In Visual Studio: 1. Repeat Steps 1 to 5 in the Add Codeunit Web Service as a Web Reference section. 2. Instead of using the DemoCU service, click View Service for the Customer service and then click Add Reference.
FIGURE 13.8 THE CUSTOMER WEB SERVICE DESCRIPTION
Type the Code The following steps show how to create a code to consume the codeunit Web service.
13-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options In Visual Studio: 1. On the Program.cs tab, type the following: using System; using System.Collections.Generic; using System.Text; namespace UseDemoPage { // import newly generated Web service proxy using localhost; class Program { static void Main(string[] args) { //create instance of service and setting credentials Customer_Service service = new Customer_Service(); service.UseDefaultCredentials = true; service.Url ="http://localhost:7047/DynamicsNAV/WS/CRONUS_International _Ltd/Page/Customer";
//create instance of customer Customer cust = new Customer(); cust.Name ="Customer New"; //insert customer service.Create(ref cust); PrintCustomer(cust); Msg("The program inserted a new customer, press [ENTER] to continue"); Console.ReadLine(); //create filter for searching for customers List filter = new List(); Customer_Filter nameFilter = new Customer_Filter(); nameFilter.Field = Customer_Fields.Name; nameFilter.Criteria ="C*"; filter.Add(nameFilter); Msg("List before modification"); PrintCustomerList(service, filter); Console.ReadLine();
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
13-15
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 //modify customer cust.Name = cust.Name + " and Modified"; service.Update(ref cust); PrintCustomer(cust); Msg("The program modified the new customer name, press [ENTER] to continue"); Console.ReadLine(); Msg("List after modification"); PrintCustomerList(service, filter); Console.ReadLine(); //delete customer service.Delete(cust.Key); Msg("List after deletion"); PrintCustomerList(service, filter); Console.ReadLine(); Msg("Press [ENTER] to exit program!"); Console.ReadLine(); } static void PrintCustomerList(Customer_Service service, List filter) { Msg("Printing Customer List"); //conduct the actual search Customer[] list = service.ReadMultiple(filter.ToArray(), null, 100); foreach (Customer c in list) { PrintCustomer(c); } Msg("End of List, press [ENTER] to continue"); } static void PrintCustomer(Customer c) { Console.WriteLine("No: {0} Name: {1}", c.No, c.Name); } static void Msg(string msg) { Console.WriteLine(msg); } } }
13-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options 2. Click File, Save All to save all the changes in the project.
FIGURE 13.9 THE CODE IN VISUAL STUDIO
Consume the Page Web Service The following steps show how to test the console application and consume the page Web service: In Visual Studio: 1. Click Debug, Start Debugging, or press F5 to run the application in debug mode. The console window opens. The application inserts a new customer named Customer New with the default Customer No. 2. Press ENTER to continue. The application prints a list of customers, which name starts with the letter C. 3. Press ENTER to continue. The application modifies the new customer name to Customer New and Modified. 4. Press ENTER to continue.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
13-17
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The application prints a customer list, which name starts with the letter C, after modification. 5. Press ENTER to continue. The application deletes the new customer and prints a customer list, which name starts with the letter C, after deletion.
FIGURE 13.10 THE CONSOLE APPLICATION RESULT
6. Press ENTER to close the console window.
ODBC Microsoft Dynamics NAV ODBC is Microsoft Dynamics NAV's implementation of Open Database Connectivity (ODBC). Microsoft Dynamics NAV ODBC lets developers transfer data between Microsoft Dynamics NAV databases and any program that supports ODBC. Applications that support ODBC can communicate with Microsoft Dynamics NAV. This means, applications such as a spreadsheet or word processor can retrieve data by communicating with Microsoft Dynamics NAV through the Microsoft Dynamics NAV ODBC driver. The Microsoft Dynamics NAV ODBC driver operates in the Microsoft Windows® platforms. In these environments, it can function either as a standalone or as a client in a client/server configuration. Microsoft Dynamics NAV client is not needed to use the Microsoft Dynamics NAV ODBC driver. The main purpose for using ODBC with Microsoft Dynamics NAV is integration with other applications. By using ODBC, users can use applications such as a word processor to create mail merge documents or a spreadsheet application to pull account information and create graphs based on that information.
13-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options Architecture The Microsoft Dynamics NAV ODBC has four components: •
Application - Performs processing and calls ODBC functions to submit Microsoft SQL statements and retrieve results.
•
Driver Manager - Loads and unloads drivers on behalf of an application. Processes ODBC function calls or passes them to a driver.
•
Driver - Processes ODBC function calls, submits SQL requests to a specific data source, and returns results to the application. If necessary, the driver modifies an application's request so that the request conforms to syntax that is supported by the associated DBMS.
•
Data source - Consists of the data that the user wants to access and its associated operating system, DBMS, and network platform (if any) that is used to access the DBMS.
The following illustration shows the relationship between these four components.
FIGURE 13.11 MICROSOFT DYNAMICS NAV ODBC ARCHITECTURE
There can be multiple drivers and data sources which allow the application to simultaneously access data from more than one data source. The ODBC API is used in two places: •
Between the application and the Driver Manager.
•
Between the Driver Manager and each driver.
The interface between the Driver Manager and the drivers is sometimes referred to as the service provider interface, or SPI. For ODBC, the applicationprogramming interface (API) and the service provider interface (SPI) are the same; that is, the Driver Manager and each driver have the same interface to the same functions.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
13-19
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 Requirements There are several requirements to use the Microsoft Dynamics NAV ODBC driver, they are as follows: •
License for Microsoft Dynamics NAV ODBC granule.
•
Users are able to connect to the Microsoft Dynamics NAV database either through a server connection (by using Microsoft Dynamics NAV database server) or through a local connection (the database is located in the client computer).
•
Users have permission to access the database. For example, if a user does not have read permission for specific table related data, they cannot read that table from either Microsoft Dynamics NAV client or from Microsoft Dynamics NAV ODBC. Also, ODBC users must have permission for System 9130, C/ODBC.
•
There are enough sessions for the users. Just as accessing the Microsoft Dynamics NAV database by using a client, accessing the database by using ODBC also requires a session.
Furthermore, if a local connection is used, only one connection to the database file can exist at any time. Also, the local license file (fin.flf) that is located in the client folder must contain the Microsoft Dynamics NAV ODBC granule.
13-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options Installation By default, the Microsoft Dynamics NAV ODBC driver is not installed when installing Microsoft Dynamics NAV 2009. The following figure shows the option to install the Microsoft Dynamics NAV ODBC.
FIGURE 13.12 INSTALL MICROSOFT DYNAMICS NAV ODBC
Limitations There are several limitations when working with Microsoft Dynamics NAV ODBC, they are as follows: •
Data that is entered through ODBC is not validated. It is important to ensure the data entered meets the criteria of the data type for that field.
•
Entries made by ODBC do not fire triggers, therefore any fields that might get automatically filled in when entering data by using the Microsoft Dynamics NAV client, has to be manually populated.
•
The ODBC driver does not support outer joins.
•
The ODBC driver does not work with SQL server. Use the Microsoft SQL ODBC driver instead. Flow fields are not calculated, because of the way they are stored on the SQL server.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
13-21
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 •
Microsoft® Access® supports zero-length strings. Microsoft Dynamics NAV ODBC does not convert the zero-length string to a value that can be used by the Microsoft Dynamics NAV database. Therefore, the zero-length string is interpreted as a NULL value and the error message is returned.
•
The Microsoft Dynamics NAV ODBC driver does not support parameter fields which Microsoft Access uses when external tables are linked.
Demonstration: Use Microsoft Dynamics NAV ODBC The following demonstration shows how to set a data source and use it with Microsoft® Excel® and Microsoft Access to read data from and write data to Microsoft Dynamics NAV.
Set a Data Source The following steps show how to create a DSN. 1. Go to Control Panel and click the Administrative Tools. 2. Click Data Sources (ODBC).The ODBC Data Source Administrator window opens. 3. Click the System DSN tab and then click Add. NOTE: User DSN is available for the current user and System DSN is available for all users on the current machine
13-22
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options 4. Select Microsoft Dynamics NAV Driver and then click Finish. The Dynamics NAV ODBC Setup window opens. 5. Enter the necessary information and then click OK to complete creating the DSN.
FIGURE 13.13 THE DYNAMICS NAV ODBC SETUP WINDOW
Read Data from Microsoft Dynamics NAV The following steps show how to use the DSN created previously to return data from Microsoft Dynamics NAV to Microsoft Excel. 1. Start Microsoft Excel with a new workbook. 2. Open the Data Connection Wizard, select ODBC DSN and then click Next. 3. Select Dynamics NAV ODBC Sample and then click Next. 4. Select Cust_ Ledger Entry table and then click Next. 5. Click Finish. The Import Data window opens. Here developers can click Properties to open the Connection Properties window where they can customize the connection such as edit the queries and so on.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
13-23
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 6. Click OK. The records from the Cust. Ledger Entry table are displayed in the Microsoft Excel worksheet.
FIGURE 13.14 THE RESULT IN MICROSOFT EXCEL
Write Data to Microsoft Dynamics NAV The following steps show how to use the DSN created previously to use Microsoft Access to write data to Microsoft Dynamics NAV. 1. Start Microsoft Access with a new blank database. 2. Create a linked table by using the ODBC Database. The Select Data Source window opens. 3. Select Dynamics NAV ODBC Sample as the DSN. The Link Tables window opens. 4. Select Location and then click OK. 5. Double-click the Location table in Microsoft Access. It displays the record from the Location table from Microsoft Dynamics NAV. 6. Type the following.
13-24
Code
Name
Address
BLACK
Black Warehouse
2 Late St
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options 7. Close the table and close Microsoft Access. 8. Verify the record is added from Microsoft Dynamics NAV from the Location Card form.
FIGURE 13.15 THE LOCATION CARD FORM
C/FRONT C/FRONT is an application programming interface that can be used to access Microsoft Dynamics NAV databases. C/FRONT facilitates high-level interaction with the Microsoft Dynamics NAV database and allows developers to manipulate any Microsoft Dynamics NAV database. The central component of C/FRONT is a library of C functions. These functions give developers access to every aspect of data storage and maintenance, and allow developers to integrate both standard and custom applications with the Microsoft Dynamics NAV database. Because C/FRONT is a front end to Microsoft Dynamics NAV, developers might want to use C/FRONT to add, delete or view data from their own applications. C/FRONT is much faster compared to the Microsoft Dynamics NAV ODBC driver and is as close to the native connection as with Microsoft Dynamics NAV. However, to use C/FRONT, developers must use some other programming language such as C++, C, or Visual Basic. C/FRONT provides two methods of accessing Microsoft Dynamics NAV which is either through a C style DLL or through the use of the OCX interface.
Requirements There are several requirements to use C/FRONT, they are as follows: •
License for C/FRONT granule.
•
C/FRONT is very particular and looks in different places at different times for the license file. Ensure that the license is loaded everywhere it needs to be, that is the client, server, and so on.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
13-25
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 •
Users have permission to access the database. For example, if a user does not have read permission for specific table related data, they cannot read that table from either the Microsoft Dynamics NAV client or by using C/FRONT. Also, users must have permission for System 9110, C/FRONT.
•
There are enough sessions for the users. Just as accessing the Microsoft Dynamics NAV database by using a client, accessing the database by using C/FRONT also requires a session.
Installation By default, C/FRONT is not installed when installing Microsoft Dynamics NAV 2009. The following figure shows the option to install C/FRONT.
FIGURE 13.16 INSTALL C/FRONT
NOTE: When C/FRONT is installed, two .dll files - cfront.dll and cfrontsql.dll are copied. If Microsoft SQL Server is used, select cfrontsql.dll, otherwise select cfront.dll. Generally, the C/FRONT library (cfront.dll/cfrontsql.dll) reads the registry to locate the Microsoft Dynamics NAV client. However, if multiple Microsoft Dynamics NAV are installed or if Microsoft Dynamics NAV is not present on the system, the function SetNavisionPath in the cfront.dll/cfrontsql.dll library must be called to specify the path to the directory where Microsoft Dynamics
13-26
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options NAV is installed or to a directory containing the following files from Microsoft Dynamics NAV. •
dbm.dll
•
nc_netb.dll
•
nc_tcp.dll
•
slave.exe
•
fin.etx
•
fin.stx
•
fin.flf
List of C/FRONT Files C/FRONT consists of the following files. File name
Description
cfront.dll
C/FRONT C-API library for Microsoft Dynamics NAV Database Server
cfrontsql.dll
C/FRONT C-API library for Microsoft SQL Server
cfront.ocx
C/FRONT OCX
cf.h
C/FRONT header file
libload.c
Source file containing functions to load and unload cfront.dll
dberror.txt
Database error/return codes
A sample application (written in C) and a .NET application are installed together with C/FRONT installation.
Limitations There are several limitations when working with C/FRONT, they are as follows: •
Entries made by C/FRONT do not fire triggers to execute any code validation.
•
Only active keys are available to C/FRONT. Keys cannot be activated within C/FRONT.
•
Microsoft Windows does not go in to standby or hibernation if there is an open server connection from C/FRONT.
OCX Custom controls are also known as OLE Controls and Microsoft ActiveX® Controls. Because they often have the extension .ocx, they are also known as OCXs.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
13-27
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 NOTE: Custom controls can also have the extension .dll. OCX lets developers take advantage of code that is made commercially available or allows them to write code once and have the ability to call that code from any program that supports custom controls. The main reason to use custom controls is to save development time and reduce costs.
Requirements There are several requirements to use OCX, they are as follows: •
License for OCX granule. This is needed only for development. The customers, who run the objects, do not need the OCX granule. They only need the compiled object loaded on their computers along with the custom control that needs to be registered.
•
To use a custom control, it must be loaded on the computer that is being used for development and all other computers that use the application that uses the custom control. Therefore, an important part of using an OCX that is developed by another company is to ensure that the developer working on this has the license to redistribute the OCX. The OCX must be installed on each machine that needs to use the code. After the OCX is copied to a machine, register the control from the Microsoft Dynamics NAV Classic client.
•
Users must have permission for System 9140, C/OCX to be able to run an object that works with an OCX.
Installation The first requirement for using a custom control is that it is physically installed on the target machine. But a control also has to be registered with the operating system to be used. If the control is already physically installed by copying it to the hard disk, but is not yet registered, use the following steps to register the control from the Microsoft Dynamics NAV Classic client. 1. Copy the control from the distribution media to the hard disk. 2. On the Microsoft Dynamics NAV Classic client, click Tools, Custom Controls. The Custom Controls window opens. 3. Click Control, Browse. The Register Custom Control window opens. 4. Locate the OCX, select it, and click Open. This registers the control with the system. A confirmation message appears after the registration is complete.
13-28
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options 5. Click OK to return to the Custom Controls window. Verify that the control is added by closing this window and click Tools, Custom Controls again.
FIGURE 13.17 THE CUSTOM CONTROLS WINDOW
Limitations There are several limitations when working with OCX, they are as follows: •
When an object is modified and that object depends on an OCX that is not registered on the development computer, the object cannot be compiled.
•
Incoming data must conform to C/AL data type. For example, strings are limited to 1024 characters in Microsoft Dynamics NAV. Therefore, custom controls being used must return the appropriate string value.
•
Only non-visual controls are supported. This means graphical elements cannot be added to a C/SIDE object (for example, a third party control cannot be added to a form). However, developers can use controls that display information and interact with the user in a window of its own.
•
C/SIDE does not allow the retrieval of information about exceptions from a control or automation server through the Invoke method of the IDispatch interface and the EXCEPINFO structure. There are ways to work around this limitation.
•
C/SIDE does not support call back for OCX. Therefore, developers cannot respond to an event from OCX.
Demonstration: Use OCX Controls To demonstrate the ease of registering and using a custom control in Microsoft Dynamics NAV, the C/FRONT.OCX is used.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
13-29
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 This demonstration uses this control to create a form that connects to a server, opens a database, and then opens a company and returns the number of records in a table. This page has access to the functions and properties supported by the C/FRONT OCX.
Define Variables for the New Form The following steps show how to create a new page and define the necessary variables. 1. Create a new blank form. 2. Click View, C/AL Globals. The C/AL Globals window opens. 3. Define the following variables in the Variables tab. Name
DataType
Subtype
Length
cfront
OCX
CFRONT Control
TableNo
Integer
MyCompany
Text
50
MyDatabase
Text
50
MyServerName
Text
50
Driver
Option
4. Open the Properties window for the Driver variable and set the OptionString property to NDBCS,NDBCN.
FIGURE 13.18 THE C/AL GLOBALS WINDOW
5. Close the Properties window and compile and save the form with the ID 90005 and the Name Test OCX Form.
13-30
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options Design the Form The following steps show how to add controls to the form. 1. Open the Toolbox and add five text boxes with attached labels to the form. 2. Set the Caption and SourceExpr property of the text boxes as follows: Text Box
Caption
SourceExpr
1
Server
MyServerName
2
Database
MyDatabase
3
Company
MyCompany
4
Server Type
Driver
5
Table No.
TableNo
3. Add a command button to the form. 4. Set the Caption property of the command button to Connect.
FIGURE 13.19 THE FORM DESIGNER
Add Code to the Form The following steps show how to add code to the form. 1. Select the command button, and then click View, C/AL Code. The C/AL Editor opens.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
13-31
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 2. Type the following code in the OnPush trigger of the button. CLEAR(cfront); cfront.ConnectServerAndOpenDatabase(FORMAT(Driver),MyServer Name,'tcp',MyDatabase,0,FALSE,TRUE,'',''); cfront.OpenCompany(MyCompany); IF cfront.OpenTable(TableNo,TableNo) THEN MESSAGE('The %2 table contains %1 records',cfront.RecCount(TableNo),cfront.TableName(TableNo) ); cfront.CloseTable(TableNo); MESSAGE('Table closed'); cfront.CloseCompany(); MESSAGE('Company Closed'); cfront.DisconnectServer(); MESSAGE('Disconnect')
3. Close the C/AL Editor, and then compile, save and close the form.
Run the Form Run the form in the Classic client, enter valid information and then click the Connect button.
FIGURE 13.20 THE TEST OCX FORM
Automation Server Automation provides a seamless interface to applications outside Microsoft Dynamics NAV 2009 without user intervention. For example, a letter can be created in Microsoft® Word whenever certain conditions take place, such as when a new customer is added. The main purpose of using Automation is to provide a seamless interface to outside applications without user intervention. A second reason for using automation is to save development time which also reduces the cost of development.
13-32
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options Requirements There are several requirements to use Automation, they are as follows: •
The program to be used as Automation must be an Automation server. Examples of automation servers include Microsoft Word, Microsoft Excel, and Microsoft® Outlook®.
•
The Automation server must be loaded on the computer that is being used for development and all other computers that use the application that use the Automation.
Installation The following steps outline the procedures for using an Automation server from C/SIDE. 1. Declare the top-level interface (class) of the Automation server as a variable of type Automation. 2. Declare all the other interfaces (classes) as variables of type Automation. 3. Use the C/AL function CREATE on the variable declared in step 1. Do not use CREATE on any other variables. 4. Use the methods and properties of the Automation server in the C/AL code. Write the code in this step. The syntax and the semantics of these methods and properties are described in the documentation for each Automation server. Using these methods and properties in C/AL does not involve any new or modified syntax. 5. Use the C/AL function CLEAR to destroy the top-level object. Otherwise, it is destroyed automatically when the variable goes out of scope.
Considerations There are two major concerns when deciding where to write code that uses Automation. •
The first is the fact that an object that uses Automation can be compiled only if the Automation server is installed on the machine where the compilation takes place. This means that if an object is to be recompiled and modified on a machine where the Automation server is not installed, developers have to modify the code drastically to compile it again. Therefore, it is recommended to isolate code that uses Automation in separate codeunits.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
13-33
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 •
The second concern is performance. There is some overhead involved in using an Automation server by using the CREATE function call. If the Automation server is to be used repetitively, it gives better performance if the code is arranged so that the Automation server is created only one time, as opposed to using a series of CREATE/CLEAR function calls.
Because these two concerns sometimes clash, there may be instances when developers must make some trade-offs based on the actual context in which their code is used.
Creating the Variables To control a Automation server, developers define a variable (global or local) of type Automation and reference the Automation Server as the subtype of this variable. The only Automation Servers that appear in the list are those that are loaded on the development machine. Once the Automation Server is selected, a list of all the classes available for that Automation server is displayed. Typically, the application is the first class selected. Afterwards, declare variables for all the other interfaces (classes) that control or interact with the code. Determining what classes must be defined depends on the understanding of the Automation server. If these are Microsoft programs, to determine what each of the classes do, view the Microsoft Visual Basic Help. Generally, which classes to use is determined by considering the application. For example, to call Microsoft Word, consider the application and then the document. Likewise, if to call Microsoft Excel, consider the application, the workbook, the worksheet, and the Range of cells.
Responding to Events C/SIDE can receive events from the Automation servers that it controls. When declaring a global variable of the type Automation, set the WithEvents property for the variable to specify whether to receive events. Setting the WithEvents property to Yes automatically generates C/AL triggers for the events that the component provides. A trigger name consists of the name of the Automation variable followed by "::<Event name>." For example, if an Automation variable named MyEventVar, and the component provides the event MessageReceived(...), the name of the trigger is MyEventVar::MessageReceived(...). NOTE: If a global variable of type Automation is deleted, the event triggers and their code are also deleted. Furthermore, if the DataType or SubType for a global variable is modified, then all the event triggers and their code are deleted.
13-34
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options Limitations There are several limitations when working with Automation, they are as follows: •
When an object is modified and that object depends on an Automation that is not registered on the development computer, the object cannot be compiled.
•
C/SIDE does not allow the retrieval of information about exceptions from a control or automation server through the Invoke method of the IDispatch interface and the EXCEPINFO structure. There are ways to work around this limitation.
•
Incoming data must conform to C/AL data type. For example, strings are limited to 1024 characters in Microsoft Dynamics NAV.
In addition, when C/SIDE is enabled to receive events from the Automation server, that is, the WithEvents property is set to Yes, there are limitations to the triggers that are automatically generated which are provided by the Automation.
Demonstration: Create a Report with Automation The following demonstration shows how to create a report with Automation capabilities.
Define Variables for the New Report The following steps show how to create a new report and define the necessary variables. 1. 2. 3. 4.
Create a new blank report. Add Customer for the data item. Click View, C/AL Globals. The C/AL Globals window opens. Define the following variables in the Variables tab.
Name
DataType
Subtype
CustAmount
Record
Customer Amount
CustFilter
Text
250
CustDateFilter
Text
30
j
Text
30
NoOfRecordsToPrint
Integer
i
Integer
MaxAmount
Decimal
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Length
13-35
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 5. Open the Properties window for the CustAmount variable, set the Temporary property to Yes and then close the Properties window. 6. Define several other variables. Name
DataType
Automation Server
Automation Object
Excel
Automation
Microsoft Excel 12.0 Object Library
Application
Book
Automation
Microsoft Excel 12.0 Object Library
Workbook
Range
Automation
Microsoft Excel 12.0 Object Library
Range
Sheet
Automation
Microsoft Excel 12.0 Object Library
Worksheet
Chart
Automation
Microsoft Excel 12.0 Object Library
Chart
NOTE: The Microsoft Excel version may vary.
FIGURE 13.21 THE C/AL GLOBALS WINDOW
7. Compile and save the report with the ID 90002 and the Name Sample Automation.
13-36
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options Change the Report Properties and Add Code to the Report The following steps show how to change the report properties and add code to the report. 1. Open the Properties window for the report, and set the ProcessingOnly property to Yes, and then close the Properties window. 2. Click an empty line in the Report Designer and then click View, C/AL Code. The C/AL Editor opens. 3. Add the following code in the OnPreReport trigger. CustFilter := Customer.GETFILTERS; CustDateFilter := Customer.GETFILTER("Date Filter");
4. Close the C/AL Editor. 5. Click the Customer data item, and then click View, C/AL Code. The C/AL Editor opens. 6. Add the following code in the OnPreDataItem trigger. i := 0; NoOfRecordsToPrint := 10; CustAmount.DELETEALL; CurrReport.CREATETOTALS("Sales (LCY)","Profit (LCY)"); CREATE(Excel); Excel.Visible(TRUE); Book:=Excel.Workbooks.Add(-4167); Sheet:=Excel.ActiveSheet; Sheet.Name := 'TOP 10';
The first four lines of the code initialize values to variables, delete records in the Customer Amount table and maintain totals for two fields when iterating the Customer data item. The fifth line creates an instance of Microsoft Excel and the sixth line makes the Microsoft Excel visible. NOTE: Microsoft Excel generates a General Protection Fault error when closing an Excel worksheet that is created when Microsoft Excel is invisible. To solve the problem, make Microsoft Excel visible immediately after a new worksheet is created. Alternatively, make Microsoft Excel visible just before creating a new Excel worksheet, and then make it invisible immediately after the worksheet is created.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
13-37
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The seventh to the tenth lines add a workbook to the application, use the ActiveSheet property of the application to ensure that what is done next affects the active sheet of the new workbook and then give a name to the sheet. 7. Add the following code in the OnAfterGetRecord trigger. CALCFIELDS("Sales (LCY)","Profit (LCY)"); IF ("Sales (LCY)" = 0) AND ("Profit (LCY)" = 0) THEN CurrReport.SKIP; CustAmount.INIT; CustAmount."Customer No." :="No."; CustAmount."Amount (LCY)" := -"Sales (LCY)"; CustAmount."Amount 2 (LCY)" := -"Profit (LCY)"; CustAmount.INSERT; IF (NoOfRecordsToPrint = 0) OR (i < NoOfRecordsToPrint) THEN i := i + 1 ELSE BEGIN CustAmount.FINDLAST; CustAmount.DELETE; END;
The first line of the code calls the CALCFIELDS function to calculate the values for Sales (LCY) and Profit (LCY). The second line of the code checks whether both the fields equal zero. If they do, the record is skipped. Otherwise, it proceeds to the next lines of code. The third to seventh lines of code initialize the CustAmount record, assign the Customer No. and the amounts field, and insert the record. The negative value is used so that the graph displays upright. If the NoOfRecordsToPrint equals zero or the value i is less than the NoOfRecordsToPrint, increment i. Otherwise, find the last record and delete it. The reason for doing this is that as a record is inserted, the records are placed in order from highest to lowest (based on the key in the Customer Amount table). Therefore, the CustAmount table will have only the top 10 records for the amount.
13-38
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options 8. Add the following code in the OnPostDataItem trigger. Sheet.Range('A2').Value := 'No.'; Sheet.Range('B2').Value := 'Name'; Sheet.Range('C2').Value := 'Sales (LCY)'; Sheet.Range('D2').Value := 'Profit (LCY)'; IF CustAmount.FINDSET THEN BEGIN j:='3'; REPEAT Customer.GET(CustAmount."Customer No."); Sheet.Range('A'+j).Value := CustAmount."Customer No."; Sheet.Range('B'+j).Value := Customer.Name; Sheet.Range('C'+j).Value := -CustAmount."Amount (LCY)"; Sheet.Range('D'+j).Value := -CustAmount."Amount 2 (LCY)"; j:=INCSTR(j); UNTIL CustAmount.NEXT = 0; END; Range:=Sheet.Range('B3:D12'); Chart:=Book.Charts.Add; Chart.Name := 'Top 10 Customers - Graph'; Chart.ChartWizard(Range,-4100,2,2,1,0,0,'Top 10 Customers','Customer','Sales (LCY)');
These lines of code write data from the CustAmount table to the Microsoft Excel instance. The last five lines of code add a chart to the Microsoft Excel instance by first setting a range based on the rows and column in the Excel sheet and then using the ChartWizard to plot the chart. 9. Compile, save and close the report.
Run the Report Run the report in the Classic client and click OK at the Request Form.
FIGURE 13.22 THE RESULT IN THE MICROSOFT EXCEL WORKSHEET
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
13-39
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 The following chart is displayed in Microsoft Excel.
FIGURE 13.23 THE CHART IN THE MICROSOFT EXCEL WORKSHEET
Summary Microsoft Dynamics NAV 2009 offers a set of technologies to integrate with external applications, they include the following: •
Web service
•
Microsoft Dynamics NAV ODBC
•
C/FRONT
•
OCX
•
Automation
Each of the technology has its own advantage and disadvantage over one another and the choice of which technology to use can depend on many factors. Understanding integration options available to Microsoft Dynamics NAV 2009, completes the introduction to C/SIDE development.
13-40
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Chapter 13: Integration Options
Test Your Knowledge 1. What must be done to use Microsoft Dynamics NAV ODBC? (Select the correct answers.) o o o o
Install Microsoft's ODBC driver. Purchase the Microsoft Dynamics NAV ODBC granule. Set up permissions for the users. Set up a DSN.
2. True or False. Any Microsoft Dynamics NAV ODBC version can be used to open up any Microsoft Dynamics NAV database. 3. True or False. Microsoft Dynamics NAV uses Microsoft's ADO for all connections. 4. True or False. Microsoft Dynamics NAV ODBC driver supports outer joins. 5. True or False. Entering data through ODBC is validated just as in the Microsoft Dynamics NAV client. 6. What is C/FRONT? 7. Does C/FRONT use a session? 8. Can keys be activated from within C/FRONT? 9. True or False. C/FRONT does not require any files from the Microsoft Dynamics NAV client directory. 10. What is the purpose of using OCX control? 11. What must be done to use OCX control? 12. What may be the reason for not being able to select OCX as a data type? 13. Is calling a method or setting properties of an OCX any different from any other standard Microsoft Dynamics NAV object? 14. What is the purpose of using Automation in Microsoft Dynamics NAV? 15. Yes or No. It is possible to respond to Automation Events in Microsoft Dynamics NAV? 16. True or False. The CREATE function must be used before using an Automation object. 17. True or False. The FREE function is used to release the Automation object from memory.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
13-41
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Quick Interaction: Lessons Learned Take a moment and write down three key points you have learned from this chapter 1.
2.
3.
13-42
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Appendix A: Solutions to Test Your Knowledge
APPENDIX A: SOLUTIONS TO EXERCISES Test Your Knowledge Answers (CH2) 1. What is the option string for the Reserve field in the Customer table? Never,Optional,Always 2. What is the value of the TableRelation property of the Global Dimension 1 Code field in the Customer table? Currency 3. What type of field is the Date Filter field in the G/L Account table? Date, FlowFilter 4. What two major items can be defined within a table description? Fields and Keys 5. What table property defines the default lookup form for the table? LookupFormID 6. What field property is used to force the user to enter a value into a Primary key field? NotBlank 7. What number range can be used for new fields that are added to the customer table? 50000 to 99999 8. To view customers in order by the city that they live in, what needs to be changed in the table description? Add a secondary key that contains the City field as the first field 9. What change needs to be made to the Salesperson Code field in the Customer table so that the user is only able to look up Salespeople that have a Commission % larger than zero? Add a table filter to the table relation property that filters the Salespeople where Commission % > 0 10. What type of table is the Customer table? Master table for Sales and Receivables functional area 11. What type of table is the Item Vendor table? Subsidiary to the Vendor and the Item tables
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
A-1
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 12. What type of table is the Currency table? Supplemental to all functional areas 13. What type of table is the Item Ledger Entry table? Ledger for the Inventory functional area
A-2
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Appendix A: Solutions to Test Your Knowledge
Test Your Knowledge Answers (CH3) 1. True or False. All forms are bound. False. Some forms are not related to any table (unbound) 2. True or False. The Form Wizard is not useful. False. Most forms can be created with the wizard. The only additional items that must be added are usually buttons. 3. Which property must be set on the Command button for the RunObject property to work? Set PushAction property to RunObject 4. Which control enables a form to display more than one record at a time? Tablebox 5. Which control enables one form to display another form? Subform 6. Which property of a Text box binds it to a field in a table? SourceExpr 7. What form property binds a form to a table? SourceTable 8. How is a menu item turned into a submenu on a menu button? Indent other menu items under it using the Right button on the Menu Designer window. 9. How is a label attached to another control so that the label follows the other control if it is moved? Click the Add Label button on the Toolbox window before adding the other control, or set the ParentControl property of the label to the other control. 10. What are the steps to create a List form for a table? Create a tabular form for the table using the wizard. Change the Editable property of the form to False. Add appropriate buttons to go to the Card, Ledger Entries, and Statistics.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
A-3
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Test Your Knowledge Answers (CH5) 1. What is the programming language of C/SIDE called? C/AL (Client Application Language) 2. List three or more uses of programming code. Data Manipulation Data Presentation Data Acquisition To control the execution of C/AL objects To implement business rules, etc 3. Where can programming language statements be found? In Application Objects (e.g. Forms, Tables, Reports, Codeunits and Dataports). Also, in the triggers within those Application Objects. 4. What is used to modify code in an object? The C/AL Editor 5. List the three basic kinds of triggers. Documentation Triggers, Event Triggers, Function Triggers 6. What key is pressed to view or modify code in an object (other than a codeunit object)? F9 7. What data type is used to store an employee's birthday? Date 8. What data type is used for an employee's name? Text 9. What data type is used for an employee's weekly salary (it must be recorded to the penny)? Decimal 10. What data type is used to record whether an employee is income tax exempt? Boolean 11. Write down the data type of this constant: 'You must enter a positive value.' Text
A-4
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Appendix A: Solutions to Test Your Knowledge 12. Write down the data type of this constant: 123197 Integer 13. Write down the data type of this constant: 327.01 Decimal 14. Write down the data type of this constant: 3,498 This is an invalid constant, due to the comma appearing outside of quotes. 15. Which complex data type is used to store bitmaps (pictures)? BLOB 16. Which complex data type corresponds to a row in a table? Record 17. What two data types are used to read from and write to objects of the Automation and OCX data types? Instream and Outstream 18. Which complex data type can contain up to two gigabytes of text data? BigText
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
A-5
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Test Your Knowledge Answers (CH6) 1. Underline the expression in this assignment statement: TextA := TextB; 2. In mathematics, the things that operators operate on are called "operands." What are these things called in programming expressions? Terms 3. What does the plus operator (+) do to text variables or constants? It concatenates them 4. Underline the expression in this assignment statement: TextA := 'The ' + TextB; 5. Underline the operator(s) in the expression: TextA := 'The ' + TextB; 6. Underline the term(s) in the expression: TextA := 'The ' + TextB; 7. Write down the result type and value of each of these expressions: a. 57 * 10 Integer, 570 b. 57 / 10 Decimal, 5.7 c. 57 DIV 10 Integer, 5 d. 57 MOD 10 Integer, 7 e. 2000000 * 3000 Decimal, 6000000000 f.
9 / 4 - 9 DIV 4 Decimal, 0.25
g. (3 - 10) * - 5 - 10 + 2.5 * 4 Decimal, 35
A-6
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Appendix A: Solutions to Test Your Knowledge h. 02201996D + 14 Date, 03051996D i.
02101996D - 14 Date, 01271996D
j.
01201996D - 02101996D Integer, -21
8. For each question, write down the value of the result of evaluating the logical or relational expression: a. 5 * 7 > 3 FALSE b. 5 * -7 > -36 TRUE c. (3 > 5 - 1) OR (7 < 5 * 2) TRUE d. (27 MOD 5 = 2) AND (27 DIV 5 = 5) TRUE e. (5 > 3) XOR (7 = 7) AND (9 >= 10) TRUE f.
(10 > 2) AND ('10' > '2') FALSE
g. NOT (11 + 7 < 15) OR ('Great' > 'Greater') AND ('Less' < 'Lesser') TRUE h. TRUE OR FALSE = TRUE TRUE i.
Given that X is a Boolean Variable: NOT (X AND TRUE OR FALSE) = (NOT X OR FALSE) AND TRUE TRUE
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
A-7
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Test Your Knowledge Answers (CH7 Part 1) 1. Here is the same set of statements, indented correctly, with lines drawn from each ELSE to its corresponding IF, so that you can see the relationship. IF (X1 > X2) OR B3 THEN BEGIN IF X7 < X2 THEN A1 := (X1 + X7) / 2 ELSE IF X6 < X2 THEN A1 := (X1 + X6) / 2; X7 := X6 + 1; END ELSE IF (X1 < X2) AND B5 THEN IF X6 > X7 THEN BEGIN IF B2 THEN A2 := X1 / 2 + X7 / 2 ELSE A2 := X1 * 2 + X7 * 2; END ELSE A1 := X1 ELSE A2 := X2; IF B1 THEN EXIT;
2. Below are the same statements that have had the commented sections removed and are indented correctly. A5 := 7; B1 := FALSE; B2 := TRUE; A1 := 11; A2 := 2 * A5; IF (A1 < A5) OR B1 THEN A5 := 3 * A5 ELSE A5 := A1 + A5;
A5 = 18
A-8
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Appendix A: Solutions to Test Your Knowledge
Test Your Knowledge Answers (CH7 Part 2) 1. In each of these examples, explain if this is an allowable application for arrays. a. You have a list of students, numbered from 1 to 99. Each student takes a test. You want to put the numeric score (from 0 to 100) for each student into an array, with student 1's score going in element 1, student 2's score in element 2, and so on. This Works b. You have a list of students, numbered from 1 to 99. Each student takes a test. You want to create a two-dimensional array with two rows of 99 columns. In the first row, put the corresponding student's name, with student 1's name in element 1,1, student 2's name in element 1,2, and so on. In the second row, put the corresponding student's numeric test score (from 0 to 100), with student 1's score going in element 2,1, student 2's score going in element 2,2, and so on. This does not work. Every element in an array must have the same data type. In this case, the student names are text and their scores are integers. For this to work, you must use two separate arrays. c. You create an array containing the number of households in each ZIP code. There is one array element for each five-digit ZIP code and each element contains the number of households in that ZIP code. The number of households that have a ZIP code of 30071 goes into element 30071, and so on. This works. The maximum integer is over two billion, while the maximum ZIP code is less than one hundred thousand. Also, the maximum number of elements in a single array is one million. You are well within the limits. d. You create an array containing the number of households in each state. There is one array element for each two-character postal state code and each element contains the number of households in that state. The number of households in Georgia goes into element 'GA', and so on. This does not work. Although array elements can be of any type, array index values must be integer. In this case, the array index is text or code. 2. Which repetitive statement must be used if how many times the statements have to be executed is known? The FOR statement 3. Which repetitive statement does not require a BEGIN and END to execute more than one statement repetitively? The REPEAT statement
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
A-9
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 4. Which repetitive statements test the condition at the beginning of each loop? The FOR statement and the WHILE statement 5. Rewrite the following WHILE statement as a REPEAT statement. Describe the differences in how it is executed. WHILE X > 0 DO BEGIN Y := A * X * X + B * X + C; X := X - 1; END;
Rewrite as follows: REPEAT Y := A * X * X + B * X + C; X := X - 1; UNTIL X <= 0;
The difference is that if X starts out less than or equal to zero, no statements in the loop is executed in the case of the WHILE statement, while in the case of the REPEAT statement, the two statements in the loop are executed once. In the case that X starts out greater than zero, there is no difference in the way these are executed
A-10
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Appendix A: Solutions to Test Your Knowledge
Test Your Knowledge Answers (CH8 Part 1) The questions on this self-test relate to the following code. Hand-execute this code to determine the answers. Use the C/AL Symbol Menu and online Help to determine what the various functions do. All these functions can be found in the String group of the SYSTEM element. Do not actually run this code in the test codeunit until reaching question seven. // UserInput is a Text variable of length 100. The other variables are Integers. UserInput := 'The colors are red, orange, yellow, green, blue and violet.'; Count := 0; REPEAT Comma := STRPOS(UserInput,','); //Q1 IF Comma > 0 THEN BEGIN //Q2 Count := Count + 1; UserInput := DELSTR(UserInput,Comma,1); //Q3 UserInput := COPYSTR(INSSTR(UserInput, ' and',Comma),1,MAXSTRLEN(UserInput)); END; UNTIL Comma <= 0; // Display Results MESSAGE('The sentence is "%1". Number of commas is %2.',UserInput,Count); EXIT(Qty * Unit);
1. What is the value of Comma after the statement labeled Q1 is executed the first time? 19 2. Is the value of Comma ever less than zero in this code (refer to the statement labeled Q2)? No 3. What is the value of UserInput after the statement labeled Q3 is executed the first time? The colors are red orange, yellow, green, blue and violet. 4. What is the value of Count when the comment line is reached the first time? 4 5. Suppose that UserInput is redefined so that it is a Text of length 60. Now, what is its value when the MESSAGE function after the comment line is reached? The colors are red and orange and yellow and green and blue.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
A-11
C/SIDE Introduction in Microsoft Dynamics® NAV 2009 6. The end of the sentence can be lost under these circumstances. Modify the UNTIL clause of the REPEAT statement so that it looks as follows: UNTIL (Comma <= 0) OR (STRLEN(UserInput) + 3 > MAXSTRLEN(UserInput));
Although better, this is not the result desired. Why did it not work? Because a REPEAT loop is always executed at least once and the test was done after the variable had already been changed. 7. Run this code in a codeunit. Do not forget to define the variables. Make the simplest change possible to address the problem uncovered in question seven. Write down the changes. Here is one possible answer: UserInput := 'The colors are red, orange, yellow, green, blue and violet.'; Count := 0; WHILE (STRPOS(UserInput,',') <> 0) AND (STRLEN(UserInput) + 3 <= MAXSTRLEN(UserInput)) DO BEGIN Comma := STRPOS(UserInput,','); Count := Count + 1; UserInput := DELSTR(UserInput,Comma,1); UserInput := INSSTR(UserInput,' and',Comma); END; MESSAGE('The sentence is "%1". Number of commas is %2.',UserInput,Count);
Note that the REPEAT loop was changed into a WHILE loop. In order to do this, the condition had to be logically negated, since a REPEAT loop continues as long as the condition is FALSE, whereas a WHILE loop continues as long as the condition is TRUE. To logically negate any logical expression, put a NOT in front of it and enclose the entire expression in parentheses. Or do as above: Change every relational operator to its opposite ( "=" to "<>" and vice versa, ">" to "<=" and vice versa and "<" to ">=" and vice versa), plus change every AND to an OR and every OR to an AND.
A-12
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Appendix A: Solutions to Test Your Knowledge
Test Your Knowledge Answers (CH8 Part 2) In the Object Designer, locate codeunit 358, DateFilter-Calc. Design this codeunit, and answer the following questions by looking at this object. Remember, if a question is about the Function Definition, it is best to examine the Function tab in the C/AL Globals window, and at the C/AL Locals window. If a question is about the code, it is best to examine the trigger code. 1. How many Parameters does the CreateFiscalYearFilter function have?
Four 2. What type of value (if any) is returned by the CreateAccountingPeriodFilter function?
The function does not return any value 3. In the CreateAccountingDateFilter function, is the first parameter (Filter) passed by value or passed by reference?
Pass by reference 4. In the CreateAccountingDateFilter function, is the third parameter (FiscalYear) passed by value or passed by reference?
Pass by value 5. In the CreateAccountingDateFilter function, how many local variables are defined?
None
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
A-13
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Test Your Knowledge Answers (CH9) 1. True or False: All reports must print at least one page. False. Some reports do not print anything. They are called processing only reports. 2. List the names of the Designers used with reports, and describe their function. Report Designer – design the data model for the report. Sections Designer – design the page layout for the report. Request Options Form Designer – design the Options tab of the request form. Request Options Page Designer – design the request page. Microsoft Visual Studio Report Designer – design the RDL data for layout of reports in the RoleTailored client. 3. How many times does a Header section print on a report for an indented data item (assume PrintOnEvery page is turned off and there is data in the table)? What if the data item is not indented? Once for every record in the data item that it is indented under. Once for the entire report. 4. What data item property can be used to remove the Data Items tab on the request form (assume there are no request filter fields set)? DataitemTableView. Select a key to sort the data item. 5. What two properties of a data item must be set to print a subtotal of a field on a group footer section? GroupTotalFields and TotalFields. 6. When does a TransHeader section print for a data item? Whenever the data item's body sections fill one page and force a new page to be created. It does not print if another data item causes the new page. 7. What property can be set to start a new page every time that a record is read? NewPagePerRecord on the data item. 8. What two properties can be used to print a footer at the bottom of every page? PrintOnEveryPage=Yes and PrintInBottom=Yes for the footer section.
A-14
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Appendix A: Solutions to Test Your Knowledge 9. What C/AL code can be written that most closely resembles a report that has two data items, with the second indented? Nested loops. While DataItem1.GetRecord DO While DataItem2.GetRecord DO; 10. What property can be used to filter an indented data item based on fields in the unindented data item above it? DataitemLink
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
A-15
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Test Your Knowledge Answers (CH10) 1. What is the difference between the description of a report and the description of a dataport? Instead of sections, the dataport has dataport fields. 2. What cannot be done with a data item in a dataport that can be done with a data item in a report? Indent data items. 3. In an import dataport, what must the dataport fields created in the Dataport Field Designer match? The fields must match the file that to be imported. 4. In an import dataport, if the AutoSave property is set to No and the AutoUpdate property is set to Yes, what does the dataport do with the records from the external file? Nothing. If AutoSave is no, the dataport does not insert or modify any records automatically. 5. When must the StartPos and Width properties of a dataport field be used? When the file type is Fixed. 6. True or False. Every dataport field must be bound to a real field in the data item. False. Dataport fields can be bound to variables or other fields in record variables (for exporting other values are also acceptable). 7. What does the Calcfields property do on a data item? It tells the dataport to calculate the values of FlowFields that are to be exported. 8. When exporting, which dataport file type lines up the information in columns? Fixed 9. When exporting, which dataport file type creates the smallest possible file? Variable. There are no extra spaces between dataport fields. 10. When importing, which dataport properties can be set so that the user cannot view the options tab? Filename property to the name of the file (the user cannot change it). Import to Yes (the user cannot change it). The options tab disappears.
A-16
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Appendix A: Solutions to Test Your Knowledge 11. What is the main difference between a Dataport and an XMLport? While both objects are used to export data, XMLports encapsulate the data in XML format. 12. The XML node name information is stored in what field? NodeName 13. Which field is used to specify whether the name in the NodeName field represents data of the type element or attribute? NodeType 14. Which field specifies the data structure that the node name corresponds to in the Microsoft Dynamics NAV database? SourceType. The three options are Text, Table and Field 15. How are the XMLports run? XMLports are called from other objects. They cannot be run in a stand-alone mode. 16. True or False. An XMLport cannot modify existing data in the database. True. XMLports cannot modify existing data, they cannot find and delete data in the database, nor can they query the database for data. 17. What is the purpose of the Direction property in the XMLport? This property is used to specify whether the XMLport can Import, Export, or Import and Export data.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
A-17
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Test Your Knowledge Answers (CH11) 1. What triggers are available in every codeunit? Documentation and OnRun 2. What key can be pressed to open the Symbol Menu? F5 3. What must be done to call a function in a codeunit from another object? Create a variable for the codeunit with the correct subtype. 4. Can two codeunit variables refer to the same instance of a codeunit? Yes 5. Can two codeunit variables declared in the same object refer to different instances of a codeunit? Yes 6. What change needs to be made to a codeunit variable to point to the same instance of a codeunit as another codeunit variable? Assignment CU1 := CU2; 7. What function can be used to make a codeunit variable point to a new instance of a codeunit? CLEAR(CU1); 8. If a codeunit is designed as a single instance codeunit, can two codeunit variables refer to different instances of that codeunit? No 9. What is the correct way to address a global variable of a codeunit from an object that has a variable, called CU, for that codeunit? Global variables within a codeunit cannot be directly addressed from outside the codeunit. Add functions in the codeunit that returned or changed the value of the variables. 10. Can a function named Power be created in a codeunit? No. Power is already a built-in function.
A-18
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Appendix A: Solutions to Test Your Knowledge
Test Your Knowledge Answers (CH12) 1. True or False. A MenuSuite cannot be accessed programmatically. True 2. What is the name of the design area used to work with the MenuSuites? Navigation Pane Designer 3. With the exception of the Add-on level, how many instances of a MenuSuite can there be for each Design Level? One 4. How many instances of the MenuSuite can there be for the Add-on level? 10 5. What are the two ways to open the Navigation Pane Designer? By selecting a MenuSuite Object in Object Designer and then clicking Design By choosing Tools from the Tool Menu, then Navigation Pane Designer 6. True or False. A MenuSuite object can be run from the Object Designer. False. MenuSuite objects cannot be run. 7. When creating a new item in a MenuSuite and Report is selected as the Object Type, what is displayed when the Lookup button on the Object ID is clicked? The Report List 8. Name the six selections available in the Object Type field for a menu item that is created for the Classic client. Table, Form, Report, Batch Job, Codeunit, and Dataport 9. What are the levels on which a MenuSuite can be categorized? Region, Country, Add-on, Partner and Company
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
A-19
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
Test Your Knowledge Answers (CH13) 1. What must be done to use Microsoft Dynamics NAV ODBC? (Select the correct answers.) – Install Microsoft's ODBC driver. – Purchase the Microsoft Dynamics NAV ODBC granule. – Set up permissions for the users. – Set up a DSN. 2. True or False. Any Microsoft Dynamics NAV ODBC version can be used to open up any Microsoft Dynamics NAV database. False, the Microsoft Dynamics NAV ODBC driver and client versions must be the same. 3. True or False. Microsoft Dynamics NAV uses Microsoft's ADO for all connections. False, Microsoft Navision doesn't support ADO. 4. True or False. Microsoft Dynamics NAV ODBC driver supports outer joins. False 5. True or False. Entering data through ODBC is validated just as in the Microsoft Dynamics NAV client. False 6. What is C/FRONT? C/FRONT is an application programming interface that can be used to access a C/SIDE database. 7. Does C/FRONT use a session? Yes 8. Can keys be activated from within C/FRONT? No 9. True or False. C/FRONT does not require any files from the Microsoft Dynamics NAV client directory. False 10. What is the purpose of using OCX control? To save on development time and to reduce costs 11. What must be done to use OCX control? Load and register the OCX on each machine.
A-20
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
Appendix A: Solutions to Test Your Knowledge 12. What may be the reason for not being able to select OCX as a data type? The OCX granule is not included in the license. 13. Is calling a method or setting properties of an OCX any different from any other standard Microsoft Dynamics NAV object? No 14. What is the purpose of using Automation in Microsoft Dynamics NAV? To provide a seamless interface to outside applications To save on development time To reduce costs To automate a process 15. Yes or No. It is possible to respond to Automation Events in Microsoft Dynamics NAV? Yes 16. True or False. The CREATE function must be used before using an Automation object. True 17. True or False. The FREE function is used to release the Automation object from memory. False. Use the CLEAR function instead.
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement
A-21
C/SIDE Introduction in Microsoft Dynamics® NAV 2009
A-22
Microsoft Official Training Materials for Microsoft Dynamics ® Your use of this content is subject to your current services agreement